- register based api registration

- move review whitelist into config
This commit is contained in:
j 2010-12-22 13:15:37 +05:30
parent a6cf963b6e
commit 7ca86a952e
16 changed files with 245 additions and 177 deletions

View file

@ -24,9 +24,10 @@ from ox.django.http import HttpFileResponse
import ox import ox
import models import models
from api.actions import actions
@login_required_json @login_required_json
def api_addLayer(request): def addLayer(request):
''' '''
param data param data
{key: value} {key: value}
@ -35,9 +36,10 @@ def api_addLayer(request):
''' '''
response = {'status': {'code': 501, 'text': 'not implemented'}} response = {'status': {'code': 501, 'text': 'not implemented'}}
return render_to_json_response(response) return render_to_json_response(response)
actions.register(addLayer)
@login_required_json @login_required_json
def api_removeLayer(request): def removeLayer(request):
''' '''
param data param data
{key: value} {key: value}
@ -46,9 +48,10 @@ def api_removeLayer(request):
''' '''
response = {'status': {'code': 501, 'text': 'not implemented'}} response = {'status': {'code': 501, 'text': 'not implemented'}}
return render_to_json_response(response) return render_to_json_response(response)
actions.register(removeLayer)
@login_required_json @login_required_json
def api_editLayer(request): def editLayer(request):
''' '''
param data param data
{key: value} {key: value}
@ -66,4 +69,5 @@ def api_editLayer(request):
response = json_response(status=501, text='not implemented') response = json_response(status=501, text='not implemented')
return render_to_json_response(response) return render_to_json_response(response)
actions.register(editLayer)

70
pandora/api/actions.py Normal file
View file

@ -0,0 +1,70 @@
import sys
from ox.django.shortcuts import render_to_json_response, get_object_or_404_json, json_response
def trim(docstring):
if not docstring:
return ''
# Convert tabs to spaces (following the normal Python rules)
# and split into a list of lines:
lines = docstring.expandtabs().splitlines()
# Determine minimum indentation (first line doesn't count):
indent = sys.maxint
for line in lines[1:]:
stripped = line.lstrip()
if stripped:
indent = min(indent, len(line) - len(stripped))
# Remove indentation (first line is special):
trimmed = [lines[0].strip()]
if indent < sys.maxint:
for line in lines[1:]:
trimmed.append(line[indent:].rstrip())
# Strip off trailing and leading blank lines:
while trimmed and not trimmed[-1]:
trimmed.pop()
while trimmed and not trimmed[0]:
trimmed.pop(0)
# Return a single string:
return '\n'.join(trimmed)
class ApiActions(dict):
def __init__(self):
def api(request):
'''
returns list of all known api action
return {'status': {'code': int, 'text': string},
'data': {actions: ['api', 'hello', ...]}}
'''
actions = self.keys()
actions.sort()
return render_to_json_response(json_response({'actions': actions}))
self['api'] = api
def apidoc(request):
'''
returns array of actions with documentation
'''
actions = self.keys()
actions.sort()
docs = {}
for f in actions:
docs[f] = self.doc(f)
return render_to_json_response(json_response({'actions': docs}))
self['apidoc'] = apidoc
def doc(self, f):
return trim(self[f].__doc__)
def register(self, method, action=None):
if not action:
action = method.func_name
self[action] = method
def unregister(self, action):
if action in self:
del self[action]
actions = ApiActions()

View file

@ -26,17 +26,24 @@ import ox
import models import models
from pandora.user.models import get_user_json from pandora.user.models import get_user_json
from pandora.user.views import api_login, api_logout, api_register, api_contact, api_recover, api_preferences, api_findUser
from pandora.archive.views import api_update, api_upload, api_editFile, api_encodingProfile
from pandora.archive.models import File from pandora.archive.models import File
from pandora.archive import extract from pandora.archive import extract
from pandora.item.views import *
from pandora.itemlist.views import * from actions import actions
from pandora.place.views import *
from pandora.date.views import * #register all api actions
from django.utils.importlib import import_module
from django.utils.module_loading import module_has_submodule
for app in settings.INSTALLED_APPS:
if app != 'api':
mod = import_module(app)
try:
import_module('%s.views'%app)
except:
if module_has_submodule(mod, 'views'):
raise
def api(request): def api(request):
if request.META['REQUEST_METHOD'] == "OPTIONS": if request.META['REQUEST_METHOD'] == "OPTIONS":
@ -45,12 +52,21 @@ def api(request):
response['Access-Control-Allow-Origin'] = '*' response['Access-Control-Allow-Origin'] = '*'
return response return response
if not 'action' in request.POST: if not 'action' in request.POST:
return apidoc(request) methods = actions.keys()
api = []
for f in sorted(methods):
api.append({
'name': f,
'doc': actions.doc(f).replace('\n', '<br>\n')
})
context = RequestContext(request, {'api': api,
'sitename': settings.SITENAME,})
return render_to_response('api.html', context)
function = request.POST['action'] function = request.POST['action']
#FIXME: possible to do this in f #FIXME: possible to do this in f
#data = json.loads(request.POST['data']) #data = json.loads(request.POST['data'])
f = globals().get('api_'+function, None) f = actions.get(function, None)
if f: if f:
response = f(request) response = f(request)
else: else:
@ -59,30 +75,7 @@ def api(request):
response['Access-Control-Allow-Origin'] = '*' response['Access-Control-Allow-Origin'] = '*'
return response return response
def api_api(request): def hello(request):
'''
returns list of all known api action
return {'status': {'code': int, 'text': string},
'data': {actions: ['api', 'hello', ...]}}
'''
actions = globals().keys()
actions = map(lambda a: a[4:], filter(lambda a: a.startswith('api_'), actions))
actions.sort()
return render_to_json_response(json_response({'actions': actions}))
def api_apidoc(request):
'''
returns array of actions with documentation
'''
actions = globals().keys()
actions = map(lambda a: a[4:], filter(lambda a: a.startswith('api_'), actions))
actions.sort()
docs = {}
for f in actions:
docs[f] = get_api_doc(f)
return render_to_json_response(json_response({'actions': docs}))
def api_hello(request):
''' '''
return {'status': {'code': int, 'text': string}, return {'status': {'code': int, 'text': string},
'data': {user: object}} 'data': {user: object}}
@ -94,70 +87,13 @@ def api_hello(request):
else: else:
response['data']['user'] = {'name': 'Guest', 'group': 'guest', 'preferences': {}} response['data']['user'] = {'name': 'Guest', 'group': 'guest', 'preferences': {}}
return render_to_json_response(response) return render_to_json_response(response)
actions.register(hello)
def api_error(request): def error(request):
''' '''
trows 503 error this action is used to test api error codes, it should return a 503 error
''' '''
success = error_is_success success = error_is_success
return render_to_json_response({}) return render_to_json_response({})
actions.register(error)
def get_api_doc(f):
f = 'api_' + f
import sys
def trim(docstring):
if not docstring:
return ''
# Convert tabs to spaces (following the normal Python rules)
# and split into a list of lines:
lines = docstring.expandtabs().splitlines()
# Determine minimum indentation (first line doesn't count):
indent = sys.maxint
for line in lines[1:]:
stripped = line.lstrip()
if stripped:
indent = min(indent, len(line) - len(stripped))
# Remove indentation (first line is special):
trimmed = [lines[0].strip()]
if indent < sys.maxint:
for line in lines[1:]:
trimmed.append(line[indent:].rstrip())
# Strip off trailing and leading blank lines:
while trimmed and not trimmed[-1]:
trimmed.pop()
while trimmed and not trimmed[0]:
trimmed.pop(0)
# Return a single string:
return '\n'.join(trimmed)
return trim(globals()[f].__doc__)
def apidoc(request):
'''
this is used for online documentation at http://127.0.0.1:8000/api/
'''
functions = filter(lambda x: x.startswith('api_'), globals().keys())
api = []
for f in sorted(functions):
api.append({
'name': f[4:],
'doc': get_api_doc(f[4:]).replace('\n', '<br>\n')
})
context = RequestContext(request, {'api': api,
'sitename': settings.SITENAME,})
return render_to_response('api.html', context)
'''
ajax html snapshots
http://code.google.com/web/ajaxcrawling/docs/html-snapshot.html
'''
def html_snapshot(request):
fragment = unquote(request.GET['_escaped_fragment_'])
url = request.build_absolute_uri('/ra')
url = 'http://'+settings.URL
response = HttpResponse('sorry, server side rendering for %s!#%s not yet implemented'%(url, fragment))
return response

View file

@ -8,9 +8,10 @@ from ox.django.shortcuts import json_response, render_to_json_response, get_obje
import models import models
from api.views import html_snapshot
from item.models import siteJson from item.models import siteJson
from api.actions import actions
def intro(request): def intro(request):
context = RequestContext(request, {'settings':settings}) context = RequestContext(request, {'settings':settings})
return render_to_response('intro.html', context) return render_to_response('intro.html', context)
@ -25,14 +26,16 @@ def timeline(request):
context = RequestContext(request, {'settings':settings}) context = RequestContext(request, {'settings':settings})
return render_to_response('timeline.html', context) return render_to_response('timeline.html', context)
def api_getPage(request): def getPage(request):
data = json.loads(request.POST['data']) data = json.loads(request.POST['data'])
name = data['page'] name = data['page']
page = get_object_or_404_json(models.Archive, name=name) page = get_object_or_404_json(models.Archive, name=name)
response = json_response({'name': page.name, 'body': page.body}) response = json_response({'name': page.name, 'body': page.body})
return render_to_json_response(response) return render_to_json_response(response)
actions.register(getPage)
def site_json(request): def site_json(request):
'''
return render_to_json_response(siteJson()) return render_to_json_response(siteJson())
''' '''
siteSettings = {} siteSettings = {}
@ -40,4 +43,4 @@ def site_json(request):
siteSettings[s.key] = s.value siteSettings[s.key] = s.value
context = RequestContext(request, {'settings':settings, 'siteSettings': siteSettings}) context = RequestContext(request, {'settings':settings, 'siteSettings': siteSettings})
return render_to_response('site.json', context, mimetype="application/javascript") return render_to_response('site.json', context, mimetype="application/javascript")
'''

View file

@ -25,6 +25,7 @@ except ImportError:
from ox.django.decorators import login_required_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.shortcuts import render_to_json_response, get_object_or_404_json, json_response
from ox.django.http import HttpFileResponse from ox.django.http import HttpFileResponse
from ox.django.views import task_status
import ox import ox
import models import models
@ -32,9 +33,10 @@ import models
from item.utils import oxid, parse_path from item.utils import oxid, parse_path
from item.models import get_item from item.models import get_item
import item.tasks import item.tasks
from api.actions import actions
@login_required_json @login_required_json
def api_removeVolume(request): def removeVolume(request):
data = json.loads(request.POST['data']) data = json.loads(request.POST['data'])
user = request.user user = request.user
try: try:
@ -45,9 +47,10 @@ def api_removeVolume(request):
except models.Volume.DoesNotExist: except models.Volume.DoesNotExist:
response = json_response(status=404, text='volume not found') response = json_response(status=404, text='volume not found')
return render_to_json_response(response) return render_to_json_response(response)
actions.register(removeVolume)
@login_required_json @login_required_json
def api_update(request): def update(request):
''' '''
2 calls possible: 2 calls possible:
volume/files volume/files
@ -157,15 +160,16 @@ def api_update(request):
response['data']['file'] = [f.file.oshash for f in files.filter(file__is_subtitle=True)] response['data']['file'] = [f.file.oshash for f in files.filter(file__is_subtitle=True)]
return render_to_json_response(response) return render_to_json_response(response)
actions.register(update)
@login_required_json @login_required_json
def api_encodingProfile(request): def encodingProfile(request):
response = json_response({'profile': settings.VIDEO_PROFILE}) response = json_response({'profile': settings.VIDEO_PROFILE})
return render_to_json_response(response) return render_to_json_response(response)
actions.register(encodingProfile)
@login_required_json @login_required_json
def api_upload(request): def upload(request):
''' '''
oshash: string oshash: string
frame: [] //multipart frames frame: [] //multipart frames
@ -197,6 +201,7 @@ def api_upload(request):
else: else:
response = json_response(status=403, text='permissino denied') response = json_response(status=403, text='permissino denied')
return render_to_json_response(response) return render_to_json_response(response)
actions.register(upload)
class VideoChunkForm(forms.Form): class VideoChunkForm(forms.Form):
chunk = forms.FileField() chunk = forms.FileField()
@ -229,7 +234,9 @@ def firefogg_upload(request):
f.save() f.save()
#FIXME: this fails badly if rabbitmq goes down #FIXME: this fails badly if rabbitmq goes down
try: try:
item.tasks.update_streams.delay(f.item.itemId) task_id = 'update_streams_' + f.item.itemId
t = item.tasks.update_streams.delay(f.item.itemId, task_id=task_id)
data['resultUrl'] = t.task_id
except: except:
pass pass
response['result'] = 1 response['result'] = 1
@ -254,12 +261,23 @@ def firefogg_upload(request):
return render_to_json_response(response) return render_to_json_response(response)
@login_required_json @login_required_json
def api_editFile(request): #FIXME: should this be file.files. or part of update 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)
actions.register(taskStatus)
@login_required_json
def editFile(request): #FIXME: should this be file.files. or part of update
''' '''
change file / imdb link change file / imdb link
''' '''
response = json_response(status=501, text='not implemented') response = json_response(status=501, text='not implemented')
return render_to_json_response(response) return render_to_json_response(response)
actions.register(editFile)
def lookup_file(request, oshash): def lookup_file(request, oshash):
@ -268,7 +286,7 @@ def lookup_file(request, oshash):
""" """
def api_fileInfo(request): def fileInfo(request):
''' '''
param data param data
oshash string oshash string
@ -282,8 +300,9 @@ def api_fileInfo(request):
f = models.ItemFile.objects.get(oshash=oshash) f = models.ItemFile.objects.get(oshash=oshash)
response = {'data': f.json()} response = {'data': f.json()}
return render_to_json_response(response) return render_to_json_response(response)
actions.register(fileInfo)
def api_subtitles(request): def subtitles(request):
''' '''
param data param data
oshash string oshash string
@ -317,4 +336,5 @@ def api_subtitles(request):
l = models.Subtitles.objects.filter(item_file__oshash=oshash).values('language') l = models.Subtitles.objects.filter(item_file__oshash=oshash).values('language')
response['data']['languages'] = [f['language'] for f in l] response['data']['languages'] = [f['language'] for f in l]
return render_to_json_response(response) return render_to_json_response(response)
actions.register(subtitles)
""" """

View file

@ -25,9 +25,10 @@ from ox.django.http import HttpFileResponse
import ox import ox
import models import models
from api.actions import actions
@login_required_json @login_required_json
def api_addDate(request): def addDate(request):
data = json.loads(request.POST['data']) data = json.loads(request.POST['data'])
if models.Date.filter(name=data['name']).count() == 0: if models.Date.filter(name=data['name']).count() == 0:
place = models.Date(name = data['name']) place = models.Date(name = data['name'])
@ -36,9 +37,10 @@ def api_addDate(request):
else: else:
response = json_response(status=403, text='place name exists') response = json_response(status=403, text='place name exists')
return render_to_json_response(response) return render_to_json_response(response)
actions.register(addDate)
@login_required_json @login_required_json
def api_editDate(request): def editDate(request):
''' '''
param data param data
{ {
@ -65,13 +67,15 @@ def api_editDate(request):
else: else:
response = json_response(status=403, text='permission denied') response = json_response(status=403, text='permission denied')
return render_to_json_response(response) return render_to_json_response(response)
actions.register(editDate)
@login_required_json @login_required_json
def api_removeDate(request): def removeDate(request):
response = json_response(status=501, text='not implemented') response = json_response(status=501, text='not implemented')
return render_to_json_response(response) return render_to_json_response(response)
actions.register(removeDate)
def api_findDate(request): def findDate(request):
''' '''
param data param data
{'query': query, 'sort': array, 'range': array} {'query': query, 'sort': array, 'range': array}
@ -110,4 +114,5 @@ Positions
for p in Dates.objects.find(data['query']): for p in Dates.objects.find(data['query']):
response['data']['dates'].append(p.json()) response['data']['dates'].append(p.json())
return render_to_json_response(response) return render_to_json_response(response)
actions.register(findDate)

View file

@ -76,7 +76,6 @@ def parseCondition(condition):
q = Q(**{k:v}) q = Q(**{k:v})
return q return q
else: #number or date else: #number or date
#FIXME: this part needs to be moved to use key/value find db
def parseDate(d): def parseDate(d):
while len(d) < 3: while len(d) < 3:
d.append(1) d.append(1)

View file

@ -267,12 +267,11 @@ class Item(models.Model):
def reviews(self): def reviews(self):
reviews = self.get('reviews', []) reviews = self.get('reviews', [])
whitelist = [w for w in ReviewWhitelist.objects.all()]
_reviews = {} _reviews = {}
for r in reviews: for r in reviews:
for w in whitelist: for url in settings.REVIEW_WHITELIST:
if w.url in r[0]: if url in r[0]:
_reviews[w.title] = r[0] _reviews[settings.REVIEW_WHITELIST[url]] = r[0]
return _reviews return _reviews
def update_imdb(self): def update_imdb(self):
@ -338,6 +337,7 @@ class Item(models.Model):
''' '''
JSON cache related functions JSON cache related functions
''' '''
#FIXME: this should not be used
_public_fields = { _public_fields = {
'itemId': 'id', 'itemId': 'id',
'title': 'title', 'title': 'title',
@ -767,6 +767,7 @@ class ItemFind(models.Model):
key = models.CharField(max_length=200, db_index=True) key = models.CharField(max_length=200, db_index=True)
value = models.TextField(blank=True) value = models.TextField(blank=True)
#FIXME: make sort based on site.json
class ItemSort(models.Model): class ItemSort(models.Model):
""" """
used to sort items, all sort values are in here used to sort items, all sort values are in here
@ -849,22 +850,6 @@ class Facet(models.Model):
self.value_sort = self.value self.value_sort = self.value
super(Facet, self).save(*args, **kwargs) super(Facet, self).save(*args, **kwargs)
class ReviewWhitelist(models.Model):
name = models.CharField(max_length=255, unique=True)
url = models.CharField(max_length=255, unique=True)
class Collection(models.Model):
created = models.DateTimeField(auto_now_add=True)
modified = models.DateTimeField(auto_now=True)
users = models.ManyToManyField(User, related_name='collections')
name = models.CharField(blank=True, max_length=2048)
subdomain = models.CharField(unique=True, max_length=2048)
items = models.ForeignKey(Item)
def editable(self, user):
return self.users.filter(id=user.id).count() > 0
class Stream(models.Model): class Stream(models.Model):
class Meta: class Meta:
unique_together = ("item", "profile") unique_together = ("item", "profile")
@ -876,8 +861,8 @@ class Stream(models.Model):
available = models.BooleanField(default=False) available = models.BooleanField(default=False)
info = fields.DictField(default={}) info = fields.DictField(default={})
#def __unicode__(self): def __unicode__(self):
# return self.video return u"%s/%s" % (self.item, self.profile)
def path(self): def path(self):
return self.item.path(self.profile) return self.item.path(self.profile)
@ -922,9 +907,6 @@ class Stream(models.Model):
self.available=True self.available=True
self.save() self.save()
def __unicode__(self):
return u"%s (%s)" % (self.profile, self.item)
def save(self, *args, **kwargs): def save(self, *args, **kwargs):
if self.video and not self.info: if self.video and not self.info:
self.info = ox.avinfo(self.video.path) self.info = ox.avinfo(self.video.path)

View file

@ -27,7 +27,7 @@ def find_item(fileId):
f = models.File.objects.get(pk=fileId) f = models.File.objects.get(pk=fileId)
f.find_item() f.find_item()
@task(ignore_resulsts=True, queue="encoding") @task(queue="encoding")
def update_streams(itemId): def update_streams(itemId):
''' '''
create stream, extract timeline and create derivatives create stream, extract timeline and create derivatives
@ -35,5 +35,4 @@ def update_streams(itemId):
item = models.Item.objects.get(itemId=itemId) item = models.Item.objects.get(itemId=itemId)
if item.files.filter(is_main=True, is_video=True, available=False).count() == 0: if item.files.filter(is_main=True, is_video=True, available=False).count() == 0:
item.update_streams() item.update_streams()
return True

View file

@ -33,6 +33,7 @@ from user.models import get_user_json
from archive.models import File from archive.models import File
from archive import extract from archive import extract
from api.actions import actions
def _order_query(qs, sort, prefix='sort__'): def _order_query(qs, sort, prefix='sort__'):
order_by = [] order_by = []
@ -74,7 +75,7 @@ def _get_positions(ids, get_ids):
pass pass
return positions return positions
def api_find(request): def find(request):
''' '''
param data param data
{'query': query, 'sort': array, 'range': array} {'query': query, 'sort': array, 'range': array}
@ -209,7 +210,10 @@ Positions
response['data']['size'] = r['size__sum'] response['data']['size'] = r['size__sum']
return render_to_json_response(response) return render_to_json_response(response)
def api_getItem(request): actions.register(find)
def getItem(request):
''' '''
param data param data
string id string id
@ -225,9 +229,10 @@ def api_getItem(request):
info['layers'] = item.get_layers() info['layers'] = item.get_layers()
response['data'] = {'item': info} response['data'] = {'item': info}
return render_to_json_response(response) return render_to_json_response(response)
actions.register(getItem)
@login_required_json @login_required_json
def api_editItem(request): def editItem(request):
''' '''
param data param data
{id: string, key: value,..} {id: string, key: value,..}
@ -242,9 +247,10 @@ def api_editItem(request):
else: else:
response = json_response(status=403, text='permissino denied') response = json_response(status=403, text='permissino denied')
return render_to_json_response(response) return render_to_json_response(response)
actions.register(editItem)
@login_required_json @login_required_json
def api_removeItem(request): def removeItem(request):
''' '''
param data param data
string id string id
@ -259,11 +265,12 @@ def api_removeItem(request):
else: else:
response = json_response(status=403, text='permission denied') response = json_response(status=403, text='permission denied')
return render_to_json_response(response) return render_to_json_response(response)
actions.register(removeItem)
''' '''
Poster API Poster API
''' '''
def api_parse(request): #parse path and return info def parse(request): #parse path and return info
''' '''
param data param data
{path: string} {path: string}
@ -273,9 +280,10 @@ def api_parse(request): #parse path and return info
path = json.loads(request.POST['data'])['path'] path = json.loads(request.POST['data'])['path']
response = json_response(utils.parse_path(path)) response = json_response(utils.parse_path(path))
return render_to_json_response(response) return render_to_json_response(response)
actions.register(parse)
def api_setPosterFrame(request): #parse path and return info def setPosterFrame(request): #parse path and return info
''' '''
param data param data
{id: itemId, position: float} {id: itemId, position: float}
@ -292,8 +300,9 @@ def api_setPosterFrame(request): #parse path and return info
else: else:
response = json_response(status=403, text='permissino denied') response = json_response(status=403, text='permissino denied')
return render_to_json_response(response) return render_to_json_response(response)
actions.register(setPosterFrame)
def api_setPoster(request): #parse path and return info def setPoster(request): #parse path and return info
''' '''
param data param data
{id: itemId, url: string} {id: itemId, url: string}
@ -317,8 +326,9 @@ def api_setPoster(request): #parse path and return info
else: else:
response = json_response(status=403, text='permission denied') response = json_response(status=403, text='permission denied')
return render_to_json_response(response) return render_to_json_response(response)
actions.register(setPoster)
def api_getImdbId(request): def getImdbId(request):
''' '''
param data param data
{title: string, director: string, year: string} {title: string, director: string, year: string}
@ -331,6 +341,7 @@ def api_getImdbId(request):
else: else:
response = json_response(status=404, text='not found') response = json_response(status=404, text='not found')
return render_to_json_response(response) return render_to_json_response(response)
actions.register(getImdbId)
''' '''
media delivery media delivery

View file

@ -23,12 +23,13 @@ from ox.django.shortcuts import render_to_json_response, get_object_or_404_json,
from ox.django.http import HttpFileResponse from ox.django.http import HttpFileResponse
import ox import ox
from api.actions import actions
''' '''
List API List API
''' '''
@login_required_json @login_required_json
def api_addListItem(request): def addListItem(request):
''' '''
param data param data
{list: listId, {list: listId,
@ -53,9 +54,10 @@ def api_addListItem(request):
else: else:
response = json_response(status=501, text='not implemented') response = json_response(status=501, text='not implemented')
return render_to_json_response(response) return render_to_json_response(response)
actions.register(addListItem)
@login_required_json @login_required_json
def api_removeListItem(request): def removeListItem(request):
''' '''
param data param data
{list: listId, {list: listId,
@ -80,9 +82,10 @@ def api_removeListItem(request):
else: else:
response = json_response(status=501, text='not implemented') response = json_response(status=501, text='not implemented')
return render_to_json_response(response) return render_to_json_response(response)
actions.register(removeListItem)
@login_required_json @login_required_json
def api_addList(request): def addList(request):
''' '''
param data param data
{name: value} {name: value}
@ -97,9 +100,10 @@ def api_addList(request):
else: else:
response = json_response(status=403, text='list name exists') response = json_response(status=403, text='list name exists')
return render_to_json_response(response) return render_to_json_response(response)
actions.register(addList)
@login_required_json @login_required_json
def api_editList(request): def editList(request):
''' '''
param data param data
{key: value} {key: value}
@ -116,8 +120,9 @@ def api_editList(request):
else: else:
response = json_response(status=403, text='not allowed') response = json_response(status=403, text='not allowed')
return render_to_json_response(response) return render_to_json_response(response)
actions.register(editList)
def api_removeList(request): def removeList(request):
''' '''
param data param data
{key: value} {key: value}
@ -131,4 +136,5 @@ def api_removeList(request):
else: else:
response = json_response(status=403, text='not allowed') response = json_response(status=403, text='not allowed')
return render_to_json_response(response) return render_to_json_response(response)
actions.register(removeList)

View file

@ -25,12 +25,13 @@ from ox.django.http import HttpFileResponse
import ox import ox
import models import models
from api.actions import actions
''' '''
fixme, require admin fixme, require admin
''' '''
@login_required_json @login_required_json
def api_addPlace(request): def addPlace(request):
''' '''
param data param data
{ {
@ -53,9 +54,10 @@ def api_addPlace(request):
else: else:
response = json_response(status=403, text='place name exists') response = json_response(status=403, text='place name exists')
return render_to_json_response(response) return render_to_json_response(response)
actions.register(addPlace)
@login_required_json @login_required_json
def api_editPlace(request): def editPlace(request):
''' '''
param data param data
{ {
@ -82,13 +84,15 @@ def api_editPlace(request):
else: else:
response = json_response(status=403, text='permission denied') response = json_response(status=403, text='permission denied')
return render_to_json_response(response) return render_to_json_response(response)
actions.register(editPlace)
@login_required_json @login_required_json
def api_removePlace(request): def removePlace(request):
response = json_response(status=501, text='not implemented') response = json_response(status=501, text='not implemented')
return render_to_json_response(response) return render_to_json_response(response)
actions.register(removePlace)
def api_findPlace(request): def findPlace(request):
''' '''
param data param data
{'query': query, 'sort': array, 'range': array, 'area': array} {'query': query, 'sort': array, 'range': array, 'area': array}
@ -128,4 +132,5 @@ Positions
for p in Places.objects.find(data['query']): for p in Places.objects.find(data['query']):
response['data']['places'].append(p.json()) response['data']['places'].append(p.json())
return render_to_json_response(response) return render_to_json_response(response)
actions.register(findPlace)

View file

@ -45,6 +45,7 @@ BROKER_PORT = 5672
BROKER_USER = "pandora" BROKER_USER = "pandora"
BROKER_PASSWORD = "box" BROKER_PASSWORD = "box"
BROKER_VHOST = "/pandora" BROKER_VHOST = "/pandora"
SEND_CELERY_ERROR_EMAILS=False
# Local time zone for this installation. Choices can be found here: # Local time zone for this installation. Choices can be found here:
@ -120,7 +121,6 @@ INSTALLED_APPS = (
'annotaion', 'annotaion',
'app', 'app',
'api',
'archive', 'archive',
'date', 'date',
'item', 'item',
@ -130,6 +130,7 @@ INSTALLED_APPS = (
'text', 'text',
'torrent', 'torrent',
'user', 'user',
'api',
) )
AUTH_PROFILE_MODULE = 'user.UserProfile' AUTH_PROFILE_MODULE = 'user.UserProfile'
@ -169,6 +170,16 @@ POSTER_PRECEDENCE = (
'other' 'other'
) )
REVIEW_WHITELIST = {
u'filmcritic.com': u'Filmcritic',
u'metacritic.com': u'Metacritic',
u'nytimes.com': u'New York Times',
u'rottentomatoes.com': u'Rotten Tomatoes',
u'salon.com': u'Salon.com',
u'sensesofcinema.com': u'Senses of Cinema',
u'villagevoice.com': u'Village Voice'
}
#0xdb.org #0xdb.org
#POSTER_SERVICES=['http://data.0xdb.org/poster/'] #POSTER_SERVICES=['http://data.0xdb.org/poster/']

View file

@ -17,9 +17,9 @@ from ox.django.http import HttpFileResponse
import ox import ox
import models import models
from api.actions import actions
def getNews(request):
def api_getNews(request):
''' '''
param data param data
string id string id
@ -31,14 +31,16 @@ def api_getNews(request):
item = get_object_or_404_json(models.News, pk=itemId) item = get_object_or_404_json(models.News, pk=itemId)
response['data']['page'] = item.html() response['data']['page'] = item.html()
return render_to_json_response(response) return render_to_json_response(response)
actions.register(getNews)
def api_findNews(request): def findNews(request):
''' '''
''' '''
response = json_response({}) response = json_response({})
return render_to_json_response(response) return render_to_json_response(response)
actions.register(findNews)
def api_getText(request): def getText(request):
''' '''
param data param data
string id string id
@ -50,10 +52,12 @@ def api_getText(request):
item = get_object_or_404_json(models.Text, pk=itemId) item = get_object_or_404_json(models.Text, pk=itemId)
response['data']['page'] = item.html() response['data']['page'] = item.html()
return render_to_json_response(response) return render_to_json_response(response)
actions.register(getText)
def api_findText(request): def findText(request):
''' '''
''' '''
response = json_response({}) response = json_response({})
return render_to_json_response(response) return render_to_json_response(response)
actions.register(findText)

View file

@ -5,10 +5,10 @@ from django.conf.urls.defaults import *
urlpatterns = patterns("user.views", urlpatterns = patterns("user.views",
(r'^preferences', 'api_preferences'), (r'^preferences', 'preferences'),
(r'^login', 'api_login'), (r'^login', 'login'),
(r'^logout', 'api_logout'), (r'^logout', 'logout'),
(r'^register', 'api_register'), (r'^register', 'register'),
(r'^recover', 'api_recover'), (r'^recover', 'recover'),
) )

View file

@ -17,6 +17,8 @@ from ox.django.decorators import login_required_json
import models import models
from api.actions import actions
def json_errors(form): def json_errors(form):
return {'status': {'code': 402, 'text': 'form error', 'data': form.errors}} return {'status': {'code': 402, 'text': 'form error', 'data': form.errors}}
@ -24,7 +26,7 @@ class LoginForm(forms.Form):
username = forms.TextInput() username = forms.TextInput()
password = forms.TextInput() password = forms.TextInput()
def api_login(request): def login(request):
''' '''
param data param data
{'username': username, 'password': password} {'username': username, 'password': password}
@ -53,8 +55,9 @@ def api_login(request):
response = json_response(status=400, text='invalid data') response = json_response(status=400, text='invalid data')
return render_to_json_response(response) return render_to_json_response(response)
actions.register(login)
def api_logout(request): def logout(request):
''' '''
param data param data
{} {}
@ -65,13 +68,14 @@ def api_logout(request):
if request.user.is_authenticated(): if request.user.is_authenticated():
logout(request) logout(request)
return render_to_json_response(response) return render_to_json_response(response)
actions.register(logout)
class RegisterForm(forms.Form): class RegisterForm(forms.Form):
username = forms.TextInput() username = forms.TextInput()
password = forms.TextInput() password = forms.TextInput()
email = forms.TextInput() email = forms.TextInput()
def api_register(request): def register(request):
''' '''
param data param data
{'username': username, 'password': password, 'email': email} {'username': username, 'password': password, 'email': email}
@ -86,8 +90,12 @@ def api_register(request):
elif models.User.objects.filter(email=form.data['email']).count() > 0: elif models.User.objects.filter(email=form.data['email']).count() > 0:
response = json_response(status=400, text='username or email exists') response = json_response(status=400, text='username or email exists')
else: else:
first_user = models.User.objects.count() == 0
user = models.User(username=form.data['username'], email=form.data['email']) user = models.User(username=form.data['username'], email=form.data['email'])
user.set_password(form.data['password']) user.set_password(form.data['password'])
#make first user admin
user.is_superuser = first_user
user.is_staff = first_user
user.save() user.save()
user = authenticate(username=form.data['username'], user = authenticate(username=form.data['username'],
password=form.data['password']) password=form.data['password'])
@ -96,6 +104,7 @@ def api_register(request):
else: else:
response = json_response(status=400, text='username exists') response = json_response(status=400, text='username exists')
return render_to_json_response(response) return render_to_json_response(response)
actions.register(register)
class RecoverForm(forms.Form): class RecoverForm(forms.Form):
username_or_email = forms.TextInput() username_or_email = forms.TextInput()
@ -139,8 +148,9 @@ def api_recover(request):
else: else:
response = json_response(status=400, text='invalid data') response = json_response(status=400, text='invalid data')
return render_to_json_response(response) return render_to_json_response(response)
actions.register(api_recover, 'recover')
def api_findUser(request): def findUser(request):
''' '''
param data param data
{key: "username", value: "foo", operator: "="} {key: "username", value: "foo", operator: "="}
@ -157,6 +167,7 @@ def api_findUser(request):
response = json_response(status=200, text='ok') response = json_response(status=200, text='ok')
response['data']['users'] = [u.username for u in User.objects.filter(username__iexact=data['value'])] response['data']['users'] = [u.username for u in User.objects.filter(username__iexact=data['value'])]
return render_to_json_response(response) return render_to_json_response(response)
actions.register(findUser)
def recover(request, key): def recover(request, key):
qs = models.UserProfile.objects.filter(recover_key=key) qs = models.UserProfile.objects.filter(recover_key=key)
@ -179,7 +190,7 @@ class ContactForm(forms.Form):
subject = forms.TextInput() subject = forms.TextInput()
message = forms.TextInput() message = forms.TextInput()
def api_contact(request): def contact(request):
''' '''
param data param data
{'email': string, 'message': string} {'email': string, 'message': string}
@ -206,10 +217,10 @@ def api_contact(request):
else: else:
response = json_response(status=400, text='invalid data') response = json_response(status=400, text='invalid data')
return render_to_json_response(response) return render_to_json_response(response)
actions.register(contact)
@login_required_json @login_required_json
def api_preferences(request): def preferences(request):
''' '''
param data param data
string string
@ -245,3 +256,5 @@ def api_preferences(request):
for key in data: for key in data:
models.set_preference(request.user, key, data[key]) models.set_preference(request.user, key, data[key])
return render_to_json_response(response) return render_to_json_response(response)
actions.register(preferences)