def main(request, username): """ API Endpoint for Device Synchronisation """ if request.method == 'GET': return JsonResponse(get_sync_status(request.user)) else: try: actions = json.loads(request.raw_post_data) except Exception as e: return HttpResponseBadRequest(str(e)) synclist = actions.get('synchronize', []) stopsync = actions.get('stop-synchronize', []) try: update_sync_status(request.user, synclist, stopsync) except ValueError as e: return HttpResponseBadRequest(str(e)) except DeviceDoesNotExist as e: return HttpResponseNotFound(str(e)) # reload user to get current sync status user = User.get(request.user._id) return JsonResponse(get_sync_status(user))
def get_tags(url): """ queries the public API of delicious.com and retrieves a dictionary of all tags that have been used for the url, with the number of users that have used each tag """ split = urlparse.urlsplit(url) if split.path == "": split = urlparse.SplitResult(split.scheme, split.netloc, "/", split.query, split.fragment) url = split.geturl() m = hashlib.md5() try: m.update(url.encode("ascii")) except: return {} url_md5 = m.hexdigest() req = "http://feeds.delicious.com/v2/json/urlinfo/%s" % url_md5 resp = urllib.urlopen(req).read() try: resp_obj = json.loads(resp) except ValueError: return {} tags = {} for o in resp_obj: if (not "top_tags" in o) or (not o["top_tags"]): return {} for tag, count in o["top_tags"].iteritems(): tags[tag] = count return tags
def episodes(request, username, version=1): version = int(version) now = datetime.now() now_ = get_timestamp(now) ua_string = request.META.get('HTTP_USER_AGENT', '') if request.method == 'POST': try: actions = json.loads(request.raw_post_data) except (JSONDecodeError, UnicodeDecodeError) as e: log('Advanced API: could not decode episode update POST data for user %s: %s' % (username, e)) return HttpResponseBadRequest() try: update_urls = update_episodes(request.user, actions, now, ua_string) except DeviceUIDException as e: import traceback log('could not update episodes for user %s: %s %s: %s' % (username, e, traceback.format_exc(), actions)) return HttpResponseBadRequest(str(e)) return JsonResponse({'timestamp': now_, 'update_urls': update_urls}) elif request.method == 'GET': podcast_url= request.GET.get('podcast', None) device_uid = request.GET.get('device', None) since_ = request.GET.get('since', None) aggregated = parse_bool(request.GET.get('aggregated', False)) try: since = datetime.fromtimestamp(float(since_)) if since_ else None except ValueError: return HttpResponseBadRequest('since-value is not a valid timestamp') if podcast_url: podcast = Podcast.for_url(podcast_url) if not podcast: raise Http404 else: podcast = None if device_uid: try: device = request.user.get_device_by_uid(device_uid) except DeviceDoesNotExist as e: return HttpResponseNotFound(str(e)) else: device = None changes = get_episode_changes(request.user, podcast, device, since, now, aggregated, version) return JsonResponse(changes)
def main(request, username, scope): def user_settings(user): return user, user def device_settings(user, uid): device = user.get_device_by_uid(uid) # get it from the user directly so that changes # to settings_obj are reflected in user (bug 1344) settings_obj = user.get_device_by_uid(uid) return user, settings_obj def podcast_settings(user, url): podcast = Podcast.for_url(url) if not podcast: raise Http404 obj = PodcastUserState.for_user_podcast(user, podcast) return obj, obj def episode_settings(user, url, podcast_url): episode = Episode.for_podcast_url(podcast_url, url) if episode is None: raise Http404 episode_state = episode.get_user_state(user) return episode_state, episode_state models = dict( account = lambda: user_settings (request.user), device = lambda: device_settings (request.user, request.GET.get('device', '')), podcast = lambda: podcast_settings(request.user, request.GET.get('podcast', '')), episode = lambda: episode_settings(request.user, request.GET.get('episode', ''), request.GET.get('podcast', '')) ) if scope not in models.keys(): return HttpResponseBadRequest('undefined scope %s' % scope) try: base_obj, settings_obj = models[scope]() except DeviceDoesNotExist as e: return HttpResponseNotFound(str(e)) if request.method == 'GET': return JsonResponse( settings_obj.settings ) elif request.method == 'POST': actions = json.loads(request.raw_post_data) ret = update_settings(settings_obj, actions) base_obj.save() return JsonResponse(ret)
def get_photo_sizes(photo_id): api_key = settings.FLICKR_API_KEY request = 'http://api.flickr.com/services/rest/?method=flickr.photos.getSizes&api_key=%s&photo_id=%s&format=json' % (api_key, photo_id) resp = urllib.urlopen(request).read() extract_re = '^jsonFlickrApi\((.*)\)$' resp_content = re.match(extract_re, resp).group(1) resp_obj = json.loads(resp_content) try: return resp_obj['sizes']['size'] except KeyError: return []
def subscriptions(request, username, device_uid): now = datetime.now() now_ = get_timestamp(now) if request.method == 'GET': try: device = request.user.get_device_by_uid(device_uid) except DeviceDoesNotExist as e: return HttpResponseNotFound(str(e)) since_ = request.GET.get('since', None) if since_ == None: return HttpResponseBadRequest('parameter since missing') try: since = datetime.fromtimestamp(float(since_)) except ValueError: return HttpResponseBadRequest('since-value is not a valid timestamp') changes = get_subscription_changes(request.user, device, since, now) return JsonResponse(changes) elif request.method == 'POST': d = get_device(request.user, device_uid, request.META.get('HTTP_USER_AGENT', '')) if not request.raw_post_data: return HttpResponseBadRequest('POST data must not be empty') actions = json.loads(request.raw_post_data) add = actions['add'] if 'add' in actions else [] rem = actions['remove'] if 'remove' in actions else [] add = filter(None, add) rem = filter(None, rem) try: update_urls = update_subscriptions(request.user, d, add, rem) except IntegrityError, e: return HttpResponseBadRequest(e) return JsonResponse({ 'timestamp': now_, 'update_urls': update_urls, })
def device(request, username, device_uid): d = get_device(request.user, device_uid, request.META.get('HTTP_USER_AGENT', '')) data = json.loads(request.raw_post_data) if 'caption' in data: if not data['caption']: return HttpResponseBadRequest('caption must not be empty') d.name = data['caption'] if 'type' in data: if not valid_devicetype(data['type']): return HttpResponseBadRequest('invalid device type %s' % data['type']) d.type = data['type'] request.user.update_device(d) return HttpResponse()
def chapters(request, username): now = datetime.utcnow() now_ = int(time.mktime(now.timetuple())) if request.method == 'POST': req = json.loads(request.raw_post_data) if not 'podcast' in req: return HttpResponseBadRequest('Podcast URL missing') if not 'episode' in req: return HttpResponseBadRequest('Episode URL missing') podcast_url = req.get('podcast', '') episode_url = req.get('episode', '') update_urls = [] # podcast sanitizing s_podcast_url = sanitize_url(podcast_url) if s_podcast_url != podcast_url: req['podcast'] = s_podcast_url update_urls.append((podcast_url, s_podcast_url)) # episode sanitizing s_episode_url = sanitize_url(episode_url, 'episode') if s_episode_url != episode_url: req['episode'] = s_episode_url update_urls.append((episode_url, s_episode_url)) if (s_podcast_url != '') and (s_episode_url != ''): try: update_chapters(req, request.user) except ParameterMissing, e: return HttpResponseBadRequest(e) return JsonResponse({ 'update_url': update_url, 'timestamp': now_ })
def parse_subscription(raw_post_data, format): if format == 'txt': urls = raw_post_data.split('\n') elif format == 'opml': begin = raw_post_data.find('<?xml') end = raw_post_data.find('</opml>') + 7 i = Importer(content=raw_post_data[begin:end]) urls = [p['url'] for p in i.items] elif format == 'json': begin = raw_post_data.find('[') end = raw_post_data.find(']') + 1 urls = json.loads(raw_post_data[begin:end]) else: return [] urls = sanitize_urls(urls) urls = filter(None, urls) urls = set(urls) return urls