[PubSub] add podcast to pubsub subscription
[mygpo.git] / mygpo / pubsub / __init__.py
blob1dda2e59a451a336d43aaedf21ad843f06d5d405
1 # -*- coding: utf-8 -*-
3 # PubSubHubbub subscriber mygpo
7 import urllib
8 import urllib2
9 import logging
11 from django.core.urlresolvers import reverse
13 from mygpo.utils import random_token
14 from mygpo.pubsub.models import HubSubscription, SubscriptionError
16 logger = logging.getLogger(__name__)
19 def subscribe(podcast, feedurl, huburl, base_url, mode='subscribe'):
20 """ Subscribe to the feed at a Hub """
22 logger.info('subscribing for {feed} at {hub}'.format(feed=feedurl,
23 hub=huburl))
24 verify = 'sync'
26 token_max_len = HubSubscription._meta.get_field('verify_token').max_length
27 subscription, created = HubSubscription.objects.get_or_create(
28 topic_url=feedurl,
29 defaults={
30 'verify_token': random_token(token_max_len),
31 'mode': '',
32 'podcast': podcast,
36 if subscription.mode == mode:
37 if subscription.verified:
38 logger.info('subscription already exists')
39 return
41 else:
42 logger.info('subscription exists but has wrong mode: ' +
43 'old: %(oldmode)s, new: %(newmode)s. Overwriting.' %
44 dict(oldmode=subscription.mode, newmode=mode))
46 subscription.topic_url = feedurl
47 subscription.mode = mode
48 subscription.save()
50 data = {
51 "hub.callback": callback_url(feedurl, base_url),
52 "hub.mode": mode,
53 "hub.topic": feedurl,
54 "hub.verify": verify,
55 "hub.verify_token": subscription.verify_token,
58 data = urllib.urlencode(data.items())
59 logger.debug('sending request: %s' % repr(data))
61 resp = None
63 try:
64 resp = urllib2.urlopen(huburl, data)
66 except urllib2.HTTPError, e:
67 if e.code != 204: # we actually expect a 204 return code
68 msg = 'Could not send subscription to Hub: HTTP Error %d: %s' % \
69 (e.code, e.reason)
70 logger.warn(msg)
71 raise SubscriptionError(msg)
73 except Exception, e:
74 msg = 'Could not send subscription to Hub: %s' % repr(e)
75 logger.warn(msg)
76 raise SubscriptionError(msg)
78 if resp:
79 status = resp.code
80 if status != 204:
81 logger.warn('received incorrect status %d' % status)
82 raise SubscriptionError('Subscription has not been accepted by '
83 'the Hub')
86 def callback_url(feedurl, base_url):
87 callback = reverse('pubsub-subscribe')
88 param = urllib.urlencode([('url', feedurl)])
89 return '{base}{callback}?{param}'.format(base=base_url, callback=callback,
90 param=param)