2 # This file is part of my.gpodder.org.
4 # my.gpodder.org is free software: you can redistribute it and/or modify it
5 # under the terms of the GNU Affero General Public License as published by
6 # the Free Software Foundation, either version 3 of the License, or (at your
7 # option) any later version.
9 # my.gpodder.org is distributed in the hope that it will be useful, but
10 # WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
11 # or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public
12 # License for more details.
14 # You should have received a copy of the GNU Affero General Public License
15 # along with my.gpodder.org. If not, see <http://www.gnu.org/licenses/>.
18 from functools
import partial
19 from itertools
import imap
, chain
20 from collections
import defaultdict
, namedtuple
21 from datetime
import datetime
23 import dateutil
.parser
30 from django
.http
import HttpResponse
, HttpResponseBadRequest
, Http404
, HttpResponseNotFound
31 from django
.contrib
.sites
.models
import RequestSite
32 from django
.views
.decorators
.csrf
import csrf_exempt
33 from django
.views
.decorators
.cache
import never_cache
35 from mygpo
.api
.constants
import EPISODE_ACTION_TYPES
, DEVICE_TYPES
36 from mygpo
.api
.httpresponse
import JsonResponse
37 from mygpo
.api
.sanitizing
import sanitize_url
, sanitize_urls
38 from mygpo
.api
.advanced
.directory
import episode_data
, podcast_data
39 from mygpo
.api
.backend
import get_device
, BulkSubscribe
40 from mygpo
.log
import log
41 from mygpo
.utils
import parse_time
, format_time
, parse_bool
, get_timestamp
42 from mygpo
.decorators
import allowed_methods
, repeat_on_conflict
43 from mygpo
.core
import models
44 from mygpo
.core
.models
import SanitizingRule
, Podcast
45 from mygpo
.core
.tasks
import auto_flattr_episode
46 from mygpo
.users
.models
import PodcastUserState
, EpisodeAction
, \
47 EpisodeUserState
, DeviceDoesNotExist
, DeviceUIDException
, \
48 InvalidEpisodeActionAttributes
49 from mygpo
.users
.settings
import FLATTR_AUTO
50 from mygpo
.core
.json
import json
, JSONDecodeError
51 from mygpo
.api
.basic_auth
import require_valid_user
, check_username
52 from mygpo
.db
.couchdb
import BulkException
, bulk_save_retry
53 from mygpo
.db
.couchdb
.episode
import episode_by_id
, \
54 favorite_episodes_for_user
, episodes_for_podcast
55 from mygpo
.db
.couchdb
.podcast
import podcast_for_url
56 from mygpo
.db
.couchdb
.podcast_state
import subscribed_podcast_ids_by_device
57 from mygpo
.db
.couchdb
.episode_state
import get_podcasts_episode_states
, \
58 episode_state_for_ref_urls
, get_episode_actions
61 # keys that are allowed in episode actions
62 EPISODE_ACTION_KEYS
= ('position', 'episode', 'action', 'device', 'timestamp',
63 'started', 'total', 'podcast')
70 @allowed_methods(['GET', 'POST'])
71 def subscriptions(request
, username
, device_uid
):
74 now_
= get_timestamp(now
)
76 if request
.method
== 'GET':
79 device
= request
.user
.get_device_by_uid(device_uid
)
80 except DeviceDoesNotExist
as e
:
81 return HttpResponseNotFound(str(e
))
83 since_
= request
.GET
.get('since', None)
85 return HttpResponseBadRequest('parameter since missing')
87 since
= datetime
.fromtimestamp(float(since_
))
89 return HttpResponseBadRequest('since-value is not a valid timestamp')
91 changes
= get_subscription_changes(request
.user
, device
, since
, now
)
93 return JsonResponse(changes
)
95 elif request
.method
== 'POST':
96 d
= get_device(request
.user
, device_uid
,
97 request
.META
.get('HTTP_USER_AGENT', ''))
99 if not request
.raw_post_data
:
100 return HttpResponseBadRequest('POST data must not be empty')
102 actions
= json
.loads(request
.raw_post_data
)
103 add
= actions
['add'] if 'add' in actions
else []
104 rem
= actions
['remove'] if 'remove' in actions
else []
106 add
= filter(None, add
)
107 rem
= filter(None, rem
)
110 update_urls
= update_subscriptions(request
.user
, d
, add
, rem
)
111 except ValueError, e
:
112 return HttpResponseBadRequest(e
)
114 return JsonResponse({
116 'update_urls': update_urls
,
120 def update_subscriptions(user
, device
, add
, remove
):
124 raise ValueError('can not add and remove %s at the same time' % a
)
126 add_s
= list(sanitize_urls(add
, 'podcast'))
127 rem_s
= list(sanitize_urls(remove
, 'podcast'))
129 assert len(add
) == len(add_s
) and len(remove
) == len(rem_s
)
131 updated_urls
= filter(lambda (a
, b
): a
!= b
, zip(add
+ remove
, add_s
+ rem_s
))
133 add_s
= filter(None, add_s
)
134 rem_s
= filter(None, rem_s
)
136 # If two different URLs (in add and remove) have
137 # been sanitized to the same, we ignore the removal
138 rem_s
= filter(lambda x
: x
not in add_s
, rem_s
)
140 subscriber
= BulkSubscribe(user
, device
)
143 subscriber
.add_action(a
, 'subscribe')
146 subscriber
.add_action(r
, 'unsubscribe')
150 except BulkException
as be
:
151 for err
in be
.errors
:
152 log('Advanced API: %(username)s: Updating subscription for '
153 '%(podcast_url)s on %(device_uid)s failed: '
154 '%(rerror)s (%(reason)s)'.format(username
=user
.username
,
155 podcast_url
=err
.doc
, device_uid
=device
.uid
,
156 error
=err
.error
, reason
=err
.reason
)
162 def get_subscription_changes(user
, device
, since
, until
):
163 add_urls
, rem_urls
= device
.get_subscription_changes(since
, until
)
164 until_
= get_timestamp(until
)
165 return {'add': add_urls
, 'remove': rem_urls
, 'timestamp': until_
}
172 @allowed_methods(['GET', 'POST'])
173 def episodes(request
, username
, version
=1):
175 version
= int(version
)
177 now_
= get_timestamp(now
)
178 ua_string
= request
.META
.get('HTTP_USER_AGENT', '')
180 if request
.method
== 'POST':
182 actions
= json
.loads(request
.raw_post_data
)
183 except (JSONDecodeError
, UnicodeDecodeError) as e
:
184 msg
= 'Advanced API: could not decode episode update POST data for user %s: %s' % (username
, e
)
186 return HttpResponseBadRequest(msg
)
189 update_urls
= update_episodes(request
.user
, actions
, now
, ua_string
)
190 except DeviceUIDException
as e
:
192 log('could not update episodes for user %s: %s %s: %s' % (username
, e
, traceback
.format_exc(), actions
))
193 return HttpResponseBadRequest(str(e
))
194 except InvalidEpisodeActionAttributes
as e
:
196 log('could not update episodes for user %s: %s %s: %s' % (username
, e
, traceback
.format_exc(), actions
))
197 return HttpResponseBadRequest(str(e
))
199 return JsonResponse({'timestamp': now_
, 'update_urls': update_urls
})
201 elif request
.method
== 'GET':
202 podcast_url
= request
.GET
.get('podcast', None)
203 device_uid
= request
.GET
.get('device', None)
204 since_
= request
.GET
.get('since', None)
205 aggregated
= parse_bool(request
.GET
.get('aggregated', False))
208 since
= int(since_
) if since_
else None
210 return HttpResponseBadRequest('since-value is not a valid timestamp')
213 podcast
= podcast_for_url(podcast_url
)
222 device
= request
.user
.get_device_by_uid(device_uid
)
223 except DeviceDoesNotExist
as e
:
224 return HttpResponseNotFound(str(e
))
229 changes
= get_episode_changes(request
.user
, podcast
, device
, since
,
230 now_
, aggregated
, version
)
232 return JsonResponse(changes
)
236 def convert_position(action
):
237 """ convert position parameter for API 1 compatibility """
238 pos
= getattr(action
, 'position', None)
240 action
.position
= format_time(pos
)
245 def get_episode_changes(user
, podcast
, device
, since
, until
, aggregated
, version
):
247 devices
= dict( (dev
.id, dev
.uid
) for dev
in user
.devices
)
250 if podcast
is not None:
251 args
['podcast_id'] = podcast
.get_id()
253 if device
is not None:
254 args
['device_id'] = device
.id
256 actions
= get_episode_actions(user
._id
, since
, until
, **args
)
259 actions
= imap(convert_position
, actions
)
261 clean_data
= partial(clean_episode_action_data
,
262 user
=user
, devices
=devices
)
264 actions
= map(clean_data
, actions
)
265 actions
= filter(None, actions
)
268 actions
= dict( (a
['episode'], a
) for a
in actions
).values()
270 return {'actions': actions
, 'timestamp': until
}
275 def clean_episode_action_data(action
, user
, devices
):
277 if None in (action
.get('podcast', None), action
.get('episode', None)):
280 if 'device_id' in action
:
281 device_id
= action
['device_id']
282 device_uid
= devices
.get(device_id
)
284 action
['device'] = device_uid
286 del action
['device_id']
288 # remove superfluous keys
289 for x
in action
.keys():
290 if x
not in EPISODE_ACTION_KEYS
:
293 # set missing keys to None
294 for x
in EPISODE_ACTION_KEYS
:
298 if action
['action'] != 'play':
299 if 'position' in action
:
300 del action
['position']
302 if 'total' in action
:
305 if 'started' in action
:
306 del action
['started']
308 if 'playmark' in action
:
309 del action
['playmark']
312 action
['position'] = action
.get('position', False) or 0
320 def update_episodes(user
, actions
, now
, ua_string
):
323 grouped_actions
= defaultdict(list)
325 # group all actions by their episode
326 for action
in actions
:
328 podcast_url
= action
['podcast']
329 podcast_url
= sanitize_append(podcast_url
, 'podcast', update_urls
)
330 if podcast_url
== '': continue
332 episode_url
= action
['episode']
333 episode_url
= sanitize_append(episode_url
, 'episode', update_urls
)
334 if episode_url
== '': continue
336 act
= parse_episode_action(action
, user
, update_urls
, now
, ua_string
)
337 grouped_actions
[ (podcast_url
, episode_url
) ].append(act
)
340 auto_flattr_episodes
= []
342 # Prepare the updates for each episode state
345 for (p_url
, e_url
), action_list
in grouped_actions
.iteritems():
346 episode_state
= episode_state_for_ref_urls(user
, p_url
, e_url
)
348 if any(a
['action'] == 'play' for a
in actions
):
349 auto_flattr_episodes
.append(episode_state
.episode
)
351 fun
= partial(update_episode_actions
, action_list
=action_list
)
352 obj_funs
.append( (episode_state
, fun
) )
354 bulk_save_retry(obj_funs
)
356 if user
.get_wksetting(FLATTR_AUTO
):
357 for episode_id
in auto_flattr_episodes
:
358 auto_flattr_episode
.delay(user
, episode_id
)
363 def update_episode_actions(episode_state
, action_list
):
364 """ Adds actions to the episode state and saves if necessary """
366 len1
= len(episode_state
.actions
)
367 episode_state
.add_actions(action_list
)
369 if len(episode_state
.actions
) == len1
:
376 def parse_episode_action(action
, user
, update_urls
, now
, ua_string
):
377 action_str
= action
.get('action', None)
378 if not valid_episodeaction(action_str
):
379 raise Exception('invalid action %s' % action_str
)
381 new_action
= EpisodeAction()
383 new_action
.action
= action
['action']
385 if action
.get('device', False):
386 device
= get_device(user
, action
['device'], ua_string
)
387 new_action
.device
= device
.id
389 if action
.get('timestamp', False):
390 new_action
.timestamp
= dateutil
.parser
.parse(action
['timestamp'])
392 new_action
.timestamp
= now
393 new_action
.timestamp
= new_action
.timestamp
.replace(microsecond
=0)
395 new_action
.upload_timestamp
= get_timestamp(now
)
397 new_action
.started
= action
.get('started', None)
398 new_action
.playmark
= action
.get('position', None)
399 new_action
.total
= action
.get('total', None)
408 # Workaround for mygpoclient 1.0: It uses "PUT" requests
409 # instead of "POST" requests for uploading device settings
410 @allowed_methods(['POST', 'PUT'])
411 def device(request
, username
, device_uid
):
412 d
= get_device(request
.user
, device_uid
,
413 request
.META
.get('HTTP_USER_AGENT', ''))
415 data
= json
.loads(request
.raw_post_data
)
417 if 'caption' in data
:
418 if not data
['caption']:
419 return HttpResponseBadRequest('caption must not be empty')
420 d
.name
= data
['caption']
423 if not valid_devicetype(data
['type']):
424 return HttpResponseBadRequest('invalid device type %s' % data
['type'])
425 d
.type = data
['type']
428 request
.user
.update_device(d
)
430 return HttpResponse()
433 def valid_devicetype(type):
434 for t
in DEVICE_TYPES
:
439 def valid_episodeaction(type):
440 for t
in EPISODE_ACTION_TYPES
:
450 @allowed_methods(['GET'])
451 def devices(request
, username
):
452 devices
= filter(lambda d
: not d
.deleted
, request
.user
.devices
)
453 devices
= map(device_data
, devices
)
454 return JsonResponse(devices
)
457 def device_data(device
):
460 caption
= device
.name
,
462 subscriptions
= len(subscribed_podcast_ids_by_device(device
)),
467 def get_podcast_data(podcasts
, domain
, url
):
468 """ Gets podcast data for a URL from a dict of podcasts """
469 podcast
= podcasts
.get(url
)
470 return podcast_data(podcast
, domain
)
473 def get_episode_data(podcasts
, domain
, clean_action_data
, include_actions
, episode_status
):
474 """ Get episode data for an episode status object """
475 podcast_id
= episode_status
.episode
.podcast
476 podcast
= podcasts
.get(podcast_id
, None)
477 t
= episode_data(episode_status
.episode
, domain
, podcast
)
478 t
['status'] = episode_status
.status
480 # include latest action (bug 1419)
481 if include_actions
and episode_status
.action
:
482 t
['action'] = clean_action_data(episode_status
.action
)
491 def updates(request
, username
, device_uid
):
493 now_
= get_timestamp(now
)
496 device
= request
.user
.get_device_by_uid(device_uid
)
497 except DeviceDoesNotExist
as e
:
498 return HttpResponseNotFound(str(e
))
500 since_
= request
.GET
.get('since', None)
502 return HttpResponseBadRequest('parameter since missing')
504 since
= datetime
.fromtimestamp(float(since_
))
506 return HttpResponseBadRequest('since-value is not a valid timestamp')
508 include_actions
= parse_bool(request
.GET
.get('include_actions', False))
510 ret
= get_subscription_changes(request
.user
, device
, since
, now
)
511 domain
= RequestSite(request
).domain
513 subscriptions
= list(device
.get_subscribed_podcasts())
515 podcasts
= dict( (p
.url
, p
) for p
in subscriptions
)
516 prepare_podcast_data
= partial(get_podcast_data
, podcasts
, domain
)
518 ret
['add'] = map(prepare_podcast_data
, ret
['add'])
520 devices
= dict( (dev
.id, dev
.uid
) for dev
in request
.user
.devices
)
521 clean_action_data
= partial(clean_episode_action_data
,
522 user
=request
.user
, devices
=devices
)
524 # index subscribed podcasts by their Id for fast access
525 podcasts
= dict( (p
.get_id(), p
) for p
in subscriptions
)
526 prepare_episode_data
= partial(get_episode_data
, podcasts
, domain
,
527 clean_action_data
, include_actions
)
529 episode_updates
= get_episode_updates(request
.user
, subscriptions
, since
)
530 ret
['updates'] = map(prepare_episode_data
, episode_updates
)
532 return JsonResponse(ret
)
535 def get_episode_updates(user
, subscribed_podcasts
, since
):
536 """ Returns the episode updates since the timestamp """
538 EpisodeStatus
= namedtuple('EpisodeStatus', 'episode status action')
544 episode_jobs
= [gevent
.spawn(episodes_for_podcast
, p
, since
) for p
in
546 gevent
.joinall(episode_jobs
)
547 episodes
= chain
.from_iterable(job
.get() for job
in episode_jobs
)
550 episodes
= chain
.from_iterable(episodes_for_podcast(p
, since
) for p
551 in subscribed_podcasts
)
554 for episode
in episodes
:
555 episode_status
[episode
._id
] = EpisodeStatus(episode
, 'new', None)
560 e_action_jobs
= [gevent
.spawn(get_podcasts_episode_states
, p
, user
._id
)
561 for p
in subscribed_podcasts
]
562 gevent
.joinall(e_action_jobs
)
563 e_actions
= chain
.from_iterable(job
.get() for job
in e_action_jobs
)
566 e_actions
= [get_podcasts_episode_states(p
, user
._id
) for p
567 in subscribed_podcasts
]
570 for action
in e_actions
:
571 e_id
= action
['episode_id']
573 if e_id
in episode_status
:
574 episode
= episode_status
[e_id
].episode
576 episode
= episode_by_id(e_id
)
578 episode_status
[e_id
] = EpisodeStatus(episode
, action
['action'], action
)
580 return episode_status
.itervalues()
586 def favorites(request
, username
):
587 favorites
= favorite_episodes_for_user(request
.user
)
588 domain
= RequestSite(request
).domain
589 e_data
= lambda e
: episode_data(e
, domain
)
590 ret
= map(e_data
, favorites
)
591 return JsonResponse(ret
)
594 def sanitize_append(url
, obj_type
, sanitized_list
):
595 urls
= sanitize_url(url
, obj_type
)
597 sanitized_list
.append( (url
, urls
) )