From 7ca86a952e02feccb6421158963fecf1bb8cc5ab Mon Sep 17 00:00:00 2001 From: j <0x006A@0x2620.org> Date: Wed, 22 Dec 2010 13:15:37 +0530 Subject: [PATCH] - register based api registration - move review whitelist into config --- pandora/annotaion/views.py | 10 ++- pandora/api/actions.py | 70 +++++++++++++++++++++ pandora/api/views.py | 124 +++++++++---------------------------- pandora/app/views.py | 9 ++- pandora/archive/views.py | 38 +++++++++--- pandora/date/views.py | 13 ++-- pandora/item/managers.py | 1 - pandora/item/models.py | 32 +++------- pandora/item/tasks.py | 5 +- pandora/item/views.py | 27 +++++--- pandora/itemlist/views.py | 16 +++-- pandora/place/views.py | 13 ++-- pandora/settings.py | 13 +++- pandora/text/views.py | 14 +++-- pandora/user/urls.py | 10 +-- pandora/user/views.py | 27 +++++--- 16 files changed, 245 insertions(+), 177 deletions(-) create mode 100644 pandora/api/actions.py diff --git a/pandora/annotaion/views.py b/pandora/annotaion/views.py index 4cc290e7..58c6f124 100644 --- a/pandora/annotaion/views.py +++ b/pandora/annotaion/views.py @@ -24,9 +24,10 @@ from ox.django.http import HttpFileResponse import ox import models +from api.actions import actions @login_required_json -def api_addLayer(request): +def addLayer(request): ''' param data {key: value} @@ -35,9 +36,10 @@ def api_addLayer(request): ''' response = {'status': {'code': 501, 'text': 'not implemented'}} return render_to_json_response(response) +actions.register(addLayer) @login_required_json -def api_removeLayer(request): +def removeLayer(request): ''' param data {key: value} @@ -46,9 +48,10 @@ def api_removeLayer(request): ''' response = {'status': {'code': 501, 'text': 'not implemented'}} return render_to_json_response(response) +actions.register(removeLayer) @login_required_json -def api_editLayer(request): +def editLayer(request): ''' param data {key: value} @@ -66,4 +69,5 @@ def api_editLayer(request): response = json_response(status=501, text='not implemented') return render_to_json_response(response) +actions.register(editLayer) diff --git a/pandora/api/actions.py b/pandora/api/actions.py new file mode 100644 index 00000000..f570dadb --- /dev/null +++ b/pandora/api/actions.py @@ -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() diff --git a/pandora/api/views.py b/pandora/api/views.py index b352747c..49834bce 100644 --- a/pandora/api/views.py +++ b/pandora/api/views.py @@ -26,17 +26,24 @@ import ox import models 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 import extract -from pandora.item.views import * -from pandora.itemlist.views import * -from pandora.place.views import * -from pandora.date.views import * + +from actions import actions + +#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): if request.META['REQUEST_METHOD'] == "OPTIONS": @@ -45,12 +52,21 @@ def api(request): response['Access-Control-Allow-Origin'] = '*' return response 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', '
\n') + }) + context = RequestContext(request, {'api': api, + 'sitename': settings.SITENAME,}) + return render_to_response('api.html', context) function = request.POST['action'] #FIXME: possible to do this in f #data = json.loads(request.POST['data']) - f = globals().get('api_'+function, None) + f = actions.get(function, None) if f: response = f(request) else: @@ -59,30 +75,7 @@ def api(request): response['Access-Control-Allow-Origin'] = '*' return response -def api_api(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): +def hello(request): ''' return {'status': {'code': int, 'text': string}, 'data': {user: object}} @@ -94,70 +87,13 @@ def api_hello(request): else: response['data']['user'] = {'name': 'Guest', 'group': 'guest', 'preferences': {}} 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 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', '
\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 diff --git a/pandora/app/views.py b/pandora/app/views.py index 7c14357f..82965bdb 100644 --- a/pandora/app/views.py +++ b/pandora/app/views.py @@ -8,9 +8,10 @@ from ox.django.shortcuts import json_response, render_to_json_response, get_obje import models -from api.views import html_snapshot from item.models import siteJson +from api.actions import actions + def intro(request): context = RequestContext(request, {'settings':settings}) return render_to_response('intro.html', context) @@ -25,14 +26,16 @@ def timeline(request): context = RequestContext(request, {'settings':settings}) return render_to_response('timeline.html', context) -def api_getPage(request): +def getPage(request): data = json.loads(request.POST['data']) name = data['page'] page = get_object_or_404_json(models.Archive, name=name) response = json_response({'name': page.name, 'body': page.body}) return render_to_json_response(response) +actions.register(getPage) def site_json(request): + ''' return render_to_json_response(siteJson()) ''' siteSettings = {} @@ -40,4 +43,4 @@ def site_json(request): siteSettings[s.key] = s.value context = RequestContext(request, {'settings':settings, 'siteSettings': siteSettings}) return render_to_response('site.json', context, mimetype="application/javascript") - ''' + diff --git a/pandora/archive/views.py b/pandora/archive/views.py index 7a585d16..b476b6f3 100644 --- a/pandora/archive/views.py +++ b/pandora/archive/views.py @@ -25,6 +25,7 @@ except ImportError: 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.http import HttpFileResponse +from ox.django.views import task_status import ox import models @@ -32,9 +33,10 @@ import models from item.utils import oxid, parse_path from item.models import get_item import item.tasks +from api.actions import actions @login_required_json -def api_removeVolume(request): +def removeVolume(request): data = json.loads(request.POST['data']) user = request.user try: @@ -45,9 +47,10 @@ def api_removeVolume(request): except models.Volume.DoesNotExist: response = json_response(status=404, text='volume not found') return render_to_json_response(response) +actions.register(removeVolume) @login_required_json -def api_update(request): +def update(request): ''' 2 calls possible: 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)] return render_to_json_response(response) - +actions.register(update) @login_required_json -def api_encodingProfile(request): +def encodingProfile(request): response = json_response({'profile': settings.VIDEO_PROFILE}) return render_to_json_response(response) +actions.register(encodingProfile) @login_required_json -def api_upload(request): +def upload(request): ''' oshash: string frame: [] //multipart frames @@ -197,6 +201,7 @@ def api_upload(request): else: response = json_response(status=403, text='permissino denied') return render_to_json_response(response) +actions.register(upload) class VideoChunkForm(forms.Form): chunk = forms.FileField() @@ -229,7 +234,9 @@ def firefogg_upload(request): f.save() #FIXME: this fails badly if rabbitmq goes down 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: pass response['result'] = 1 @@ -254,12 +261,23 @@ def firefogg_upload(request): return render_to_json_response(response) @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 ''' response = json_response(status=501, text='not implemented') return render_to_json_response(response) +actions.register(editFile) def lookup_file(request, oshash): @@ -268,7 +286,7 @@ def lookup_file(request, oshash): """ -def api_fileInfo(request): +def fileInfo(request): ''' param data oshash string @@ -282,8 +300,9 @@ def api_fileInfo(request): f = models.ItemFile.objects.get(oshash=oshash) response = {'data': f.json()} return render_to_json_response(response) +actions.register(fileInfo) -def api_subtitles(request): +def subtitles(request): ''' param data oshash string @@ -317,4 +336,5 @@ def api_subtitles(request): l = models.Subtitles.objects.filter(item_file__oshash=oshash).values('language') response['data']['languages'] = [f['language'] for f in l] return render_to_json_response(response) +actions.register(subtitles) """ diff --git a/pandora/date/views.py b/pandora/date/views.py index 378476f5..348f56c6 100644 --- a/pandora/date/views.py +++ b/pandora/date/views.py @@ -25,9 +25,10 @@ from ox.django.http import HttpFileResponse import ox import models +from api.actions import actions @login_required_json -def api_addDate(request): +def addDate(request): data = json.loads(request.POST['data']) if models.Date.filter(name=data['name']).count() == 0: place = models.Date(name = data['name']) @@ -36,9 +37,10 @@ def api_addDate(request): else: response = json_response(status=403, text='place name exists') return render_to_json_response(response) +actions.register(addDate) @login_required_json -def api_editDate(request): +def editDate(request): ''' param data { @@ -65,13 +67,15 @@ def api_editDate(request): else: response = json_response(status=403, text='permission denied') return render_to_json_response(response) +actions.register(editDate) @login_required_json -def api_removeDate(request): +def removeDate(request): response = json_response(status=501, text='not implemented') return render_to_json_response(response) +actions.register(removeDate) -def api_findDate(request): +def findDate(request): ''' param data {'query': query, 'sort': array, 'range': array} @@ -110,4 +114,5 @@ Positions for p in Dates.objects.find(data['query']): response['data']['dates'].append(p.json()) return render_to_json_response(response) +actions.register(findDate) diff --git a/pandora/item/managers.py b/pandora/item/managers.py index 1e37296b..167bc251 100644 --- a/pandora/item/managers.py +++ b/pandora/item/managers.py @@ -76,7 +76,6 @@ def parseCondition(condition): q = Q(**{k:v}) return q else: #number or date - #FIXME: this part needs to be moved to use key/value find db def parseDate(d): while len(d) < 3: d.append(1) diff --git a/pandora/item/models.py b/pandora/item/models.py index 4f713c78..cda7c0a4 100644 --- a/pandora/item/models.py +++ b/pandora/item/models.py @@ -267,12 +267,11 @@ class Item(models.Model): def reviews(self): reviews = self.get('reviews', []) - whitelist = [w for w in ReviewWhitelist.objects.all()] _reviews = {} for r in reviews: - for w in whitelist: - if w.url in r[0]: - _reviews[w.title] = r[0] + for url in settings.REVIEW_WHITELIST: + if url in r[0]: + _reviews[settings.REVIEW_WHITELIST[url]] = r[0] return _reviews def update_imdb(self): @@ -338,6 +337,7 @@ class Item(models.Model): ''' JSON cache related functions ''' + #FIXME: this should not be used _public_fields = { 'itemId': 'id', 'title': 'title', @@ -767,6 +767,7 @@ class ItemFind(models.Model): key = models.CharField(max_length=200, db_index=True) value = models.TextField(blank=True) +#FIXME: make sort based on site.json class ItemSort(models.Model): """ used to sort items, all sort values are in here @@ -849,22 +850,6 @@ class Facet(models.Model): self.value_sort = self.value 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 Meta: unique_together = ("item", "profile") @@ -876,8 +861,8 @@ class Stream(models.Model): available = models.BooleanField(default=False) info = fields.DictField(default={}) - #def __unicode__(self): - # return self.video + def __unicode__(self): + return u"%s/%s" % (self.item, self.profile) def path(self): return self.item.path(self.profile) @@ -922,9 +907,6 @@ class Stream(models.Model): self.available=True self.save() - def __unicode__(self): - return u"%s (%s)" % (self.profile, self.item) - def save(self, *args, **kwargs): if self.video and not self.info: self.info = ox.avinfo(self.video.path) diff --git a/pandora/item/tasks.py b/pandora/item/tasks.py index 57b13d6e..4c1503e0 100644 --- a/pandora/item/tasks.py +++ b/pandora/item/tasks.py @@ -27,7 +27,7 @@ def find_item(fileId): f = models.File.objects.get(pk=fileId) f.find_item() -@task(ignore_resulsts=True, queue="encoding") +@task(queue="encoding") def update_streams(itemId): ''' create stream, extract timeline and create derivatives @@ -35,5 +35,4 @@ def update_streams(itemId): item = models.Item.objects.get(itemId=itemId) if item.files.filter(is_main=True, is_video=True, available=False).count() == 0: item.update_streams() - - + return True diff --git a/pandora/item/views.py b/pandora/item/views.py index d41dec4c..ea6134a5 100644 --- a/pandora/item/views.py +++ b/pandora/item/views.py @@ -33,6 +33,7 @@ from user.models import get_user_json from archive.models import File from archive import extract +from api.actions import actions def _order_query(qs, sort, prefix='sort__'): order_by = [] @@ -74,7 +75,7 @@ def _get_positions(ids, get_ids): pass return positions -def api_find(request): +def find(request): ''' param data {'query': query, 'sort': array, 'range': array} @@ -209,7 +210,10 @@ Positions response['data']['size'] = r['size__sum'] return render_to_json_response(response) -def api_getItem(request): +actions.register(find) + + +def getItem(request): ''' param data string id @@ -225,9 +229,10 @@ def api_getItem(request): info['layers'] = item.get_layers() response['data'] = {'item': info} return render_to_json_response(response) +actions.register(getItem) @login_required_json -def api_editItem(request): +def editItem(request): ''' param data {id: string, key: value,..} @@ -242,9 +247,10 @@ def api_editItem(request): else: response = json_response(status=403, text='permissino denied') return render_to_json_response(response) +actions.register(editItem) @login_required_json -def api_removeItem(request): +def removeItem(request): ''' param data string id @@ -259,11 +265,12 @@ def api_removeItem(request): else: response = json_response(status=403, text='permission denied') return render_to_json_response(response) +actions.register(removeItem) ''' Poster API ''' -def api_parse(request): #parse path and return info +def parse(request): #parse path and return info ''' param data {path: string} @@ -273,9 +280,10 @@ def api_parse(request): #parse path and return info path = json.loads(request.POST['data'])['path'] response = json_response(utils.parse_path(path)) 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 {id: itemId, position: float} @@ -292,8 +300,9 @@ def api_setPosterFrame(request): #parse path and return info else: response = json_response(status=403, text='permissino denied') 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 {id: itemId, url: string} @@ -317,8 +326,9 @@ def api_setPoster(request): #parse path and return info else: response = json_response(status=403, text='permission denied') return render_to_json_response(response) +actions.register(setPoster) -def api_getImdbId(request): +def getImdbId(request): ''' param data {title: string, director: string, year: string} @@ -331,6 +341,7 @@ def api_getImdbId(request): else: response = json_response(status=404, text='not found') return render_to_json_response(response) +actions.register(getImdbId) ''' media delivery diff --git a/pandora/itemlist/views.py b/pandora/itemlist/views.py index 19f6bb3b..e2d6c70d 100644 --- a/pandora/itemlist/views.py +++ b/pandora/itemlist/views.py @@ -23,12 +23,13 @@ from ox.django.shortcuts import render_to_json_response, get_object_or_404_json, from ox.django.http import HttpFileResponse import ox +from api.actions import actions ''' List API ''' @login_required_json -def api_addListItem(request): +def addListItem(request): ''' param data {list: listId, @@ -53,9 +54,10 @@ def api_addListItem(request): else: response = json_response(status=501, text='not implemented') return render_to_json_response(response) +actions.register(addListItem) @login_required_json -def api_removeListItem(request): +def removeListItem(request): ''' param data {list: listId, @@ -80,9 +82,10 @@ def api_removeListItem(request): else: response = json_response(status=501, text='not implemented') return render_to_json_response(response) +actions.register(removeListItem) @login_required_json -def api_addList(request): +def addList(request): ''' param data {name: value} @@ -97,9 +100,10 @@ def api_addList(request): else: response = json_response(status=403, text='list name exists') return render_to_json_response(response) +actions.register(addList) @login_required_json -def api_editList(request): +def editList(request): ''' param data {key: value} @@ -116,8 +120,9 @@ def api_editList(request): else: response = json_response(status=403, text='not allowed') return render_to_json_response(response) +actions.register(editList) -def api_removeList(request): +def removeList(request): ''' param data {key: value} @@ -131,4 +136,5 @@ def api_removeList(request): else: response = json_response(status=403, text='not allowed') return render_to_json_response(response) +actions.register(removeList) diff --git a/pandora/place/views.py b/pandora/place/views.py index 82de0fe8..433b613c 100644 --- a/pandora/place/views.py +++ b/pandora/place/views.py @@ -25,12 +25,13 @@ from ox.django.http import HttpFileResponse import ox import models +from api.actions import actions ''' fixme, require admin ''' @login_required_json -def api_addPlace(request): +def addPlace(request): ''' param data { @@ -53,9 +54,10 @@ def api_addPlace(request): else: response = json_response(status=403, text='place name exists') return render_to_json_response(response) +actions.register(addPlace) @login_required_json -def api_editPlace(request): +def editPlace(request): ''' param data { @@ -82,13 +84,15 @@ def api_editPlace(request): else: response = json_response(status=403, text='permission denied') return render_to_json_response(response) +actions.register(editPlace) @login_required_json -def api_removePlace(request): +def removePlace(request): response = json_response(status=501, text='not implemented') return render_to_json_response(response) +actions.register(removePlace) -def api_findPlace(request): +def findPlace(request): ''' param data {'query': query, 'sort': array, 'range': array, 'area': array} @@ -128,4 +132,5 @@ Positions for p in Places.objects.find(data['query']): response['data']['places'].append(p.json()) return render_to_json_response(response) +actions.register(findPlace) diff --git a/pandora/settings.py b/pandora/settings.py index 6705ceb8..c2312c3b 100644 --- a/pandora/settings.py +++ b/pandora/settings.py @@ -45,6 +45,7 @@ BROKER_PORT = 5672 BROKER_USER = "pandora" BROKER_PASSWORD = "box" BROKER_VHOST = "/pandora" +SEND_CELERY_ERROR_EMAILS=False # Local time zone for this installation. Choices can be found here: @@ -120,7 +121,6 @@ INSTALLED_APPS = ( 'annotaion', 'app', - 'api', 'archive', 'date', 'item', @@ -130,6 +130,7 @@ INSTALLED_APPS = ( 'text', 'torrent', 'user', + 'api', ) AUTH_PROFILE_MODULE = 'user.UserProfile' @@ -169,6 +170,16 @@ POSTER_PRECEDENCE = ( '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 #POSTER_SERVICES=['http://data.0xdb.org/poster/'] diff --git a/pandora/text/views.py b/pandora/text/views.py index 11d59f00..b86393fb 100644 --- a/pandora/text/views.py +++ b/pandora/text/views.py @@ -17,9 +17,9 @@ from ox.django.http import HttpFileResponse import ox import models +from api.actions import actions - -def api_getNews(request): +def getNews(request): ''' param data string id @@ -31,14 +31,16 @@ def api_getNews(request): item = get_object_or_404_json(models.News, pk=itemId) response['data']['page'] = item.html() return render_to_json_response(response) +actions.register(getNews) -def api_findNews(request): +def findNews(request): ''' ''' response = json_response({}) return render_to_json_response(response) +actions.register(findNews) -def api_getText(request): +def getText(request): ''' param data string id @@ -50,10 +52,12 @@ def api_getText(request): item = get_object_or_404_json(models.Text, pk=itemId) response['data']['page'] = item.html() return render_to_json_response(response) +actions.register(getText) -def api_findText(request): +def findText(request): ''' ''' response = json_response({}) return render_to_json_response(response) +actions.register(findText) diff --git a/pandora/user/urls.py b/pandora/user/urls.py index 131f1401..4ac2218d 100644 --- a/pandora/user/urls.py +++ b/pandora/user/urls.py @@ -5,10 +5,10 @@ from django.conf.urls.defaults import * urlpatterns = patterns("user.views", - (r'^preferences', 'api_preferences'), - (r'^login', 'api_login'), - (r'^logout', 'api_logout'), - (r'^register', 'api_register'), - (r'^recover', 'api_recover'), + (r'^preferences', 'preferences'), + (r'^login', 'login'), + (r'^logout', 'logout'), + (r'^register', 'register'), + (r'^recover', 'recover'), ) diff --git a/pandora/user/views.py b/pandora/user/views.py index 8be14197..60b9117a 100644 --- a/pandora/user/views.py +++ b/pandora/user/views.py @@ -17,6 +17,8 @@ from ox.django.decorators import login_required_json import models +from api.actions import actions + def json_errors(form): return {'status': {'code': 402, 'text': 'form error', 'data': form.errors}} @@ -24,7 +26,7 @@ class LoginForm(forms.Form): username = forms.TextInput() password = forms.TextInput() -def api_login(request): +def login(request): ''' param data {'username': username, 'password': password} @@ -53,8 +55,9 @@ def api_login(request): response = json_response(status=400, text='invalid data') return render_to_json_response(response) +actions.register(login) -def api_logout(request): +def logout(request): ''' param data {} @@ -65,13 +68,14 @@ def api_logout(request): if request.user.is_authenticated(): logout(request) return render_to_json_response(response) +actions.register(logout) class RegisterForm(forms.Form): username = forms.TextInput() password = forms.TextInput() email = forms.TextInput() -def api_register(request): +def register(request): ''' param data {'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: response = json_response(status=400, text='username or email exists') else: + first_user = models.User.objects.count() == 0 user = models.User(username=form.data['username'], email=form.data['email']) user.set_password(form.data['password']) + #make first user admin + user.is_superuser = first_user + user.is_staff = first_user user.save() user = authenticate(username=form.data['username'], password=form.data['password']) @@ -96,6 +104,7 @@ def api_register(request): else: response = json_response(status=400, text='username exists') return render_to_json_response(response) +actions.register(register) class RecoverForm(forms.Form): username_or_email = forms.TextInput() @@ -139,8 +148,9 @@ def api_recover(request): else: response = json_response(status=400, text='invalid data') return render_to_json_response(response) +actions.register(api_recover, 'recover') -def api_findUser(request): +def findUser(request): ''' param data {key: "username", value: "foo", operator: "="} @@ -157,6 +167,7 @@ def api_findUser(request): response = json_response(status=200, text='ok') response['data']['users'] = [u.username for u in User.objects.filter(username__iexact=data['value'])] return render_to_json_response(response) +actions.register(findUser) def recover(request, key): qs = models.UserProfile.objects.filter(recover_key=key) @@ -179,7 +190,7 @@ class ContactForm(forms.Form): subject = forms.TextInput() message = forms.TextInput() -def api_contact(request): +def contact(request): ''' param data {'email': string, 'message': string} @@ -206,10 +217,10 @@ def api_contact(request): else: response = json_response(status=400, text='invalid data') return render_to_json_response(response) - +actions.register(contact) @login_required_json -def api_preferences(request): +def preferences(request): ''' param data string @@ -245,3 +256,5 @@ def api_preferences(request): for key in data: models.set_preference(request.user, key, data[key]) return render_to_json_response(response) +actions.register(preferences) +