pandora/pandora/archive/views.py

549 lines
19 KiB
Python
Raw Normal View History

# -*- coding: utf-8 -*-
# vi:si:et:sw=4:sts=4:ts=4
from __future__ import division
import os.path
from datetime import datetime
from django import forms
2011-01-01 11:44:42 +00:00
from django.shortcuts import get_object_or_404, redirect
from django.conf import settings
2011-10-18 20:06:01 +00:00
from django.db.models import Count
import ox
2010-12-25 10:14:52 +00:00
from ox.utils import json
from ox.django.decorators import login_required_json
from ox.django.shortcuts import render_to_json_response, get_object_or_404_json, json_response
from ox.django.views import task_status
2011-01-29 11:19:11 +00:00
from item import utils
from item.models import get_item, Item
2011-02-22 15:26:06 +00:00
from item.views import parse_query
2010-11-08 16:34:25 +00:00
import item.tasks
from api.actions import actions
import models
import tasks
2010-08-10 22:01:41 +00:00
@login_required_json
def removeVolume(request):
2010-08-10 22:01:41 +00:00
data = json.loads(request.POST['data'])
user = request.user
try:
volume = models.Volume.objects.get(user=user, name=data['volume'])
volume.files.delete()
volume.delete()
response = json_response()
2010-08-10 22:01:41 +00:00
except models.Volume.DoesNotExist:
response = json_response(status=404, text='volume not found')
return render_to_json_response(response)
2011-01-13 08:33:14 +00:00
actions.register(removeVolume, cache=False)
2010-08-10 22:01:41 +00:00
2011-01-01 11:44:42 +00:00
2010-08-10 22:01:41 +00:00
@login_required_json
def update(request):
'''
2010-08-10 22:01:41 +00:00
2 calls possible:
volume/files
info
call volume/files first and fill in requested info after that
2010-12-24 10:31:44 +00:00
param data {
2010-08-10 22:01:41 +00:00
volume: '',
2010-08-07 14:31:20 +00:00
files: [
2010-12-24 10:31:44 +00:00
{oshash:, path:, mtime:, },
...
],
2010-08-07 14:31:20 +00:00
info: {oshash: object}
2010-12-24 10:31:44 +00:00
}
return {
status: {'code': int, 'text': string},
data: {
info: list,
data: list,
file: list
}
}
'''
data = json.loads(request.POST['data'])
2010-08-07 14:31:20 +00:00
user = request.user
upload_only = data.get('upload', False)
2010-08-07 14:31:20 +00:00
2010-08-10 22:01:41 +00:00
response = json_response({'info': [], 'data': [], 'file': []})
2010-09-17 21:06:01 +00:00
volume = None
2010-08-07 14:31:20 +00:00
if 'files' in data:
#update files info async, this takes to long otherwise
#FIXME: how can client know if update is done? possibly with taksStatus?
t = tasks.update_files.delay(user.username, data['volume'], data['files'])
response['data']['taskId'] = t.task_id
2010-08-07 14:31:20 +00:00
user_profile = user.get_profile()
user_profile.files_updated = datetime.now()
user_profile.save()
if 'info' in data:
for oshash in data['info']:
info = data['info'][oshash]
2010-11-08 17:43:59 +00:00
instance = models.Instance.objects.filter(file__oshash=oshash, volume__user=user)
2010-08-07 14:31:20 +00:00
if instance.count()>0:
instance = instance[0]
if not instance.file.info:
2010-08-10 22:01:41 +00:00
for key in ('atime', 'mtime', 'ctime'):
if key in info:
del info[key]
2010-08-07 14:31:20 +00:00
instance.file.info = info
instance.file.save()
if not upload_only:
files = models.Instance.objects.filter(volume__user=user, file__available=False)
if volume:
files = files.filter(volume=volume)
response['data']['info'] = [f.file.oshash for f in files.filter(file__info='{}')]
response['data']['data'] = [f.file.oshash for f in files.filter(file__is_video=True,
2011-08-23 17:39:34 +00:00
file__available=False,
file__wanted=True)]
response['data']['data'] += [f.file.oshash for f in files.filter(file__is_audio=True,
2011-08-23 17:39:34 +00:00
file__available=False,
file__wanted=True)]
response['data']['file'] = [f.file.oshash for f in files.filter(file__is_subtitle=True,
2011-08-26 14:32:00 +00:00
file__available=False,
path__endswith='.srt')]
2010-08-07 14:31:20 +00:00
return render_to_json_response(response)
2011-01-13 08:33:14 +00:00
actions.register(update, cache=False)
2010-08-07 14:31:20 +00:00
2011-01-01 11:44:42 +00:00
@login_required_json
def encodingProfile(request):
2011-09-06 12:06:59 +00:00
config = settings.CONFIG['video']
2011-08-19 15:37:37 +00:00
profile = "%sp.%s" % (config['resolutions'][0], config['formats'][0])
response = json_response({'profile': profile})
return render_to_json_response(response)
actions.register(encodingProfile)
2011-01-01 11:44:42 +00:00
2010-08-10 22:01:41 +00:00
@login_required_json
def upload(request):
'''
2011-06-27 13:39:35 +00:00
id: string
2010-08-24 17:16:33 +00:00
frame: [] //multipart frames
file: [] //multipart file
2010-12-24 10:31:44 +00:00
return {
status: {'code': int, 'text': string},
data: {
info: object,
rename: object
}
}
'''
2011-02-23 17:32:30 +00:00
response = json_response({})
2011-06-27 13:39:35 +00:00
f = get_object_or_404_json(models.File, oshash=request.POST['id'])
2010-08-24 17:16:33 +00:00
if 'frame' in request.FILES:
if f.frames.count() == 0:
for frame in request.FILES.getlist('frame'):
name = frame.name
#float required?
position = float(os.path.splitext(name)[0])
2011-02-22 16:52:03 +00:00
fr, created = models.Frame.objects.get_or_create(file=f, position=position)
2010-08-24 17:16:33 +00:00
fr.frame.save(name, frame)
else:
response = json_response(status=403, text='permissino denied')
if 'file' in request.FILES:
2010-09-17 21:06:01 +00:00
if not f.available:
2011-08-26 14:32:00 +00:00
if f.data:
f.data.delete()
2010-09-03 13:28:44 +00:00
f.data.save('data.raw', request.FILES['file'])
2010-09-17 21:06:01 +00:00
f.save()
2011-08-26 15:40:37 +00:00
item.tasks.load_subtitles.delay(f.item.itemId)
response = json_response(text='file saved')
2010-08-24 17:16:33 +00:00
else:
response = json_response(status=403, text='permissino denied')
2010-08-07 14:31:20 +00:00
return render_to_json_response(response)
2011-01-13 08:33:14 +00:00
actions.register(upload, cache=False)
2010-08-07 14:31:20 +00:00
2011-01-01 11:44:42 +00:00
2010-08-07 14:31:20 +00:00
class VideoChunkForm(forms.Form):
chunk = forms.FileField()
chunkId = forms.IntegerField(required=False)
done = forms.IntegerField(required=False)
2011-01-01 11:44:42 +00:00
2010-08-07 14:31:20 +00:00
@login_required_json
def firefogg_upload(request):
2010-08-13 17:17:23 +00:00
profile = request.GET['profile']
2011-06-27 13:39:35 +00:00
oshash = request.GET['id']
2011-09-06 12:06:59 +00:00
config = settings.CONFIG['video']
2011-08-19 15:37:37 +00:00
video_profile = "%sp.%s" % (config['resolutions'][0], config['formats'][0])
2010-08-07 14:31:20 +00:00
#handle video upload
if request.method == 'POST':
#post next chunk
2010-08-13 17:17:23 +00:00
if 'chunk' in request.FILES and oshash:
2010-09-03 13:28:44 +00:00
f = get_object_or_404(models.File, oshash=oshash)
2010-08-07 14:31:20 +00:00
form = VideoChunkForm(request.POST, request.FILES)
2011-08-19 15:37:37 +00:00
if form.is_valid() and profile == video_profile and f.editable(request.user):
2010-08-07 14:31:20 +00:00
c = form.cleaned_data['chunk']
chunk_id = form.cleaned_data['chunkId']
response = {
'result': 1,
'resultUrl': request.build_absolute_uri('/')
}
if not f.save_chunk(c, chunk_id, form.cleaned_data['done']):
2010-08-07 14:31:20 +00:00
response['result'] = -1
elif form.cleaned_data['done']:
2011-08-23 17:39:34 +00:00
f.uploading = False
2010-09-03 13:28:44 +00:00
f.save()
#FIXME: this fails badly if rabbitmq goes down
try:
2011-08-19 16:54:42 +00:00
t = tasks.process_stream.delay(f.id)
2011-01-01 11:44:42 +00:00
response['resultUrl'] = t.task_id
except:
pass
2010-08-07 14:31:20 +00:00
response['result'] = 1
response['done'] = 1
return render_to_json_response(response)
2010-09-03 13:28:44 +00:00
#init upload
2011-08-19 15:37:37 +00:00
elif oshash and profile == video_profile:
2010-08-13 17:17:23 +00:00
#404 if oshash is not know, files must be registered via update api first
f = get_object_or_404(models.File, oshash=oshash)
2010-09-03 13:28:44 +00:00
if f.editable(request.user):
2011-08-18 18:19:09 +00:00
f.streams.all().delete()
2011-08-23 17:39:34 +00:00
f.uploading = True
2010-09-03 13:28:44 +00:00
f.save()
response = {
#is it possible to no hardcode url here?
2011-06-27 13:39:35 +00:00
'uploadUrl': request.build_absolute_uri('/api/upload/?id=%s&profile=%s' % (f.oshash, profile)),
2010-09-03 13:28:44 +00:00
'result': 1
}
return render_to_json_response(response)
2010-08-07 14:31:20 +00:00
response = json_response(status=400, text='this request requires POST')
return render_to_json_response(response)
2011-01-01 11:44:42 +00:00
@login_required_json
def taskStatus(request):
#FIXME: should check if user has permissions to get status
data = json.loads(request.POST['data'])
user = request.user
task_id = data['task_id']
response = task_status(request, task_id)
return render_to_json_response(response)
2011-01-13 08:33:14 +00:00
actions.register(taskStatus, cache=False)
2011-06-27 13:39:35 +00:00
2011-06-15 13:05:06 +00:00
@login_required_json
def moveFiles(request):
'''
change file / item link
param data {
2011-07-03 18:11:35 +00:00
ids: ids of files
2011-06-15 13:05:06 +00:00
itemId: new itemId
}
return {
status: {'code': int, 'text': string},
data: {
}
}
'''
data = json.loads(request.POST['data'])
if Item.objects.filter(itemId=data['itemId']).count() == 1:
i = Item.objects.get(itemId=data['itemId'])
2011-07-03 18:30:47 +00:00
else:
if len(data['itemId']) != 7:
del data['itemId']
2011-08-17 18:37:24 +00:00
if 'director' in data and isinstance(data['director'], basestring):
if data['director'] == '':
data['director'] = []
else:
data['director'] = data['director'].split(', ')
2011-07-05 14:28:22 +00:00
i = get_item(data)
2011-07-03 18:30:47 +00:00
else:
2011-07-05 14:28:22 +00:00
i = get_item({'imdbId': data['itemId']})
2011-08-16 17:03:14 +00:00
changed = [i.itemId]
2011-06-15 13:05:06 +00:00
for f in models.File.objects.filter(oshash__in=data['ids']):
2011-07-05 14:28:22 +00:00
if f.item.id != i.itemId and f.editable(request.user):
2011-07-03 18:30:47 +00:00
if f.item.itemId not in changed:
changed.append(f.item.itemId)
2011-07-05 14:28:22 +00:00
f.item = i
2011-06-15 13:05:06 +00:00
f.save()
2011-07-03 18:30:47 +00:00
for itemId in changed:
c = Item.objects.get(itemId=itemId)
2011-08-16 17:03:14 +00:00
if c.files.count() == 0:
c.delete()
else:
c.rendered = False
c.save()
2011-08-19 16:54:42 +00:00
item.tasks.update_timeline.delay(itemId)
2011-06-15 13:05:06 +00:00
response = json_response(text='updated')
2011-07-05 14:28:22 +00:00
response['data']['itemId'] = i.itemId
2011-06-15 13:05:06 +00:00
return render_to_json_response(response)
actions.register(moveFiles, cache=False)
2011-01-01 11:44:42 +00:00
2011-10-23 16:19:47 +00:00
@login_required_json
def editFiles(request):
'''
change file / item link
param data {
ids: ids of files
part:
language:
ignore: boolean
}
return {
status: {'code': int, 'text': string},
data: {
}
}
'''
data = json.loads(request.POST['data'])
files = models.File.objects.filter(oshash__in=data['ids'])
response = json_response()
#FIXME: only editable files!
if True:
if 'ignore' in data:
models.Instance.objects.filter(file__in=files).update(ignore=data['ignore'])
files.update(auto=True)
#FIXME: is this to slow to run sync?
for i in Item.objects.filter(files__in=files).distinct():
i.update_selected()
i.update_wanted()
response = json_response(status=200, text='updated')
updates = {}
for key in ('part', 'language'):
if key in data:
updates[key] = data[key]
if updates:
files.update(**updates)
response = json_response(status=200, text='updated')
else:
response = json_response(status=403, text='permissino denied')
return render_to_json_response(response)
actions.register(editFiles, cache=False)
2011-06-27 13:39:35 +00:00
@login_required_json
def editFile(request):
'''
change file / item link
2010-12-24 10:31:44 +00:00
param data {
2011-06-27 13:39:35 +00:00
id: hash of file
part:
2011-10-18 20:06:01 +00:00
language:
ignore: boolean
2010-12-24 10:31:44 +00:00
}
return {
status: {'code': int, 'text': string},
data: {
}
}
'''
data = json.loads(request.POST['data'])
2011-06-27 13:39:35 +00:00
f = get_object_or_404_json(models.File, oshash=data['id'])
response = json_response()
2011-10-18 20:06:01 +00:00
if f.editable(request.user):
update = False
#FIXME: should all instances be ignored?
if 'ignore' in data:
2011-10-23 11:57:52 +00:00
f.auto = True
f.instances.update(ignore=data['ignore'])
f.save()
2011-10-18 20:06:01 +00:00
#FIXME: is this to slow to run sync?
f.item.update_selected()
2011-10-23 11:57:52 +00:00
f.item.update_wanted()
2011-10-18 20:06:01 +00:00
for key in ('part', 'language'):
if key in data:
2011-06-27 13:39:35 +00:00
setattr(f, key, data[key])
2011-10-18 20:06:01 +00:00
f.auto = False
update = True
if update:
f.save()
response = json_response(status=200, text='updated')
else:
response = json_response(status=403, text='permissino denied')
2010-08-07 14:31:20 +00:00
return render_to_json_response(response)
2011-01-13 08:33:14 +00:00
actions.register(editFile, cache=False)
2010-08-07 14:31:20 +00:00
2011-01-01 11:44:42 +00:00
2010-09-14 14:10:37 +00:00
def lookup_file(request, oshash):
f = get_object_or_404(models.File, oshash=oshash)
2010-09-23 16:01:48 +00:00
return redirect(f.item.get_absolute_url())
2010-09-14 14:10:37 +00:00
2011-01-19 12:06:03 +00:00
def _order_query(qs, sort, prefix=''):
order_by = []
if len(sort) == 1:
sort.append({'operator': '+', 'key': 'path'})
2011-01-19 12:06:03 +00:00
sort.append({'operator': '-', 'key': 'created'})
2011-01-19 12:06:03 +00:00
for e in sort:
operator = e['operator']
if operator != '-':
operator = ''
2011-02-01 13:19:34 +00:00
key = {
'id': 'item__itemId',
'users': 'instances__volume__user__username',
'resolution': 'width',
'path': 'sort_path'
2011-02-01 13:19:34 +00:00
}.get(e['key'], e['key'])
2011-01-19 12:06:03 +00:00
#if operator=='-' and '%s_desc'%key in models.ItemSort.descending_fields:
# key = '%s_desc' % key
order = '%s%s%s' % (operator, prefix, key)
order_by.append(order)
if order_by:
qs = qs.order_by(*order_by)
return qs
def findFiles(request):
2011-01-01 11:44:42 +00:00
'''
2011-01-19 12:06:03 +00:00
param data {
'query': query,
'sort': array,
'range': array
}
query: query object, more on query syntax at
https://wiki.0x2620.org/wiki/pandora/QuerySyntax
sort: array of key, operator dics
[
{
key: "year",
operator: "-"
},
{
key: "director",
operator: ""
}
]
range: result range, array [from, to]
keys: array of keys to return
group: group elements by, country, genre, director...
with keys, items is list of dicts with requested properties:
return {'status': {'code': int, 'text': string},
'data': {items: array}}
Groups
param data {
'query': query,
'key': string,
'group': string,
'range': array
}
query: query object, more on query syntax at
https://wiki.0x2620.org/wiki/pandora/QuerySyntax
range: result range, array [from, to]
keys: array of keys to return
group: group elements by, country, genre, director...
possible values for keys: path, items
2011-01-19 12:06:03 +00:00
with keys
items contains list of {'path': string, 'items': int}:
2011-01-19 12:06:03 +00:00
return {'status': {'code': int, 'text': string},
'data': {items: array}}
without keys: return number of items in given query
return {'status': {'code': int, 'text': string},
'data': {items: int}}
Positions
param data {
'query': query,
2011-06-01 11:03:43 +00:00
'positions': []
2011-01-19 12:06:03 +00:00
}
query: query object, more on query syntax at
https://wiki.0x2620.org/wiki/pandora/QuerySyntax
2011-06-01 11:03:43 +00:00
positions: ids of items for which positions are required
2011-01-19 12:06:03 +00:00
return {
status: {...},
data: {
positions: {
id: position
}
}
}
2011-01-01 11:44:42 +00:00
'''
2011-01-19 12:06:03 +00:00
data = json.loads(request.POST['data'])
2011-02-22 15:26:06 +00:00
query = parse_query(data, request.user)
2011-01-19 12:06:03 +00:00
response = json_response({})
if 'group' in query:
if 'sort' in query:
if len(query['sort']) == 1 and query['sort'][0]['key'] == 'items':
if query['group'] == "year":
order_by = query['sort'][0]['operator'] == '-' and 'items' or '-items'
else:
order_by = query['sort'][0]['operator'] == '-' and '-items' or 'items'
if query['group'] != "keyword":
order_by = (order_by, 'value_sort')
else:
order_by = (order_by,)
else:
order_by = query['sort'][0]['operator'] == '-' and '-value_sort' or 'value_sort'
order_by = (order_by, 'items')
else:
order_by = ('-value_sort', 'items')
response['data']['items'] = []
items = 'items'
item_qs = query['qs']
qs = models.Facet.objects.filter(key=query['group']).filter(item__id__in=item_qs)
qs = qs.values('value').annotate(items=Count('id')).order_by(*order_by)
2011-06-01 11:03:43 +00:00
if 'positions' in query:
2011-01-19 12:06:03 +00:00
#FIXME: this does not scale for larger results
response['data']['positions'] = {}
ids = [j['value'] for j in qs]
2011-06-01 11:03:43 +00:00
response['data']['positions'] = utils.get_positions(ids, query['positions'])
2011-01-19 12:06:03 +00:00
elif 'range' in data:
qs = qs[query['range'][0]:query['range'][1]]
response['data']['items'] = [{'path': i['value'], 'items': i[items]} for i in qs]
2011-01-19 12:06:03 +00:00
else:
response['data']['items'] = qs.count()
2011-06-01 11:03:43 +00:00
elif 'positions' in query:
2011-01-19 12:06:03 +00:00
#FIXME: this does not scale for larger results
2011-06-20 17:09:53 +00:00
qs = models.File.objects.filter(item__in=query['qs'])
qs = _order_query(qs, query['sort'])
2011-01-19 12:06:03 +00:00
response['data']['positions'] = {}
2011-06-20 17:21:21 +00:00
ids = [j['oshash'] for j in qs.values('oshash')]
2011-06-01 11:03:43 +00:00
response['data']['positions'] = utils.get_positions(ids, query['positions'])
2011-01-19 12:06:03 +00:00
elif 'keys' in query:
response['data']['items'] = []
qs = models.File.objects.filter(item__in=query['qs'])
2011-02-01 13:19:34 +00:00
qs = _order_query(qs, query['sort'])
qs = qs.select_related()
2011-01-19 12:06:03 +00:00
keys = query['keys']
qs = qs[query['range'][0]:query['range'][1]]
response['data']['items'] = [f.json(keys) for f in qs]
else: # otherwise stats
items = query['qs']
files = models.File.objects.filter(item__in=query['qs'])
2011-01-29 11:19:11 +00:00
response['data']['items'] = files.count()
2011-01-19 12:06:03 +00:00
return render_to_json_response(response)
actions.register(findFiles)
def parsePath(request): #parse path and return info
'''
param data {
path: string
}
return {
status: {'code': int, 'text': string},
data: {
imdb: string
}
}
'''
path = json.loads(request.POST['data'])['path']
response = json_response(ox.parse_movie_path(path))
return render_to_json_response(response)
actions.register(parsePath)