[Migration] fix typo
[mygpo.git] / mygpo / db / couchdb / podcastlist.py
blob0ef8c1cb166bf729107b0bf78d020c74b516f449
1 from random import random
3 from django.core.cache import cache
5 from mygpo.share.models import PodcastList
6 from mygpo.cache import cache_result
7 from mygpo.decorators import repeat_on_conflict
8 from mygpo.db import QueryParameterMissing
9 from mygpo.db.couchdb import get_main_database, get_single_result
12 def podcastlist_for_user_slug(user_id, slug):
14 if not user_id:
15 raise QueryParameterMissing('user_id')
17 if not slug:
18 raise QueryParameterMissing('slug')
20 db = get_main_database()
21 l = get_single_result(db, 'podcastlists/by_user_slug',
22 key = [user_id, slug],
23 include_docs = True,
24 schema = PodcastList,
27 return l
31 def podcastlists_for_user(user_id):
33 if not user_id:
34 raise QueryParameterMissing('user_id')
36 r = PodcastList.view('podcastlists/by_user_slug',
37 startkey = [user_id, None],
38 endkey = [user_id, {}],
39 include_docs = True,
41 return list(r)
45 @cache_result(timeout=60*69)
46 def podcastlists_by_rating(**kwargs):
47 r = PodcastList.view('podcastlists/by_rating',
48 descending = True,
49 include_docs = True,
50 stale = 'update_after',
51 **kwargs
53 return list(r)
57 @cache_result(timeout=60*60)
58 def podcastlist_count(with_rating=True):
59 view = 'podcastlists/by_rating' if with_rating else \
60 'podcastlists/by_user_slug'
62 return PodcastList.view(view,
63 limit = 0,
64 stale = 'update_after',
65 ).total_rows
69 def random_podcastlists(chunk_size=1):
71 while True:
72 rnd = random()
73 res = PodcastList.view('podcastlists/random',
74 startkey = rnd,
75 include_docs = True,
76 limit = chunk_size,
77 stale = 'ok',
80 if not res:
81 break
83 for r in res:
84 yield r
87 @repeat_on_conflict(['plist'])
88 def add_podcast_to_podcastlist(plist, podcast_id):
89 plist.podcasts.append(podcast_id)
90 plist.save()
93 @repeat_on_conflict(['plist'])
94 def remove_podcast_from_podcastlist(plist, podcast_id):
96 if podcast_id in plist.podcasts:
97 plist.podcasts.remove(podcast_id)
99 if not podcast_id in plist.podcasts:
100 # the podcast might be there with another id
101 podcast = Podcast.objects.get(id=podcast_id)
102 podcast_id = podcast.get_id()
103 if podcast_id in plist.podcasts:
104 plist.podcasts.remove(podcast_id)
106 plist.save()
108 @repeat_on_conflict(['plist'])
109 def delete_podcastlist(plist):
110 plist.delete()