move all User and EpisodetUserState db queries into separate module
[mygpo.git] / mygpo / db / couchdb / user.py
blob93b6da45eb84c24cb5072b1966b331ce6b01ff62
1 from mygpo.cache import cache_result
4 @cache_result(timeout=60)
5 def get_num_listened_episodes(user):
6 db = get_main_database()
7 r = db.view('listeners/by_user_podcast',
8 startkey = [user._id, None],
9 endkey = [user._id, {}],
10 reduce = True,
11 group_level = 2,
14 return map(_wrap_num_listened, r)
17 def _wrap_num_listened(obj):
18 count = obj['value']
19 podcast = obj['key'][1]
20 return (podcast, count)
23 @cache_result(timeout=60)
24 def get_num_played_episodes(self, since=None, until={}):
25 """ Number of played episodes in interval """
27 since_str = since.strftime('%Y-%m-%d') if since else None
28 until_str = until.strftime('%Y-%m-%d') if until else {}
30 startkey = [self._id, since_str]
31 endkey = [self._id, until_str]
33 db = get_main_database()
34 res = db.view('listeners/by_user',
35 startkey = startkey,
36 endkey = endkey,
37 reduce = True,
40 val = res.one()
41 return val['value'] if val else 0
46 @cache_result(timeout=60)
47 def get_latest_episodes(self, count=10):
48 """ Returns the latest episodes that the user has accessed """
50 startkey = [self._id, {}]
51 endkey = [self._id, None]
53 db = get_main_database()
54 res = db.view('listeners/by_user',
55 startkey = startkey,
56 endkey = endkey,
57 include_docs = True,
58 descending = True,
59 limit = count,
60 reduce = False,
63 keys = [r['value'] for r in res]
64 return list(episodes_by_id(keys))
68 @cache_result(timeout=60)
69 def get_seconds_played(self, since=None, until={}):
70 """ Returns the number of seconds that the user has listened
72 Can be selected by timespan, podcast and episode """
74 since_str = since.strftime('%Y-%m-%dT%H:%M:%S') if since else None
75 until_str = until.strftime('%Y-%m-%dT%H:%M:%S') if until else {}
77 startkey = [self._id, since_str]
78 endkey = [self._id, until_str]
80 db = get_main_database()
81 res = db.view('listeners/times_played_by_user',
82 startkey = startkey,
83 endkey = endkey,
84 reduce = True,
87 val = res.one()
88 return val['value'] if val else 0
92 @cache_result(timeout=60*60)
93 def suggestions_for_user(user):
94 r = Suggestions.view('suggestions/by_user',
95 key = user._id,
96 include_docs = True,
99 if r:
100 return r.first()
102 else:
103 s = Suggestions()
104 s.user = user._id
105 return s