]> git.gir.st - subscriptionfeed.git/blob - app/webhooks.py
fix old videos from showing up in subscriptions
[subscriptionfeed.git] / app / webhooks.py
1 """
2 This is the webhook server that interfaces with Google's WebSub (formerly pubsubhubbub) server. This is its own server, so it can live on a different host than the frontend.
3 """
4
5 #TODO: fold update-websub.py into this?
6
7 import time
8 import sqlite3
9 from flask import Flask, request
10 from urllib.parse import parse_qs
11
12 from common import *
13
14 app = Flask(__name__)
15
16 @app.route('/websub/v1/<int:timestamp>/<nonce>/<subject>/<sig>', methods=["GET"])
17 def websub(timestamp, nonce, subject, sig):
18 mode = request.args.get('hub.mode', '')
19 topic = request.args.get('hub.topic', '')
20 challenge = request.args.get('hub.challenge', '')
21 until = int(request.args.get('hub.lease_seconds', '0'))
22
23 channel_id = parse_qs(topic.split('?')[1]).get('channel_id', [''])[0] # TODO: support playlists # XXX: can raise indexerror
24 if not channel_id:
25 return '', 400
26
27 if time.time() - timestamp > int(cf['websub']['lease']):
28 return '', 400
29 # TODO: implement hmac check: return '',400 unless hmac_sha1_hex("$timestamp/$nonce", $HMACKEY) eq $sig
30
31 if mode != "subscribe":
32 return '', 200
33 # Note: channels are not purged from the websub dbtable.
34
35 with sqlite3.connect(cf['global']['database']) as conn:
36 c = conn.cursor()
37 c.execute("""
38 INSERT OR REPLACE INTO websub (channel_id, subscribed_until)
39 VALUES (?, datetime(?, 'unixepoch'))
40 """, (channel_id, time.time()+until))
41 return challenge, 200
42
43 @app.route('/websub/v1/<int:timestamp>/<nonce>/<subject>/<sig>', methods=["POST"])
44 def websub_post(timestamp, nonce, subject, sig):
45 # TODO: implement hmac check: return '',400 unless hmac_sha1_hex("$timestamp/$nonce", $HMACKEY) eq $sig
46 # todo: # say 400 and exit unless hmac_sha1_hex($body, $HMACKEY) eq $ENV{X-Hub-Signature }
47
48 with sqlite3.connect(cf['global']['database']) as conn:
49 c = conn.cursor()
50 ok = update_channel(conn, request.data)
51 if not ok:
52 with open('/tmp/websub-subscriptions.err', 'a') as f:
53 f.write(f"<!-- {time.ctime()} ({int(time.time())}) -->\n{xmlfeed}\n")
54 return '', 200
55
56 if __name__ == '__main__':
57 app.run(debug=True)
Imprint / Impressum