aboutsummaryrefslogtreecommitdiff
path: root/stream/pshb.py
blob: 929a4fe36a962805b5136573d68509e2b52335fc (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
#  gLifestream Copyright (C) 2010 Wojciech Polak
#
#  This program is free software; you can redistribute it and/or modify it
#  under the terms of the GNU General Public License as published by the
#  Free Software Foundation; either version 3 of the License, or (at your
#  option) any later version.
#
#  This program is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU General Public License for more details.
#
#  You should have received a copy of the GNU General Public License along
#  with this program.  If not, see <http://www.gnu.org/licenses/>.

import hmac
import hashlib
import urlparse
from datetime import timedelta
from django.conf import settings
from django.core import urlresolvers
from glifestream.utils import httpclient
from glifestream.utils.time import now
from glifestream.stream.models import Pshb


def subscribe(service, verbose=False):
    try:
        webfeed = __import__('glifestream.apis.webfeed', {}, {}, ['API'])
    except ImportError:
        return {'rc': 1, 'error': 'ImportError apis.webfeed'}
    webfeed_api = getattr(webfeed, 'API')

    try:
        mod = __import__('glifestream.apis.%s' % service.api, {}, {}, ['API'])
    except ImportError:
        return {'rc': 1, 'error': 'ImportError apis.%s' % service.api}
    mod_api = getattr(mod, 'API')
    api = mod_api(service, False, False)

    if not isinstance(api, webfeed_api):
        return {'rc': 1, 'error': 'PSHB is not supported by this API.'}

    api.fetch_only = True
    api.run()
    if api.fp_error:
        return {'rc': 1, 'error': api.fp.bozo_exception}

    hub = None
    for link in api.fp.feed.links:
        if link.rel == 'hub':
            hub = link.href
            break
    if not hub:
        return {'rc': 2}

    secret = hashlib.md5('%s:%d/%s/%s' % (hub, service.id, api.url,
                                          settings.SECRET_KEY)).hexdigest()
    hash = hashlib.sha1(secret).hexdigest()[0:20]
    secret = secret[0:8] if 'https://' in hub else None

    save_db = False
    try:
        db = Pshb.objects.get(hash=hash, service=service)
    except Pshb.DoesNotExist:
        db = Pshb(hash=hash, service=service, hub=hub, secret=secret)
        save_db = True

    topic = __get_absolute_url(
        urlresolvers.reverse('index')) + '?format=atom'
    callback = __get_absolute_url(urlresolvers.reverse('pshb', args=[hash]))

    if settings.PSHB_HTTPS_CALLBACK:
        callback = callback.replace('http://', 'https://')

    data = {'hub.mode': 'subscribe',
            'hub.topic': topic,
            'hub.callback': callback,
            'hub.verify': 'async'}
    if secret:
        data['hub.secret'] = secret

    try:
        r = httpclient.urlopen(hub, data)
        if verbose:
            print 'Response code: %d' % r.code
        if save_db:
            db.save()
        return {'hub': hub, 'rc': r.code}
    except (IOError, httpclient.HTTPError), e:
        error = ''
        if hasattr(e, 'read'):
            error = e.read()
        if verbose:
            print '%s, Response: "%s"' % (e, error)
        return {'hub': hub, 'rc': error}


def unsubscribe(id, verbose=False):
    try:
        db = Pshb.objects.get(id=id)
    except Pshb.DoesNotExist:
        return {'rc': 1}

    topic = __get_absolute_url(
        urlresolvers.reverse('index')) + '?format=atom'
    callback = __get_absolute_url(
        urlresolvers.reverse('pshb', args=[db.hash]))

    if settings.PSHB_HTTPS_CALLBACK:
        callback = callback.replace('http://', 'https://')

    data = {'hub.mode': 'unsubscribe',
            'hub.topic': topic,
            'hub.callback': callback,
            'hub.verify': 'sync'}

    try:
        r = httpclient.urlopen(db.hub, data)
        if verbose:
            print 'Response code: %d' % r.code
        return {'hub': db.hub, 'rc': r.code}
    except (IOError, httpclient.HTTPError), e:
        error = ''
        if hasattr(e, 'read'):
            error = e.read()
        if verbose:
            print '%s, Response: "%s"' % (e, error)
        return {'hub': db.hub, 'rc': error}


def verify(id, GET):
    mode = GET.get('hub.mode', None)
    lease_seconds = GET.get('hub.lease_seconds', None)

    if mode == 'subscribe':
        try:
            db = Pshb.objects.get(hash=id)
            db.verified = True
            if lease_seconds:
                db.expire = now() + timedelta(seconds=int(lease_seconds))
            db.save()
        except Pshb.DoesNotExist:
            return False
    elif mode == 'unsubscribe':
        try:
            Pshb.objects.get(hash=id).delete()
        except Pshb.DoesNotExist:
            return False

    return GET.get('hub.challenge', '')


def publish(hubs=None, verbose=False):
    hubs = hubs or settings.PSHB_HUBS
    url = __get_absolute_url(urlresolvers.reverse('index')) + '?format=atom'
    if 'localhost' in url:
        return
    for hub in hubs:
        hub = hub.replace('https://', 'http://')  # it's just a ping.
        data = {'hub.mode': 'publish', 'hub.url': url}
        try:
            r = httpclient.urlopen(hub, data, timeout=7)
            if verbose:
                if r.code == 204:
                    print '%s: Successfully pinged.' % hub
                else:
                    print '%s: Pinged and got %d.' % (hub, r.code)
        except (IOError, httpclient.HTTPError), e:
            if hasattr(e, 'code') and e.code == 204:
                continue
            if verbose:
                error = ''
                if hasattr(e, 'read'):
                    error = e.read()
                print '%s, Response: "%s"' % (e, error)


def accept_payload(id, payload, meta={}):
    try:
        db = Pshb.objects.get(hash=id)
    except Pshb.DoesNotExist:
        return False
    if db.secret:
        s = hmac.new(str(db.secret), payload, hashlib.sha1).hexdigest()
        signature = meta.get('HTTP_X_HUB_SIGNATURE', None)
        if signature and 'sha1=' in signature:
            signature = signature[5:]
        if s != signature:
            return False  # signature mismatch
    try:
        mod = __import__('glifestream.apis.%s' %
                         db.service.api, {}, {}, ['API'])
    except ImportError:
        return False
    mod_api = getattr(mod, 'API')
    api = mod_api(db.service, False, False)
    api.payload = payload
    api.run()
    return True


def renew_subscriptions(force=False, verbose=False):
    subscriptions = Pshb.objects.all().order_by('id')
    for s in subscriptions:
        if s.expire:
            d = s.expire - timedelta(days=7)
            if now() > d or force:
                subscribe(s.service, verbose)


def list(raw=False):
    subscriptions = Pshb.objects.all().order_by('id')
    if raw:
        return subscriptions
    for s in subscriptions:
        print '%4d V=%d hash=%s, hub=%s, topic=%s, expire=%s' % \
            (s.id, s.verified, s.hash, s.hub, s.service.url, s.expire)


def __get_absolute_url(path=''):
    url = urlparse.urlsplit(settings.BASE_URL)
    return '%s://%s%s' % (url.scheme, url.netloc, path)

Return to:

Send suggestions and report system problems to the System administrator.