+class BookHandler(BaseHandler):
+ model = Book
+ #fields = ('slug', 'title')
+
+ def read(self, request, slug=None):
+ if slug:
+ return get_object_or_404(Book, slug=slug)
+ else:
+ return Book.objects.all()
+"""
+
+
+class WLHandler(BaseHandler):
+
+ @staticmethod
+ def fields(request, name):
+ fields_str = request.GET.get(name) if request is not None else None
+ return fields_str.split(',') if fields_str is not None else None
+
+ @staticmethod
+ def book_dict(book, fields=None, extra_fields=None):
+ obj = {}
+ for field in ('slug', 'title', 'description',
+ 'extra_info', 'gazeta_link', 'wiki_link'):
+ if getattr(book, field):
+ obj[field] = getattr(book, field)
+ for field in ('created_at', 'changed_at'):
+ obj[field] = timestamp(getattr(book, field))
+ for field in ('xml', 'epub', 'txt', 'pdf', 'html'):
+ f = getattr(book, field+'_file')
+ if f:
+ obj[field] = f.url
+ for media in book.medias.all():
+ obj.setdefault(media.type, []).append(media.file.url)
+ if book.parent:
+ obj['parent'] = book.parent.id
+ obj['parent_number'] = book.parent_number
+ if fields is not None:
+ for key in obj.keys():
+ if key not in fields:
+ del obj[key]
+
+ # if there's still extra_info, we can parse it
+ if 'extra_info' in obj:
+ extra = json.loads(obj['extra_info'])
+ if extra_fields is not None:
+ for key in extra.keys():
+ if key not in extra_fields:
+ del extra[key]
+ obj['extra_info'] = extra
+
+ obj['id'] = book.id
+ return obj
+
+ @classmethod
+ def book_changes(cls, since=0, request=None):
+ since = datetime.fromtimestamp(float(since))
+ book_fields = cls.fields(request, 'book_fields')
+ extra_fields = cls.fields(request, 'extra_fields')
+
+ added = []
+ changed = []
+ deleted = []
+
+ last_change = since
+ for book in Book.objects.filter(changed_at__gt=since):
+ if book.changed_at > last_change:
+ last_change = book.changed_at
+ book_d = cls.book_dict(book, book_fields, extra_fields)
+ if book.created_at > since:
+ added.append(book_d)
+ else:
+ changed.append(book_d)
+
+ for book in Deleted.objects.filter(type='Book', deleted_at__gt=since, created_at__lte=since):
+ if book.deleted_at > last_change:
+ last_change = book.deleted_at
+ deleted.append(book.id)
+ return {'added': added, 'changed': changed, 'deleted': deleted, 'last_change': timestamp(last_change)}