X-Git-Url: https://git.mdrn.pl/wolnelektury.git/blobdiff_plain/9a938c8b406ce05e3bca4a5a483d473ece9e17b0..75957f735219259d3b4bc361f80ccd3d7b92a0e9:/src/social/utils.py diff --git a/src/social/utils.py b/src/social/utils.py old mode 100755 new mode 100644 index 63a42279b..e713fcdbc --- a/src/social/utils.py +++ b/src/social/utils.py @@ -3,6 +3,8 @@ # Copyright © Fundacja Nowoczesna Polska. See NOTICE for more information. # from collections import defaultdict +from random import randint + from django.contrib.contenttypes.models import ContentType from django.db.models import Q from django.utils.functional import lazy @@ -50,6 +52,15 @@ def get_set(user, name): except Tag.DoesNotExist: tag = Tag.objects.create( category='set', user=user, name=name, slug=utils.get_random_hash(name), sort_key=name.lower()) + except Tag.MultipleObjectsReturned: + # fix duplicated noname shelf + tags = list(Tag.objects.filter(category='set', user=user, name=name)) + tag = tags[0] + for other_tag in tags[1:]: + for item in other_tag.items.all(): + Tag.objects.remove_tag(item, other_tag) + Tag.objects.add_tag(item, tag) + other_tag.delete() return tag @@ -76,3 +87,35 @@ def set_sets(user, work, sets): def cites_for_tags(tags): """Returns a QuerySet with all Cites for books with given tags.""" return Cite.objects.filter(book__in=Book.tagged.with_all(tags)) + + +# tag_ids is never used +def choose_cite(book_id=None, tag_ids=None): + """Choose a cite for main page, for book or for set of tags.""" + if book_id is not None: + cites = Cite.objects.filter(Q(book=book_id) | Q(book__ancestor=book_id)) + elif tag_ids is not None: + tags = Tag.objects.filter(pk__in=tag_ids) + cites = cites_for_tags(tags) + else: + cites = Cite.objects.all() + stickies = cites.filter(sticky=True) + count = len(stickies) + if count: + cites = stickies + else: + count = len(cites) + if count: + cite = cites[randint(0, count - 1)] + else: + cite = None + return cite + + +def get_or_choose_cite(request, book_id=None, tag_ids=None): + try: + assert request.user.is_staff + assert 'banner' in request.GET + return Cite.objects.get(pk=request.GET['banner']) + except (AssertionError, Cite.DoesNotExist): + return choose_cite(book_id, tag_ids)