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
20 from collections
import defaultdict
, namedtuple
21 from datetime
import datetime
22 from importlib
import import_module
24 import dateutil
.parser
26 from django
.http
import HttpResponse
, HttpResponseBadRequest
, Http404
, HttpResponseNotFound
27 from django
.contrib
.sites
.models
import RequestSite
28 from django
.views
.decorators
.csrf
import csrf_exempt
29 from django
.views
.decorators
.cache
import never_cache
30 from django
.conf
import settings
as dsettings
32 from mygpo
.api
.constants
import EPISODE_ACTION_TYPES
, DEVICE_TYPES
33 from mygpo
.api
.httpresponse
import JsonResponse
34 from mygpo
.api
.advanced
.directory
import episode_data
35 from mygpo
.api
.backend
import get_device
, BulkSubscribe
36 from mygpo
.utils
import format_time
, parse_bool
, get_timestamp
, \
37 parse_request_body
, normalize_feed_url
38 from mygpo
.decorators
import allowed_methods
, cors_origin
39 from mygpo
.core
.tasks
import auto_flattr_episode
40 from mygpo
.users
.models
import EpisodeAction
, \
41 DeviceDoesNotExist
, DeviceUIDException
, \
42 InvalidEpisodeActionAttributes
43 from mygpo
.users
.settings
import FLATTR_AUTO
44 from mygpo
.core
.json
import JSONDecodeError
45 from mygpo
.api
.basic_auth
import require_valid_user
, check_username
46 from mygpo
.db
.couchdb
import BulkException
, bulk_save_retry
, \
48 from mygpo
.db
.couchdb
.episode
import favorite_episodes_for_user
49 from mygpo
.db
.couchdb
.podcast
import podcast_for_url
50 from mygpo
.db
.couchdb
.podcast_state
import subscribed_podcast_ids_by_device
51 from mygpo
.db
.couchdb
.episode_state
import episode_state_for_ref_urls
, \
53 from mygpo
.db
.couchdb
.user
import set_device
57 logger
= logging
.getLogger(__name__
)
60 # keys that are allowed in episode actions
61 EPISODE_ACTION_KEYS
= ('position', 'episode', 'action', 'device', 'timestamp',
62 'started', 'total', 'podcast')
69 @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', ''))
100 return HttpResponseBadRequest('POST data must not be empty')
103 actions
= parse_request_body(request
)
104 except (JSONDecodeError
, UnicodeDecodeError, ValueError) as e
:
105 msg
= (u
'Could not decode subscription update POST data for ' +
106 'user %s: %s') % (username
,
107 request
.body
.decode('ascii', errors
='replace'))
108 logger
.exception(msg
)
109 return HttpResponseBadRequest(msg
)
111 add
= actions
['add'] if 'add' in actions
else []
112 rem
= actions
['remove'] if 'remove' in actions
else []
114 add
= filter(None, add
)
115 rem
= filter(None, rem
)
118 update_urls
= update_subscriptions(request
.user
, d
, add
, rem
)
119 except ValueError, e
:
120 return HttpResponseBadRequest(e
)
122 return JsonResponse({
124 'update_urls': update_urls
,
128 def update_subscriptions(user
, device
, add
, remove
):
132 raise ValueError('can not add and remove %s at the same time' % a
)
134 add_s
= map(normalize_feed_url
, add
)
135 rem_s
= map(normalize_feed_url
, remove
)
137 assert len(add
) == len(add_s
) and len(remove
) == len(rem_s
)
139 updated_urls
= filter(lambda (a
, b
): a
!= b
, zip(add
+ remove
, add_s
+ rem_s
))
141 add_s
= filter(None, add_s
)
142 rem_s
= filter(None, rem_s
)
144 # If two different URLs (in add and remove) have
145 # been sanitized to the same, we ignore the removal
146 rem_s
= filter(lambda x
: x
not in add_s
, rem_s
)
148 subscriber
= BulkSubscribe(user
, device
)
151 subscriber
.add_action(a
, 'subscribe')
154 subscriber
.add_action(r
, 'unsubscribe')
158 except BulkException
as be
:
159 for err
in be
.errors
:
160 loger
.error('Advanced API: %(username)s: Updating subscription for '
161 '%(podcast_url)s on %(device_uid)s failed: '
162 '%(rerror)s (%(reason)s)'.format(username
=user
.username
,
163 podcast_url
=err
.doc
, device_uid
=device
.uid
,
164 error
=err
.error
, reason
=err
.reason
)
170 def get_subscription_changes(user
, device
, since
, until
):
171 add_urls
, rem_urls
= device
.get_subscription_changes(since
, until
)
172 until_
= get_timestamp(until
)
173 return {'add': add_urls
, 'remove': rem_urls
, 'timestamp': until_
}
180 @allowed_methods(['GET', 'POST'])
182 def episodes(request
, username
, version
=1):
184 version
= int(version
)
186 now_
= get_timestamp(now
)
187 ua_string
= request
.META
.get('HTTP_USER_AGENT', '')
189 if request
.method
== 'POST':
191 actions
= parse_request_body(request
)
192 except (JSONDecodeError
, UnicodeDecodeError, ValueError) as e
:
193 msg
= ('Could not decode episode update POST data for ' +
194 'user %s: %s') % (username
,
195 request
.body
.decode('ascii', errors
='replace'))
196 logger
.exception(msg
)
197 return HttpResponseBadRequest(msg
)
199 logger
.info('start: user %s: %d actions from %s' % (request
.user
._id
, len(actions
), ua_string
))
201 # handle in background
202 if len(actions
) > dsettings
.API_ACTIONS_MAX_NONBG
:
203 bg_handler
= dsettings
.API_ACTIONS_BG_HANDLER
204 if bg_handler
is not None:
206 modname
, funname
= bg_handler
.rsplit('.', 1)
207 mod
= import_module(modname
)
208 fun
= getattr(mod
, funname
)
210 fun(request
.user
, actions
, now
, ua_string
)
212 # TODO: return 202 Accepted
213 return JsonResponse({'timestamp': now_
, 'update_urls': []})
217 update_urls
= update_episodes(request
.user
, actions
, now
, ua_string
)
218 except DeviceUIDException
as e
:
219 logger
.warn('invalid device UID while uploading episode actions for user %s', username
)
220 return HttpResponseBadRequest(str(e
))
222 except InvalidEpisodeActionAttributes
as e
:
223 logger
.exception('invalid episode action attributes while uploading episode actions for user %s' % (username
,))
224 return HttpResponseBadRequest(str(e
))
226 logger
.info('done: user %s: %d actions from %s' % (request
.user
._id
, len(actions
), ua_string
))
227 return JsonResponse({'timestamp': now_
, 'update_urls': update_urls
})
229 elif request
.method
== 'GET':
230 podcast_url
= request
.GET
.get('podcast', None)
231 device_uid
= request
.GET
.get('device', None)
232 since_
= request
.GET
.get('since', None)
233 aggregated
= parse_bool(request
.GET
.get('aggregated', False))
236 since
= int(since_
) if since_
else None
238 return HttpResponseBadRequest('since-value is not a valid timestamp')
241 podcast
= podcast_for_url(podcast_url
)
250 device
= request
.user
.get_device_by_uid(device_uid
)
251 except DeviceDoesNotExist
as e
:
252 return HttpResponseNotFound(str(e
))
257 changes
= get_episode_changes(request
.user
, podcast
, device
, since
,
258 now_
, aggregated
, version
)
260 return JsonResponse(changes
)
264 def convert_position(action
):
265 """ convert position parameter for API 1 compatibility """
266 pos
= getattr(action
, 'position', None)
268 action
.position
= format_time(pos
)
273 def get_episode_changes(user
, podcast
, device
, since
, until
, aggregated
, version
):
275 devices
= dict( (dev
.id, dev
.uid
) for dev
in user
.devices
)
278 if podcast
is not None:
279 args
['podcast_id'] = podcast
.get_id()
281 if device
is not None:
282 args
['device_id'] = device
.id
284 actions
= get_episode_actions(user
._id
, since
, until
, **args
)
287 actions
= imap(convert_position
, actions
)
289 clean_data
= partial(clean_episode_action_data
,
290 user
=user
, devices
=devices
)
292 actions
= map(clean_data
, actions
)
293 actions
= filter(None, actions
)
296 actions
= dict( (a
['episode'], a
) for a
in actions
).values()
298 return {'actions': actions
, 'timestamp': until
}
303 def clean_episode_action_data(action
, user
, devices
):
305 if None in (action
.get('podcast', None), action
.get('episode', None)):
308 if 'device_id' in action
:
309 device_id
= action
['device_id']
310 device_uid
= devices
.get(device_id
)
312 action
['device'] = device_uid
314 del action
['device_id']
316 # remove superfluous keys
317 for x
in action
.keys():
318 if x
not in EPISODE_ACTION_KEYS
:
321 # set missing keys to None
322 for x
in EPISODE_ACTION_KEYS
:
326 if action
['action'] != 'play':
327 if 'position' in action
:
328 del action
['position']
330 if 'total' in action
:
333 if 'started' in action
:
334 del action
['started']
336 if 'playmark' in action
:
337 del action
['playmark']
340 action
['position'] = action
.get('position', False) or 0
348 def update_episodes(user
, actions
, now
, ua_string
):
351 grouped_actions
= defaultdict(list)
353 # group all actions by their episode
354 for action
in actions
:
356 podcast_url
= action
['podcast']
357 podcast_url
= sanitize_append(podcast_url
, update_urls
)
358 if podcast_url
== '':
361 episode_url
= action
['episode']
362 episode_url
= sanitize_append(episode_url
, update_urls
)
363 if episode_url
== '':
366 act
= parse_episode_action(action
, user
, update_urls
, now
, ua_string
)
367 grouped_actions
[ (podcast_url
, episode_url
) ].append(act
)
370 auto_flattr_episodes
= []
372 # Prepare the updates for each episode state
375 for (p_url
, e_url
), action_list
in grouped_actions
.iteritems():
376 episode_state
= episode_state_for_ref_urls(user
, p_url
, e_url
)
378 if any(a
['action'] == 'play' for a
in actions
):
379 auto_flattr_episodes
.append(episode_state
.episode
)
381 fun
= partial(update_episode_actions
, action_list
=action_list
)
382 obj_funs
.append( (episode_state
, fun
) )
384 udb
= get_userdata_database()
385 bulk_save_retry(obj_funs
, udb
)
387 if user
.get_wksetting(FLATTR_AUTO
):
388 for episode_id
in auto_flattr_episodes
:
389 auto_flattr_episode
.delay(user
, episode_id
)
394 def update_episode_actions(episode_state
, action_list
):
395 """ Adds actions to the episode state and saves if necessary """
397 len1
= len(episode_state
.actions
)
398 episode_state
.add_actions(action_list
)
400 if len(episode_state
.actions
) == len1
:
407 def parse_episode_action(action
, user
, update_urls
, now
, ua_string
):
408 action_str
= action
.get('action', None)
409 if not valid_episodeaction(action_str
):
410 raise Exception('invalid action %s' % action_str
)
412 new_action
= EpisodeAction()
414 new_action
.action
= action
['action']
416 if action
.get('device', False):
417 device
= get_device(user
, action
['device'], ua_string
)
418 new_action
.device
= device
.id
420 if action
.get('timestamp', False):
421 new_action
.timestamp
= dateutil
.parser
.parse(action
['timestamp'])
423 new_action
.timestamp
= now
424 new_action
.timestamp
= new_action
.timestamp
.replace(microsecond
=0)
426 new_action
.upload_timestamp
= get_timestamp(now
)
428 new_action
.started
= action
.get('started', None)
429 new_action
.playmark
= action
.get('position', None)
430 new_action
.total
= action
.get('total', None)
439 # Workaround for mygpoclient 1.0: It uses "PUT" requests
440 # instead of "POST" requests for uploading device settings
441 @allowed_methods(['POST', 'PUT'])
443 def device(request
, username
, device_uid
):
444 d
= get_device(request
.user
, device_uid
,
445 request
.META
.get('HTTP_USER_AGENT', ''))
448 data
= parse_request_body(request
)
449 except (JSONDecodeError
, UnicodeDecodeError, ValueError) as e
:
450 msg
= ('Could not decode device update POST data for ' +
451 'user %s: %s') % (username
,
452 request
.body
.decode('ascii', errors
='replace'))
453 logger
.exception(msg
)
454 return HttpResponseBadRequest(msg
)
456 if 'caption' in data
:
457 if not data
['caption']:
458 return HttpResponseBadRequest('caption must not be empty')
459 d
.name
= data
['caption']
462 if not valid_devicetype(data
['type']):
463 return HttpResponseBadRequest('invalid device type %s' % data
['type'])
464 d
.type = data
['type']
467 set_device(request
.user
, d
)
469 return HttpResponse()
472 def valid_devicetype(type):
473 for t
in DEVICE_TYPES
:
478 def valid_episodeaction(type):
479 for t
in EPISODE_ACTION_TYPES
:
489 @allowed_methods(['GET'])
491 def devices(request
, username
):
492 devices
= filter(lambda d
: not d
.deleted
, request
.user
.devices
)
493 devices
= map(device_data
, devices
)
494 return JsonResponse(devices
)
497 def device_data(device
):
500 caption
= device
.name
,
502 subscriptions
= len(subscribed_podcast_ids_by_device(device
)),
510 def favorites(request
, username
):
511 favorites
= favorite_episodes_for_user(request
.user
)
512 domain
= RequestSite(request
).domain
513 e_data
= lambda e
: episode_data(e
, domain
)
514 ret
= map(e_data
, favorites
)
515 return JsonResponse(ret
)
518 def sanitize_append(url
, sanitized_list
):
519 urls
= normalize_feed_url(url
)
521 sanitized_list
.append( (url
, urls
or '') )