APIο
The framework for interacting with a remote API.
All methods that interact with the API should return raw, unprocessed responses.
Classes:
|
Collection of endpoints for a remote API. |
- class musify.libraries.remote.core.api.RemoteAPI(authoriser, wrangler, cache=None)ο
Bases:
Generic
Collection of endpoints for a remote API. See
RequestHandler
andAuthoriser
for more info on which params to pass to authorise and execute requests.- Parameters:
wrangler (
RemoteDataWrangler
) β TheRemoteDataWrangler
for this API type.authoriser (
TypeVar
(A
, bound=Authoriser
)) β The authoriser to use when authorising requests to the API.cache (
ResponseCache
|None
(default:None
)) β When given, attempt to use this cache for certain request types before calling the API. Repository and cachable request types can be set up by child classes.
Attributes:
Map of
RemoteObjectType
for remote collections to theRemoteObjectType
of the items they holdA set of possible saved item types that can be retrieved for the currently authenticated user
The key to use when getting an ID from a response
The key to use when getting the URL from a response
ID of the currently authorised user
Name of the currently authorised user
The base URL of the API
The name of the API service
The
MusifyLogger
for this objectA
RemoteDataWrangler
object for processing URIsThe
RequestHandler
for handling authorised requests to the APIStores the loaded user data for the currently authorised user
Stores the loaded user playlists data for the currently authorised user
Methods:
Main method for authorisation, tests/refreshes/reauthorises as needed
close
()Close the current session.
Load and store user data for the currently authorised user in this API object
Load and store user playlists data for the currently authorised user in this API object
print_item
(i,Β name,Β uri[,Β length,Β total,Β ...])Pretty print item data for displaying to the user.
print_collection
([value,Β kind,Β limit])Pretty print collection data for displaying to the user.
get_playlist_url
(playlist)Determine the type of the given
playlist
and return its API URL.get_self
([update_user_data])GET
- Get API response for information on current userquery
(query,Β kind[,Β limit])GET
- Query for items.extend_items
(response[,Β kind,Β key,Β leave_bar])Extend the items for a given API
response
.get_items
(values[,Β kind,Β limit,Β extend])GET
- Get information for givenvalues
.get_tracks
(values[,Β limit])Wrapper for
get_items()
which only returns Track type responses.get_user_items
([user,Β kind,Β limit])GET
- Get saved items for a given user.create_playlist
(name,Β *args,Β **kwargs)POST
- Create an empty playlist for the current user with the given name.add_to_playlist
(playlist,Β items[,Β limit,Β ...])POST
- Add list of tracks to a given playlist.get_or_create_playlist
(name,Β *args,Β **kwargs)Attempt to find the playlist with the given
name
and return it.follow_playlist
(playlist,Β *args,Β **kwargs)PUT
- Follow a given playlist.delete_playlist
(playlist)DELETE
- Unfollow/delete a given playlist.clear_from_playlist
(playlist[,Β items,Β limit])DELETE
- Clear tracks from a given playlist.- collection_item_map = {RemoteObjectType.PLAYLIST: RemoteObjectType.TRACK, RemoteObjectType.ALBUM: RemoteObjectType.TRACK, RemoteObjectType.SHOW: RemoteObjectType.EPISODE, RemoteObjectType.AUDIOBOOK: RemoteObjectType.CHAPTER}ο
Map of
RemoteObjectType
for remote collections to theRemoteObjectType
of the items they hold
- user_item_types = {RemoteObjectType.PLAYLIST, RemoteObjectType.TRACK, RemoteObjectType.ALBUM, RemoteObjectType.ARTIST, RemoteObjectType.SHOW, RemoteObjectType.EPISODE, RemoteObjectType.AUDIOBOOK}ο
A set of possible saved item types that can be retrieved for the currently authenticated user
- id_key = 'id'ο
The key to use when getting an ID from a response
- url_key = 'href'ο
The key to use when getting the URL from a response
- abstract property user_id: str | Noneο
ID of the currently authorised user
- abstract property user_name: str | Noneο
Name of the currently authorised user
- property url: URLο
The base URL of the API
- property source: strο
The name of the API service
-
logger:
MusifyLogger
ο The
MusifyLogger
for this object
- wranglerο
A
RemoteDataWrangler
object for processing URIs
-
handler:
RequestHandler
[TypeVar
(A
, bound=Authoriser
),dict
[str
,str
|int
|float
|list
|dict
|bool
|None
]]ο The
RequestHandler
for handling authorised requests to the API
-
user_data:
dict
[str
,Any
]ο Stores the loaded user data for the currently authorised user
-
user_playlist_data:
dict
[str
,dict
[str
,Any
]]ο Stores the loaded user playlists data for the currently authorised user
- async authorise()ο
Main method for authorisation, tests/refreshes/reauthorises as needed
- Returns:
Self
β Self.- Raises:
APIError β If the token cannot be validated.
- async close()ο
Close the current session. No more requests will be possible once this has been called.
- Return type:
None
- async load_user()ο
Load and store user data for the currently authorised user in this API object
- Return type:
None
- abstract async load_user_playlists()ο
Load and store user playlists data for the currently authorised user in this API object
- Return type:
None
- print_item(i, name, uri, length=0, total=1, max_width=50)ο
Pretty print item data for displaying to the user. Format =
<i> - <name> | <length> | <URI> - <URL>
.- Parameters:
i (
int
) β The position of this item in the collection.name (
str
) β The name of the item.uri (
str
) β The URI of the item.length (
float
(default:0
)) β The duration of the item in seconds.total (
int
(default:1
)) β The total number of items in the collectionmax_width (
int
(default:50
)) β The maximum width to print names as. Any name lengths longer than this will be truncated.
- Return type:
None
- abstract async print_collection(value=None, kind=None, limit=20)ο
Pretty print collection data for displaying to the user. Runs
print_item()
for each item in the collection.value
may be:A string representing a URL/URI/ID.
A remote API JSON response for a collection with a valid ID value under an
id
key.A RemoteResponse representing some remote collection of items.
- Parameters:
value (
GenericAlias
[RemoteResponse
] |None
(default:None
)) β The value representing some remote collection. See description for allowed value types.kind (
RemoteIDType
|None
(default:None
)) β When an ID is provided, give the kind of ID this is here. If None and ID is given, user will be prompted to give the kind anyway.limit (
int
(default:20
)) β The number of results to call per request and, therefore, the number of items in each printed block.
- Return type:
None
- abstract async get_playlist_url(playlist)ο
Determine the type of the given
playlist
and return its API URL. If type cannot be determined, attempt to find the playlist in the list of the currently authenticated userβs playlists.- Parameters:
playlist (
GenericAlias
[RemoteResponse
]) β In URL/URI/ID form, or the name of one of the currently authenticated userβs playlists.- Returns:
URL
β The playlist URL.- Raises:
RemoteIDTypeError β Raised when the function cannot determine the item type of the input
playlist
. Or when it does not recognise the type of the inputplaylist
parameter.
- abstract async get_self(update_user_data=True)ο
GET
- Get API response for information on current user- Parameters:
update_user_data (
bool
(default:True
)) β When True, update the_user_data
stored in this API object.- Return type:
dict
[str
,Any
]
- abstract async query(query, kind, limit=10)ο
GET
- Query for items. Modify result types returned with kind parameter- Parameters:
query (
str
) β Search query.kind (
RemoteObjectType
) β The remote object type to search for.limit (
int
(default:10
)) β Number of results to get and return.
- Returns:
list
[dict
[str
,Any
]] β The response from the endpoint.
- abstract async extend_items(response, kind=None, key=None, leave_bar=None)ο
Extend the items for a given API
response
. The function requests each page of the collection returning a list of all items found across all pages for this URL.Updates the value of the
items
key in-place by extending the value of theitems
key with new results.If a
RemoteResponse
, this function will not refresh it with the new response. The user must call refresh manually after execution.- Parameters:
response (
MutableMapping
[str
,Any
] |RemoteResponse
) β A remote API JSON response for an items type endpoint.kind (
RemoteObjectType
|str
|None
(default:None
)) β The type of response being extended. Optional, used only for logging.key (
RemoteObjectType
|None
(default:None
)) β The type of response of the child objects.leave_bar (
bool
|None
(default:None
)) β When a progress bar is displayed, toggle whether this bar should continue to be displayed after the operation is finished. When None, allow the logger to decide this setting.
- Returns:
list
[dict
[str
,Any
]] β API JSON responses for each item
- abstract async get_items(values, kind=None, limit=50, extend=True)ο
GET
- Get information for givenvalues
.values
may be:A string representing a URL/URI/ID.
A MutableSequence of strings representing URLs/URIs/IDs of the same type.
A remote API JSON response for a collection.
A MutableSequence of remote API JSON responses for a collection.
A RemoteResponse of the appropriate type for this RemoteAPI which holds a valid API JSON response as described above.
A Sequence of RemoteResponses as above.
If JSON response(s) given, this updates each response given by merging with the new response.
If
RemoteResponse
values are given, this function will call refresh on them.- Parameters:
values (
GenericAlias
[RemoteResponse
]) β The values representing some remote objects. See description for allowed value types. These items must all be of the same type of item i.e. all tracks OR all artists etc.kind (
RemoteObjectType
|None
(default:None
)) β Item type if given string is ID.limit (
int
(default:50
)) β When requests can be batched, size of batches to request. This value will be limited to be between1
and50
.extend (
bool
(default:True
)) β When True and the givenkind
is a collection of items, extend the response to include all items in this collection.
- Returns:
list
[dict
[str
,Any
]] β API JSON responses for each item.- Raises:
RemoteObjectTypeError β Raised when the function cannot determine the item type of the input
values
. Or when it does not recognise the type of the inputvalues
parameter.
- abstract async get_tracks(values, limit=50, *args, **kwargs)ο
Wrapper for
get_items()
which only returns Track type responses. Seeget_items()
for more info.- Return type:
list
[dict
[str
,Any
]]
- abstract async get_user_items(user=None, kind=RemoteObjectType.PLAYLIST, limit=50)ο
GET
- Get saved items for a given user.- Parameters:
user (
str
|None
(default:None
)) β The ID of the user to get playlists for. If None, use the currently authenticated user.kind (
RemoteObjectType
(default:<RemoteObjectType.PLAYLIST: 1>
)) β Item type to retrieve for the user.limit (
int
(default:50
)) β Size of each batch of items to request in the collection items request. This value will be limited to be between1
and50
.
- Returns:
list
[dict
[str
,Any
]] β API JSON responses for each collection.- Raises:
RemoteIDTypeError β Raised when the input
user
does not represent a user URL/URI/ID.RemoteObjectTypeError β When the given
kind
is not a valid user item/collection.
- abstract async create_playlist(name, *args, **kwargs)ο
POST
- Create an empty playlist for the current user with the given name.- Parameters:
name (
str
) β Name of playlist to create.- Returns:
dict
[str
,Any
] β API JSON response for the created playlist.
- abstract async add_to_playlist(playlist, items, limit=50, skip_dupes=True)ο
POST
- Add list of tracks to a given playlist.- Parameters:
playlist (
GenericAlias
[RemoteResponse
]) β One of the following to identify the playlist to clear: - playlist URL/URI/ID, - the name of the playlist in the current userβs playlists, - the API response of a playlist. - a RemoteResponse object representing a remote playlist.items (
Sequence
[str
]) β List of URLs/URIs/IDs of the tracks to add.limit (
int
(default:50
)) β Size of each batch of IDs to add. This value will be limited to be between1
and50
.skip_dupes (
bool
(default:True
)) β Skip duplicates.
- Returns:
int
β The number of tracks added to the playlist.- Raises:
RemoteIDTypeError β Raised when the input
playlist
does not represent a playlist URL/URI/ID.RemoteObjectTypeError β Raised when the item types of the input
items
are not all tracks or IDs.
- async get_or_create_playlist(name, *args, **kwargs)ο
Attempt to find the playlist with the given
name
and return it. Otherwise, create a new playlist.Any given args and kwargs are passed directly onto
create_playlist()
when a matching loaded playlist is not found.When a playlist is created, persist the response back to the loaded playlists in this object.
- Parameters:
name (
str
) β The case-sensitive name of the playlist to get/create.- Returns:
dict
[str
,Any
] β API JSON response for the loaded/created playlist.
- async follow_playlist(playlist, *args, **kwargs)ο
PUT
- Follow a given playlist.- Parameters:
playlist (
GenericAlias
[RemoteResponse
]) β One of the following to identify the playlist to clear: - playlist URL/URI/ID, - the name of the playlist in the current userβs playlists, - the API response of a playlist. - a RemoteResponse object representing a remote playlist.- Returns:
URL
β API URL for playlist.
- abstract async delete_playlist(playlist)ο
DELETE
- Unfollow/delete a given playlist. WARNING: This function will destructively modify your remote playlists.- Parameters:
playlist (
GenericAlias
[RemoteResponse
]) β One of the following to identify the playlist to clear: - playlist URL/URI/ID, - the name of the playlist in the current userβs playlists, - the API response of a playlist. - a RemoteResponse object representing a remote playlist.- Returns:
URL
β API URL for playlist.
- abstract async clear_from_playlist(playlist, items=None, limit=100)ο
DELETE
- Clear tracks from a given playlist. WARNING: This function can destructively modify your remote playlists.- Parameters:
playlist (
GenericAlias
[RemoteResponse
]) β One of the following to identify the playlist to clear: - playlist URL/URI/ID, - the name of the playlist in the current userβs playlists, - the API response of a playlist. - a RemoteResponse object representing a remote playlist.items (
Collection
[str
] |None
(default:None
)) β List of URLs/URIs/IDs of the tracks to remove. If None, clear all songs from the playlist.limit (
int
(default:100
)) β Size of each batch of IDs to clear in a single request. This value will be limited to be between1
and100
.
- Returns:
int
β The number of tracks cleared from the playlist.- Raises:
RemoteIDTypeError β Raised when the input
playlist
does not represent a playlist URL/URI/ID.RemoteObjectTypeError β Raised when the item types of the input
items
are not all tracks or IDs.