|
| 1 | +import pathlib |
| 2 | +import shutil |
| 3 | + |
| 4 | +import audible |
| 5 | +import requests |
| 6 | + |
| 7 | + |
| 8 | +# get download link(s) for book |
| 9 | +def _get_download_link(asin, codec="LC_128_44100_stereo"): |
| 10 | + try: |
| 11 | + content_url = f"https://cde-ta-g7g.amazon.com/FionaCDEServiceEngine/FSDownloadContent" |
| 12 | + params = { |
| 13 | + 'type': 'AUDI', |
| 14 | + 'currentTransportMethod': 'WIFI', |
| 15 | + 'key': asin, |
| 16 | + 'codec': codec |
| 17 | + } |
| 18 | + |
| 19 | + signed_headers = client._sign_request('GET', content_url, params, {}) |
| 20 | + headers = client.headers.copy() |
| 21 | + for item in signed_headers: |
| 22 | + headers[item] = signed_headers[item] |
| 23 | + |
| 24 | + r = client.session.request('GET', content_url, headers=headers, params=params, json={}, allow_redirects=False) |
| 25 | + link = r.headers['Location'] |
| 26 | + |
| 27 | + # prepare link |
| 28 | + # see https://github.com/mkb79/Audible/issues/3#issuecomment-518099852 |
| 29 | + tld = auth.locale.audible_api.split("api.audible.")[1] |
| 30 | + new_link = link.replace("cds.audible.com", f"cds.audible.{tld}") |
| 31 | + return new_link |
| 32 | + |
| 33 | + except Exception as e: |
| 34 | + print(f"Error: {e}") |
| 35 | + return |
| 36 | + |
| 37 | + |
| 38 | +def download_file(url): |
| 39 | + r = requests.get(url, stream=True) |
| 40 | + |
| 41 | + title = r.headers["Content-Disposition"].split("filename=")[1] |
| 42 | + filename = pathlib.Path.cwd() / "audiobooks" / title |
| 43 | + |
| 44 | + with open(filename, 'wb') as f: |
| 45 | + shutil.copyfileobj(r.raw, f) |
| 46 | + return filename |
| 47 | + |
| 48 | + |
| 49 | +if __name__ == "__main__": |
| 50 | + password = input("Password for file: ") |
| 51 | + |
| 52 | + auth = audible.FileAuthenticator( |
| 53 | + filename="FILENAME", |
| 54 | + encryption="json", |
| 55 | + password=password |
| 56 | + ) |
| 57 | + client = audible.AudibleAPI(auth) |
| 58 | + |
| 59 | + books, _ = client.get( |
| 60 | + "library", |
| 61 | + response_groups="product_attrs", |
| 62 | + num_results="999" |
| 63 | + ) |
| 64 | + |
| 65 | + for book in books["items"]: |
| 66 | + asin = book["asin"] |
| 67 | + dl_link = _get_download_link(asin) |
| 68 | + |
| 69 | + if dl_link: |
| 70 | + print(f"download link now: {dl_link}") |
| 71 | + status = download_file(dl_link) |
| 72 | + print(f"downloaded file: {status}") |
0 commit comments