Skip to content

Commit be52426

Browse files
committed
merge
2 parents 780b718 + e6bf023 commit be52426

33 files changed

+819
-97
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)
@@ -183,6 +193,7 @@
183193
'mocambola',
184194
'lang',
185195
'south',
196+
'celery',
186197
'sorl.thumbnail',
187198
)
188199

app/django-bbx/bbx/static/css/main.css

+1-1
Original file line numberDiff line numberDiff line change
@@ -100,7 +100,7 @@ a {text-decoration: none;}
100100
/*
101101
* footer
102102
*/
103-
#usage-content {padding: 6px; font-size: 10px; font-weight: bold }
103+
#usage-content {padding: 6px; font-size: 9px; font-weight: bold }
104104
#usage-content .usage-bar,
105105
#usage-content .legend {width: 700px; height: 15px; padding-left: 6px }
106106
#usage-content .legend .available {color: #000; width: 150px; margin-right: 5px}

app/django-bbx/bbx/static/js/modules/bbx/functions.js

+5-5
Original file line numberDiff line numberDiff line change
@@ -263,10 +263,10 @@ define([
263263
};
264264

265265
// set mucua variables from API
266-
mucuaData.totalDiskSpace = BBX.mucua.info['total disk space'];
267-
mucuaData.usedByAnnex = BBX.mucua.info['local annex size'];
268-
mucuaData.usedByOther = BBX.mucua.info['local used by other'];
269-
mucuaData.availableLocalDiskSpace = BBX.mucua.info['available local disk space'];
266+
mucuaData.totalDiskSpace = String(BBX.mucua.info['total disk space'])
267+
mucuaData.usedByAnnex = String(BBX.mucua.info['local annex size']);
268+
mucuaData.usedByOther = String(BBX.mucua.info['local used by other']);
269+
mucuaData.availableLocalDiskSpace = String(BBX.mucua.info['available local disk space'])
270270
mucuaData.demanded = 0; // TODO: dynamic var
271271

272272
total = mucuaData.totalDiskSpace.match(reStripUnit);
@@ -286,7 +286,7 @@ define([
286286
mucuaData.usedByAnnexPercent = parseFloat(parseFloat(mucuaData.usedByAnnex) / parseFloat(mucuaData.total) * 100).toFixed(1);
287287
mucuaData.availableLocalDiskSpacePercent = parseFloat(parseFloat(mucuaData.availableLocalDiskSpace) / parseFloat(mucuaData.total) * 100).toFixed(1);
288288
mucuaData.demandedPercent = parseFloat(parseFloat(mucuaData.demanded) / parseFloat(mucuaData.total) * 100).toFixed(1);
289-
289+
290290
BBX.mucua.info = mucuaData;
291291
}
292292
});

app/django-bbx/bbx/static/js/modules/media/functions.js

+1
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,7 @@ define([
5050

5151
var __parseUrlSearch = function(terms) {
5252
var config = __getConfig();
53+
terms = terms.replace(/\s/g, '\/');
5354
return config.interfaceUrl + config.MYREPOSITORY + '/' + config.mucua + '/bbx/search/' + terms;
5455
}
5556

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

+4-1
Original file line numberDiff line numberDiff line change
@@ -89,7 +89,10 @@ <h3><%= media.name %></h3>
8989
<div class="blocks clear-both solicit-copy">
9090
<p class="solicit-copy">
9191
<a href="">
92-
<span class="title-bold">{% trans "request local copy" %} local</span>
92+
<span class="title-bold">
93+
local</span>
94+
<a href="<%= '/api/' + media.repository + '/' + media.origin + '/media/' + media.uuid %>/request">
95+
<span class="title-bold">{% trans "request local copy" %}</span>
9396
<span class="image"></span>
9497
</a>
9598
</p>

app/django-bbx/media/models.py

+56-4
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
@@ -27,7 +28,7 @@
2728
TYPE_CHOICES = (('audio', 'audio'), ('imagem', 'imagem'), ('video', 'video'),
2829
('arquivo', 'arquivo'))
2930
FORMAT_CHOICES = (('ogg', 'ogg'), ('ogv', 'ogv'), ('webm', 'webm'), ('mp4', 'mp4'),
30-
('jpg', 'jpg'), ('png', 'png'), ('pdf', 'pdf'), ('gif', 'gif'))
31+
('jpg', 'jpg'), ('png', 'png'), ('pdf', 'pdf'), ('gif', 'gif'), ('odp','odp'))
3132

3233

3334
def media_file_name(instance, file_name):
@@ -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

+7-8
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):
@@ -128,9 +128,8 @@ def get_mucua_disk():
128128
df = subprocess.Popen(["df", MEDIA_ROOT], stdout=subprocess.PIPE)
129129
output = df.communicate()[0]
130130
data = []
131-
data.append(int(output.split("\n")[1].split()[1]) / 1024 / 1024) # size
132-
data.append(int(output.split("\n")[1].split()[2]) / 1024 / 1024) # used
133-
131+
data.append(float(output.split("\n")[1].split()[1]) / 1024 / 1024) # size
132+
data.append(float(output.split("\n")[1].split()[2]) / 1024 / 1024) # used
134133
return data
135134

136135

app/django-bbx/mucua/views.py

+10-7
Original file line numberDiff line numberDiff line change
@@ -92,14 +92,14 @@ def mucua_get_info(request, uuid, repository=None):
9292
'terabyte': 'TB',
9393
'terabytes': 'TB'
9494
}
95-
95+
9696
mucua_full = json.loads(get_mucua_info(repository))
9797
size, used = get_mucua_disk()
9898
mucua_info = {
9999
"local annex size": mucua_full["local annex size"],
100100
"local annex keys": mucua_full["local annex keys"],
101-
"available local disk space": str(size - used) + 'GB',
102-
"total disk space": str(size) + 'GB',
101+
"available local disk space": str(int(size) - int(used)) + 'GB',
102+
"total disk space": str(int(size)) + 'GB',
103103
"local used by other": 0,
104104
"network size" : mucua_full["size of annexed files in working tree"]
105105
}
@@ -110,10 +110,13 @@ def mucua_get_info(request, uuid, repository=None):
110110

111111
mucua_info['local annex size'] = convertToGB(
112112
str(float(local_annex_size.group(1))), size_list[local_annex_size.group(2)])
113-
mucua_info['local used by other'] = str(
114-
round(
115-
used - float(re_crop_unit.match(mucua_info['local annex size']).group(1))
116-
, 2)) + 'GB'
113+
mucua_info['local used by other'] = convertToGB(
114+
str(used - float(re_crop_unit.match(mucua_info['local annex size']).group(1))
115+
), size_list[network_size.group(2)]
116+
)
117+
if mucua_info['local used by other'] < 0:
118+
mucua_info['local used by other'] = 0
119+
117120
mucua_info['network size'] = convertToGB(
118121
str(float(network_size.group(1))), size_list[network_size.group(2)])
119122

0 commit comments

Comments
 (0)