1 # -*- coding: utf-8 -*-
3 # PubSubHubbub subscriber mygpo
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
,
26 token_max_len
= HubSubscription
._meta
.get_field('verify_token').max_length
27 subscription
, created
= HubSubscription
.objects
.get_or_create(
30 'verify_token': random_token(token_max_len
),
36 if subscription
.mode
== mode
:
37 if subscription
.verified
:
38 logger
.info('subscription already exists')
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
51 "hub.callback": callback_url(feedurl
, base_url
),
55 "hub.verify_token": subscription
.verify_token
,
58 data
= urllib
.urlencode(data
.items())
59 logger
.debug('sending request: %s' % repr(data
))
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' % \
71 raise SubscriptionError(msg
)
74 msg
= 'Could not send subscription to Hub: %s' % repr(e
)
76 raise SubscriptionError(msg
)
81 logger
.warn('received incorrect status %d' % status
)
82 raise SubscriptionError('Subscription has not been accepted by '
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
,