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
21 from datetime
import datetime
22 from importlib
import import_module
24 import dateutil
.parser
26 from django
.http
import (HttpResponse
, HttpResponseBadRequest
, Http404
,
27 HttpResponseNotFound
, )
28 from django
.core
.exceptions
import ValidationError
29 from django
.contrib
.sites
.models
import RequestSite
30 from django
.views
.decorators
.csrf
import csrf_exempt
31 from django
.views
.decorators
.cache
import never_cache
32 from django
.conf
import settings
as dsettings
33 from django
.shortcuts
import get_object_or_404
35 from mygpo
.podcasts
.models
import Podcast
, Episode
36 from mygpo
.subscriptions
.models
import Subscription
37 from mygpo
.api
.constants
import EPISODE_ACTION_TYPES
38 from mygpo
.api
.httpresponse
import JsonResponse
39 from mygpo
.api
.advanced
.directory
import episode_data
40 from mygpo
.api
.backend
import get_device
41 from mygpo
.utils
import format_time
, parse_bool
, get_timestamp
, \
42 parse_request_body
, normalize_feed_url
43 from mygpo
.decorators
import allowed_methods
, cors_origin
44 from mygpo
.history
.models
import EpisodeHistoryEntry
45 from mygpo
.core
.tasks
import auto_flattr_episode
46 from mygpo
.users
.models
import Client
, InvalidEpisodeActionAttributes
47 from mygpo
.users
.settings
import FLATTR_AUTO
48 from mygpo
.favorites
.models
import FavoriteEpisode
49 from mygpo
.core
.json
import JSONDecodeError
50 from mygpo
.api
.basic_auth
import require_valid_user
, check_username
54 logger
= logging
.getLogger(__name__
)
57 # keys that are allowed in episode actions
58 EPISODE_ACTION_KEYS
= ('position', 'episode', 'action', 'device', 'timestamp',
59 'started', 'total', 'podcast')
66 @allowed_methods(['GET', 'POST'])
68 def episodes(request
, username
, version
=1):
70 version
= int(version
)
71 now
= datetime
.utcnow()
72 now_
= get_timestamp(now
)
73 ua_string
= request
.META
.get('HTTP_USER_AGENT', '')
75 if request
.method
== 'POST':
77 actions
= parse_request_body(request
)
78 except (JSONDecodeError
, UnicodeDecodeError, ValueError) as e
:
79 msg
= ('Could not decode episode update POST data for ' +
80 'user %s: %s') % (username
,
81 request
.body
.decode('ascii', errors
='replace'))
82 logger
.warn(msg
, exc_info
=True)
83 return HttpResponseBadRequest(msg
)
85 logger
.info('start: user %s: %d actions from %s' % (request
.user
, len(actions
), ua_string
))
87 # handle in background
88 if len(actions
) > dsettings
.API_ACTIONS_MAX_NONBG
:
89 bg_handler
= dsettings
.API_ACTIONS_BG_HANDLER
90 if bg_handler
is not None:
92 modname
, funname
= bg_handler
.rsplit('.', 1)
93 mod
= import_module(modname
)
94 fun
= getattr(mod
, funname
)
96 fun(request
.user
, actions
, now
, ua_string
)
98 # TODO: return 202 Accepted
99 return JsonResponse({'timestamp': now_
, 'update_urls': []})
103 update_urls
= update_episodes(request
.user
, actions
, now
, ua_string
)
104 except ValidationError
as e
:
105 logger
.warn(u
'Validation Error while uploading episode actions for user %s: %s', username
, unicode(e
))
106 return HttpResponseBadRequest(str(e
))
108 except InvalidEpisodeActionAttributes
as e
:
109 msg
= 'invalid episode action attributes while uploading episode actions for user %s' % (username
,)
110 logger
.warn(msg
, exc_info
=True)
111 return HttpResponseBadRequest(str(e
))
113 logger
.info('done: user %s: %d actions from %s' % (request
.user
, len(actions
), ua_string
))
114 return JsonResponse({'timestamp': now_
, 'update_urls': update_urls
})
116 elif request
.method
== 'GET':
117 podcast_url
= request
.GET
.get('podcast', None)
118 device_uid
= request
.GET
.get('device', None)
119 since_
= request
.GET
.get('since', None)
120 aggregated
= parse_bool(request
.GET
.get('aggregated', False))
123 since
= int(since_
) if since_
else None
124 if since
is not None:
125 since
= datetime
.utcfromtimestamp(since
)
127 return HttpResponseBadRequest('since-value is not a valid timestamp')
130 podcast
= get_object_or_404(Podcast
, urls__url
=podcast_url
)
138 device
= user
.client_set
.get(uid
=device_uid
)
139 except Client
.DoesNotExist
as e
:
140 return HttpResponseNotFound(str(e
))
145 changes
= get_episode_changes(request
.user
, podcast
, device
, since
,
146 now
, aggregated
, version
)
148 return JsonResponse(changes
)
152 def convert_position(action
):
153 """ convert position parameter for API 1 compatibility """
154 pos
= getattr(action
, 'position', None)
156 action
.position
= format_time(pos
)
161 def get_episode_changes(user
, podcast
, device
, since
, until
, aggregated
, version
):
163 history
= EpisodeHistoryEntry
.objects
.filter(user
=user
,
167 history
= history
.filter(timestamp__gte
=since
)
169 if podcast
is not None:
170 history
= history
.filter(episode__podcast
=podcast
)
172 if device
is not None:
173 history
= history
.filter(client
=device
)
176 history
= imap(convert_position
, history
)
178 actions
= [episode_action_json(a
, user
) for a
in history
]
181 actions
= dict( (a
['episode'], a
) for a
in actions
).values()
183 return {'actions': actions
, 'timestamp': until
}
186 def episode_action_json(history
, user
):
189 'podcast': history
.podcast_ref_url
or history
.episode
.podcast
.url
,
190 'episode': history
.episode_ref_url
or history
.episode
.url
,
191 'action': history
.action
,
192 'timestamp': history
.timestamp
.isoformat(),
196 action
['device'] = history
.client
.uid
198 if history
.action
== EpisodeHistoryEntry
.PLAY
:
199 action
['started'] = history
.started
200 action
['position'] = history
.stopped
# TODO: check "playmark"
201 action
['total'] = history
.total
206 def update_episodes(user
, actions
, now
, ua_string
):
208 auto_flattr
= user
.profile
.settings
.get_wksetting(FLATTR_AUTO
)
210 # group all actions by their episode
211 for action
in actions
:
213 podcast_url
= action
['podcast']
214 podcast_url
= sanitize_append(podcast_url
, update_urls
)
215 if podcast_url
== '':
218 episode_url
= action
['episode']
219 episode_url
= sanitize_append(episode_url
, update_urls
)
220 if episode_url
== '':
223 podcast
= Podcast
.objects
.get_or_create_for_url(podcast_url
)
224 episode
= Episode
.objects
.get_or_create_for_url(podcast
, episode_url
)
226 # parse_episode_action returns a EpisodeHistoryEntry obj
227 history
= parse_episode_action(action
, user
, update_urls
, now
,
230 EpisodeHistoryEntry
.create_entry(user
, episode
, history
.action
,
231 history
.client
, history
.timestamp
,
232 history
.started
, history
.stopped
,
233 history
.total
, podcast_url
,
236 if history
.action
== EpisodeHistoryEntry
.PLAY
and auto_flattr
:
237 auto_flattr_episode
.delay(user
, episode
.id)
242 def parse_episode_action(action
, user
, update_urls
, now
, ua_string
):
243 action_str
= action
.get('action', None)
244 if not valid_episodeaction(action_str
):
245 raise Exception('invalid action %s' % action_str
)
247 history
= EpisodeHistoryEntry()
249 history
.action
= action
['action']
251 if action
.get('device', False):
252 client
= get_device(user
, action
['device'], ua_string
)
253 history
.client
= client
255 if action
.get('timestamp', False):
256 history
.timestamp
= dateutil
.parser
.parse(action
['timestamp'])
258 history
.timestamp
= now
260 history
.started
= action
.get('started', None)
261 history
.stopped
= action
.get('position', None)
262 history
.total
= action
.get('total', None)
271 # Workaround for mygpoclient 1.0: It uses "PUT" requests
272 # instead of "POST" requests for uploading device settings
273 @allowed_methods(['POST', 'PUT'])
275 def device(request
, username
, device_uid
):
276 d
= get_device(request
.user
, device_uid
,
277 request
.META
.get('HTTP_USER_AGENT', ''))
280 data
= parse_request_body(request
)
281 except (JSONDecodeError
, UnicodeDecodeError, ValueError) as e
:
282 msg
= ('Could not decode device update POST data for ' +
283 'user %s: %s') % (username
,
284 request
.body
.decode('ascii', errors
='replace'))
285 logger
.warn(msg
, exc_info
=True)
286 return HttpResponseBadRequest(msg
)
288 if 'caption' in data
:
289 if not data
['caption']:
290 return HttpResponseBadRequest('caption must not be empty')
291 d
.name
= data
['caption']
294 if not valid_devicetype(data
['type']):
295 return HttpResponseBadRequest('invalid device type %s' % data
['type'])
296 d
.type = data
['type']
299 return HttpResponse()
302 def valid_devicetype(type):
303 for t
in Client
.TYPES
:
308 def valid_episodeaction(type):
309 for t
in EPISODE_ACTION_TYPES
:
319 @allowed_methods(['GET'])
321 def devices(request
, username
):
323 clients
= user
.client_set
.filter(deleted
=False)
324 client_data
= [get_client_data(user
, client
) for client
in clients
]
325 return JsonResponse(client_data
)
328 def get_client_data(user
, client
):
331 caption
= client
.name
,
333 subscriptions
= Subscription
.objects
.filter(user
=user
, client
=client
)\
342 def favorites(request
, username
):
343 favorites
= FavoriteEpisode
.episodes_for_user(request
.user
)
344 domain
= RequestSite(request
).domain
345 e_data
= lambda e
: episode_data(e
, domain
)
346 ret
= map(e_data
, favorites
)
347 return JsonResponse(ret
)
350 def sanitize_append(url
, sanitized_list
):
351 urls
= normalize_feed_url(url
)
353 sanitized_list
.append( (url
, urls
or '') )