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
6 from mygpo
.cache
import cache_result
7 from mygpo
.db
.couchdb
.utils
import multi_request_view
8 from mygpo
.db
import QueryParameterMissing
11 @cache_result(timeout
=60*60)
12 def category_for_tag(tag
):
15 raise QueryParameterMissing('tag')
17 r
= Category
.view('categories/by_tags',
20 stale
= 'update_after',
22 return r
.first() if r
else None
25 @cache_result(timeout
=60*60)
26 def top_categories(offset
, count
, with_podcasts
=False):
29 raise QueryParameterMissing('offset')
32 raise QueryParameterMissing('count')
36 r
= Category
.view('categories/by_update',
41 stale
= 'update_after'
45 db
= get_main_database()
46 r
= db
.view('categories/by_update',
50 stale
= 'update_after',
51 wrapper
= _category_wrapper
,
57 def _category_wrapper(r
):
59 c
.label
= r
['value'][0]
60 c
._weight
= r
['value'][1]
64 def tags_for_podcast(podcast
):
65 """ all tags for the podcast, in decreasing order of importance """
68 raise QueryParameterMissing('podcast')
71 db
= get_main_database()
72 res
= db
.view('tags/by_podcast',
73 startkey
= [podcast
.get_id(), None],
74 endkey
= [podcast
.get_id(), {}],
78 stale
= 'update_after',
81 tags
= Counter(dict((x
['key'][1], x
['value']) for x
in res
))
83 res
= db
.view('usertags/by_podcast',
84 startkey
= [podcast
.get_id(), None],
85 endkey
= [podcast
.get_id(), {}],
91 tags
.update(Counter(dict( (x
['key'][1], x
['value']) for x
in res
)))
93 get_tag
= itemgetter(0)
94 return map(get_tag
, tags
.most_common())
97 def tags_for_user(user
, podcast_id
=None):
98 """ mapping of all podcasts tagged by the user with a list of tags """
101 raise QueryParameterMissing('user')
104 db
= get_main_database()
105 res
= db
.view('tags/by_user',
106 startkey
= [user
._id
, podcast_id
],
107 endkey
= [user
._id
, podcast_id
or {}]
110 tags
= defaultdict(list)
112 tags
[r
['key'][1]].append(r
['value'])
119 Some tags might be returned twice """
120 db
= get_main_database()
121 res
= multi_request_view(db
, 'podcasts/by_tag',
131 res
= multi_request_view(db
, 'usertags/podcasts',
142 @cache_result(timeout
=60*60)
143 def toplist(res_cls
, view
, key
, limit
, **view_args
):
146 raise QueryParameterMissing('limit')
149 r
= res_cls
.view(view
,
150 startkey
= key
+ [{}],
151 endkey
= key
+ [None],
155 stale
= 'update_after',