|
| 1 | +import asyncio |
| 2 | + |
| 3 | +import aiohttp |
| 4 | +import audible |
| 5 | + |
| 6 | + |
| 7 | +class ClientRequest(aiohttp.ClientRequest): |
| 8 | + def __init__(self, *args, **kwargs) -> None: |
| 9 | + super().__init__(*args, **kwargs) |
| 10 | + self.apply_auth_flow() |
| 11 | + |
| 12 | + def apply_auth_flow(self) -> None: |
| 13 | + body = self.body |
| 14 | + if isinstance(body, aiohttp.BytesPayload): |
| 15 | + body = body._value |
| 16 | + |
| 17 | + sign_headers = audible.auth.sign_request( |
| 18 | + method=self.method, |
| 19 | + path=self.url.path_qs, |
| 20 | + body=body, |
| 21 | + adp_token=self._session._audible_auth.adp_token, |
| 22 | + private_key=self._session._audible_auth.device_private_key |
| 23 | + ) |
| 24 | + for header, value in sign_headers.items(): |
| 25 | + self.headers.add(header, value) |
| 26 | + |
| 27 | + |
| 28 | +class ClientSession(aiohttp.ClientSession): |
| 29 | + def __init__(self, *args, audible_auth: audible.Authenticator, **kwargs): |
| 30 | + if "request_class" in kwargs: |
| 31 | + raise Exception("`request_class` keyword is not supported") |
| 32 | + |
| 33 | + super().__init__(*args, request_class=ClientRequest, **kwargs) |
| 34 | + self._audible_auth = audible_auth |
| 35 | + |
| 36 | + |
| 37 | +if __name__ == "__main__": |
| 38 | + async def main(asin): |
| 39 | + body = { |
| 40 | + "supported_drm_types": ["Mpeg", "Adrm"], |
| 41 | + "quality": "Extreme", |
| 42 | + "consumption_type": "Download", |
| 43 | + "response_groups": ( |
| 44 | + "last_position_heard, pdf_url, content_reference, chapter_info" |
| 45 | + ) |
| 46 | + } |
| 47 | + |
| 48 | + fn = "credentials.json" |
| 49 | + auth = audible.Authenticator.from_file(fn) |
| 50 | + |
| 51 | + async with ClientSession(audible_auth=auth) as session: |
| 52 | + async with session.post( |
| 53 | + f"https://api.audible.de/1.0/content/{asin}/licenserequest", |
| 54 | + json=body |
| 55 | + ) as r: |
| 56 | + print(await r.json()) |
| 57 | + #print(r.request_info) |
| 58 | + print(r.status) |
| 59 | + |
| 60 | + loop = asyncio.get_event_loop() |
| 61 | + loop.run_until_complete(main("B004V0WRPG")) |
0 commit comments