1 from collections
import defaultdict
, Counter
2 from operator
import itemgetter
4 from mygpo
.directory
.models
import Category
5 from mygpo
.db
.couchdb
import get_main_database
, get_categories_database
, \
7 from mygpo
.cache
import cache_result
8 from mygpo
.db
.couchdb
.utils
import multi_request_view
9 from mygpo
.db
import QueryParameterMissing
12 def category_for_tag_uncached(tag
):
15 raise QueryParameterMissing('tag')
17 db
= get_categories_database()
18 r
= db
.view('categories/by_tags',
21 stale
= 'update_after',
34 category_for_tag
= cache_result(timeout
=60*60)(category_for_tag_uncached
)
37 @cache_result(timeout
=60*60)
38 def top_categories(offset
, count
, with_podcasts
=False):
41 raise QueryParameterMissing('offset')
44 raise QueryParameterMissing('count')
46 db
= get_categories_database()
49 r
= db
.view('categories/by_update',
54 stale
= 'update_after',
59 r
= db
.view('categories/by_update',
63 stale
= 'update_after',
64 wrapper
= _category_wrapper
,
69 for cat
in categories
:
75 def _category_wrapper(r
):
77 c
.label
= r
['value'][0]
78 c
._weight
= r
['value'][1]
82 def save_category(category
):
83 db
= get_categories_database()
87 def tags_for_podcast(podcast
):
88 """ all tags for the podcast, in decreasing order of importance """
91 raise QueryParameterMissing('podcast')
94 db
= get_main_database()
95 res
= db
.view('tags/by_podcast',
96 startkey
= [podcast
.get_id(), None],
97 endkey
= [podcast
.get_id(), {}],
101 stale
= 'update_after',
104 tags
= Counter(dict((x
['key'][1], x
['value']) for x
in res
))
106 udb
= get_userdata_database()
107 res
= udb
.view('usertags/by_podcast',
108 startkey
= [podcast
.get_id(), None],
109 endkey
= [podcast
.get_id(), {}],
115 tags
.update(Counter(dict( (x
['key'][1], x
['value']) for x
in res
)))
117 get_tag
= itemgetter(0)
118 return map(get_tag
, tags
.most_common())
121 def tags_for_user(user
, podcast_id
=None):
122 """ mapping of all podcasts tagged by the user with a list of tags """
125 raise QueryParameterMissing('user')
128 udb
= get_userdata_database()
129 res
= udb
.view('usertags/by_user',
130 startkey
= [user
._id
, podcast_id
],
131 endkey
= [user
._id
, podcast_id
or {}]
134 tags
= defaultdict(list)
136 tags
[r
['key'][1]].append(r
['value'])
143 Some tags might be returned twice """
144 db
= get_main_database()
145 res
= multi_request_view(db
, 'podcasts/by_tag',
155 udb
= get_userdata_database()
156 res
= multi_request_view(udb
, 'usertags/podcasts',
167 @cache_result(timeout
=60*60)
168 def toplist(res_cls
, view
, key
, limit
, **view_args
):
171 raise QueryParameterMissing('limit')
174 r
= res_cls
.view(view
,
175 startkey
= key
+ [{}],
176 endkey
= key
+ [None],
180 stale
= 'update_after',