Skip to content

Commit c5507b2

Browse files
authored
chore: Jul 2022 update (#148)
Now that this is one of the Critical Projects (thanks?) I should update it to be more modern, clean up some of the crap, and run it through flake8 at least.
1 parent 992efed commit c5507b2

File tree

6 files changed

+72
-42
lines changed

6 files changed

+72
-42
lines changed

CHANGELOG.md

+1-1
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44
bug: accept all VAPID key instances (thanks @mthu)
55

66
## 1.13.0 (2021-03-15)
7-
Support requests_session param in webpush fn too
7+
Support requests_session param in webpush fn too (thanks @bwindels)
88

99
## 1.12.0 (2021-03-15)
1010
chore: library update, remove nose tests

README.md

+12-13
Original file line numberDiff line numberDiff line change
@@ -1,23 +1,22 @@
1-
[![Build
2-
Status](https://travis-ci.org/web-push-libs/pywebpush.svg?branch=main)](https://travis-ci.org/web-push-libs/pywebpush)
3-
[![Requirements
4-
Status](https://requires.io/github/web-push-libs/pywebpush/requirements.svg?branch=main)](https://requires.io/github/web-push-libs/pywebpush/requirements/?branch=main)
5-
61
# Webpush Data encryption library for Python
72

8-
This is a work in progress.
3+
[![Build Status](https://travis-ci.org/web-push-libs/pywebpush.svg?branch=main)](https://travis-ci.org/web-push-libs/pywebpush)
4+
[![Requirements Status](https://requires.io/github/web-push-libs/pywebpush/requirements.svg?branch=main)](https://requires.io/github/web-push-libs/pywebpush/requirements/?branch=main)
5+
96
This library is available on [pypi as pywebpush](https://pypi.python.org/pypi/pywebpush).
10-
Source is available on
11-
[github](https://github.com/mozilla-services/pywebpush).
7+
Source is available on [github](https://github.com/mozilla-services/pywebpush).
8+
Please note: This library was designated as a `Critical Project` by PyPi, it is currently
9+
maintained by [a single person](https://xkcd.com/2347/). I still accept PRs and Issues, but
10+
make of that what you will.
1211

1312
## Installation
1413

15-
You'll need to run `python virtualenv`.
14+
You'll need to run `python -m venv venv`.
1615
Then
1716

18-
```
19-
bin/pip install -r requirements.txt
20-
bin/python setup.py develop
17+
```bash
18+
venv/bin/pip install -r requirements.txt
19+
venv/bin/python setup.py develop
2120
```
2221

2322
## Usage
@@ -82,7 +81,7 @@ a base64 encoded DER formatted private key, or the path to an OpenSSL exported p
8281

8382
e.g. the output of:
8483

85-
```
84+
```bash
8685
openssl ecparam -name prime256v1 -genkey -noout -out private_key.pem
8786
```
8887

README.rst

+19-13
Original file line numberDiff line numberDiff line change
@@ -1,21 +1,25 @@
1-
|Build Status| |Requirements Status|
2-
31
Webpush Data encryption library for Python
42
==========================================
53

6-
This is a work in progress. This library is available on `pypi as
4+
|Build Status| |Requirements Status|
5+
6+
This library is available on `pypi as
77
pywebpush <https://pypi.python.org/pypi/pywebpush>`__. Source is
88
available on `github <https://github.com/mozilla-services/pywebpush>`__.
9+
Please note: This library was designated as a ``Critical Project`` by
10+
PyPi, it is currently maintained by `a single
11+
person <https://xkcd.com/2347/>`__. I still accept PRs and Issues, but
12+
make of that what you will.
913

1014
Installation
1115
------------
1216

13-
You’ll need to run ``python virtualenv``. Then
17+
You’ll need to run ``python -m venv venv``. Then
1418

15-
::
19+
.. code:: bash
1620
17-
bin/pip install -r requirements.txt
18-
bin/python setup.py develop
21+
venv/bin/pip install -r requirements.txt
22+
venv/bin/python setup.py develop
1923
2024
Usage
2125
-----
@@ -85,7 +89,7 @@ file.
8589

8690
e.g. the output of:
8791

88-
::
92+
.. code:: bash
8993
9094
openssl ecparam -name prime256v1 -genkey -noout -out private_key.pem
9195
@@ -193,11 +197,13 @@ Stand Alone Webpush
193197
If you’re not really into coding your own solution, there’s also a
194198
“stand-alone” ``pywebpush`` command in the ./bin directory.
195199

196-
This uses two files: \* the *data* file, which contains the message to
197-
send, in whatever form you like. \* the *subscription info* file, which
198-
contains the subscription information as JSON encoded data. This is
199-
usually returned by the Push ``subscribe`` method and looks something
200-
like:
200+
This uses two files:
201+
202+
- the *data* file, which contains the message to send, in whatever form
203+
you like.
204+
- the *subscription info* file, which contains the subscription
205+
information as JSON encoded data. This is usually returned by the
206+
Push ``subscribe`` method and looks something like:
201207

202208
.. code:: json
203209

pywebpush/__init__.py

+14-5
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
import json
88
import os
99
import time
10+
import logging
1011

1112
try:
1213
from urllib.parse import urlparse
@@ -164,7 +165,7 @@ def __init__(self, subscription_info, requests_session=None,
164165

165166
def verb(self, msg, *args, **kwargs):
166167
if self.verbose:
167-
print(msg.format(*args, **kwargs))
168+
logging.info(msg.format(*args, **kwargs))
168169

169170
def _repad(self, data):
170171
"""Add base64 padding to the end of a string, if required"""
@@ -198,6 +199,7 @@ def encode(self, data, content_encoding="aes128gcm"):
198199
if content_encoding == "aesgcm":
199200
self.verb("Generating salt for aesgcm...")
200201
salt = os.urandom(16)
202+
logging.debug("Salt: {}".format(salt))
201203
# The server key is an ephemeral ECDH key used only for this
202204
# transaction
203205
server_key = ec.generate_private_key(ec.SECP256R1, default_backend())
@@ -442,7 +444,7 @@ def webpush(subscription_info,
442444
vapid_headers = None
443445
if vapid_claims:
444446
if verbose:
445-
print("Generating VAPID headers...")
447+
logging.info("Generating VAPID headers...")
446448
if not vapid_claims.get('aud'):
447449
url = urlparse(subscription_info.get('endpoint'))
448450
aud = "{}://{}".format(url.scheme, url.netloc)
@@ -454,24 +456,31 @@ def webpush(subscription_info,
454456
# encryption lives for 12 hours
455457
vapid_claims['exp'] = int(time.time()) + (12 * 60 * 60)
456458
if verbose:
457-
print("Setting VAPID expry to {}...".format(
459+
logging.info("Setting VAPID expry to {}...".format(
458460
vapid_claims['exp']))
459461
if not vapid_private_key:
460462
raise WebPushException("VAPID dict missing 'private_key'")
461463
if isinstance(vapid_private_key, Vapid01):
464+
if verbose:
465+
logging.info("Looks like we already have a valid VAPID key")
462466
vv = vapid_private_key
463467
elif os.path.isfile(vapid_private_key):
464468
# Presume that key from file is handled correctly by
465469
# py_vapid.
470+
if verbose:
471+
logging.info(
472+
"Reading VAPID key from file {}".format(vapid_private_key))
466473
vv = Vapid.from_file(
467474
private_key_file=vapid_private_key) # pragma no cover
468475
else:
476+
if verbose:
477+
logging.info("Reading VAPID key from arguments")
469478
vv = Vapid.from_string(private_key=vapid_private_key)
470479
if verbose:
471-
print("\t claims: {}".format(vapid_claims))
480+
logging.info("\t claims: {}".format(vapid_claims))
472481
vapid_headers = vv.sign(vapid_claims)
473482
if verbose:
474-
print("\t headers: {}".format(vapid_headers))
483+
logging.info("\t headers: {}".format(vapid_headers))
475484
headers.update(vapid_headers)
476485

477486
response = WebPusher(

pywebpush/__main__.py

+24-9
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,11 @@
11
import argparse
22
import os
33
import json
4+
import logging
45

5-
from pywebpush import webpush
6+
from requests import JSONDecodeError
7+
8+
from pywebpush import webpush, WebPushException
69

710

811
def get_config():
@@ -21,25 +24,37 @@ def get_config():
2124
args = parser.parse_args()
2225

2326
if not args.info:
24-
raise Exception("Subscription Info argument missing.")
27+
raise WebPushException("Subscription Info argument missing.")
2528
if not os.path.exists(args.info):
26-
raise Exception("Subscription Info file missing.")
29+
raise WebPushException("Subscription Info file missing.")
2730
try:
2831
with open(args.info) as r:
29-
args.sub_info = json.loads(r.read())
32+
try:
33+
args.sub_info = json.loads(r.read())
34+
except JSONDecodeError as e:
35+
raise WebPushException(
36+
"Could not read the subscription info file: {}", e)
3037
if args.data:
3138
with open(args.data) as r:
3239
args.data = r.read()
3340
if args.head:
3441
with open(args.head) as r:
35-
args.head = json.loads(r.read())
42+
try:
43+
args.head = json.loads(r.read())
44+
except JSONDecodeError as e:
45+
raise WebPushException(
46+
"Could not read the header arguments: {}", e)
3647
if args.claims:
3748
if not args.key:
38-
raise Exception("No private --key specified for claims")
49+
raise WebPushException("No private --key specified for claims")
3950
with open(args.claims) as r:
40-
args.claims = json.loads(r.read())
51+
try:
52+
args.claims = json.loads(r.read())
53+
except JSONDecodeError as e:
54+
raise WebPushException(
55+
"Could not read the VAPID claims file {}".format(e))
4156
except Exception as ex:
42-
print("Couldn't read input {}.".format(ex))
57+
logging.error("Couldn't read input {}.".format(ex))
4358
raise ex
4459
return args
4560

@@ -60,7 +75,7 @@ def main():
6075
headers=args.head)
6176
print(result)
6277
except Exception as ex:
63-
print("ERROR: {}".format(ex))
78+
logging.error("{}".format(ex))
6479

6580

6681
if __name__ == "__main__":

pywebpush/tests/test_webpush.py

+2-1
Original file line numberDiff line numberDiff line change
@@ -80,7 +80,8 @@ def test_init(self):
8080
push = WebPusher(subscription_info)
8181
assert push.subscription_info != subscription_info
8282
assert push.subscription_info['keys'] != subscription_info['keys']
83-
assert push.subscription_info['endpoint'] == subscription_info['endpoint']
83+
assert push.subscription_info['endpoint'] == \
84+
subscription_info['endpoint']
8485
assert push.receiver_key == rk_decode
8586
assert push.auth_key == b'\x93\xc2U\xea\xc8\xddn\x10"\xd6}\xff,0K\xbc'
8687

0 commit comments

Comments
 (0)