move_detect/edge/alert.py

46 lines
1.5 KiB
Python

import base64
import hashlib
import hmac
import json
from edge.events import Event
def sign(secret: str, nonce: str, ts: str, body: str | bytes) -> str:
if isinstance(body, str):
body = body.encode()
msg = nonce.encode() + ts.encode() + body
return hmac.new(secret.encode(), msg, hashlib.sha256).hexdigest()
class PostClient:
def __init__(self, url: str, device_id: str, secret: str,
nonce_fn, now_fn, http_post=None, timeout: float = 5.0):
self.url = url
self.device_id = device_id
self.secret = secret
self.nonce_fn = nonce_fn
self.now_fn = now_fn
self.timeout = timeout
if http_post is None:
import requests
http_post = requests.post
self._post = http_post
def send(self, event: Event, snapshots: list[bytes]) -> bool:
payload = event.to_payload(self.device_id)
payload["snapshots"] = [base64.b64encode(s).decode() for s in snapshots]
body = json.dumps(payload, sort_keys=True)
nonce = self.nonce_fn()
ts = str(self.now_fn())
headers = {
"Content-Type": "application/json",
"X-Nonce": nonce,
"X-Timestamp": ts,
"X-Signature": sign(self.secret, nonce, ts, body.encode()),
}
try:
resp = self._post(self.url, data=body, headers=headers, timeout=self.timeout)
except Exception:
return False
return 200 <= resp.status_code < 300