Merge branch 'master' of git@github.com:fnp/wolnelektury
[wolnelektury.git] / apps / catalogue / views.py
index de9d0b2..556bae1 100644 (file)
@@ -45,6 +45,16 @@ class LazyEncoder(simplejson.JSONEncoder):
             return force_unicode(obj)
         return obj
 
+# shortcut for JSON reponses
+class JSONResponse(HttpResponse):
+    def __init__(self, data={}, callback=None, **kwargs):
+        # get rid of mimetype
+        kwargs.pop('mimetype', None)
+        data = simplejson.dumps(data)
+        if callback:
+            data = callback + "(" + data + ");" 
+        super(JSONResponse, self).__init__(data, mimetype="application/json", **kwargs)
+
 
 def main_page(request):
     if request.user.is_authenticated():
@@ -63,12 +73,24 @@ def main_page(request):
 
 
 def book_list(request):
-    books = models.Book.objects.all()
     form = forms.SearchForm()
 
-    books_by_first_letter = SortedDict()
-    for book in books:
-        books_by_first_letter.setdefault(book.title[0], []).append(book)
+    books_by_parent = {}
+    for book in models.Book.objects.all().order_by('parent_number'):
+        books_by_parent.setdefault(book.parent, []).append(book)
+
+    orphans = []
+    books_by_author = SortedDict()
+    for tag in models.Tag.objects.filter(category='author'):
+        books_by_author[tag] = []
+
+    for book in books_by_parent[None]:
+        authors = list(book.tags.filter(category='author'))
+        if authors:
+            for author in authors:
+                books_by_author[author].append(book)
+        else:
+            orphans.append(book)
 
     return render_to_response('catalogue/book_list.html', locals(),
         context_instance=RequestContext(request))
@@ -204,6 +226,13 @@ def book_detail(request, slug):
     tags = list(book.tags.filter(~Q(category='set')))
     categories = split_tags(tags)
     book_children = book.children.all().order_by('parent_number')
+    
+    _book = book
+    parents = []
+    while _book.parent:
+        parents.append(_book.parent)
+        _book = _book.parent
+    parents = reversed(parents)
 
     theme_counter = book.theme_counter
     book_themes = models.Tag.objects.filter(pk__in=theme_counter.keys())
@@ -304,7 +333,6 @@ def _tags_starting_with(prefix, user=None):
         tags = tags.filter(~Q(category='book') & (~Q(category='set') | Q(user=user)))
     else:
         tags = tags.filter(~Q(category='book') & ~Q(category='set'))
-
     return list(books) + list(tags) + list(book_stubs)
 
 
@@ -321,7 +349,7 @@ def _get_result_type(match):
         type = 'book'
     else:
         type = match.category
-    return dict(models.TAG_CATEGORIES)[type]
+    return type
 
 
 
@@ -379,8 +407,29 @@ def tags_starting_with(request):
     # Prefix must have at least 2 characters
     if len(prefix) < 2:
         return HttpResponse('')
-
-    return HttpResponse('\n'.join(tag.name for tag in _tags_starting_with(prefix, request.user)))
+    tags_list = []
+    result = ""   
+    for tag in _tags_starting_with(prefix, request.user):
+        if not tag.name in tags_list:
+            result += "\n" + tag.name
+            tags_list.append(tag.name)
+    return HttpResponse(result)
+
+def json_tags_starting_with(request, callback=None):
+    # Callback for JSONP
+    prefix = request.GET.get('q', '')
+    callback = request.GET.get('callback', '')
+    # Prefix must have at least 2 characters
+    if len(prefix) < 2:
+        return HttpResponse('')
+    tags_list = []
+    result = ""   
+    for tag in _tags_starting_with(prefix, request.user):
+        if not tag.name in tags_list:
+            result += "\n" + tag.name
+            tags_list.append(tag.name)
+    dict_result = {"matches": tags_list}
+    return JSONResponse(dict_result, callback)
 
 # ====================
 # = Shelf management =
@@ -480,13 +529,15 @@ def download_shelf(request, slug):
     temp = tempfile.TemporaryFile()
     archive = zipfile.ZipFile(temp, 'w')
 
+    already = set()
     for book in collect_books(models.Book.tagged.with_all(shelf)):
         if 'pdf' in formats and book.pdf_file:
             filename = book.pdf_file.path
             archive.write(filename, str('%s.pdf' % book.slug))
-        if 'epub' in formats and book.epub_file:
-            filename = book.epub_file.path
-            archive.write(filename, str('%s.epub' % book.slug))
+        if book.root_ancestor not in already and 'epub' in formats and book.root_ancestor.epub_file:
+            filename = book.root_ancestor.epub_file.path
+            archive.write(filename, str('%s.epub' % book.root_ancestor.slug))
+            already.add(book.root_ancestor)
         if 'odt' in formats and book.odt_file:
             filename = book.odt_file.path
             archive.write(filename, str('%s.odt' % book.slug))
@@ -522,7 +573,7 @@ def shelf_book_formats(request, shelf):
     for book in collect_books(models.Book.tagged.with_all(shelf)):
         if book.pdf_file:
             formats['pdf'] = True
-        if book.epub_file:
+        if book.root_ancestor.epub_file:
             formats['epub'] = True
         if book.odt_file:
             formats['odt'] = True