accessed/viewed/update to new site.json syntax

This commit is contained in:
j 2011-01-25 20:09:03 +05:30
parent 392a12da5f
commit 4f3d8027ce
2 changed files with 77 additions and 47 deletions

View file

@ -125,18 +125,12 @@ class Item(models.Model):
return default return default
def access(self, user): def access(self, user):
if user.is_authenticated():
access, created = Access.objects.get_or_create(item=self, user=user)
else:
access, created = Access.objects.get_or_create(item=self, user=None)
access.save()
if self.public and self.available: if self.public and self.available:
return True return True
elif user.is_staff or \ elif user.is_authenticated() and \
self.user == user or \ (user.is_staff or self.user == user or \
self.groups.filter(id__in=user.groups.all()).count() > 0: self.groups.filter(id__in=user.groups.all()).count() > 0):
return True return True
return False return False
def editable(self, user): def editable(self, user):
@ -431,13 +425,18 @@ class Item(models.Model):
sort_value = u'' sort_value = u''
return sort_value return sort_value
def set_value(s, name, value):
if not value:
value = None
setattr(s, name, value)
base_keys = ( base_keys = (
'id', 'id',
'aspectratio', 'aspectratio',
'duration', 'duration',
'color', 'hue',
'saturation', 'saturation',
'brightness', 'lightness',
'volume', 'volume',
'clips', 'clips',
'cuts', 'cuts',
@ -448,24 +447,19 @@ class Item(models.Model):
'pixels', 'pixels',
'size', 'size',
'bitrate', 'bitrate',
'files', 'numberoffiles',
'filename',
'published', 'published',
'modified', 'modified',
'popularity' 'popularity',
) )
max_int = 9223372036854775807L
def set_value(s, name, value): for key in filter(lambda k: 'columnWidth' in k, config['itemKeys']):
if not value:
value = None
setattr(s, name, value)
for key in filter(lambda k: 'sort' in k, config['itemKeys']):
name = key['id'] name = key['id']
source = name source = name
sort_type = key['sort'].get('type', key['type']) sort_type = key.get('sort', key['type'])
if 'value' in key: if 'value' in key:
if 'layer' in key['value']:
continue
source = key['value']['key'] source = key['value']['key']
sort_type = key['value'].get('type', sort_type) sort_type = key['value'].get('type', sort_type)
@ -525,8 +519,7 @@ class Item(models.Model):
if 'bitrate' in videos[0].info: if 'bitrate' in videos[0].info:
s.bitrate = videos[0].info['bitrate'] s.bitrate = videos[0].info['bitrate']
s.pixels = sum([v.pixels for v in videos]) s.pixels = sum([v.pixels for v in videos])
s.filename = ' '.join([v.name for v in videos])[:955] s.numberoffiles = self.files.all().count()
s.files = self.files.all().count()
s.size = sum([v.size for v in videos]) #FIXME: only size of movies? s.size = sum([v.size for v in videos]) #FIXME: only size of movies?
s.volume = 0 s.volume = 0
else: else:
@ -540,10 +533,12 @@ class Item(models.Model):
s.size = None s.size = None
s.volume = None s.volume = None
s.color = int(sum(self.data.get('color', []))) if 'color' in self.data:
s.saturation = None #FIXME s.hue, s.saturation, s.brightness = self.data['color']
s.brightness = None #FIXME else:
s.hue = None
s.saturation = None
s.brighness = None
s.cuts = len(self.data.get('cuts', [])) s.cuts = len(self.data.get('cuts', []))
if s.duration: if s.duration:
s.cutsperminute = s.cuts / (s.duration/60) s.cutsperminute = s.cuts / (s.duration/60)
@ -559,7 +554,7 @@ class Item(models.Model):
if not isinstance(current_values, list): if not isinstance(current_values, list):
current_values = [current_values] current_values = [current_values]
saved_values = [i.value for i in Facet.objects.filter(item=self, key=key)] saved_values = [i.value for i in Facet.objects.filter(item=self, key=key)]
removed_values = filter(lambda x: x not in current_values, saved_values) removed_values = filter(lambda i: i not in current_values, saved_values)
if removed_values: if removed_values:
Facet.objects.filter(item=self, key=key, value__in=removed_values).delete() Facet.objects.filter(item=self, key=key, value__in=removed_values).delete()
for value in current_values: for value in current_values:
@ -570,12 +565,6 @@ class Item(models.Model):
f = Facet(key=key, value=value, value_sort=value_sort) f = Facet(key=key, value=value, value_sort=value_sort)
f.item = self f.item = self
f.save() f.save()
year = self.get('year', None)
if year:
f, created = Facet.objects.get_or_create(key='year', value=year,
value_sort=year, item=self)
else:
Facet.objects.filter(item=self, key='year').delete()
def path(self, name=''): def path(self, name=''):
h = self.itemId h = self.itemId
@ -789,13 +778,13 @@ class Item(models.Model):
config = site_config() config = site_config()
Item.facet_keys = [] Item.facet_keys = []
for key in filter(lambda k: 'find' in k, config['itemKeys']): for key in config['itemKeys']:
if 'autocomplete' in key['find'] and not 'autocompleteSortKey' in key['find']: if 'autocomplete' in key and not 'autocompleteSortKey' in key:
Item.facet_keys.append(key['id']) Item.facet_keys.append(key['id'])
Item.person_keys = [] Item.person_keys = []
for key in filter(lambda k: 'sort' in k, config['itemKeys']): for key in config['itemKeys']:
if key['sort'].get('type', '') == 'person': if 'sort' in key and key['sort'] == 'person':
Item.person_keys.append(key['id']) Item.person_keys.append(key['id'])
class ItemFind(models.Model): class ItemFind(models.Model):
@ -822,10 +811,12 @@ attrs = {
'__module__': 'item.models', '__module__': 'item.models',
'item': models.OneToOneField('Item', related_name='sort', primary_key=True), 'item': models.OneToOneField('Item', related_name='sort', primary_key=True),
} }
for key in filter(lambda k: 'sort' in k, config['itemKeys']): for key in filter(lambda k: 'columnWidth' in k, config['itemKeys']):
name = key['id'] name = key['id']
name = {'id': 'itemId'}.get(name, name) name = {'id': 'itemId'}.get(name, name)
sort_type = key['sort'].get('type', key['type']) sort_type = key.get('sort', key['type'])
if isinstance(sort_type, list):
sort_type = sort_type[0]
model = { model = {
'char': (models.CharField, dict(null=True, max_length=1000, db_index=True)), 'char': (models.CharField, dict(null=True, max_length=1000, db_index=True)),
'year': (models.CharField, dict(null=True, max_length=4, db_index=True)), 'year': (models.CharField, dict(null=True, max_length=4, db_index=True)),
@ -840,6 +831,7 @@ for key in filter(lambda k: 'sort' in k, config['itemKeys']):
'words': 'integer', 'words': 'integer',
'length': 'integer', 'length': 'integer',
'date': 'date', 'date': 'date',
'hue': 'float',
}.get(sort_type, sort_type)] }.get(sort_type, sort_type)]
attrs[name] = model[0](**model[1]) attrs[name] = model[0](**model[1])
@ -854,6 +846,13 @@ class Access(models.Model):
access = models.DateTimeField(auto_now=True) access = models.DateTimeField(auto_now=True)
item = models.ForeignKey(Item, related_name='accessed') item = models.ForeignKey(Item, related_name='accessed')
user = models.ForeignKey(User, null=True, related_name='accessed_items') user = models.ForeignKey(User, null=True, related_name='accessed_items')
accessed = models.IntegerField(default=0)
def save(self, *args, **kwargs):
if not self.accessed:
self.accessed = 0
self.accessed += 1
super(Access, self).save(*args, **kwargs)
def __unicode__(self): def __unicode__(self):
if self.user: if self.user:

View file

@ -2,8 +2,9 @@
# vi:si:et:sw=4:sts=4:ts=4 # vi:si:et:sw=4:sts=4:ts=4
from __future__ import division from __future__ import division
import os.path import os.path
from datetime import datetime
from django.db.models import Count, Sum from django.db.models import Count, Sum, Max
from django.http import HttpResponse, Http404 from django.http import HttpResponse, Http404
from django.shortcuts import get_object_or_404, redirect from django.shortcuts import get_object_or_404, redirect
from django.conf import settings from django.conf import settings
@ -48,8 +49,14 @@ def _order_query(qs, sort, prefix='sort__'):
operator = e['operator'] operator = e['operator']
if operator != '-': if operator != '-':
operator = '' operator = ''
key = {'id': 'itemId'}.get(e['key'], e['key']) key = {
order = '%s%s%s' % (operator, prefix, key) 'id': 'itemId',
'accessed': 'accessed__access',
'viewed': 'accessed__access'
}.get(e['key'], e['key'])
if key not in ('accessed__access', ):
key = "%s%s" % (prefix, key)
order = '%s%s' % (operator, key)
order_by.append(order) order_by.append(order)
if order_by: if order_by:
qs = qs.order_by(*order_by, nulls_last=True) qs = qs.order_by(*order_by, nulls_last=True)
@ -189,6 +196,18 @@ Positions
response['data']['items'] = [] response['data']['items'] = []
qs = _order_query(query['qs'], query['sort']) qs = _order_query(query['qs'], query['sort'])
_p = query['keys'] _p = query['keys']
def only_p_sums(m):
r = {}
for p in _p:
if p in ('accessed', 'viewed'):
r[p] = getattr(m, 'viewed')
elif p == 'popularity':
r[p] = getattr(m, p)
else:
r[p] = m.json.get(p, '')
if isinstance(r[p], datetime):
r[p] = r[p].strftime('%Y-%m-%dT%H:%M:%SZ')
return r
def only_p(m): def only_p(m):
r = {} r = {}
if m: if m:
@ -196,9 +215,21 @@ Positions
for p in _p: for p in _p:
r[p] = m.get(p, '') r[p] = m.get(p, '')
return r return r
if 'viewed' in _p and request.user.is_authenticated():
qs = qs.filter(accessed__user=request.user)
qs = qs[query['range'][0]:query['range'][1]] qs = qs[query['range'][0]:query['range'][1]]
#response['data']['items'] = [m.get_json(_p) for m in qs] #response['data']['items'] = [m.get_json(_p) for m in qs]
response['data']['items'] = [only_p(m['json']) for m in qs.values('json')] if 'popularity' in _p:
qs = qs.annotate(popularity=Sum('accessed__accessed'))
response['data']['items'] = [only_p_sums(m) for m in qs]
elif 'viewed' in _p and request.user.is_authenticated():
qs = qs.annotate(viewed=Max('accessed__access'))
response['data']['items'] = [only_p_sums(m) for m in qs]
elif 'accessed' in _p:
qs = qs.annotate(viewed=Max('accessed__access'))
response['data']['items'] = [only_p_sums(m) for m in qs]
else:
response['data']['items'] = [only_p(m['json']) for m in qs.values('json')]
else: # otherwise stats else: # otherwise stats
items = query['qs'] items = query['qs']
files = File.objects.all().filter(item__in=items).filter(size__gt=0) files = File.objects.all().filter(item__in=items).filter(size__gt=0)