Browse Source

accept parameters for the daily notification time

pull/5/head
Trent Larson 6 months ago
parent
commit
62c76eb651
  1. 40
      app.py

40
app.py

@ -133,7 +133,7 @@ class WebPushService():
@staticmethod
def _send_push_notification(subscription_info: Dict, message: Dict, vapid_key: VAPIDKey) -> bool:
def _send_push_notification(subscription_info: Dict, message: Dict, vapid_key: VAPIDKey) -> Dict[str, any]:
"""
Sends a push notification using the provided subscription information, message, and VAPID key.
@ -311,9 +311,8 @@ class WebPushService():
# Sleep before repeating
time.sleep(5 * 60)
# This is an endpoint, routed in __init__
def ping(self) -> Response:
def ping(self) -> str:
"""
Endpoint to show liveness info
@ -323,9 +322,8 @@ class WebPushService():
return f"pong ... with latest subscription run at {self.latest_subscription_run}"
# This is an endpoint, routed in __init__
def regenerate_vapid(self) -> Tuple[str, int]:
def regenerate_vapid(self) -> Tuple[Response, int, dict[str, str]] | Tuple[Response, int]:
"""
Endpoint to regenerate VAPID keys.
@ -338,7 +336,7 @@ class WebPushService():
Header: Authentication: Basic ...
Returns:
- tuple with "success" as True or False, and "message" message string
- Tuple with "success" as True or False, and "message" message string
Notes:
- If the operation is successful, a JSON response with a success message is returned with a 200 status code.
@ -402,7 +400,7 @@ class WebPushService():
@staticmethod
@app.route('/web-push/subscribe', methods=['POST'])
def subscribe() -> Tuple[str, int]:
def subscribe() -> Tuple[Response, int]:
"""
Endpoint to handle new web push subscription requests.
@ -434,10 +432,21 @@ class WebPushService():
if not vapid_key:
return jsonify(success=False, message="No VAPID keys available"), 500
# Constructing the notify_time string
notify_time = "13:13" # random time that is in most people's waking hours (server time, typically UTC)
if ('notifyTime' in content) and ('utcHour' in content['notifyTime']):
notify_hour = content['notifyTime']['utcHour']
if 'minute' in content['notifyTime']:
notify_minute = content['notifyTime']['minute']
else:
notify_minute = 0
notify_time = '{:02d}'.format(notify_hour) + ":" + '{:02d}'.format(notify_minute)
# Creating a new Subscription instance with the provided data
subscription = Subscription(endpoint=content['endpoint'],
subscription = Subscription(auth=content['keys']['auth'],
endpoint=content['endpoint'],
notify_time=notify_time,
p256dh=content['keys']['p256dh'],
auth=content['keys']['auth'],
vapid_key_id=vapid_key.id)
# Saving the subscription data to the database
@ -445,7 +454,8 @@ class WebPushService():
db.session.commit()
# Introducing a delay (ensure that gateway endpoint is available)
time.sleep(10)
# ... which I'm now commenting out because there's no pending request so it doesn't make sense... we'll see if things still work
#time.sleep(10)
# Constructing the subscription information for the push notification
subscription_info = {
@ -463,12 +473,12 @@ class WebPushService():
result = WebPushService._send_push_notification(subscription_info, message, vapid_key)
# Returning the operation status
return jsonify(success=result["success"], message=result["message"])
return jsonify(success=result["success"], message=result["message"]), 200
@staticmethod
@app.route('/web-push/unsubscribe', methods=['POST'])
def unsubscribe() -> Tuple[str, int]:
def unsubscribe() -> Tuple[Response, int]:
"""
Endpoint to handle web push unsubscription requests.
@ -499,7 +509,7 @@ class WebPushService():
if subscription:
db.session.delete(subscription)
db.session.commit()
return jsonify(success=True, message="Subscription deleted successfully")
return jsonify(success=True, message="Subscription deleted successfully"), 200
# If the subscription is not found, return an error message
else:
@ -508,7 +518,7 @@ class WebPushService():
@staticmethod
@app.route('/web-push/send-test', methods=['POST'])
def send_test() -> Tuple[str, int]:
def send_test() -> Tuple[Response, int]:
"""
Endpoint to send a test push notification to a specific client.
@ -563,7 +573,7 @@ class WebPushService():
)
print(f"Test sent: {result['success']}")
return jsonify(success=result["success"], message=result["message"])
return jsonify(success=result["success"], message=result["message"]), 200
else:
print(f"Test failed due to missing subscription. Request: {json.dumps(content)}")
return jsonify({"success": False, "message": "Subscription not found"}), 404

Loading…
Cancel
Save