Skip to content

Commit e6bf023

Browse files
committed
Merge branch 'requests_logic'
2 parents 1a2fa89 + 3af175b commit e6bf023

File tree

16 files changed

+350
-51
lines changed

16 files changed

+350
-51
lines changed

app/django-bbx/bbx/__init__.py

+5
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
from __future__ import absolute_import
2+
3+
# This will make sure the app is always imported when
4+
# Django starts so that shared_task will use this app.
5+
from .celery import app as celery_app

app/django-bbx/bbx/celery.py

+32
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
from __future__ import absolute_import
2+
3+
import os
4+
5+
from celery import Celery
6+
7+
from django.conf import settings
8+
9+
# set the default Django settings module for the 'celery' program.
10+
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'bbx.settings')
11+
12+
app = Celery('bbx',
13+
broker='amqp://',
14+
backend='amqp://',
15+
include=['repository.tasks'])
16+
17+
# Optional configuration, see the application user guide.
18+
app.conf.update(
19+
CELERY_TASK_RESULT_EXPIRES=3600,
20+
)
21+
22+
23+
# Using a string here means the worker will not have to
24+
# pickle the object when using Windows.
25+
app.config_from_object('django.conf:settings')
26+
app.autodiscover_tasks(lambda: settings.INSTALLED_APPS)
27+
28+
29+
@app.task(bind=True)
30+
def debug_task(self):
31+
print('Request: {0!r}'.format(self.request))
32+

app/django-bbx/bbx/settings.example.py

+11
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,16 @@
1414
# Example: "/var/www/example.com/media/"
1515
MEDIA_ROOT = "/data/bbx/"
1616

17+
## Broker settings.
18+
BROKER_URL = 'amqp://guest:guest@localhost:5672//'
19+
20+
# List of modules to import when celery starts.
21+
CELERY_IMPORTS = ('repository.tasks',)
22+
23+
## Using the database to store task state and results.
24+
CELERY_RESULT_BACKEND = 'amqp'
25+
CELERY_TASK_RESULT_EXPIRES = 18000 # 5 hours.
26+
1727
# Change this to the full path to your own repository
1828
REPOSITORY_DIR_NAME ="repositories"
1929
REPOSITORY_DIR = os.path.join(MEDIA_ROOT, REPOSITORY_DIR_NAME)
@@ -173,6 +183,7 @@
173183
'repository',
174184
'mocambola',
175185
'south',
186+
'celery',
176187
'sorl.thumbnail',
177188
)
178189

app/django-bbx/bbx/static/templates/media/MediaView.html

+1-1
Original file line numberDiff line numberDiff line change
@@ -87,7 +87,7 @@ <h3><%= media.name %></h3>
8787
<% if (!media.is_local) { %>
8888
<div class="blocks clear-both solicit-copy">
8989
<p class="solicit-copy">
90-
<a href="">
90+
<a href="<%= '/api/' + media.repository + '/' + media.origin + '/media/' + media.uuid %>/request">
9191
<span class="title-bold">solicitar cópia local</span>
9292
<span class="image"></span>
9393
</a>

app/django-bbx/bbx/templates/admin/base_site.html

+1-1
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44
{% block title %}{{ title }} | {% trans 'Quintão do Baobáxia' %}{% endblock %}
55

66
{% block branding %}
7-
<h1 id="site-name">{% trans 'Quintão do Baobáxia' %}</h1>
7+
<h1 id="site-name">{% trans 'Quintal do Baobáxia' %}</h1>
88
{% endblock %}
99

1010
{% block nav-global %}{% endblock %}

app/django-bbx/media/models.py

+55-3
Original file line numberDiff line numberDiff line change
@@ -16,8 +16,9 @@
1616
from django.utils.functional import lazy
1717

1818
from tag.models import Tag
19-
from bbx.settings import REPOSITORY_DIR
19+
from bbx.settings import REPOSITORY_DIR, DEFAULT_MUCUA
2020
from bbx.utils import logger
21+
from repository.tasks import git_annex_get
2122

2223
try:
2324
from django.utils.encoding import force_unicode # NOQA
@@ -51,6 +52,7 @@ def get_file_path(instance):
5152
return os.path.join(REPOSITORY_DIR, get_media_path(instance))
5253

5354
def get_media_path(instance):
55+
# FIX: se mudar a data quebra o path
5456
if instance.date == '':
5557
t = datetime.now
5658
date = t.strftime("%y/%m/%d/")
@@ -142,6 +144,7 @@ class Media(models.Model):
142144
_('is requested'),
143145
help_text=_('True if media content is awaiting a local copy'),
144146
default=False)
147+
# FIX: request_code desnessesario.. usando o uuid mesmo
145148
request_code = models.CharField(max_length=100, editable=False, blank=True)
146149
num_copies = models.IntegerField(
147150
_('number of copies'), default=1, blank=True,
@@ -180,7 +183,7 @@ def get_format(self):
180183
return self.format
181184

182185
# FIX (Nao pega na primeira save)
183-
def _set_is_local(self):
186+
def set_is_local(self):
184187
self.is_local = os.path.isfile(os.path.join(get_file_path(self),
185188
self.get_file_name()))
186189

@@ -198,8 +201,53 @@ def where_is(self):
198201
def get_tags(self):
199202
return self.tags
200203

204+
def request_copy(self):
205+
u"""
206+
Gera um pedido de copia local do media
207+
208+
Os pedidos tem um codigo uuid e são gravados em
209+
/repository/mucua/requests/uuid
210+
211+
O arquivo atualmente contem somente o caminho para o media no
212+
repositorio.
213+
214+
"""
215+
self.set_is_local()
216+
if not self.is_local:
217+
self.is_requested = True
218+
self.save()
219+
try:
220+
requests_path = os.path.join(REPOSITORY_DIR, self.get_repository(),
221+
DEFAULT_MUCUA,
222+
'requests')
223+
if not os.path.exists(requests_path):
224+
os.makedirs(requests_path)
225+
226+
request_filename = os.path.join(requests_path, self.uuid)
227+
logger.info("REQUESTING: " + request_filename)
228+
request_file = open(request_filename, 'a')
229+
request_file.write(self.media_file.path)
230+
request_file.close
231+
# TODO: Need to git add
232+
logger.debug("ADDING REQUEST: " + os.path.basename(request_filename))
233+
logger.debug("ADDED ON: " + os.path.dirname(request_filename))
234+
from repository.models import git_add
235+
git_add(os.path.basename(request_filename), os.path.dirname(request_filename))
236+
237+
except IOError:
238+
logger.info(u'Alo! I can\'t write request file!')
239+
240+
logger.debug("get_file_path: " + get_file_path(self))
241+
logger.debug("media_file.name: " + os.path.basename(self.media_file.name))
242+
243+
async_result = git_annex_get.delay(get_file_path(self), os.path.basename(self.media_file.name))
244+
#logger.debug(async_result.get)
245+
#logger.debug(async_result.info)
246+
247+
248+
201249
def save(self, *args, **kwargs):
202-
self._set_is_local()
250+
self.set_is_local()
203251
if self.pk is not None:
204252
self._set_num_copies()
205253
self.url = self.get_url()
@@ -213,6 +261,10 @@ class TagPolicyDoesNotExist(exceptions.Exception):
213261
def __init__(self, args=None):
214262
self.args = args
215263

264+
class MediaDoesNotExist(exceptions.Exception):
265+
def __init__(self, args=None):
266+
self.args = args
267+
216268

217269
@receiver(post_save, sender=Media)
218270
def start_post_save_policies(instance, **kwargs):

app/django-bbx/media/urls.py

+1
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
'(?P<width>[0-9]{2,4})x(?P<height>[0-9]{2,4})\.(?P<format_type>[a-zA-Z]{3,4})$', 'show_image'),
88
url(r'^(?P<repository>\w+)/(?P<mucua>[a-zA-Z0-9\-]+)/media/(?P<uuid>[a-z0-9\-]+)/url$', 'media_url'),
99
url(r'^(?P<repository>\w+)/(?P<mucua>[a-zA-Z0-9\-]+)/media/(?P<uuid>[a-z0-9\-]+)/whereis$', 'media_where_is'),
10+
url(r'^(?P<repository>\w+)/(?P<mucua>[a-zA-Z0-9\-]+)/media/(?P<uuid>[a-z0-9\-]+)/request$', 'media_request_copy'),
1011
url(r'^(?P<repository>\w+)/(?P<mucua>[a-zA-Z0-9\-]+)/media/last/' +
1112
'(?P<qtd>[\d]*)$', 'media_last'),
1213
url(r'^(?P<repository>\w+)/(?P<mucua>[a-zA-Z0-9\-]+)/media/last',

app/django-bbx/media/views.py

+13
Original file line numberDiff line numberDiff line change
@@ -455,3 +455,16 @@ def media_where_is(request, repository, mucua, uuid):
455455
io = media.where_is()
456456
data = json.loads(io)
457457
return Response(data)
458+
459+
@api_view(['GET'])
460+
#@renderer_classes((BrowsableAPIRenderer))
461+
def media_request_copy(request, repository, mucua, uuid):
462+
try:
463+
media = Media.objects.get(uuid=uuid)
464+
media.request_copy()
465+
except Media.DoesNotExist:
466+
return Response(status=status.HTTP_404_NOT_FOUND)
467+
return HttpResponseRedirect('/#' + repository +
468+
'/' + mucua +
469+
'/media/' + uuid )
470+

app/django-bbx/mocambola/models.py

+2-1
Original file line numberDiff line numberDiff line change
@@ -103,7 +103,8 @@ def mocambola_post_save(instance, **kwargs):
103103
fout.close()
104104
git_add(mocamboladata, mocambolapath)
105105
git_commit(mocamboladata, instance.user.get_username(),
106-
instance.user.email, instance.repository.get_path())
106+
instance.user.email, instance.repository.get_path(),
107+
os.path.join(mocambolapath, mocamboladata))
107108

108109
# TODO HIGH: Precisa serializar o user tambem na criaçao e update
109110
# diretamente pelo usuario

app/django-bbx/mucua/models.py

+5-5
Original file line numberDiff line numberDiff line change
@@ -26,17 +26,17 @@ def update_mucuas_list(repository):
2626
u"""Atualiza a lista de mucuas disponivéis no repositório"""
2727
mucuas = get_available_mucuas(None, repository)
2828
for mucua in mucuas:
29-
print ">>> Mucua description: " + mucua[1]
30-
print ">>> Mucua uuid: " + mucua[0]
3129
mucua_description = str(mucua[1])
3230
mucua_uuid = str(mucua[0])
3331
try:
3432
mucua = Mucua.objects.get(description=mucua_description)
35-
print "Vi a mucuaa"
33+
logger.info("Vi a mucua " + mucua_description +
34+
", UUID: " + mucua_uuid)
3635
except Mucua.DoesNotExist:
3736
m = Mucua(description=mucua_description, uuid=mucua_uuid)
3837
m.save()
39-
print "Criei a mucua " + mucua_description
38+
logger.info("Criei a mucua " + mucua_description +
39+
", UUID: " + mucua_uuid)
4040

4141

4242
# Helper function to map repository description to correct
@@ -109,7 +109,7 @@ def get_available_mucuas(uuid=None, repository=None):
109109
in json_repository_status['trusted repositories']])
110110

111111
mucuas = [(m[0], rpr(m[1].replace('[','').replace(']',''))) for m in mucuas]
112-
logger.debug(u'Mucuas: %s' % mucuas)
112+
# logger.debug(u'Mucuas: %s' % mucuas)
113113
return mucuas
114114

115115
def get_mucua_info(uuid, repository=None):
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,76 @@
1+
import os
2+
import shutil
3+
4+
from django.core.management.base import BaseCommand
5+
6+
from repository.tasks import git_annex_get
7+
from repository.models import git_remote_get_list, git_annex_drop, git_add, git_rm
8+
from media.models import Media, MediaDoesNotExist, get_file_path
9+
from bbx.settings import REPOSITORY_DIR
10+
from bbx.utils import logger
11+
12+
"""
13+
Definicoes do comando para processar os pedidos.
14+
"""
15+
16+
class Command(BaseCommand):
17+
"""Processa os pedidos em espera."""
18+
help = 'Process pending requests'
19+
20+
def handle(self, *args, **options):
21+
repository = args[0]
22+
mucua = args[1]
23+
# Here we copy mucuas requests from all "linked mucuas"
24+
linked_mucuas = git_remote_get_list(repository)
25+
requests_path = os.path.join(REPOSITORY_DIR, repository, mucua, "requests")
26+
if not os.path.exists(requests_path):
27+
os.makedirs(requests_path)
28+
29+
for lmucua in linked_mucuas:
30+
src_files = os.listdir(os.path.join(REPOSITORY_DIR, repository, lmucua, "requests"))
31+
for file_name in src_files:
32+
full_file_name = os.path.join(src, file_name)
33+
if (os.path.isfile(full_file_name)):
34+
shutil.copy(full_file_name, requests_path)
35+
# TODO: Need to git add
36+
logger.debug('ADDING REQUEST: ' + os.path.basename(full_file_name))
37+
logger.debug('ADDED ON: ' + requests_path)
38+
git_add(os.path.basename(full_file_name), requests_path)
39+
40+
request_list = [uuid for uuid in os.listdir(requests_path)]
41+
42+
for request_uuid in request_list:
43+
if os.path.isfile(os.path.join(requests_path, request_uuid)):
44+
try:
45+
media = Media.objects.get(uuid=request_uuid)
46+
media.set_is_local()
47+
if media.is_local:
48+
request_list = [uuid for uuid in request_list if uuid != request_uuid]
49+
logger.debug('REMOVING REQUEST: ' + request_uuid)
50+
git_rm(request_uuid, requests_path)
51+
# Here we also git annex drop the file because
52+
# it's only a "transport copy", couse of
53+
# media.is_requested = False.
54+
if not media.is_requested:
55+
requests = []
56+
# Check if we can drop, couse linked mucuas doesn't have pending request
57+
for lmucua in linked_mucuas:
58+
requests_path = os.path.join(REPOSITORY_DIR,
59+
repository, lmucua, "requests")
60+
for name in os.listdir(requests_path):
61+
if os.path.isfile(os.path.join(requests_path, name)):
62+
requests.append(name)
63+
if request_uuid not in requests:
64+
git_annex_drop(media)
65+
66+
media.save()
67+
else:
68+
repository_path = os.path.join(REPOSITORY_DIR, media.get_repository())
69+
async_result = git_annex_get.delay(get_file_path(media),
70+
os.path.basename(media.media_file.name))
71+
logger.debug(async_result.info)
72+
media.save()
73+
except MediaDoesNotExist:
74+
request_list = [uuid for uuid in request_list if uuid != request_uuid]
75+
logger.debug('Requested media not found')
76+

0 commit comments

Comments
 (0)