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:
ABC
Collection of endpoints for a remote API. See
RequestHandler
andAPIAuthoriser
for more info on which params to pass to authorise and execute requests.- Parameters:
wrangler (
RemoteDataWrangler
) – TheRemoteDataWrangler
for this API type.authoriser (
APIAuthoriser
) – 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
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
Methods:
authorise
([force_load, force_new])Main method for authorisation, tests/refreshes/reauthorises as needed
close
()Close the current session.
Load and store user data in this API object for the currently authorised user
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])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.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
- 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: str
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
The
RequestHandler
for handling authorised requests to the API
-
user_data:
dict
[str
,Any
] Stores the loaded user data for the currently authorised user
- authorise(force_load=False, force_new=False)
Main method for authorisation, tests/refreshes/reauthorises as needed
- Parameters:
force_load (
bool
(default:False
)) – Reloads the token even if it’s already been loaded into the object. Ignored when force_new is True.force_new (
bool
(default:False
)) – Ignore saved/loaded token and generate new token.
- Returns:
Self
– Self.- Raises:
APIError – If the token cannot be validated.
- close()
Close the current session. No more requests will be possible once this has been called.
- Return type:
None
- load_user_data()
Load and store user data in this API object for the currently authorised user
- 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 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 (
str
|Mapping
[str
,Any
] |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 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 (
str
|Mapping
[str
,Any
] |RemoteResponse
) – In URL/URI/ID form, or the name of one of the currently authenticated user’s playlists.- Returns:
str
– 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 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 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 extend_items(response, kind=None, key=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 itself 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.
- Returns:
list
[dict
[str
,Any
]] – API JSON responses for each item
- abstract 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 (
Union
[str
,MutableSequence
[str
],MutableMapping
[str
,Any
],MutableSequence
[MutableMapping
[str
,Any
]],RemoteResponse
,Sequence
[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 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 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 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:
str
– API URL for playlist.
- abstract add_to_playlist(playlist, items, limit=50, skip_dupes=True)
POST
- Add list of tracks to a given playlist.- Parameters:
playlist (
str
|Mapping
[str
,Any
] |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
]) – 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.
- abstract delete_playlist(playlist)
DELETE
- Unfollow/delete a given playlist. WARNING: This function will destructively modify your remote playlists.- Parameters:
playlist (
str
|Mapping
[str
,Any
] |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:
str
– API URL for playlist.
- abstract 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 (
str
|Mapping
[str
,Any
] |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.