Modules Documentation
audible package
- class audible.AsyncClient(auth, country_code=None, headers=None, timeout=10, response_callback=None, **session_kwargs)[source]
Bases:
BaseClient[AsyncClient]- Parameters:
auth (
Authenticator)country_code (
str|None)headers (
Union[Headers,Mapping[str,str],Mapping[bytes,bytes],Sequence[Tuple[str,str]],Sequence[Tuple[bytes,bytes]],None])timeout (
int)response_callback (
Callable[[Response],Any] |None)session_kwargs (
Any)
- async delete(path, response_callback=None, **kwargs)[source]
- Parameters:
path (
str)response_callback (
Callable[[Response],Any] |None)kwargs (
dict[str,Any])
- Return type:
Any
- async get(path, response_callback=None, **kwargs)[source]
- Parameters:
path (
str)response_callback (
Callable[[Response],Any] |None)kwargs (
dict[str,Any])
- Return type:
Any
- class audible.Authenticator(*, crypto_provider=None)[source]
Bases:
AuthAudible Authenticator class.
Note
A new class instance have to be instantiated with
Authenticator.from_login()orAuthenticator.from_file().Added in version v0.8: The with_username attribute.
Note
Auth data saved with v0.8 or later can not be loaded with versions less than v0.8! If an auth file for a pre-Amazon account (with_username=True) was created with v0.7.1 or v0.7.2 set auth.with_username to True and save the data again. After this deregistration, refreshing access tokens and requesting cookies for another domain will work for pre-Amazon accounts.
- Thread Safety:
Authenticator instances are not thread-safe and should not be shared across threads. The internal state (access tokens, RSA key cache) can be modified during request signing and token refresh operations, leading to race conditions.
For multi-threaded applications, create separate Authenticator instances per thread, or use appropriate locking mechanisms around Authenticator usage.
Note
The
device_private_keyattribute is monitored for changes. When modified, the cached RSA key is automatically invalidated to ensure the correct key is used for signing. The new key will be loaded and cached on the next signing operation.- Parameters:
crypto_provider (
CryptoProvider|type[CryptoProvider] |None)
-
access_token:
str|None= None
- property access_token_expired: bool
- property access_token_expires: timedelta
-
activation_bytes:
str|None= None
-
adp_token:
str|None= None
- auth_flow(request)[source]
Auth flow to be executed on every request by
httpx.- Parameters:
request (
Request) – The request made byhttpx.- Yields:
httpx.Request – The authenticated request with signed headers.
- Raises:
AuthFlowError – If no auth flow is available.
- Return type:
Generator[Request,Response,None]
- property available_auth_modes: list[str]
-
customer_info:
dict[str,Any] |None= None
-
device_info:
dict[str,Any] |None= None
-
device_private_key:
str|None= None
-
encryption:
str|bool|None= None
-
expires:
float|None= None
-
filename:
Path|None= None
- classmethod from_dict(data, locale=None, *, crypto_provider=None)[source]
Instantiate an Authenticator from authentication file.
Added in version v0.7.1.
- Parameters:
data (
dict[str,Any]) – A dictionary with the authentication datalocale (
str|Locale|None) – The country code of the Audible marketplace to interact with. IfNonethe country code from file is used.crypto_provider (
CryptoProvider|type[CryptoProvider] |None) – Optional provider override (class or instance).
- Return type:
- Returns:
A new Authenticator instance.
- classmethod from_file(filename, password=None, locale=None, encryption=None, crypto_provider=None, **kwargs)[source]
Instantiate an Authenticator from authentication file.
Added in version v0.5.0.
- Parameters:
filename (
str|Path) – The name of the file with the authentication data.password (
str|None) – The password of the authentication file.locale (
str|Locale|None) – The country code of the Audible marketplace to interact with. IfNonethe country code from file is used.encryption (
bool|str|None) – The encryption style to use. Can bejsonorbytes. IfNone, encryption will be auto detected.crypto_provider (
CryptoProvider|type[CryptoProvider] |None) – Optional provider override (class or instance).**kwargs (
Any) – Keyword arguments are passed to theAESCipherclass. See below.
- Keyword Arguments:
key_size (int, Optional)
salt_marker (Optional[bytes])
kdf_iterations (
int, optional)hashmod
mac
- Return type:
- Returns:
A new Authenticator instance.
- Raises:
FileEncryptionError – If file ist encrypted without providing a password
- classmethod from_login(username, password, locale, serial=None, with_username=False, captcha_callback=None, otp_callback=None, cvf_callback=None, approval_callback=None, crypto_provider=None)[source]
Instantiate a new Authenticator with authentication data from login.
Added in version v0.5.0.
Added in version v0.5.4: The serial argument The with_username argument
- Parameters:
username (
str) – The Amazon email address.password (
str) – The Amazon password.locale (
str|Locale) – Thecountry_codeoraudible.localization.Localeinstance for the marketplace to login.serial (
str|None) – The device serial. IfNonea custom one will be created.with_username (
bool) – IfTruelogin with Audible username instead of Amazon account.captcha_callback (
Callable[[str],str] |None) – A custom callback to handle captcha requests during login.otp_callback (
Callable[[],str] |None) – A custom callback to handle one-time password requests during login.cvf_callback (
Callable[[],str] |None) – A custom callback to handle verify code requests during login.approval_callback (
Callable[[],Any] |None) – A custom Callable for handling approval alerts.crypto_provider (
CryptoProvider|type[CryptoProvider] |None) – Optional provider override (class or instance).
- Returns:
New authenticator populated with registration data.
- Return type:
- classmethod from_login_external(locale, serial=None, with_username=False, login_url_callback=None, crypto_provider=None)[source]
Instantiate a new Authenticator from login with external browser.
Added in version v0.5.1.
Added in version v0.5.4: The serial argument The with_username argument
- Parameters:
locale (
str|Locale) – Thecountry_codeoraudible.localization.Localeinstance for the marketplace to login.serial (
str|None) – The device serial. IfNonea custom one will be created.with_username (
bool) – IfTruelogin with Audible username instead of Amazon account.login_url_callback (
Callable[[str],str] |None) – A custom Callable for handling login with external browsers.crypto_provider (
CryptoProvider|type[CryptoProvider] |None) – Optional provider override (class or instance).
- Returns:
New authenticator populated with registration data.
- Return type:
- get_activation_bytes(filename=None, extract=True, force_refresh=False)[source]
Get Activation bytes from Audible.
- Parameters:
filename (
Path|str|None) – [Optional] filename to save the activation blobextract (
Literal[True,False]) – [Optional] if True, returns the extracted activation bytes otherwise the whole activation blobforce_refresh (
bool) – [Optional] if True, existing activation bytes in auth file will be ignored and new activation bytes will be requested from server.
- Return type:
str|bytes- Returns:
The activation bytes
Added in version 0.5.1: The
force_refreshargument. Fetched activation bytes are now stored to Authententicator.activation_bytes.
-
refresh_token:
str|None= None
-
requires_request_body:
bool= True
- set_website_cookies_for_country(country_code)[source]
- Parameters:
country_code (
str)- Return type:
None
- sign_request(request)[source]
Sign a request.
Deprecated since version 0.5.0: Use
self._apply_signing_auth_flow()instead.- Parameters:
request (
Request)- Return type:
None
-
store_authentication_cookie:
dict[str,Any] |None= None
- to_dict()[source]
Returns authentication data as dict.
Added in version 0.7.1.
Added in version v0.8: The returned dict now contains the with_username attribute
- Return type:
dict[str,Any]
- to_file(filename=None, password=None, encryption='default', indent=4, set_default=True, **kwargs)[source]
Save authentication data to file.
Added in version 0.5.1: Save activation bytes to auth file
Added in version v0.8: The saved file now contains the with_username attribute
- Parameters:
filename (
Path|str|None)password (
str|None)encryption (
bool|str)indent (
int)set_default (
bool)kwargs (
Any)
- Return type:
None
-
website_cookies:
dict[str,Any] |None= None
-
with_username:
bool|None= False
- class audible.Client(auth, country_code=None, headers=None, timeout=10, response_callback=None, **session_kwargs)[source]
Bases:
BaseClient[Client]- Parameters:
auth (
Authenticator)country_code (
str|None)headers (
Union[Headers,Mapping[str,str],Mapping[bytes,bytes],Sequence[Tuple[str,str]],Sequence[Tuple[bytes,bytes]],None])timeout (
int)response_callback (
Callable[[Response],Any] |None)session_kwargs (
Any)
- delete(path, response_callback=None, **kwargs)[source]
- Parameters:
path (
str)response_callback (
Callable[[Response],Any] |None)kwargs (
dict[str,Any])
- Return type:
Any
- get(path, response_callback=None, **kwargs)[source]
- Parameters:
path (
str)response_callback (
Callable[[Response],Any] |None)kwargs (
dict[str,Any])
- Return type:
Any
audible.activation_bytes module
- audible.activation_bytes.extract_activation_bytes(data)[source]
Extracts the activation bytes from activation blob.
- Parameters:
data (
bytes) – A activation blob returned byfetch_activationfunction- Return type:
str- Returns:
The extracted activation bytes.
- Raises:
ValueError – If data is not a valid activation blob.
- audible.activation_bytes.fetch_activation(player_token)[source]
Fetches the activation blob with player token from Audible server.
- Parameters:
player_token (
str) – A player token returned byget_player_tokenfunction.- Return type:
bytes- Returns:
The activation blob.
- audible.activation_bytes.fetch_activation_sign_auth(auth)[source]
Fetches the activation blob with sign authentication from Audible server.
- Parameters:
auth (
Authenticator) – AAuthenticatorinstance with validadp_tokenanddevice_private_cert.- Return type:
bytes- Returns:
The activation blob.
- Raises:
AuthFlowError – If no valid auth method is available.
- audible.activation_bytes.get_activation_bytes(auth, filename=None, extract=True)[source]
Fetches the activation blob from Audible and extracts the bytes.
- Parameters:
auth (
Authenticator) – The Authenticator.filename (
str|Path|None) – The filename to save the activation blob (Default: None).extract (
Literal[True,False]) – If True, returns the extracted activation bytes otherwise the whole activation blob (Default: True).
- Return type:
str|bytes- Returns:
The activation bytes or activation blob.
- Raises:
AuthFlowError – If no valid auth method is available.
- audible.activation_bytes.get_player_token(auth)[source]
Fetches a player token for further authentication.
- Parameters:
auth (
Authenticator) – The Authenticator.- Return type:
str- Returns:
The player token.
- Raises:
Exception – If playerToken not found in response url query.
audible.aescipher module
- class audible.aescipher.AESCipher(password, *, key_size=32, salt_marker=b'$', kdf_iterations=1000, hashmod=<built-in function openssl_sha256>, mac=<module 'hmac' from '/home/docs/.asdf/installs/python/3.13.3/lib/python3.13/hmac.py'>, crypto_provider=None)[source]
Bases:
objectEncrypt/Decrypt data using password to generate key.
The encryption algorithm used is symmetric AES in cipher-block chaining (CBC) mode.
The key is derived via the PBKDF2 key derivation function (KDF) from the password and a random salt of 16 bytes (the AES block size) minus the length of the salt header (see below). The hash function used by PBKDF2 is SHA256 per default. You can pass a different hash function module via the
hashmodargument. The module must adhere to the Python API for Cryptographic Hash Functions (PEP 247). PBKDF2 uses a number of iterations of the hash function to derive the key, which can be set via thekdf_iterationskeyword argument. The default number is 1000 and the maximum 65535. The header and the salt are written to the first block of the encrypted output (bytes mode) or written as key/value pairs (dict mode). The header consist of the number of KDF iterations encoded as a big-endian word bytes wrapped bysalt_markeron both sides. With the default value ofsalt_marker = b'$', the header size is thus 4 and the salt 12 bytes. The salt marker must be a byte string of 1-6 bytes length. The last block of the encrypted output is padded with up to 16 bytes, all having the value of the length of the padding. All values in dict mode are written as base64 encoded string.Note
Every encryption call generates a fresh, random IV using
secrets.token_bytes(). While the probability of IV reuse is negligible, consumers should avoid reusing IVs manually as CBC mode requires a unique IV per message to maintain semantic security.- Parameters:
password (
str) – The password for encryption/decryption.key_size (
int) – The size of the key. Can be16,24or32(Default: 32).salt_marker (
bytes) – The salt marker with max. length of 6 bytes (Default: $).kdf_iterations (
int) – The number of iterations of the hash function to derive the key (Default: 1000).hashmod (
Callable[...,HashAlgorithm]) – The hash method to use (Default: sha256).mac (
Any) – The mac module to use (Default: hmac).crypto_provider (
type[CryptoProvider] |None) – Optional provider override (class or instance).
- Raises:
TypeError – If type of salt_marker is not bytes.
ValueError – If salt_marker is not one to six bytes long or if kdf_iterations is greater than 65535.
- from_bytes(data)[source]
Decrypts data previously encrypted with
AESCipher.to_bytes().- Parameters:
data (
bytes) – The encrypted data in bytes style.- Return type:
str- Returns:
The decrypted data.
- from_dict(data)[source]
Decrypts data previously encrypted with
AESCipher.to_dict().- Parameters:
data (
dict[str,str]) – The encrypted data in json style.- Return type:
str- Returns:
The decrypted data.
- from_file(filename, encryption='json')[source]
Loads and decrypts data from given file.
- Parameters:
filename (
Path) – The name of the file to load the data from.encryption (
str) – The encryption style which where used. Can bejsonorbytes(Default: json).
- Return type:
str- Returns:
The decrypted data.
- Raises:
ValueError – If encryption is not
jsonorbytes.
- to_bytes(data)[source]
Encrypts data in bytes style.
The output bytes contains the (packed) salt, iv and ciphertext.
- Parameters:
data (
str) – The data to encrypt.- Return type:
bytes- Returns:
The encrypted data in dict style.
- to_dict(data)[source]
Encrypts data in dict style.
The output dict contains the base64 encoded (packed) salt, iv and ciphertext key/value pairs and an info key/value pair with additional encryption information.
- Parameters:
data (
str) – The data to encrypt.- Return type:
dict[str,str]- Returns:
The encrypted data in dict style.
- to_file(data, filename, encryption='json', indent=4)[source]
Encrypts and saves data to given file.
- Parameters:
data (
str) – The data to encrypt.filename (
Path) – The name of the file to save the data to.encryption (
str) – The encryption style to use. Can bejsonorbytes(Default: json).indent (
int) – The indention level when saving in json style (Default: 4).
- Raises:
ValueError – If encryption is not
jsonorbytes.- Return type:
None
- audible.aescipher.aes_cbc_decrypt(key, iv, encrypted_data, padding='default', *, crypto_provider=None)[source]
Decrypts data encrypted in cipher block chaining mode of operation.
- Parameters:
key (
bytes) – The AES key used at encryption.iv (
bytes) – The initialization vector used at encryption.encrypted_data (
bytes) – The encrypted data to decrypt.padding (
str) – Can bedefaultornone(Default: default)crypto_provider (
CryptoProvider|type[CryptoProvider] |None) – Optional provider override (class or instance).
- Return type:
str- Returns:
The decrypted data.
- audible.aescipher.aes_cbc_encrypt(key, iv, data, padding='default', *, crypto_provider=None)[source]
Encrypts data in cipher block chaining mode of operation.
- Parameters:
key (
bytes) – The AES key.iv (
bytes) – The initialization vector.data (
str) – The data to encrypt.padding (
str) – Can bedefaultornone(Default: default)crypto_provider (
CryptoProvider|type[CryptoProvider] |None) – Optional provider override (class or instance).
- Return type:
bytes- Returns:
The encrypted data.
- audible.aescipher.create_salt(salt_marker, kdf_iterations)[source]
Creates the header and salt for the
derive_from_pbkdf2()function.The header consist of the number of KDF iterations encoded as a big-endian word bytes wrapped by
salt_markeron both sides. The random salt has a length of 16 bytes (the AES block size) minus the length of the salt header.- Parameters:
salt_marker (
bytes)kdf_iterations (
int)
- Return type:
tuple[bytes,bytes]
- audible.aescipher.decrypt_voucher_from_licenserequest(auth, license_response, *, crypto_provider=None)[source]
Decrypt the voucher from license request response.
- Parameters:
auth (
Authenticator) – The Authenticator.license_response (
dict[str,Any]) – The response content from aPOST /1.0/content/(string:asin)/licenserequestrequest.crypto_provider (
CryptoProvider|type[CryptoProvider] |None) – Optional provider override (class or instance).
- Return type:
dict[str,Any]- Returns:
The decrypted license voucher with needed key and iv.
- Raises:
Exception – If device info or customer info data is missing.
Note
A device registration is needed to use the auth instance for a license request and to obtain the needed device data
- audible.aescipher.derive_from_pbkdf2(password, *, key_size, salt, kdf_iterations, hashmod, mac, crypto_provider=None)[source]
Creates an AES key with the
PBKDF2key derivation class.- Parameters:
password (
str) – Source password.key_size (
int) – Desired key length in bytes.salt (
bytes) – Random salt for PBKDF2.kdf_iterations (
int) – Number of iterations.hashmod (
Callable[...,HashAlgorithm]) – Hash factory.mac (
Any) – MAC module.crypto_provider (
CryptoProvider|type[CryptoProvider] |None) – Optional provider override (class or instance).
- Return type:
bytes- Returns:
Derived key bytes produced by the PBKDF2 provider.
- audible.aescipher.detect_file_encryption(filename)[source]
Detect the encryption format from an authentication file.
- Parameters:
filename (
Path) – The name for the authentication file.- Return type:
Optional[Literal[False,'json','bytes']]- Returns:
Falseif file is not encrypted otherwise the encryption format.
- audible.aescipher.pack_salt(header, salt)[source]
Combines the header and salt created by
create_salt()function.- Parameters:
header (
bytes)salt (
bytes)
- Return type:
bytes
- audible.aescipher.remove_file_encryption(source, target, password, **kwargs)[source]
Removes the encryption from an authentication file.
Please try to load the authentication file with
audible.Authenticator.from_file()and save the authentication data as a unencrypted file first. Use this function as fallback if you ran into any error.- Parameters:
source (
str|Path) – The encrypted authentication file.target (
str|Path) – The filename for the decrypted file.password (
str) – The password for the encrypted authentication file.**kwargs (
Any) – keyword args supported byAESCipher
- Raises:
ValueError – If
sourceis not encrypted.- Return type:
None
audible.auth module
- class audible.auth.Authenticator(*, crypto_provider=None)[source]
Bases:
AuthAudible Authenticator class.
Note
A new class instance have to be instantiated with
Authenticator.from_login()orAuthenticator.from_file().Added in version v0.8: The with_username attribute.
Note
Auth data saved with v0.8 or later can not be loaded with versions less than v0.8! If an auth file for a pre-Amazon account (with_username=True) was created with v0.7.1 or v0.7.2 set auth.with_username to True and save the data again. After this deregistration, refreshing access tokens and requesting cookies for another domain will work for pre-Amazon accounts.
- Thread Safety:
Authenticator instances are not thread-safe and should not be shared across threads. The internal state (access tokens, RSA key cache) can be modified during request signing and token refresh operations, leading to race conditions.
For multi-threaded applications, create separate Authenticator instances per thread, or use appropriate locking mechanisms around Authenticator usage.
Note
The
device_private_keyattribute is monitored for changes. When modified, the cached RSA key is automatically invalidated to ensure the correct key is used for signing. The new key will be loaded and cached on the next signing operation.- Parameters:
crypto_provider (
CryptoProvider|type[CryptoProvider] |None)
-
access_token:
str|None= None
- property access_token_expired: bool
- property access_token_expires: timedelta
-
activation_bytes:
str|None= None
-
adp_token:
str|None= None
- auth_flow(request)[source]
Auth flow to be executed on every request by
httpx.- Parameters:
request (
Request) – The request made byhttpx.- Yields:
httpx.Request – The authenticated request with signed headers.
- Raises:
AuthFlowError – If no auth flow is available.
- Return type:
Generator[Request,Response,None]
- property available_auth_modes: list[str]
-
customer_info:
dict[str,Any] |None= None
-
device_info:
dict[str,Any] |None= None
-
device_private_key:
str|None= None
-
encryption:
str|bool|None= None
-
expires:
float|None= None
-
filename:
Path|None= None
- classmethod from_dict(data, locale=None, *, crypto_provider=None)[source]
Instantiate an Authenticator from authentication file.
Added in version v0.7.1.
- Parameters:
data (
dict[str,Any]) – A dictionary with the authentication datalocale (
str|Locale|None) – The country code of the Audible marketplace to interact with. IfNonethe country code from file is used.crypto_provider (
CryptoProvider|type[CryptoProvider] |None) – Optional provider override (class or instance).
- Return type:
- Returns:
A new Authenticator instance.
- classmethod from_file(filename, password=None, locale=None, encryption=None, crypto_provider=None, **kwargs)[source]
Instantiate an Authenticator from authentication file.
Added in version v0.5.0.
- Parameters:
filename (
str|Path) – The name of the file with the authentication data.password (
str|None) – The password of the authentication file.locale (
str|Locale|None) – The country code of the Audible marketplace to interact with. IfNonethe country code from file is used.encryption (
bool|str|None) – The encryption style to use. Can bejsonorbytes. IfNone, encryption will be auto detected.crypto_provider (
CryptoProvider|type[CryptoProvider] |None) – Optional provider override (class or instance).**kwargs (
Any) – Keyword arguments are passed to theAESCipherclass. See below.
- Keyword Arguments:
key_size (int, Optional)
salt_marker (Optional[bytes])
kdf_iterations (
int, optional)hashmod
mac
- Return type:
- Returns:
A new Authenticator instance.
- Raises:
FileEncryptionError – If file ist encrypted without providing a password
- classmethod from_login(username, password, locale, serial=None, with_username=False, captcha_callback=None, otp_callback=None, cvf_callback=None, approval_callback=None, crypto_provider=None)[source]
Instantiate a new Authenticator with authentication data from login.
Added in version v0.5.0.
Added in version v0.5.4: The serial argument The with_username argument
- Parameters:
username (
str) – The Amazon email address.password (
str) – The Amazon password.locale (
str|Locale) – Thecountry_codeoraudible.localization.Localeinstance for the marketplace to login.serial (
str|None) – The device serial. IfNonea custom one will be created.with_username (
bool) – IfTruelogin with Audible username instead of Amazon account.captcha_callback (
Callable[[str],str] |None) – A custom callback to handle captcha requests during login.otp_callback (
Callable[[],str] |None) – A custom callback to handle one-time password requests during login.cvf_callback (
Callable[[],str] |None) – A custom callback to handle verify code requests during login.approval_callback (
Callable[[],Any] |None) – A custom Callable for handling approval alerts.crypto_provider (
CryptoProvider|type[CryptoProvider] |None) – Optional provider override (class or instance).
- Returns:
New authenticator populated with registration data.
- Return type:
- classmethod from_login_external(locale, serial=None, with_username=False, login_url_callback=None, crypto_provider=None)[source]
Instantiate a new Authenticator from login with external browser.
Added in version v0.5.1.
Added in version v0.5.4: The serial argument The with_username argument
- Parameters:
locale (
str|Locale) – Thecountry_codeoraudible.localization.Localeinstance for the marketplace to login.serial (
str|None) – The device serial. IfNonea custom one will be created.with_username (
bool) – IfTruelogin with Audible username instead of Amazon account.login_url_callback (
Callable[[str],str] |None) – A custom Callable for handling login with external browsers.crypto_provider (
CryptoProvider|type[CryptoProvider] |None) – Optional provider override (class or instance).
- Returns:
New authenticator populated with registration data.
- Return type:
- get_activation_bytes(filename=None, extract=True, force_refresh=False)[source]
Get Activation bytes from Audible.
- Parameters:
filename (
Path|str|None) – [Optional] filename to save the activation blobextract (
Literal[True,False]) – [Optional] if True, returns the extracted activation bytes otherwise the whole activation blobforce_refresh (
bool) – [Optional] if True, existing activation bytes in auth file will be ignored and new activation bytes will be requested from server.
- Return type:
str|bytes- Returns:
The activation bytes
Added in version 0.5.1: The
force_refreshargument. Fetched activation bytes are now stored to Authententicator.activation_bytes.
-
refresh_token:
str|None= None
-
requires_request_body:
bool= True
- set_website_cookies_for_country(country_code)[source]
- Parameters:
country_code (
str)- Return type:
None
- sign_request(request)[source]
Sign a request.
Deprecated since version 0.5.0: Use
self._apply_signing_auth_flow()instead.- Parameters:
request (
Request)- Return type:
None
-
store_authentication_cookie:
dict[str,Any] |None= None
- to_dict()[source]
Returns authentication data as dict.
Added in version 0.7.1.
Added in version v0.8: The returned dict now contains the with_username attribute
- Return type:
dict[str,Any]
- to_file(filename=None, password=None, encryption='default', indent=4, set_default=True, **kwargs)[source]
Save authentication data to file.
Added in version 0.5.1: Save activation bytes to auth file
Added in version v0.8: The saved file now contains the with_username attribute
- Parameters:
filename (
Path|str|None)password (
str|None)encryption (
bool|str)indent (
int)set_default (
bool)kwargs (
Any)
- Return type:
None
-
website_cookies:
dict[str,Any] |None= None
-
with_username:
bool|None= False
- audible.auth.refresh_access_token(refresh_token, domain, with_username=False)[source]
Refreshes an access token.
- Parameters:
refresh_token (
str) – The refresh token obtained after a device registration.domain (
str) – The top level domain of the requested Amazon server (e.g. com).with_username (
bool) – IfTrueuses audible domain instead of amazon.
- Return type:
dict[str,Any]- Returns:
A dict with the new access token and expiration timestamp.
Note
The new access token is valid for 60 minutes.
Added in version v0.8: The with_username argument
- audible.auth.refresh_website_cookies(refresh_token, domain, cookies_domain, with_username=False)[source]
Fetches website cookies for a specific domain.
- Parameters:
refresh_token (
str) – The refresh token obtained after a device registration.domain (
str) – The top level domain of the requested Amazon server (e.g. com, de, fr).cookies_domain (
str) – The top level domain scope for the cookies (e.g. com, de, fr).with_username (
bool) – IfTrueuses audible domain instead of amazon.
- Return type:
dict[str,str]- Returns:
The requested cookies for the Amazon and Audible website for the given cookies_domain scope.
Added in version v0.8: The with_username argument
- audible.auth.sign_request(method, path, body, adp_token, private_key, cached_key=None, crypto_provider=None)[source]
Helper function who creates signed headers for http requests.
- Parameters:
method (
str) – The http request method (GET, POST, DELETE, …).path (
str) – The requested http url path and query.body (
bytes) – The http message body.adp_token (
str) – The adp token obtained after a device registration.private_key (
str) – The rsa key obtained after device registration.cached_key (
Any) – Optional pre-loaded RSA key object for performance. If provided, private_key parsing is skipped.crypto_provider (
CryptoProvider|type[CryptoProvider] |None) – Optional provider override (class or instance).
- Return type:
dict[str,str]- Returns:
A dict with the signed headers.
- audible.auth.user_profile(access_token, domain)[source]
Returns user profile from Amazon.
- Parameters:
access_token (
str) – The valid access token for authentication.domain (
str) – The top level domain of the requested Amazon server (e.g. com, de, fr).
- Return type:
dict[str,Any]- Returns:
The Amazon user profile for the authenticated user.
- Raises:
Exception – If the user profile is malformed
- audible.auth.user_profile_audible(access_token, domain)[source]
Returns user profile from Audible.
- Parameters:
access_token (
str) – The valid access token for authentication.domain (
str) – The top level domain of the requested Audible server (e.g. com, de, fr).
- Return type:
dict[str,Any]- Returns:
The Audible user profile for the authenticated user.
- Raises:
Exception – If the user profile is malformed
audible.client module
- class audible.client.AsyncClient(auth, country_code=None, headers=None, timeout=10, response_callback=None, **session_kwargs)[source]
Bases:
BaseClient[AsyncClient]- Parameters:
auth (
Authenticator)country_code (
str|None)headers (
Union[Headers,Mapping[str,str],Mapping[bytes,bytes],Sequence[Tuple[str,str]],Sequence[Tuple[bytes,bytes]],None])timeout (
int)response_callback (
Callable[[Response],Any] |None)session_kwargs (
Any)
- async delete(path, response_callback=None, **kwargs)[source]
- Parameters:
path (
str)response_callback (
Callable[[Response],Any] |None)kwargs (
dict[str,Any])
- Return type:
Any
- async get(path, response_callback=None, **kwargs)[source]
- Parameters:
path (
str)response_callback (
Callable[[Response],Any] |None)kwargs (
dict[str,Any])
- Return type:
Any
- class audible.client.BaseClient(auth, country_code=None, headers=None, timeout=10, response_callback=None, **session_kwargs)[source]
Bases:
Generic[ClientT]- Parameters:
auth (
Authenticator)country_code (
str|None)headers (
Union[Headers,Mapping[str,str],Mapping[bytes,bytes],Sequence[Tuple[str,str]],Sequence[Tuple[bytes,bytes]],None])timeout (
int)response_callback (
Callable[[Response],Any] |None)session_kwargs (
Any)
- property auth: Authenticator
- abstractmethod delete(path, response_callback=None, **kwargs)[source]
- Parameters:
path (
str)response_callback (
Callable[[Response],Any] |None)kwargs (
dict[str,Any])
- Return type:
Any
- abstractmethod get(path, response_callback=None, **kwargs)[source]
- Parameters:
path (
str)response_callback (
Callable[[Response],Any] |None)kwargs (
dict[str,Any])
- Return type:
Any
- property marketplace: str
- abstractmethod post(path, body, response_callback=None, **kwargs)[source]
- Parameters:
path (
str)body (
Any)response_callback (
Callable[[Response],Any] |None)kwargs (
dict[str,Any])
- Return type:
Any
- abstractmethod put(path, body, response_callback=None, **kwargs)[source]
- Parameters:
path (
str)body (
Any)response_callback (
Callable[[Response],Any] |None)kwargs (
dict[str,Any])
- Return type:
Any
- raw_request(method, url, *, stream=False, apply_auth_flow=False, apply_cookies=False, **kwargs)[source]
Sends a raw request with the underlying httpx Client.
This method ignores a set api_url and allows send request to custom hosts. The raw httpx response will be returned.
- Parameters:
method (
str) – The http request method.url (
str) – The url to make requests to.stream (
Literal[True,False]) – If True, streams the responseapply_auth_flow (
bool) – If True, theAuthenticator.auth_flow()will be applied to the request.apply_cookies (
bool) – If True, website cookies fromAuthenticator.website_cookieswill be added to request headers.**kwargs (
Any) – keyword args supported byhttpx.AsyncClient.stream,httpx.Client.stream,httpx.AsyncClient.request,httpx.Client.request.
- Return type:
Response|Coroutine[Any,Any,Response] |AbstractContextManager[Response] |AbstractAsyncContextManager[Response]- Returns:
An unprepared httpx Response object.
Added in version v0.5.1.
- switch_user(auth, switch_to_default_marketplace=False)[source]
- Parameters:
auth (
Authenticator)switch_to_default_marketplace (
bool)
- Return type:
None
- property user_name: str
- class audible.client.Client(auth, country_code=None, headers=None, timeout=10, response_callback=None, **session_kwargs)[source]
Bases:
BaseClient[Client]- Parameters:
auth (
Authenticator)country_code (
str|None)headers (
Union[Headers,Mapping[str,str],Mapping[bytes,bytes],Sequence[Tuple[str,str]],Sequence[Tuple[bytes,bytes]],None])timeout (
int)response_callback (
Callable[[Response],Any] |None)session_kwargs (
Any)
- delete(path, response_callback=None, **kwargs)[source]
- Parameters:
path (
str)response_callback (
Callable[[Response],Any] |None)kwargs (
dict[str,Any])
- Return type:
Any
- get(path, response_callback=None, **kwargs)[source]
- Parameters:
path (
str)response_callback (
Callable[[Response],Any] |None)kwargs (
dict[str,Any])
- Return type:
Any
audible.crypto_provider package
Crypto abstraction layer with support for multiple backends.
This module provides a clean abstraction layer for cryptographic operations, supporting multiple backend libraries: cryptography, pycryptodome, and legacy pure-Python implementations.
The provider is automatically selected at runtime based on availability: 1. cryptography (preferred - Rust-accelerated) 2. pycryptodome (C-based) 3. legacy (pure Python fallback)
Users can explicitly select a provider using the class-based API.
Example
>>> from audible.crypto_provider import get_crypto_providers
>>> providers = get_crypto_providers() # Auto-detect
>>> key = bytes([0]) * 16
>>> iv = bytes([1]) * 16
>>> ciphertext = providers.aes.encrypt(key, iv, "hello")
>>> providers.aes.decrypt(key, iv, ciphertext)
'hello'
>>> from audible.crypto_provider import CryptographyProvider
>>> providers = get_crypto_providers(CryptographyProvider)
>>> providers.provider_name
'cryptography'
- class audible.crypto_provider.CryptoProvider(*args, **kwargs)[source]
Bases:
ProtocolProtocol for complete crypto provider implementations.
This protocol defines the contract that all crypto providers must follow. Providers must implement all four sub-providers (AES, PBKDF2, RSA, Hash) to ensure complete cryptographic functionality.
Custom providers can be created by implementing this protocol and passing the provider class to get_crypto_providers().
Example
>>> class MyProvider: ... @property ... def aes(self) -> AESProvider: ... return MyAESProvider() ... @property ... def pbkdf2(self) -> PBKDF2Provider: ... return MyPBKDF2Provider() ... @property ... def rsa(self) -> RSAProvider: ... return MyRSAProvider() ... @property ... def hash(self) -> HashProvider: ... return MyHashProvider() ... @property ... def provider_name(self) -> str: ... return "my-custom-provider" >>> from audible.crypto_provider import get_crypto_providers >>> providers = get_crypto_providers(MyProvider) >>> providers.provider_name 'my-custom-provider'
- property aes: AESProvider
Return the AES encryption/decryption provider.
- Returns:
The AES encryption/decryption provider instance.
- property hash: HashProvider
Return the cryptographic hash provider.
- Returns:
The cryptographic hash provider instance.
- property pbkdf2: PBKDF2Provider
Return the PBKDF2 key derivation provider.
- Returns:
The PBKDF2 key derivation provider instance.
- property provider_name: str
Return the human-readable provider name.
- Returns:
The human-readable provider name (e.g., ‘cryptography’, ‘pycryptodome’, ‘legacy’).
- property rsa: RSAProvider
Return the RSA signing provider.
- Returns:
The RSA signing provider instance.
- class audible.crypto_provider.CryptographyProvider[source]
Bases:
objectUnified cryptography crypto provider.
This provider implements all cryptographic operations using the cryptography library, which provides modern, Rust-accelerated implementations.
Performance characteristics: - Comparable or better than pycryptodome - Modern API and active maintenance - Preferred choice for new installations
- Raises:
ImportError – If cryptography library is not installed.
Example
>>> from audible.crypto_provider import get_crypto_providers, CryptographyProvider >>> providers = get_crypto_providers(CryptographyProvider) >>> providers.provider_name 'cryptography'
- property aes: CryptographyAESProvider
Get the AES provider.
- property hash: CryptographyHashProvider
Get the hash provider.
- property pbkdf2: CryptographyPBKDF2Provider
Get the PBKDF2 provider.
- property provider_name: str
Get provider name.
- property rsa: CryptographyRSAProvider
Get the RSA provider.
- class audible.crypto_provider.LegacyProvider[source]
Bases:
objectUnified legacy crypto provider using pure Python libraries.
This provider uses pure Python implementations (pyaes, rsa, pbkdf2) and serves as a fallback when neither cryptography nor pycryptodome are available.
Performance: Slower than native providers (5-20x) but requires no compilation.
A UserWarning is shown on first use to encourage installing faster alternatives.
Example
>>> from audible.crypto_provider import get_crypto_providers, LegacyProvider >>> providers = get_crypto_providers(LegacyProvider) >>> providers.provider_name 'legacy'
- property aes: LegacyAESProvider
Get the AES provider.
- property hash: LegacyHashProvider
Get the hash provider.
- property pbkdf2: LegacyPBKDF2Provider
Get the PBKDF2 provider.
- property provider_name: str
Get provider name.
- property rsa: LegacyRSAProvider
Get the RSA provider.
- class audible.crypto_provider.PycryptodomeProvider[source]
Bases:
objectUnified pycryptodome crypto provider.
This provider implements all cryptographic operations using the pycryptodome library, which provides high-performance C-based implementations.
Performance characteristics: - 5-10x faster AES operations vs pure Python - 10-20x faster RSA operations vs pure Python - 3-5x faster PBKDF2 key derivation vs pure Python - 5-10x faster hashing operations vs pure Python
- Raises:
ImportError – If pycryptodome is not installed.
Example
>>> from audible.crypto_provider import get_crypto_providers, PycryptodomeProvider >>> providers = get_crypto_providers(PycryptodomeProvider) >>> providers.provider_name 'pycryptodome'
- property aes: PycryptodomeAESProvider
Get the AES provider.
- property hash: PycryptodomeHashProvider
Get the hash provider.
- property pbkdf2: PycryptodomePBKDF2Provider
Get the PBKDF2 provider.
- property provider_name: str
Get provider name.
- property rsa: PycryptodomeRSAProvider
Get the RSA provider.
- audible.crypto_provider.get_crypto_providers(provider=None)[source]
Get the crypto provider.
This is the main entry point for accessing crypto operations.
- Parameters:
provider (
CryptoProvider|type[CryptoProvider] |None) – Optional provider class or instance to use. Can be: - None: Auto-detect best available provider (default) - CryptoProvider subclass: Force the corresponding library - CryptoProvider instance: Reuse the supplied instance- Return type:
- Returns:
A CryptoProvider instance.
- Raises:
ImportError – If specified provider is unavailable.
Example
>>> from audible.crypto_provider import get_crypto_providers >>> providers = get_crypto_providers() # Auto-detect >>> providers.provider_name in {"cryptography", "pycryptodome", "legacy"} True
>>> from audible.crypto_provider import CryptographyProvider >>> providers = get_crypto_providers(CryptographyProvider) >>> providers.provider_name 'cryptography'
- audible.crypto_provider.set_default_crypto_provider(provider=None)[source]
Set or reset the global default crypto provider.
- Parameters:
provider (
CryptoProvider|type[CryptoProvider] |None) – Provider class or instance to enforce, or None to restore auto-detection.- Raises:
ImportError – If the requested provider cannot be initialized.
- Return type:
None
Notes
When switching providers the cached instances are cleared so the next call to
get_crypto_providers()returns a fresh instance.
audible.crypto_provider.protocols module
Protocol definitions for crypto providers.
This module defines the contracts that all crypto provider implementations must follow. Using Python’s Protocol allows for type-safe duck typing and enables static type checking with mypy.
- class audible.crypto_provider.protocols.AESProvider(*args, **kwargs)[source]
Bases:
ProtocolProtocol for AES-CBC encryption/decryption operations.
Implementations must provide AES encryption in CBC mode with configurable padding. Both “default” (PKCS7) and “none” (no padding) modes must be supported.
- decrypt(key, iv, encrypted_data, padding='default')[source]
Decrypt data using AES-CBC.
- Parameters:
key (
bytes) – The AES decryption key (16, 24, or 32 bytes).iv (
bytes) – The initialization vector (16 bytes).encrypted_data (
bytes) – The ciphertext to decrypt.padding (
str) – Padding mode - “default” for PKCS7, “none” for no padding.
- Return type:
str- Returns:
The decrypted plaintext as a string.
- encrypt(key, iv, data, padding='default')[source]
Encrypt data using AES-CBC.
- Parameters:
key (
bytes) – The AES encryption key (16, 24, or 32 bytes).iv (
bytes) – The initialization vector (16 bytes).data (
str) – The plaintext data to encrypt.padding (
str) – Padding mode - “default” for PKCS7, “none” for no padding.
- Return type:
bytes- Returns:
The encrypted data as bytes.
- class audible.crypto_provider.protocols.CryptoProvider(*args, **kwargs)[source]
Bases:
ProtocolProtocol for complete crypto provider implementations.
This protocol defines the contract that all crypto providers must follow. Providers must implement all four sub-providers (AES, PBKDF2, RSA, Hash) to ensure complete cryptographic functionality.
Custom providers can be created by implementing this protocol and passing the provider class to get_crypto_providers().
Example
>>> class MyProvider: ... @property ... def aes(self) -> AESProvider: ... return MyAESProvider() ... @property ... def pbkdf2(self) -> PBKDF2Provider: ... return MyPBKDF2Provider() ... @property ... def rsa(self) -> RSAProvider: ... return MyRSAProvider() ... @property ... def hash(self) -> HashProvider: ... return MyHashProvider() ... @property ... def provider_name(self) -> str: ... return "my-custom-provider" >>> from audible.crypto_provider import get_crypto_providers >>> providers = get_crypto_providers(MyProvider) >>> providers.provider_name 'my-custom-provider'
- property aes: AESProvider
Return the AES encryption/decryption provider.
- Returns:
The AES encryption/decryption provider instance.
- property hash: HashProvider
Return the cryptographic hash provider.
- Returns:
The cryptographic hash provider instance.
- property pbkdf2: PBKDF2Provider
Return the PBKDF2 key derivation provider.
- Returns:
The PBKDF2 key derivation provider instance.
- property provider_name: str
Return the human-readable provider name.
- Returns:
The human-readable provider name (e.g., ‘cryptography’, ‘pycryptodome’, ‘legacy’).
- property rsa: RSAProvider
Return the RSA signing provider.
- Returns:
The RSA signing provider instance.
- class audible.crypto_provider.protocols.HashAlgorithm(*args, **kwargs)[source]
Bases:
ProtocolProtocol for hash algorithm objects.
This protocol defines the interface that hash objects must provide. Compatible with hashlib hash objects (e.g., hashlib.sha256()).
- name
The name of the hash algorithm (e.g., ‘sha256’, ‘sha1’).
-
name:
str
- class audible.crypto_provider.protocols.HashProvider(*args, **kwargs)[source]
Bases:
ProtocolProtocol for cryptographic hash operations.
Implementations must provide SHA-256 and SHA-1 hash functions.
- class audible.crypto_provider.protocols.PBKDF2Provider(*args, **kwargs)[source]
Bases:
ProtocolProtocol for PBKDF2 key derivation operations.
Implementations must provide PBKDF2 (Password-Based Key Derivation Function 2) with configurable hash functions and iteration counts.
- derive_key(password, salt, iterations, key_size, hashmod)[source]
Derive a cryptographic key from a password using PBKDF2.
- Parameters:
password (
str) – The password to derive the key from.salt (
bytes) – Random salt for key derivation.iterations (
int) – Number of iterations (1-65535).key_size (
int) – Desired key size in bytes.hashmod (
Callable[...,HashAlgorithm]) – Hash function factory (e.g., hashlib.sha256).
- Return type:
bytes- Returns:
The derived key as bytes.
- class audible.crypto_provider.protocols.RSAProvider(*args, **kwargs)[source]
Bases:
ProtocolProtocol for RSA signing operations.
Implementations must provide RSA private key loading and PKCS#1 v1.5 signing with SHA-256. Implementations should cache parsed keys for performance.
- load_private_key(pem_data)[source]
Load and cache an RSA private key from PEM format.
This method should implement caching to avoid re-parsing the same key multiple times, as key loading can be expensive.
- Parameters:
pem_data (
str) – RSA private key in PEM format.- Return type:
Any- Returns:
The loaded RSA private key object.
- sign(key, data, algorithm='SHA-256')[source]
Sign data with an RSA private key using PKCS#1 v1.5.
- Parameters:
key (
Any) – A parsed RSA private key (from load_private_key).data (
bytes) – The data to sign.algorithm (
str) – The hash algorithm to use. Currently only “SHA-256” is supported to match Audible API requirements (SHA256withRSA).
- Return type:
bytes- Returns:
The RSA signature as bytes.
audible.crypto_provider.registry module
Provider registry for crypto backend selection.
This module implements a registry that automatically detects and selects the best available crypto provider at runtime, with support for explicit provider selection.
Auto-detection priority: 1. cryptography (Rust-accelerated, modern API) 2. pycryptodome (C-based, high performance) 3. legacy (pure Python fallback)
The registry supports both automatic detection and explicit provider selection via type-safe class-based API. Custom providers can be created by implementing the CryptoProvider protocol.
Example
>>> from audible.crypto_provider import get_crypto_providers
>>> providers = get_crypto_providers() # Auto-detect
>>> providers.provider_name in {"cryptography", "pycryptodome", "legacy"}
True
>>> from audible.crypto_provider import PycryptodomeProvider
>>> providers = get_crypto_providers(PycryptodomeProvider)
>>> providers.provider_name
'pycryptodome'
>>> from audible.crypto_provider import CryptographyProvider
>>> providers = get_crypto_providers(CryptographyProvider)
>>> providers.provider_name
'cryptography'
- audible.crypto_provider.registry.get_crypto_providers(provider=None)[source]
Get the crypto provider.
This is the main entry point for accessing crypto operations.
- Parameters:
provider (
CryptoProvider|type[CryptoProvider] |None) – Optional provider class or instance to use. Can be: - None: Auto-detect best available provider (default) - CryptoProvider subclass: Force the corresponding library - CryptoProvider instance: Reuse the supplied instance- Return type:
- Returns:
A CryptoProvider instance.
- Raises:
ImportError – If specified provider is unavailable.
Example
>>> from audible.crypto_provider import get_crypto_providers >>> providers = get_crypto_providers() # Auto-detect >>> providers.provider_name in {"cryptography", "pycryptodome", "legacy"} True
>>> from audible.crypto_provider import CryptographyProvider >>> providers = get_crypto_providers(CryptographyProvider) >>> providers.provider_name 'cryptography'
- audible.crypto_provider.registry.set_default_crypto_provider(provider=None)[source]
Set or reset the global default crypto provider.
- Parameters:
provider (
CryptoProvider|type[CryptoProvider] |None) – Provider class or instance to enforce, or None to restore auto-detection.- Raises:
ImportError – If the requested provider cannot be initialized.
- Return type:
None
Notes
When switching providers the cached instances are cleared so the next call to
get_crypto_providers()returns a fresh instance.
audible.crypto_provider.cryptography_provider module
Cryptography provider using the cryptography library.
This module implements the crypto protocols using the cryptography library, which provides modern, Rust-accelerated cryptographic operations.
The cryptography library is the recommended choice for new projects due to: - Active maintenance and security updates - Modern API design - Rust-based performance optimizations - Comprehensive cryptographic primitive support
This is the preferred provider when available, selected first during auto-detection.
- class audible.crypto_provider.cryptography_provider.CryptographyAESProvider[source]
Bases:
objectAES provider using cryptography library.
Implements AES-CBC encryption/decryption with PKCS7 padding support. Uses Rust-accelerated primitives from the cryptography library.
- decrypt(key, iv, encrypted_data, padding='default')[source]
Decrypt data using AES-CBC.
- Parameters:
key (
bytes) – AES key (16, 24, or 32 bytes).iv (
bytes) – Initialization vector (16 bytes).encrypted_data (
bytes) – Ciphertext to decrypt.padding (
str) – “default” for PKCS7 padding, “none” for no padding.
- Return type:
str- Returns:
Decrypted plaintext as string.
- Raises:
ValueError – If key/IV sizes invalid, padding incorrect, or decryption fails.
- encrypt(key, iv, data, padding='default')[source]
Encrypt data using AES-CBC.
- Parameters:
key (
bytes) – AES key (16, 24, or 32 bytes for AES-128/192/256).iv (
bytes) – Initialization vector (16 bytes).data (
str) – Plaintext string to encrypt.padding (
str) – “default” for PKCS7 padding, “none” for no padding.
- Return type:
bytes- Returns:
Encrypted ciphertext as bytes.
- Raises:
ValueError – If key/IV sizes are invalid or padding mode unknown.
- class audible.crypto_provider.cryptography_provider.CryptographyHashProvider[source]
Bases:
objectHash provider using cryptography library.
Implements SHA-256 and SHA-1 hash functions. Uses Rust-accelerated hash primitives.
- class audible.crypto_provider.cryptography_provider.CryptographyPBKDF2Provider[source]
Bases:
objectPBKDF2 provider using cryptography library.
Implements PBKDF2 key derivation with configurable hash algorithms. Uses Rust-accelerated KDF from the cryptography library.
- derive_key(password, salt, iterations, key_size, hashmod)[source]
Derive a key from password using PBKDF2.
- Parameters:
password (
str) – Password string.salt (
bytes) – Random salt bytes.iterations (
int) – Number of PBKDF2 iterations (1-65535).key_size (
int) – Desired key length in bytes.hashmod (
Callable[...,HashAlgorithm]) – Hash function factory (e.g., hashlib.sha256).
- Return type:
bytes- Returns:
Derived key bytes.
- Raises:
ValueError – If iterations out of range or parameters invalid.
- class audible.crypto_provider.cryptography_provider.CryptographyProvider[source]
Bases:
objectUnified cryptography crypto provider.
This provider implements all cryptographic operations using the cryptography library, which provides modern, Rust-accelerated implementations.
Performance characteristics: - Comparable or better than pycryptodome - Modern API and active maintenance - Preferred choice for new installations
- Raises:
ImportError – If cryptography library is not installed.
Example
>>> from audible.crypto_provider import get_crypto_providers, CryptographyProvider >>> providers = get_crypto_providers(CryptographyProvider) >>> providers.provider_name 'cryptography'
- property aes: CryptographyAESProvider
Get the AES provider.
- property hash: CryptographyHashProvider
Get the hash provider.
- property pbkdf2: CryptographyPBKDF2Provider
Get the PBKDF2 provider.
- property provider_name: str
Get provider name.
- property rsa: CryptographyRSAProvider
Get the RSA provider.
- class audible.crypto_provider.cryptography_provider.CryptographyRSAProvider[source]
Bases:
objectRSA provider using cryptography library.
Implements RSA private key loading and PKCS#1 v1.5 signing with SHA-256.
- load_private_key(pem_data)[source]
Load an RSA private key from PEM format.
- Parameters:
pem_data (
str) – RSA private key in PEM format.- Return type:
Any- Returns:
Parsed RSA private key object.
- sign(key, data, algorithm='SHA-256')[source]
Sign data with RSA private key using PKCS#1 v1.5.
- Parameters:
key (
Any) – RSA private key from load_private_key().data (
bytes) – Data to sign.algorithm (
str) – Hash algorithm, only “SHA-256” supported (Audible API requirement).
- Return type:
bytes- Returns:
Signature bytes.
- Raises:
ValueError – If algorithm is not “SHA-256” or key is invalid.
audible.crypto_provider.pycryptodome_provider module
Pycryptodome crypto provider using native C extensions.
This module implements the crypto protocols using the pycryptodome library, which provides high-performance cryptographic operations via C extensions.
This is significantly faster than the pure Python implementations but requires pycryptodome to be installed as an optional dependency.
- class audible.crypto_provider.pycryptodome_provider.PycryptodomeAESProvider[source]
Bases:
objectHigh-performance AES-CBC provider using pycryptodome.
This implementation uses native C extensions from pycryptodome for significantly faster AES encryption/decryption compared to pure Python.
- decrypt(key, iv, encrypted_data, padding='default')[source]
Decrypt data using AES-CBC with pycryptodome.
- Parameters:
key (
bytes) – The AES decryption key.iv (
bytes) – The initialization vector.encrypted_data (
bytes) – The ciphertext to decrypt.padding (
str) – Padding mode (“default” for PKCS7, “none” for no padding).
- Return type:
str- Returns:
The decrypted plaintext as a string.
- Raises:
ValueError – If key/IV sizes invalid, padding mode unknown, PKCS7 padding invalid, or UTF-8 decoding fails (wrong key/IV or corrupted data).
- encrypt(key, iv, data, padding='default')[source]
Encrypt data using AES-CBC with pycryptodome.
- Parameters:
key (
bytes) – The AES encryption key.iv (
bytes) – The initialization vector.data (
str) – The plaintext data to encrypt.padding (
str) – Padding mode (“default” for PKCS7, “none” for no padding).
- Return type:
bytes- Returns:
The encrypted ciphertext.
- Raises:
ValueError – If key/IV sizes are invalid or padding mode unknown.
- class audible.crypto_provider.pycryptodome_provider.PycryptodomeHashProvider[source]
Bases:
objectHigh-performance hash provider using pycryptodome.
This implementation uses native C extensions from pycryptodome for faster hashing operations.
- class audible.crypto_provider.pycryptodome_provider.PycryptodomePBKDF2Provider[source]
Bases:
objectHigh-performance PBKDF2 provider using pycryptodome.
This implementation uses native C extensions from pycryptodome for faster key derivation compared to pure Python.
- derive_key(password, salt, iterations, key_size, hashmod)[source]
Derive a key using PBKDF2 with pycryptodome.
- Parameters:
password (
str) – The password to derive from.salt (
bytes) – Random salt for derivation.iterations (
int) – Number of iterations (clamped to 65535 max).key_size (
int) – Desired key size in bytes.hashmod (
Callable[...,HashAlgorithm]) – Hash function factory.
- Return type:
bytes- Returns:
The derived key.
- Raises:
ValueError – If hashmod is invalid or unsupported.
- class audible.crypto_provider.pycryptodome_provider.PycryptodomeProvider[source]
Bases:
objectUnified pycryptodome crypto provider.
This provider implements all cryptographic operations using the pycryptodome library, which provides high-performance C-based implementations.
Performance characteristics: - 5-10x faster AES operations vs pure Python - 10-20x faster RSA operations vs pure Python - 3-5x faster PBKDF2 key derivation vs pure Python - 5-10x faster hashing operations vs pure Python
- Raises:
ImportError – If pycryptodome is not installed.
Example
>>> from audible.crypto_provider import get_crypto_providers, PycryptodomeProvider >>> providers = get_crypto_providers(PycryptodomeProvider) >>> providers.provider_name 'pycryptodome'
- property aes: PycryptodomeAESProvider
Get the AES provider.
- property hash: PycryptodomeHashProvider
Get the hash provider.
- property pbkdf2: PycryptodomePBKDF2Provider
Get the PBKDF2 provider.
- property provider_name: str
Get provider name.
- property rsa: PycryptodomeRSAProvider
Get the RSA provider.
- class audible.crypto_provider.pycryptodome_provider.PycryptodomeRSAProvider[source]
Bases:
objectHigh-performance RSA provider using pycryptodome.
This implementation uses native C extensions from pycryptodome for faster RSA operations.
- load_private_key(pem_data)[source]
Load an RSA private key from PEM.
Note
Caching is the caller’s responsibility for optimal performance.
- Parameters:
pem_data (
str) – RSA private key in PEM format.- Return type:
Any- Returns:
A parsed RSA.RsaKey object.
- sign(key, data, algorithm='SHA-256')[source]
Sign data with an RSA private key using PKCS#1 v1.5.
- Parameters:
key (
Any) – A parsed RSA.RsaKey object.data (
bytes) – The data to sign.algorithm (
str) – The hash algorithm. Only “SHA-256” is supported.
- Return type:
bytes- Returns:
The signature bytes.
- Raises:
TypeError – If key is not a valid RSA key object.
ValueError – If algorithm is not “SHA-256”.
audible.crypto_provider.legacy_provider module
Legacy crypto provider using pure Python libraries.
This module implements the crypto protocols using the existing pure-Python libraries: pyaes for AES, pbkdf2 for key derivation, and rsa for RSA signing.
These implementations are slower than native C extensions but are pure Python and work in all environments without compilation.
- class audible.crypto_provider.legacy_provider.LegacyAESProvider[source]
Bases:
objectAES-CBC provider using the pyaes library.
This implementation uses pure Python AES from the pyaes library. While slower than native implementations, it works everywhere and requires no compilation.
- decrypt(key, iv, encrypted_data, padding='default')[source]
Decrypt data using AES-CBC with pyaes.
- Parameters:
key (
bytes) – The AES decryption key.iv (
bytes) – The initialization vector.encrypted_data (
bytes) – The ciphertext to decrypt.padding (
str) – Padding mode (“default” for PKCS7, “none” for no padding).
- Return type:
str- Returns:
The decrypted plaintext as a string.
- Raises:
ValueError – If PKCS7 padding is invalid or UTF-8 decoding fails (wrong key/IV or corrupted data).
- encrypt(key, iv, data, padding='default')[source]
Encrypt data using AES-CBC with pyaes.
- Parameters:
key (
bytes) – The AES encryption key.iv (
bytes) – The initialization vector.data (
str) – The plaintext data to encrypt.padding (
str) – Padding mode (“default” for PKCS7, “none” for no padding).
- Return type:
bytes- Returns:
The encrypted ciphertext.
- class audible.crypto_provider.legacy_provider.LegacyHashProvider[source]
Bases:
objectHash provider using Python’s standard hashlib.
This implementation uses the standard library hashlib module.
- class audible.crypto_provider.legacy_provider.LegacyPBKDF2Provider[source]
Bases:
objectPBKDF2 provider using the pbkdf2 library.
This implementation uses pure Python PBKDF2 from the pbkdf2 library.
- derive_key(password, salt, iterations, key_size, hashmod)[source]
Derive a key using PBKDF2 with the pbkdf2 library.
- Parameters:
password (
str) – The password to derive from.salt (
bytes) – Random salt for derivation.iterations (
int) – Number of iterations (clamped to 65535 max).key_size (
int) – Desired key size in bytes.hashmod (
Callable[...,HashAlgorithm]) – Hash function factory.
- Return type:
bytes- Returns:
The derived key.
- class audible.crypto_provider.legacy_provider.LegacyProvider[source]
Bases:
objectUnified legacy crypto provider using pure Python libraries.
This provider uses pure Python implementations (pyaes, rsa, pbkdf2) and serves as a fallback when neither cryptography nor pycryptodome are available.
Performance: Slower than native providers (5-20x) but requires no compilation.
A UserWarning is shown on first use to encourage installing faster alternatives.
Example
>>> from audible.crypto_provider import get_crypto_providers, LegacyProvider >>> providers = get_crypto_providers(LegacyProvider) >>> providers.provider_name 'legacy'
- property aes: LegacyAESProvider
Get the AES provider.
- property hash: LegacyHashProvider
Get the hash provider.
- property pbkdf2: LegacyPBKDF2Provider
Get the PBKDF2 provider.
- property provider_name: str
Get provider name.
- property rsa: LegacyRSAProvider
Get the RSA provider.
- class audible.crypto_provider.legacy_provider.LegacyRSAProvider[source]
Bases:
objectRSA provider using the rsa library.
This implementation uses pure Python RSA from the rsa library.
- load_private_key(pem_data)[source]
Load an RSA private key from PEM.
Note
Caching is the caller’s responsibility for optimal performance.
- Parameters:
pem_data (
str) – RSA private key in PEM format.- Return type:
PrivateKey- Returns:
A parsed rsa.PrivateKey object.
- sign(key, data, algorithm='SHA-256')[source]
Sign data with an RSA private key using PKCS#1 v1.5.
- Parameters:
key (
Any) – A parsed rsa.PrivateKey object.data (
bytes) – The data to sign.algorithm (
str) – The hash algorithm (default: “SHA-256”).
- Return type:
bytes- Returns:
The signature bytes.
- Raises:
TypeError – If key is not an rsa.PrivateKey instance.
audible.exceptions module
- exception audible.exceptions.AuthFlowError[source]
Bases:
AudibleErrorRaised if no auth method available.
- exception audible.exceptions.BadRequest(resp, data)[source]
Bases:
StatusErrorRaised when status code 400 is returned.
Typically, when at least one search parameter was not provided.
- Parameters:
resp (
Response)data (
Any)
- exception audible.exceptions.FileEncryptionError[source]
Bases:
AudibleErrorRaised if something is wrong with file encryption.
- exception audible.exceptions.NetworkError[source]
Bases:
RequestErrorRaised if there is an issue with the network (i.e. requests.ConnectionError).
- exception audible.exceptions.NoRefreshToken[source]
Bases:
AudibleErrorRaised if refresh token is needed but not provided.
- exception audible.exceptions.NotFoundError(resp, data)[source]
Bases:
StatusErrorRaised if no result is found.
- Parameters:
resp (
Response)data (
Any)
- exception audible.exceptions.NotResponding[source]
Bases:
RequestErrorRaised if the API request timed out.
- exception audible.exceptions.RatelimitError(resp, data)[source]
Bases:
StatusErrorRaised if ratelimit is hit.
- Parameters:
resp (
Response)data (
Any)
- exception audible.exceptions.RequestError[source]
Bases:
AudibleErrorBase class for all request errors.
- exception audible.exceptions.ServerError(resp, data)[source]
Bases:
StatusErrorRaised if the api service is having issues.
- Parameters:
resp (
Response)data (
Any)
- exception audible.exceptions.StatusError(resp, data)[source]
Bases:
RequestErrorBase class for all errors except NotResponding and RatelimitDetectedError.
- Parameters:
resp (
Response)data (
Any)
- exception audible.exceptions.Unauthorized(resp, data)[source]
Bases:
StatusErrorRaised if you passed invalid credentials.
- Parameters:
resp (
Response)data (
Any)
- exception audible.exceptions.UnexpectedError(resp, data)[source]
Bases:
StatusErrorRaised if the error was not caught.
- Parameters:
resp (
Response)data (
Any)
audible.json_provider package
JSON abstraction layer with support for multiple backends.
This module provides a clean abstraction layer for JSON operations, supporting multiple backend libraries: orjson, ujson, python-rapidjson, and stdlib json.
The provider is automatically selected at runtime based on availability: 1. orjson (preferred - Rust-accelerated, with smart fallback) 2. ujson (C-based, native indent=4 support) 3. rapidjson (C++, native indent=4 support) 4. stdlib (pure Python, always available)
Users can explicitly select a provider using the class-based API.
Example
>>> from audible.json_provider import get_json_provider
>>> provider = get_json_provider() # Auto-detect
>>> data = {"name": "Audible", "version": "1.0"}
>>> json_str = provider.dumps(data, indent=4)
>>> provider.loads(json_str)
{'name': 'Audible', 'version': '1.0'}
>>> from audible.json_provider import OrjsonProvider
>>> provider = get_json_provider(OrjsonProvider)
>>> provider.provider_name
'orjson'
- exception audible.json_provider.JSONDecodeError(msg, doc='', pos=0)[source]
Bases:
JSONDecodeErrorException raised when JSON decoding fails.
This exception should be raised by all JSON providers when parsing invalid JSON data. It inherits from stdlib json.JSONDecodeError for backward compatibility.
All provider implementations must wrap their library-specific decode exceptions in this exception type to ensure consistent error handling.
- Parameters:
msg (
str) – Error message describing what went wrong.doc (
str) – The JSON document being parsed (default: empty string).pos (
int) – Position in document where error occurred (default: 0).
Example
>>> from audible.json_provider import JSONDecodeError >>> try: ... raise JSONDecodeError("Invalid JSON syntax") ... except JSONDecodeError as e: ... print(f"Caught: {type(e).__name__}") Caught: JSONDecodeError
- exception audible.json_provider.JSONEncodeError(msg)[source]
Bases:
TypeErrorException raised when JSON encoding fails.
This exception should be raised by all JSON providers when serializing objects that cannot be represented as JSON.
All provider implementations must wrap their library-specific encode exceptions in this exception type to ensure consistent error handling.
- Parameters:
msg (
str) – Error message describing what went wrong.
Example
>>> from audible.json_provider import JSONEncodeError >>> try: ... raise JSONEncodeError("Object not serializable") ... except JSONEncodeError as e: ... print(f"Caught: {type(e).__name__}") Caught: JSONEncodeError
- class audible.json_provider.JSONProvider(*args, **kwargs)[source]
Bases:
ProtocolProtocol for JSON serialization/deserialization operations.
Implementations must provide JSON encoding/decoding with configurable formatting options. Providers may implement smart fallback logic for features they don’t natively support.
The protocol supports: - Custom indentation (for human-readable output) - Custom separators (for compact output) - ASCII vs Unicode output control
- Exception Handling:
All implementations MUST raise
audible.json_provider.JSONDecodeErrorwhen JSON parsing fails, andaudible.json_provider.JSONEncodeErrorwhen serialization fails. This ensures consistent error handling across all providers and calling code.Custom providers should wrap library-specific exceptions:
from audible.json_provider import JSONDecodeError, JSONEncodeError import some_json_lib def loads(self, s: str | bytes) -> Any: try: return some_json_lib.loads(s) except some_json_lib.DecodeError as e: raise JSONDecodeError(str(e)) from e def dumps(self, obj: Any, ...) -> str: try: return some_json_lib.dumps(obj, ...) except some_json_lib.EncodeError as e: raise JSONEncodeError(str(e)) from e
- dumps(obj, *, indent=None, separators=None, ensure_ascii=True)[source]
Serialize obj to JSON string.
- Parameters:
obj (
Any) – Python object to serialize.indent (
int|None) – Number of spaces for indentation. None for compact output.separators (
tuple[str,str] |None) – (item_separator, key_separator) tuple for custom formatting.ensure_ascii (
bool) – If True, escape non-ASCII characters.
- Return type:
str- Returns:
JSON string representation.
Note
Some providers may fall back to alternative implementations for unsupported parameter combinations (e.g., orjson falls back for indent != 2 or when separators are specified).
- loads(s)[source]
Deserialize JSON string to Python object.
- Parameters:
s (
str|bytes) – JSON string or bytes to deserialize.- Return type:
Any- Returns:
Deserialized Python object.
- property provider_name: str
Return the human-readable provider name.
- Returns:
Provider identifier (e.g., “orjson”, “ujson”, “stdlib”).
- class audible.json_provider.OrjsonProvider[source]
Bases:
objectJSON provider using orjson with smart fallback logic.
This provider implements JSON operations using orjson, the fastest available JSON library for Python. When orjson cannot handle a specific feature (e.g., indent=4, custom separators), it automatically falls back to the next best available provider.
Fallback chain for unsupported features: 1. ujson (C-based, indent=4 support) 2. rapidjson (C++, indent=4 support) 3. stdlib (pure Python, all features)
Performance characteristics: - 4-5x faster than stdlib for compact/indent=2 (Rust implementation) - Automatic fallback to 2-3x faster libraries for indent=4 - Falls back to stdlib only for separators (rare use case)
- Raises:
ImportError – If orjson library is not installed.
Example
>>> from audible.json_provider import get_json_provider, OrjsonProvider >>> provider = get_json_provider(OrjsonProvider) >>> provider.provider_name 'orjson' >>> provider.dumps({"key": "value"}) # Uses orjson '{"key":"value"}' >>> print(provider.dumps({"key": "value"}, indent=4)) # Falls back to ujson { "key": "value" }
- dumps(obj, *, indent=None, separators=None, ensure_ascii=True)[source]
Serialize obj to JSON with smart fallback.
- Parameters:
obj (
Any) – Python object to serialize.indent (
int|None) – Number of spaces for indentation.separators (
tuple[str,str] |None) – (item_separator, key_separator) tuple.ensure_ascii (
bool) – If True, escape non-ASCII characters.
- Return type:
str- Returns:
JSON string representation.
- Raises:
JSONEncodeError – If obj cannot be serialized to JSON.
Note
separators -> stdlib fallback (orjson doesn’t support)
indent=4 or other -> ujson/rapidjson/stdlib fallback
indent=2 or None -> native orjson (maximum performance)
- loads(s)[source]
Deserialize JSON string using orjson.
- Parameters:
s (
str|bytes) – JSON string or bytes to deserialize.- Return type:
Any- Returns:
Deserialized Python object.
- Raises:
JSONDecodeError – If s contains invalid JSON or invalid UTF-8.
Note
orjson handles all deserialization cases natively (no fallback needed).
- property provider_name: str
Return provider name.
- class audible.json_provider.RapidjsonProvider[source]
Bases:
objectJSON provider using the python-rapidjson library.
This provider implements JSON operations using python-rapidjson, a C++ wrapper that provides excellent performance. It supports custom indentation natively, making it suitable for all common use cases.
Performance characteristics: - 2-3x faster than stdlib (C++ implementation) - Native indent support - No separators customization - Robust error handling
Limitations: - No custom separators support - Falls back to stdlib for separators
- Raises:
ImportError – If python-rapidjson library is not installed.
Example
>>> from audible.json_provider import get_json_provider, RapidjsonProvider >>> provider = get_json_provider(RapidjsonProvider) >>> provider.provider_name 'rapidjson' >>> print(provider.dumps({"key": "value"}, indent=4)) { "key": "value" }
- dumps(obj, *, indent=None, separators=None, ensure_ascii=True)[source]
Serialize obj to JSON string using python-rapidjson.
- Parameters:
obj (
Any) – Python object to serialize.indent (
int|None) – Number of spaces for indentation.separators (
tuple[str,str] |None) – If specified, falls back to stdlib (rapidjson doesn’t support this).ensure_ascii (
bool) – If True, escape non-ASCII characters.
- Return type:
str- Returns:
JSON string representation.
- Raises:
JSONEncodeError – If obj cannot be serialized to JSON.
Note
Falls back to stdlib json if separators are specified, as rapidjson doesn’t support custom separators.
- loads(s)[source]
Deserialize JSON string using python-rapidjson.
- Parameters:
s (
str|bytes) – JSON string or bytes to deserialize.- Return type:
Any- Returns:
Deserialized Python object.
- Raises:
JSONDecodeError – If s contains invalid JSON or invalid UTF-8.
- property provider_name: str
Return provider name.
- class audible.json_provider.StdlibProvider[source]
Bases:
objectJSON provider using Python’s standard library.
This provider implements all JSON operations using the built-in json module. It provides complete feature support including custom separators, arbitrary indentation levels, and all encoding options.
Performance characteristics: - Baseline performance (pure Python) - Complete feature set - Always available (no external dependencies) - Guaranteed compatibility
Example
>>> from audible.json_provider import get_json_provider, StdlibProvider >>> provider = get_json_provider(StdlibProvider) >>> provider.provider_name 'stdlib' >>> print(provider.dumps({"key": "value"}, indent=4)) { "key": "value" }
- dumps(obj, *, indent=None, separators=None, ensure_ascii=True)[source]
Serialize obj to JSON string using stdlib json.
- Parameters:
obj (
Any) – Python object to serialize.indent (
int|None) – Number of spaces for indentation.separators (
tuple[str,str] |None) – (item_separator, key_separator) tuple.ensure_ascii (
bool) – If True, escape non-ASCII characters.
- Return type:
str- Returns:
JSON string representation.
- Raises:
JSONEncodeError – If obj cannot be serialized to JSON.
- loads(s)[source]
Deserialize JSON string using stdlib json.
- Parameters:
s (
str|bytes) – JSON string or bytes to deserialize.- Return type:
Any- Returns:
Deserialized Python object.
- Raises:
JSONDecodeError – If s contains invalid JSON or invalid UTF-8.
- property provider_name: str
Return provider name.
- class audible.json_provider.UjsonProvider[source]
Bases:
objectJSON provider using the ujson library.
This provider implements JSON operations using ujson, a C-based library that offers excellent performance. It supports custom indentation natively, making it an ideal fallback for orjson when indent=4 is required.
Performance characteristics: - 2-3x faster than stdlib (C implementation) - Native indent support (any positive integer) - No separators customization (uses defaults) - Excellent for pretty-printed output
Limitations: - No custom separators support - Falls back to stdlib for separators
- Raises:
ImportError – If ujson library is not installed.
Example
>>> from audible.json_provider import get_json_provider, UjsonProvider >>> provider = get_json_provider(UjsonProvider) >>> provider.provider_name 'ujson' >>> print(provider.dumps({"key": "value"}, indent=4)) { "key": "value" }
- dumps(obj, *, indent=None, separators=None, ensure_ascii=True)[source]
Serialize obj to JSON string using ujson.
- Parameters:
obj (
Any) – Python object to serialize.indent (
int|None) – Number of spaces for indentation.separators (
tuple[str,str] |None) – If specified, falls back to stdlib (ujson doesn’t support this).ensure_ascii (
bool) – If True, escape non-ASCII characters.
- Return type:
str- Returns:
JSON string representation.
- Raises:
JSONEncodeError – If obj cannot be serialized to JSON.
Note
Falls back to stdlib json if separators are specified, as ujson doesn’t support custom separators.
- loads(s)[source]
Deserialize JSON string using ujson.
- Parameters:
s (
str|bytes) – JSON string or bytes to deserialize.- Return type:
Any- Returns:
Deserialized Python object.
- Raises:
JSONDecodeError – If s contains invalid JSON or invalid UTF-8.
- property provider_name: str
Return provider name.
- audible.json_provider.get_json_provider(provider=None)[source]
Get the JSON provider.
This is the main entry point for accessing JSON operations.
- Parameters:
provider (
JSONProvider|type[JSONProvider] |None) – Optional provider class or instance to use. Can be: - None: Auto-detect best available provider (default) - JSONProvider subclass: Force the corresponding library - JSONProvider instance: Reuse the supplied instance- Return type:
- Returns:
A JSONProvider instance.
- Raises:
ImportError – If specified provider is unavailable.
Note
This function is thread-safe. Concurrent calls will safely share cached provider instances.
Example
>>> from audible.json_provider import get_json_provider >>> provider = get_json_provider() # Auto-detect >>> provider.provider_name in {"orjson", "ujson", "rapidjson", "stdlib"} True
>>> from audible.json_provider import OrjsonProvider >>> provider = get_json_provider(OrjsonProvider) >>> provider.provider_name 'orjson'
- audible.json_provider.set_default_json_provider(provider=None)[source]
Set or reset the global default JSON provider.
- Parameters:
provider (
JSONProvider|type[JSONProvider] |None) – Provider class or instance to enforce, or None to restore auto-detection.- Raises:
ImportError – If the requested provider cannot be initialized.
- Return type:
None
Note
When switching providers the cached instances are cleared so the next call to
get_json_provider()returns a fresh instance. This function is thread-safe.Example
>>> from audible.json_provider import set_default_json_provider, StdlibProvider >>> set_default_json_provider(StdlibProvider) # Force stdlib >>> set_default_json_provider(None) # Restore auto-detection
audible.json_provider.protocols module
Protocol definitions for JSON providers.
This module defines the contracts that all JSON provider implementations must follow. Using Python’s Protocol allows for type-safe duck typing and enables static type checking with mypy.
- class audible.json_provider.protocols.JSONProvider(*args, **kwargs)[source]
Bases:
ProtocolProtocol for JSON serialization/deserialization operations.
Implementations must provide JSON encoding/decoding with configurable formatting options. Providers may implement smart fallback logic for features they don’t natively support.
The protocol supports: - Custom indentation (for human-readable output) - Custom separators (for compact output) - ASCII vs Unicode output control
- Exception Handling:
All implementations MUST raise
audible.json_provider.JSONDecodeErrorwhen JSON parsing fails, andaudible.json_provider.JSONEncodeErrorwhen serialization fails. This ensures consistent error handling across all providers and calling code.Custom providers should wrap library-specific exceptions:
from audible.json_provider import JSONDecodeError, JSONEncodeError import some_json_lib def loads(self, s: str | bytes) -> Any: try: return some_json_lib.loads(s) except some_json_lib.DecodeError as e: raise JSONDecodeError(str(e)) from e def dumps(self, obj: Any, ...) -> str: try: return some_json_lib.dumps(obj, ...) except some_json_lib.EncodeError as e: raise JSONEncodeError(str(e)) from e
- dumps(obj, *, indent=None, separators=None, ensure_ascii=True)[source]
Serialize obj to JSON string.
- Parameters:
obj (
Any) – Python object to serialize.indent (
int|None) – Number of spaces for indentation. None for compact output.separators (
tuple[str,str] |None) – (item_separator, key_separator) tuple for custom formatting.ensure_ascii (
bool) – If True, escape non-ASCII characters.
- Return type:
str- Returns:
JSON string representation.
Note
Some providers may fall back to alternative implementations for unsupported parameter combinations (e.g., orjson falls back for indent != 2 or when separators are specified).
- loads(s)[source]
Deserialize JSON string to Python object.
- Parameters:
s (
str|bytes) – JSON string or bytes to deserialize.- Return type:
Any- Returns:
Deserialized Python object.
- property provider_name: str
Return the human-readable provider name.
- Returns:
Provider identifier (e.g., “orjson”, “ujson”, “stdlib”).
audible.json_provider.exceptions module
JSON-specific exceptions for the audible library.
All JSON providers should raise these exceptions to ensure consistent error handling throughout the codebase.
- exception audible.json_provider.exceptions.JSONDecodeError(msg, doc='', pos=0)[source]
Bases:
JSONDecodeErrorException raised when JSON decoding fails.
This exception should be raised by all JSON providers when parsing invalid JSON data. It inherits from stdlib json.JSONDecodeError for backward compatibility.
All provider implementations must wrap their library-specific decode exceptions in this exception type to ensure consistent error handling.
- Parameters:
msg (
str) – Error message describing what went wrong.doc (
str) – The JSON document being parsed (default: empty string).pos (
int) – Position in document where error occurred (default: 0).
Example
>>> from audible.json_provider import JSONDecodeError >>> try: ... raise JSONDecodeError("Invalid JSON syntax") ... except JSONDecodeError as e: ... print(f"Caught: {type(e).__name__}") Caught: JSONDecodeError
- exception audible.json_provider.exceptions.JSONEncodeError(msg)[source]
Bases:
TypeErrorException raised when JSON encoding fails.
This exception should be raised by all JSON providers when serializing objects that cannot be represented as JSON.
All provider implementations must wrap their library-specific encode exceptions in this exception type to ensure consistent error handling.
- Parameters:
msg (
str) – Error message describing what went wrong.
Example
>>> from audible.json_provider import JSONEncodeError >>> try: ... raise JSONEncodeError("Object not serializable") ... except JSONEncodeError as e: ... print(f"Caught: {type(e).__name__}") Caught: JSONEncodeError
audible.json_provider.registry module
Provider registry for JSON backend selection.
This module implements a registry that automatically detects and selects the best available JSON provider at runtime, with support for explicit provider selection.
Auto-detection priority (optimized for real-world usage): 1. orjson (Rust-accelerated, fastest, with smart fallback) 2. ujson (C-based, indent=4 native support) 3. rapidjson (C++, indent=4 native support) 4. stdlib (pure Python, always available)
The registry supports both automatic detection and explicit provider selection via type-safe class-based API. Custom providers can be created by implementing the JSONProvider protocol.
Example
>>> from audible.json_provider import get_json_provider
>>> provider = get_json_provider() # Auto-detect
>>> provider.provider_name in {"orjson", "ujson", "rapidjson", "stdlib"}
True
>>> from audible.json_provider import UjsonProvider
>>> provider = get_json_provider(UjsonProvider)
>>> provider.provider_name
'ujson'
>>> from audible.json_provider import OrjsonProvider
>>> provider = get_json_provider(OrjsonProvider)
>>> provider.provider_name
'orjson'
- audible.json_provider.registry.get_json_provider(provider=None)[source]
Get the JSON provider.
This is the main entry point for accessing JSON operations.
- Parameters:
provider (
JSONProvider|type[JSONProvider] |None) – Optional provider class or instance to use. Can be: - None: Auto-detect best available provider (default) - JSONProvider subclass: Force the corresponding library - JSONProvider instance: Reuse the supplied instance- Return type:
- Returns:
A JSONProvider instance.
- Raises:
ImportError – If specified provider is unavailable.
Note
This function is thread-safe. Concurrent calls will safely share cached provider instances.
Example
>>> from audible.json_provider import get_json_provider >>> provider = get_json_provider() # Auto-detect >>> provider.provider_name in {"orjson", "ujson", "rapidjson", "stdlib"} True
>>> from audible.json_provider import OrjsonProvider >>> provider = get_json_provider(OrjsonProvider) >>> provider.provider_name 'orjson'
- audible.json_provider.registry.set_default_json_provider(provider=None)[source]
Set or reset the global default JSON provider.
- Parameters:
provider (
JSONProvider|type[JSONProvider] |None) – Provider class or instance to enforce, or None to restore auto-detection.- Raises:
ImportError – If the requested provider cannot be initialized.
- Return type:
None
Note
When switching providers the cached instances are cleared so the next call to
get_json_provider()returns a fresh instance. This function is thread-safe.Example
>>> from audible.json_provider import set_default_json_provider, StdlibProvider >>> set_default_json_provider(StdlibProvider) # Force stdlib >>> set_default_json_provider(None) # Restore auto-detection
audible.json_provider.orjson_provider module
orjson provider using the orjson library with smart fallback.
This module implements the JSON protocol using orjson, a Rust-based JSON library that provides the highest performance among all Python JSON libraries.
orjson characteristics: - 4-5x faster than stdlib for serialization/deserialization - Rust-accelerated implementation - Limited formatting options (indent=2 only) - No separators support - Returns bytes (requires decoding)
This provider implements smart fallback logic: - indent=4 or other -> falls back to ujson/rapidjson/stdlib - separators specified -> falls back to stdlib - indent=2 or None -> uses native orjson (maximum performance)
- class audible.json_provider.orjson_provider.OrjsonProvider[source]
Bases:
objectJSON provider using orjson with smart fallback logic.
This provider implements JSON operations using orjson, the fastest available JSON library for Python. When orjson cannot handle a specific feature (e.g., indent=4, custom separators), it automatically falls back to the next best available provider.
Fallback chain for unsupported features: 1. ujson (C-based, indent=4 support) 2. rapidjson (C++, indent=4 support) 3. stdlib (pure Python, all features)
Performance characteristics: - 4-5x faster than stdlib for compact/indent=2 (Rust implementation) - Automatic fallback to 2-3x faster libraries for indent=4 - Falls back to stdlib only for separators (rare use case)
- Raises:
ImportError – If orjson library is not installed.
Example
>>> from audible.json_provider import get_json_provider, OrjsonProvider >>> provider = get_json_provider(OrjsonProvider) >>> provider.provider_name 'orjson' >>> provider.dumps({"key": "value"}) # Uses orjson '{"key":"value"}' >>> print(provider.dumps({"key": "value"}, indent=4)) # Falls back to ujson { "key": "value" }
- dumps(obj, *, indent=None, separators=None, ensure_ascii=True)[source]
Serialize obj to JSON with smart fallback.
- Parameters:
obj (
Any) – Python object to serialize.indent (
int|None) – Number of spaces for indentation.separators (
tuple[str,str] |None) – (item_separator, key_separator) tuple.ensure_ascii (
bool) – If True, escape non-ASCII characters.
- Return type:
str- Returns:
JSON string representation.
- Raises:
JSONEncodeError – If obj cannot be serialized to JSON.
Note
separators -> stdlib fallback (orjson doesn’t support)
indent=4 or other -> ujson/rapidjson/stdlib fallback
indent=2 or None -> native orjson (maximum performance)
- loads(s)[source]
Deserialize JSON string using orjson.
- Parameters:
s (
str|bytes) – JSON string or bytes to deserialize.- Return type:
Any- Returns:
Deserialized Python object.
- Raises:
JSONDecodeError – If s contains invalid JSON or invalid UTF-8.
Note
orjson handles all deserialization cases natively (no fallback needed).
- property provider_name: str
Return provider name.
audible.json_provider.ujson_provider module
ujson provider using the ujson library.
This module implements the JSON protocol using ujson, a C-based JSON library that provides excellent performance while maintaining good compatibility with stdlib json.
ujson characteristics: - 2-3x faster than stdlib for serialization/deserialization - Native support for custom indentation (including indent=4) - Good compatibility with stdlib json API - No native separators support (uses default: ‘, ‘ and ‘: ‘)
This is the preferred fallback provider for orjson when indent=4 is needed.
- class audible.json_provider.ujson_provider.UjsonProvider[source]
Bases:
objectJSON provider using the ujson library.
This provider implements JSON operations using ujson, a C-based library that offers excellent performance. It supports custom indentation natively, making it an ideal fallback for orjson when indent=4 is required.
Performance characteristics: - 2-3x faster than stdlib (C implementation) - Native indent support (any positive integer) - No separators customization (uses defaults) - Excellent for pretty-printed output
Limitations: - No custom separators support - Falls back to stdlib for separators
- Raises:
ImportError – If ujson library is not installed.
Example
>>> from audible.json_provider import get_json_provider, UjsonProvider >>> provider = get_json_provider(UjsonProvider) >>> provider.provider_name 'ujson' >>> print(provider.dumps({"key": "value"}, indent=4)) { "key": "value" }
- dumps(obj, *, indent=None, separators=None, ensure_ascii=True)[source]
Serialize obj to JSON string using ujson.
- Parameters:
obj (
Any) – Python object to serialize.indent (
int|None) – Number of spaces for indentation.separators (
tuple[str,str] |None) – If specified, falls back to stdlib (ujson doesn’t support this).ensure_ascii (
bool) – If True, escape non-ASCII characters.
- Return type:
str- Returns:
JSON string representation.
- Raises:
JSONEncodeError – If obj cannot be serialized to JSON.
Note
Falls back to stdlib json if separators are specified, as ujson doesn’t support custom separators.
- loads(s)[source]
Deserialize JSON string using ujson.
- Parameters:
s (
str|bytes) – JSON string or bytes to deserialize.- Return type:
Any- Returns:
Deserialized Python object.
- Raises:
JSONDecodeError – If s contains invalid JSON or invalid UTF-8.
- property provider_name: str
Return provider name.
audible.json_provider.rapidjson_provider module
python-rapidjson provider using the python-rapidjson library.
This module implements the JSON protocol using python-rapidjson, a Python wrapper for the C++ RapidJSON library.
python-rapidjson characteristics: - 2-3x faster than stdlib for serialization/deserialization - Native support for custom indentation - Good compatibility with stdlib json API - No native separators support - Excellent for both compact and pretty-printed output
This serves as an alternative fallback provider to ujson.
- class audible.json_provider.rapidjson_provider.RapidjsonProvider[source]
Bases:
objectJSON provider using the python-rapidjson library.
This provider implements JSON operations using python-rapidjson, a C++ wrapper that provides excellent performance. It supports custom indentation natively, making it suitable for all common use cases.
Performance characteristics: - 2-3x faster than stdlib (C++ implementation) - Native indent support - No separators customization - Robust error handling
Limitations: - No custom separators support - Falls back to stdlib for separators
- Raises:
ImportError – If python-rapidjson library is not installed.
Example
>>> from audible.json_provider import get_json_provider, RapidjsonProvider >>> provider = get_json_provider(RapidjsonProvider) >>> provider.provider_name 'rapidjson' >>> print(provider.dumps({"key": "value"}, indent=4)) { "key": "value" }
- dumps(obj, *, indent=None, separators=None, ensure_ascii=True)[source]
Serialize obj to JSON string using python-rapidjson.
- Parameters:
obj (
Any) – Python object to serialize.indent (
int|None) – Number of spaces for indentation.separators (
tuple[str,str] |None) – If specified, falls back to stdlib (rapidjson doesn’t support this).ensure_ascii (
bool) – If True, escape non-ASCII characters.
- Return type:
str- Returns:
JSON string representation.
- Raises:
JSONEncodeError – If obj cannot be serialized to JSON.
Note
Falls back to stdlib json if separators are specified, as rapidjson doesn’t support custom separators.
- loads(s)[source]
Deserialize JSON string using python-rapidjson.
- Parameters:
s (
str|bytes) – JSON string or bytes to deserialize.- Return type:
Any- Returns:
Deserialized Python object.
- Raises:
JSONDecodeError – If s contains invalid JSON or invalid UTF-8.
- property provider_name: str
Return provider name.
audible.json_provider.stdlib_provider module
Stdlib JSON provider using Python’s built-in json module.
This module implements the JSON protocol using Python’s standard library json module, which provides complete feature support and is always available.
The stdlib provider serves as: - Fallback when no optimized libraries are installed - Final fallback for features unsupported by optimized providers (e.g., separators) - Reference implementation with guaranteed compatibility
- class audible.json_provider.stdlib_provider.StdlibProvider[source]
Bases:
objectJSON provider using Python’s standard library.
This provider implements all JSON operations using the built-in json module. It provides complete feature support including custom separators, arbitrary indentation levels, and all encoding options.
Performance characteristics: - Baseline performance (pure Python) - Complete feature set - Always available (no external dependencies) - Guaranteed compatibility
Example
>>> from audible.json_provider import get_json_provider, StdlibProvider >>> provider = get_json_provider(StdlibProvider) >>> provider.provider_name 'stdlib' >>> print(provider.dumps({"key": "value"}, indent=4)) { "key": "value" }
- dumps(obj, *, indent=None, separators=None, ensure_ascii=True)[source]
Serialize obj to JSON string using stdlib json.
- Parameters:
obj (
Any) – Python object to serialize.indent (
int|None) – Number of spaces for indentation.separators (
tuple[str,str] |None) – (item_separator, key_separator) tuple.ensure_ascii (
bool) – If True, escape non-ASCII characters.
- Return type:
str- Returns:
JSON string representation.
- Raises:
JSONEncodeError – If obj cannot be serialized to JSON.
- loads(s)[source]
Deserialize JSON string using stdlib json.
- Parameters:
s (
str|bytes) – JSON string or bytes to deserialize.- Return type:
Any- Returns:
Deserialized Python object.
- Raises:
JSONDecodeError – If s contains invalid JSON or invalid UTF-8.
- property provider_name: str
Return provider name.
audible.localization module
- class audible.localization.Locale(country_code=None, domain=None, market_place_id=None)[source]
Bases:
objectAdjustments for the different marketplaces who are provided by Audible.
You can try to
autodetect_localeif your marketplace is not in templates`.- Parameters:
country_code (
str|None)domain (
str|None)market_place_id (
str|None)
- property country_code: str
- property domain: str
- property market_place_id: str
- audible.localization.autodetect_locale(domain)[source]
Try to automatically detect correct settings for marketplace.
Needs the top level domain of the audible page to continue with (e.g. co.uk, co.jp) and returns results found.
- Parameters:
domain (
str) – The top level domain for the Audible marketplace to detect settings for (e.g. com).- Return type:
dict[str,str]- Returns:
The settings for the found Audible marketplace.
- Raises:
ConnectError – If site does not exist or network error raises.
Exception – If marketplace or country code can’t be found.
audible.login module
- audible.login.build_init_cookies()[source]
Build initial cookies to prevent captcha in most cases.
- Return type:
dict[str,str]
- audible.login.build_oauth_url(country_code, domain, market_place_id, code_verifier, serial=None, with_username=False)[source]
Builds the url to login to Amazon as an Audible device.
- Parameters:
country_code (
str)domain (
str)market_place_id (
str)code_verifier (
bytes)serial (
str|None)with_username (
bool)
- Return type:
tuple[str,str]
- audible.login.check_for_approval_alert(soup)[source]
Checks a Amazon login page for an approval alert.
- Parameters:
soup (
BeautifulSoup)- Return type:
bool
- audible.login.check_for_captcha(soup)[source]
Checks a Amazon login page for a captcha form.
- Parameters:
soup (
BeautifulSoup)- Return type:
bool
- audible.login.check_for_choice_mfa(soup)[source]
Checks a Amazon login page for a MFA selection form.
- Parameters:
soup (
BeautifulSoup)- Return type:
bool
- audible.login.check_for_mfa(soup)[source]
Checks a Amazon login page for a multi-factor authentication form.
- Parameters:
soup (
BeautifulSoup)- Return type:
bool
- audible.login.create_s256_code_challenge(verifier)[source]
- Parameters:
verifier (
bytes)- Return type:
bytes
- audible.login.default_approval_alert_callback()[source]
Helper function for handling approval alerts.
- Return type:
None
- audible.login.default_captcha_callback(captcha_url)[source]
Helper function for handling captcha.
- Parameters:
captcha_url (
str)- Return type:
str
- audible.login.default_cvf_callback()[source]
Helper function for handling cvf verifys.
Amazon sends a verify code via Mail or SMS.
- Return type:
str
- audible.login.default_login_url_callback(url)[source]
Helper function for login with external browsers.
- Parameters:
url (
str)- Return type:
str
- audible.login.default_otp_callback()[source]
Helper function for handling 2-factor authentication.
- Return type:
str
- audible.login.external_login(country_code, domain, market_place_id, serial=None, with_username=False, login_url_callback=None)[source]
Gives the url to login with external browser and prompt for result.
Note
If you are using MacOS and have trouble insert the login result url simply import the readline module in your script. See #34.
- Parameters:
country_code (
str) – The country code for the Audible marketplace to login.domain (
str) – The top level domain for the Audible marketplace to login.market_place_id (
str) – The id for the Audible marketplace to login.serial (
str|None) – The device serial. IfNonea custom one will be created.with_username (
bool) – IfTruelogin with Audible username instead of Amazon account.login_url_callback (
Callable[[str],str] |None) – A custom Callable for handling login with external browsers. IfNonedefault_login_url_callback()is used.
- Return type:
dict[str,Any]- Returns:
An
authorization_code, acode_verifierand thedevice serialfrom the authorized Client.
- audible.login.extract_captcha_url(soup)[source]
Returns the captcha url from a Amazon login page.
- Parameters:
soup (
BeautifulSoup)- Return type:
str
- audible.login.extract_code_from_url(url)[source]
Extracts the access token from url query after login.
- Parameters:
url (
URL)- Return type:
str
- audible.login.get_inputs_from_soup(soup, search_field=None)[source]
Extracts hidden form input fields from a Amazon login page.
- Parameters:
soup (
BeautifulSoup)search_field (
dict[str,str] |None)
- Return type:
dict[str,str]
- audible.login.get_next_action_from_soup(soup, search_field=None)[source]
- Parameters:
soup (
BeautifulSoup)search_field (
dict[str,str] |None)
- Return type:
tuple[str,str]
- audible.login.get_soup(resp, log_errors=True)[source]
- Parameters:
resp (
Response)log_errors (
bool)
- Return type:
BeautifulSoup
- audible.login.login(username, password, country_code, domain, market_place_id, serial=None, with_username=False, captcha_callback=None, otp_callback=None, cvf_callback=None, approval_callback=None)[source]
Login to Audible by simulating an Audible App for iOS.
- Parameters:
username (
str) – The Amazon email address.password (
str) – The Amazon password.country_code (
str) – The country code for the Audible marketplace to login.domain (
str) – domain: The top level domain for the Audible marketplace to login.market_place_id (
str) – The id for the Audible marketplace to login.serial (
str|None) – The device serial. IfNonea custom one will be created.with_username (
bool) – IfTruelogin with Audible username instead of Amazon account.captcha_callback (
Callable[[str],str] |None) – A custom Callable for handling captcha requests. IfNonedefault_captcha_callback()is used.otp_callback (
Callable[[],str] |None) – A custom Callable for providing one-time passwords. IfNonedefault_otp_callback()is used.cvf_callback (
Callable[[],str] |None) – A custom Callable for providing the answer for a CVF code. IfNonedefault_cvf_callback()is used.approval_callback (
Callable[[],Any] |None) – A custom Callable for handling approval alerts. IfNonedefault_approval_alert_callback()is used.
- Return type:
dict[str,Any]- Returns:
An
authorization_code, acode_verifierand thedevice serialfrom the authorized Client.- Raises:
Exception – If authorization_code is not in response url.
audible.metadata module
- class audible.metadata.XXTEA(key)[source]
Bases:
objectXXTEA wrapper class.
Easy to use and compatible (by duck typing) with the Blowfish class.
- Parameters:
key (
str|bytes) – The encryption key (must be 128-bit / 16 characters).- Raises:
XXTEAException – If the key is not exactly 16 bytes long.
Note
Partial copied from https://github.com/andersekbom/prycut and ported from PY2 to PY3
- audible.metadata.decrypt_metadata(encrypted_metadata)[source]
Decrypts metadata for testing purposes only.
- Parameters:
encrypted_metadata (
str)- Return type:
str
- audible.metadata.encrypt_metadata(metadata)[source]
Encrypts metadata to be used to log in to Amazon.
- Parameters:
metadata (
str)- Return type:
str
audible.register module
- audible.register.deregister(access_token, domain, deregister_all=False, with_username=False)[source]
Deregister a previous registered Audible device.
Note
Except of the
access_token, all authentication data will lose validation immediately.- Parameters:
access_token (
str) – The access token from the previous registered device which you want to deregister.domain (
str) – The top level domain of the requested Amazon server (e.g. com).deregister_all (
bool) – IfTrue, deregister all Audible devices on Amazon.with_username (
bool) – IfTrueuses audible domain instead of amazon.
- Return type:
Any- Returns:
The response for the deregister request. Contains errors, if some occurs.
- Raises:
Exception – If response status code is not 200.
Added in version v0.8: The with_username argument
- audible.register.register(authorization_code, code_verifier, domain, serial, with_username=False)[source]
Registers a dummy Audible device.
- Parameters:
authorization_code (
str) – The code given after a successful authorizationcode_verifier (
bytes) – The verifier code from authorizationdomain (
str) – The top level domain of the requested Amazon server (e.g. com).serial (
str) – The device serialwith_username (
bool) – IfTrueuses audible domain instead of amazon.
- Return type:
dict[str,Any]- Returns:
Additional authentication data needed for access Audible API.
- Raises:
Exception – If response status code is not 200.
Added in version v0.7.1: The with_username argument