104 lines
2.9 KiB
Python
104 lines
2.9 KiB
Python
# -*- coding: utf-8 -*-
|
|
# vi:si:et:sw=4:sts=4:ts=4
|
|
import hashlib
|
|
import json
|
|
import unicodedata
|
|
|
|
import ox
|
|
from sqlalchemy.orm import load_only
|
|
|
|
from oxtornado import actions
|
|
from . import models
|
|
import utils
|
|
import state
|
|
|
|
import logging
|
|
logger = logging.getLogger(__name__)
|
|
|
|
|
|
def editTitle(data):
|
|
'''
|
|
takes {
|
|
id string
|
|
sorttitle string
|
|
}
|
|
'''
|
|
response = {}
|
|
ids = data['id'].split(':')
|
|
data = {
|
|
'sorttitle': unicodedata.normalize('NFKD', data['sorttitle'])
|
|
}
|
|
for item in models.Item.query.filter(models.Item.id.in_(ids)):
|
|
if item.meta.get('sorttitle') != data['sorttitle']:
|
|
item.edit(data)
|
|
response['title'] = item.meta.get('title', 'Untitled')
|
|
response['sorttitle'] = item.meta['sorttitle']
|
|
return response
|
|
actions.register(editTitle)
|
|
|
|
def findTitles(data):
|
|
'''
|
|
takes {
|
|
query {
|
|
conditions [{}]
|
|
operator string
|
|
}
|
|
keys [string]
|
|
sort [{}]
|
|
range [int, int]
|
|
}
|
|
'''
|
|
response = {}
|
|
conditions = [
|
|
{'key': 'list', 'value': ':', 'operator': '=='}
|
|
]
|
|
if data.get('query', {}).get('conditions'):
|
|
value = data.get('query', {}).get('conditions')[0].get('value')
|
|
if value:
|
|
conditions.append({
|
|
'key': 'title', 'operator': '=', 'value': value
|
|
})
|
|
q = {
|
|
'qs': models.Item.find({
|
|
'query': {
|
|
'conditions': conditions, 'operator': '&'
|
|
}
|
|
}),
|
|
}
|
|
_keydata = data.copy()
|
|
for key in ('range', 'position', 'positions'):
|
|
if key in _keydata:
|
|
del _keydata[key]
|
|
key = 'title:' + hashlib.sha1(json.dumps(_keydata, sort_keys=True).encode('utf-8')).hexdigest()
|
|
titles = state.cache.get(key)
|
|
if titles is None:
|
|
state.cache.lock(key)
|
|
response['items'] = []
|
|
_titles = {}
|
|
for i in q['qs']:
|
|
title = i.meta.get('title')
|
|
if not title in _titles:
|
|
_titles[title] = {
|
|
'id': i.id,
|
|
'title': title,
|
|
'sorttitle': i.get_sorttitle()
|
|
}
|
|
else:
|
|
_titles[title]['id'] += ':' + i.id
|
|
titles = list(_titles.values())
|
|
if 'sort' in data:
|
|
titles.sort(key=lambda t: ox.sort_string(t[data['sort'][0]['key']]).lower(),
|
|
reverse=data['sort'][0]['operator']=='-')
|
|
state.cache.set(key, titles)
|
|
|
|
if 'position' in data:
|
|
pass
|
|
elif 'positions' in data:
|
|
ids = [t['id'] for t in titles]
|
|
response['positions'] = utils.get_positions(ids, data['positions'])
|
|
elif 'keys' in data:
|
|
response['items'] = titles[data['range'][0]:data['range'][1]]
|
|
else:
|
|
response['items'] = len(titles)
|
|
return response
|
|
actions.register(findTitles)
|