1 # -*- coding: utf-8 -*-
3 # PubSubHubbub subscriber mygpo
11 from couchdbkit
.ext
.django
import *
12 from django
.core
.urlresolvers
import reverse
14 from mygpo
.pubsub
.models
import Subscription
, SubscriptionError
15 from mygpo
.db
.couchdb
.pubsub
import subscription_for_topic
17 logger
= logging
.getLogger(__name__
)
20 def subscribe(feedurl
, huburl
, base_url
, mode
='subscribe'):
21 """ Subscribe to the feed at a Hub """
23 logger
.info('subscribing for {feed} at {hub}'.format(feed
=feedurl
,
27 subscription
= subscription_for_topic(feedurl
)
28 if subscription
is None:
29 subscription
= Subscription()
30 subscription
.verify_token
= random_token()
32 if subscription
.mode
== mode
:
33 if subscription
.verified
:
34 logger
.info('subscription already exists')
38 logger
.info('subscription exists but has wrong mode: ' +
39 'old: %(oldmode)s, new: %(newmode)s. Overwriting.' %
40 dict(oldmode
=subscription
.mode
, newmode
=mode
))
42 subscription
.url
= feedurl
43 subscription
.mode
= mode
47 "hub.callback": callback_url(feedurl
, base_url
),
51 "hub.verify_token": subscription
.verify_token
,
54 data
= urllib
.urlencode(data
.items())
55 logger
.debug('sending request: %s' % repr(data
))
60 resp
= urllib2
.urlopen(huburl
, data
)
61 except urllib2
.HTTPError
, e
:
62 if e
.code
!= 204: # we actually expect a 204 return code
63 msg
= 'Could not send subscription to Hub: HTTP Error %d: %s' % (e
.code
, e
.reason
)
65 raise SubscriptionError(msg
)
68 msg
= 'Could not send subscription to Hub: %s' % repr(e
)
70 raise SubscriptionError(msg
)
75 logger
.error('received incorrect status %d' % status
)
76 raise SubscriptionError('Subscription has not been accepted by '
80 def callback_url(feedurl
, base_url
):
81 callback
= reverse('pubsub-subscribe')
82 param
= urllib
.urlencode([('url', feedurl
)])
83 return '{base}{callback}?{param}'.format(base
=base_url
, callback
=callback
,
87 def random_token(length
=32):
90 return "".join(random
.sample(string
.letters
+string
.digits
, length
))