pypush-plus-plus/ids/query.py

72 lines
1.7 KiB
Python
Raw Normal View History

2023-05-09 14:36:33 -05:00
import gzip
import plistlib
import random
from base64 import b64encode
import apns
import bags
2023-08-17 20:17:13 -05:00
import logging
2023-05-09 16:03:27 -05:00
2023-05-09 18:31:09 -05:00
from ._helpers import KeyPair, PROTOCOL_VERSION
2023-05-09 17:01:32 -05:00
from . import signing
2023-05-09 14:36:33 -05:00
2023-08-17 20:17:13 -05:00
async def lookup(
2023-05-09 14:36:33 -05:00
conn: apns.APNSConnection,
2023-05-09 17:01:32 -05:00
self_uri: str,
2023-05-09 18:29:17 -05:00
id_keypair: KeyPair,
query: list[str],
topic,
2023-05-09 14:36:33 -05:00
) -> bytes:
2023-05-09 18:29:17 -05:00
BAG_KEY = "id-query"
2023-05-09 18:31:09 -05:00
2023-08-17 20:17:13 -05:00
await conn.filter([topic])
2023-05-09 18:29:17 -05:00
2023-05-09 18:31:09 -05:00
body = plistlib.dumps({"uris": query})
2023-05-09 14:36:33 -05:00
body = gzip.compress(body, mtime=0)
2023-08-17 20:17:13 -05:00
push_token = b64encode(conn.credentials.token).decode()
2023-05-09 14:36:33 -05:00
headers = {
2023-05-09 17:01:32 -05:00
"x-id-self-uri": self_uri,
2023-05-09 18:31:09 -05:00
"x-protocol-version": PROTOCOL_VERSION,
2023-05-09 14:36:33 -05:00
}
2023-08-13 18:26:57 -05:00
if 'alloy' in topic:
headers["x-id-sub-service"] = topic # Hack, if it has alloy in the name it's probably a sub-service
2023-05-09 18:31:09 -05:00
signing.add_id_signature(headers, body, BAG_KEY, id_keypair, push_token)
2023-05-09 14:36:33 -05:00
msg_id = random.randbytes(16)
req = {
"cT": "application/x-apple-plist",
"U": msg_id,
"c": 96,
2023-05-09 18:29:17 -05:00
"u": bags.ids_bag()[BAG_KEY],
2023-05-09 14:36:33 -05:00
"h": headers,
"v": 2,
"b": body,
}
2023-05-09 18:29:17 -05:00
2023-08-17 20:17:13 -05:00
await conn.send_notification(topic, plistlib.dumps(req, fmt=plistlib.FMT_BINARY))
def check(payload: apns.APNSPayload):
body = payload.fields_with_id(3)[0].value
if body is None:
2023-05-09 14:36:33 -05:00
return False
2023-08-17 20:17:13 -05:00
body = plistlib.loads(body)
return body.get('U') == msg_id
payload = await conn.expect_notification(topic, check)
2023-05-09 14:36:33 -05:00
2023-08-17 20:17:13 -05:00
resp = payload.fields_with_id(3)[0].value
2023-05-09 18:29:17 -05:00
resp = plistlib.loads(resp)
2023-05-09 14:36:33 -05:00
resp = gzip.decompress(resp["b"])
resp = plistlib.loads(resp)
2023-05-09 19:01:22 -05:00
if resp['status'] != 0:
raise Exception(f'Query failed: {resp}')
if not 'results' in resp:
raise Exception(f'No results in response: {resp}')
return resp['results']