Skip to content

Commit

Permalink
Add webpush example
Browse files Browse the repository at this point in the history
  • Loading branch information
halcy authored and halcy committed Apr 23, 2023
1 parent 34e97a9 commit 77c005c
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 0 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.rst
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ v1.8.1 (in progress)
* Add `local` and `remote` parameter to `stream_public` (thank you for the report jeafreezy)
* Fix `limit` and `lang` parameters on trend related functions not present or working (thanks for the report pdeitel)
* Fix some issues with stream reconnect handling (thanks for the report ianh)
* Added an example for how to receive webpush notifications (thanks JesseWeinstein)

v1.8.0
------
Expand Down
31 changes: 31 additions & 0 deletions docs/09_notifications.rst
Original file line number Diff line number Diff line change
Expand Up @@ -59,3 +59,34 @@ All crypto utilities require Mastodon.py's optional "webpush" feature dependenci
.. _push_subscription_generate_keys():
.. automethod:: Mastodon.push_subscription_generate_keys
.. automethod:: Mastodon.push_subscription_decrypt_push

Usage example
~~~~~~~~~~~~~

This is a minimal usage example for the push API, including a small http server to receive webpush notifications.

.. code-block:: python
api = Mastodon(...)
keys = api.push_subscription_generate_keys()
api.push_subscription_set(endpoint, keys[1], mention_events=1)
class Handler(http.server.BaseHTTPRequestHandler):
def do_POST(self):
self.send_response(201)
self.send_header('Location', '') # Mastodon doesn't seem to care about this
self.end_headers()
data = self.rfile.read(int(self.headers['content-length']))
np = api.push_subscription_decrypt_push(data, keys[0], self.headers['Encryption'], self.headers['Crypto-Key'])
n = api.notifications(id=np.notification_id)
s = n.status
self.log_message('\nFrom: %s\n%s', s.account.acct, s.content)
httpd = http.server.HTTPServer(('', 42069), Handler)
try:
httpd.serve_forever()
except KeyboardInterrupt:
pass
finally:
httpd.server_close()
api.push_subscription_delete()

0 comments on commit 77c005c

Please sign in to comment.