1 from collections
import defaultdict
2 from operator
import itemgetter
4 from mygpo
.directory
.models
import Category
5 from mygpo
.couch
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
9 from mygpo
.counter
import Counter
12 @cache_result(timeout
=60*60)
13 def category_for_tag(tag
):
16 raise QueryParameterMissing('tag')
18 r
= Category
.view('categories/by_tags',
21 stale
= 'update_after',
23 return r
.first() if r
else None
26 @cache_result(timeout
=60*60)
27 def top_categories(offset
, count
, with_podcasts
=False):
30 raise QueryParameterMissing('offset')
33 raise QueryParameterMissing('count')
37 r
= Category
.view('categories/by_update',
42 stale
= 'update_after'
46 db
= get_main_database()
47 r
= db
.view('categories/by_update',
51 stale
= 'update_after',
52 wrapper
= _category_wrapper
,
58 def _category_wrapper(r
):
60 c
.label
= r
['value'][0]
61 c
._weight
= r
['value'][1]
65 def tags_for_podcast(podcast
):
66 """ all tags for the podcast, in decreasing order of importance """
69 raise QueryParameterMissing('podcast')
72 db
= get_main_database()
73 res
= db
.view('tags/by_podcast',
74 startkey
= [podcast
.get_id(), None],
75 endkey
= [podcast
.get_id(), {}],
79 stale
= 'update_after',
82 tags
= Counter(dict((x
['key'][1], x
['value']) for x
in res
))
84 res
= db
.view('usertags/by_podcast',
85 startkey
= [podcast
.get_id(), None],
86 endkey
= [podcast
.get_id(), {}],
92 tags
.update(Counter(dict( (x
['key'][1], x
['value']) for x
in res
)))
94 get_tag
= itemgetter(0)
95 return map(get_tag
, tags
.most_common())
98 def tags_for_user(user
, podcast_id
=None):
99 """ mapping of all podcasts tagged by the user with a list of tags """
102 raise QueryParameterMissing('user')
105 db
= get_main_database()
106 res
= db
.view('tags/by_user',
107 startkey
= [user
._id
, podcast_id
],
108 endkey
= [user
._id
, podcast_id
or {}]
111 tags
= defaultdict(list)
113 tags
[r
['key'][1]].append(r
['value'])
120 Some tags might be returned twice """
121 db
= get_main_database()
122 res
= multi_request_view(db
, 'podcasts/by_tag',
132 res
= multi_request_view(db
, 'usertags/podcasts',
143 @cache_result(timeout
=60*60)
144 def toplist(res_cls
, view
, key
, limit
, **view_args
):
147 raise QueryParameterMissing('limit')
150 r
= res_cls
.view(view
,
151 startkey
= key
+ [{}],
152 endkey
= key
+ [None],
156 stale
= 'update_after',