|
- # (A) INIT
- # (A1) LOAD MODULES
- from flask import Flask, render_template, request, make_response, send_from_directory
- from pywebpush import webpush, WebPushException
- import json
- import sys
- import time
- import threading
-
- # (A2) FLASK SETTINGS + INIT - CHANGE TO YOUR OWN!
- HOST_NAME = "localhost"
- HOST_NAME = "0.0.0.0"
- HOST_PORT = 80
- VAPID_SUBJECT = "mailto:your@email.com"
- VAPID_PRIVATE = "YOUR-PRIVATE-KEY"
- app = Flask(__name__,
- static_folder='../static',
- template_folder='.',
- )
- app.debug = True
- #app.config['EXPLAIN_TEMPLATE_LOADING'] = True
-
- # (B) VIEWS
- # (B1) "LANDING PAGE"
- @app.route("/")
- def index():
- return render_template("S2_perm_sw.html")
-
- # (B2) SERVICE WORKER
- @app.route("/S3_sw.js")
- def sw():
- import sys
- print(repr(app.static_folder), file=sys.stderr)
- response = make_response(send_from_directory(app.static_folder, "S3_sw.js"))
- return response
-
- threadlist = []
-
- def donotify(sub, sleep=10):
- global threadlist
- for t in threadlist:
- t.join(0)
- threadlist = [ t for t in threadlist if t.is_alive() ]
-
- if sleep:
- time.sleep(sleep)
-
- print('sending notification...')
- try:
- # Mozilla appears to not require the vapid key.
- # Chrome requires the vapid key.
- if True:
- kwargs = dict(vapid_private_key=None,
- #vapid_claims=None,
- )
- else:
- kwargs = dict(vapid_private_key=VAPID_PRIVATE,
- vapid_claims={ "sub": VAPID_SUBJECT },
- )
-
- webpush(
- subscription_info = sub,
- data = json.dumps({
- "title" : "Welcome!",
- "body" : "Yes, it works!",
- "icon" : "static/i-ico.png",
- "image" : "static/i-banner.png"
- }), **kwargs
- )
- print('done')
- except WebPushException as ex:
- print(ex)
-
- t = threading.Thread(target=donotify, args=(sub,))
- t.run()
- threadlist.append(t)
-
-
- # (B3) PUSH DEMO
- @app.route("/push", methods=["POST"])
- def push():
- # (B3-1) GET SUBSCRIBER
- sub = json.loads(request.form["sub"])
- import sys
- print('sub:', repr(json.dumps(sub)), file=sys.stderr)
-
- # (B3-2) TEST PUSH NOTIFICATION
- result = "OK"
- donotify(sub, 1)
- return result
-
- # (C) START
- if __name__ == "__main__":
- if len(sys.argv) == 2:
- HOST_PORT = int(sys.argv[1])
- app.run(HOST_NAME, HOST_PORT)
|