introduce exception classes (#620)

This commit is contained in:
sigma67 2024-07-13 21:25:45 +02:00 • committed by GitHub
commit 12cc15eaf4
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
11 changed files with 58 additions and 28 deletions

View file

@ -4,6 +4,7 @@ from typing import Optional
from requests.structures import CaseInsensitiveDict from requests.structures import CaseInsensitiveDict
from ytmusicapi.exceptions import YTMusicError, YTMusicUserError
from ytmusicapi.helpers import * from ytmusicapi.helpers import *
path = os.path.dirname(os.path.realpath(__file__)) + os.sep path = os.path.dirname(os.path.realpath(__file__)) + os.sep
@ -46,11 +47,11 @@ def setup_browser(filepath: Optional[str] = None, headers_raw: Optional[str] = N
user_headers[header[0].lower()] = ": ".join(header[1:]) user_headers[header[0].lower()] = ": ".join(header[1:])
except Exception as e: except Exception as e:
raise Exception(f"Error parsing your input, please try again. Full error: {e}") from e raise YTMusicError(f"Error parsing your input, please try again. Full error: {e}") from e
missing_headers = {"cookie", "x-goog-authuser"} - set(k.lower() for k in user_headers.keys()) missing_headers = {"cookie", "x-goog-authuser"} - set(k.lower() for k in user_headers.keys())
if missing_headers: if missing_headers:
raise Exception( raise YTMusicUserError(
"The following entries are missing in your headers: " "The following entries are missing in your headers: "
+ ", ".join(missing_headers) + ", ".join(missing_headers)
+ ". Please try a different request (such as /browse) and make sure you are logged in." + ". Please try a different request (such as /browse) and make sure you are logged in."

View file

@ -14,6 +14,7 @@ from ytmusicapi.constants import (
OAUTH_USER_AGENT, OAUTH_USER_AGENT,
) )
from ...exceptions import YTMusicServerError
from .exceptions import BadOAuthClient, UnauthorizedOAuthClient from .exceptions import BadOAuthClient, UnauthorizedOAuthClient
from .models import AuthCodeDict, BaseTokenDict, RefreshableTokenDict from .models import AuthCodeDict, BaseTokenDict, RefreshableTokenDict
@ -94,7 +95,7 @@ class OAuthCredentials(Credentials):
"YouTubeData API is not enabled." "YouTubeData API is not enabled."
) )
else: else:
raise Exception( raise YTMusicServerError(
f"OAuth request error. status_code: {response.status_code}, url: {url}, content: {data}" f"OAuth request error. status_code: {response.status_code}, url: {url}, content: {data}"
) )
return response return response

16
ytmusicapi/exceptions.py Normal file
View file

@ -0,0 +1,16 @@
"""custom exception classes for ytmusicapi"""
class YTMusicError(Exception):
"""base error class
shall only be raised if none of the subclasses below are fitting
"""
class YTMusicUserError(YTMusicError):
"""error caused by invalid usage of ytmusicapi"""
class YTMusicServerError(YTMusicError):
"""error caused by the YouTube Music backend"""

View file

@ -1,6 +1,8 @@
import re import re
from datetime import date from datetime import date
from ytmusicapi.exceptions import YTMusicUserError
def prepare_like_endpoint(rating): def prepare_like_endpoint(rating):
if rating == "LIKE": if rating == "LIKE":
@ -16,7 +18,7 @@ def prepare_like_endpoint(rating):
def validate_order_parameter(order): def validate_order_parameter(order):
orders = ["a_to_z", "z_to_a", "recently_added"] orders = ["a_to_z", "z_to_a", "recently_added"]
if order and order not in orders: if order and order not in orders:
raise Exception( raise YTMusicUserError(
"Invalid order provided. Please use one of the following orders or leave out the parameter: " "Invalid order provided. Please use one of the following orders or leave out the parameter: "
+ ", ".join(orders) + ", ".join(orders)
) )

View file

@ -12,6 +12,7 @@ from ytmusicapi.parsers.browsing import parse_album, parse_content_list, parse_m
from ytmusicapi.parsers.library import parse_albums from ytmusicapi.parsers.library import parse_albums
from ytmusicapi.parsers.playlists import parse_playlist_items from ytmusicapi.parsers.playlists import parse_playlist_items
from ..exceptions import YTMusicError, YTMusicUserError
from ..navigation import * from ..navigation import *
from ._protocol import MixinProtocol from ._protocol import MixinProtocol
from ._utils import get_datestamp from ._utils import get_datestamp
@ -510,7 +511,7 @@ class BrowsingMixin(MixinProtocol):
} }
""" """
if not browseId or not browseId.startswith("MPRE"): if not browseId or not browseId.startswith("MPRE"):
raise Exception("Invalid album browseId provided, must start with MPRE.") raise YTMusicUserError("Invalid album browseId provided, must start with MPRE.")
body = {"browseId": browseId} body = {"browseId": browseId}
endpoint = "browse" endpoint = "browse"
@ -793,7 +794,7 @@ class BrowsingMixin(MixinProtocol):
] ]
""" """
if not browseId: if not browseId:
raise Exception("Invalid browseId provided.") raise YTMusicUserError("Invalid browseId provided.")
response = self._send_request("browse", {"browseId": browseId}) response = self._send_request("browse", {"browseId": browseId})
sections = nav(response, ["contents", *SECTION_LIST]) sections = nav(response, ["contents", *SECTION_LIST])
@ -816,7 +817,7 @@ class BrowsingMixin(MixinProtocol):
""" """
lyrics = {} lyrics = {}
if not browseId: if not browseId:
raise Exception("Invalid browseId provided. This song might not have lyrics.") raise YTMusicUserError("Invalid browseId provided. This song might not have lyrics.")
response = self._send_request("browse", {"browseId": browseId}) response = self._send_request("browse", {"browseId": browseId})
lyrics["lyrics"] = nav( lyrics["lyrics"] = nav(
@ -837,7 +838,7 @@ class BrowsingMixin(MixinProtocol):
response = self._send_get_request(url=YTM_DOMAIN) response = self._send_get_request(url=YTM_DOMAIN)
match = re.search(r'jsUrl"\s*:\s*"([^"]+)"', response.text) match = re.search(r'jsUrl"\s*:\s*"([^"]+)"', response.text)
if match is None: if match is None:
raise Exception("Could not identify the URL for base.js player.") raise YTMusicError("Could not identify the URL for base.js player.")
return YTM_DOMAIN + match.group(1) return YTM_DOMAIN + match.group(1)
@ -855,7 +856,7 @@ class BrowsingMixin(MixinProtocol):
response = self._send_get_request(url=url) response = self._send_get_request(url=url)
match = re.search(r"signatureTimestamp[:=](\d+)", response.text) match = re.search(r"signatureTimestamp[:=](\d+)", response.text)
if match is None: if match is None:
raise Exception("Unable to identify the signatureTimestamp.") raise YTMusicError("Unable to identify the signatureTimestamp.")
return int(match.group(1)) return int(match.group(1))
@ -911,7 +912,7 @@ class BrowsingMixin(MixinProtocol):
for artist in artists: for artist in artists:
if artist not in taste_profile: if artist not in taste_profile:
raise Exception(f"The artist, {artist}, was not present in taste!") raise YTMusicUserError(f"The artist {artist} was not present in taste!")
formData["selectedValues"].append(taste_profile[artist]["selectionValue"]) formData["selectedValues"].append(taste_profile[artist]["selectionValue"])
body = {"browseId": "FEmusic_home", "formData": formData} body = {"browseId": "FEmusic_home", "formData": formData}

View file

@ -5,6 +5,7 @@ from ytmusicapi.continuations import *
from ytmusicapi.parsers.browsing import * from ytmusicapi.parsers.browsing import *
from ytmusicapi.parsers.library import * from ytmusicapi.parsers.library import *
from ..exceptions import YTMusicServerError
from ._protocol import MixinProtocol from ._protocol import MixinProtocol
from ._utils import * from ._utils import *
@ -69,7 +70,7 @@ class LibraryMixin(MixinProtocol):
parse_func = lambda raw_response: parse_library_songs(raw_response) parse_func = lambda raw_response: parse_library_songs(raw_response)
if validate_responses and limit is None: if validate_responses and limit is None:
raise Exception("Validation is not supported without a limit parameter.") raise YTMusicUserError("Validation is not supported without a limit parameter.")
if validate_responses: if validate_responses:
validate_func = lambda parsed: validate_response(parsed, per_page, limit, 0) validate_func = lambda parsed: validate_response(parsed, per_page, limit, 0)
@ -297,7 +298,7 @@ class LibraryMixin(MixinProtocol):
data = nav(content, [*MUSIC_SHELF, "contents"], True) data = nav(content, [*MUSIC_SHELF, "contents"], True)
if not data: if not data:
error = nav(content, ["musicNotifierShelfRenderer", *TITLE], True) error = nav(content, ["musicNotifierShelfRenderer", *TITLE], True)
raise Exception(error) raise YTMusicServerError(error)
menu_entries = [[-1, *MENU_SERVICE, *FEEDBACK_TOKEN]] menu_entries = [[-1, *MENU_SERVICE, *FEEDBACK_TOKEN]]
songlist = parse_playlist_items(data, menu_entries) songlist = parse_playlist_items(data, menu_entries)
for song in songlist: for song in songlist:

View file

@ -348,7 +348,9 @@ class PlaylistsMixin(MixinProtocol):
self._check_auth() self._check_auth()
body: dict[str, Any] = {"playlistId": validate_playlist_id(playlistId), "actions": []} body: dict[str, Any] = {"playlistId": validate_playlist_id(playlistId), "actions": []}
if not videoIds and not source_playlist: if not videoIds and not source_playlist:
raise Exception("You must provide either videoIds or a source_playlist to add to the playlist") raise YTMusicUserError(
"You must provide either videoIds or a source_playlist to add to the playlist"
)
if videoIds: if videoIds:
for videoId in videoIds: for videoId in videoIds:
@ -388,7 +390,9 @@ class PlaylistsMixin(MixinProtocol):
self._check_auth() self._check_auth()
videos = list(filter(lambda x: "videoId" in x and "setVideoId" in x, videos)) videos = list(filter(lambda x: "videoId" in x and "setVideoId" in x, videos))
if len(videos) == 0: if len(videos) == 0:
raise Exception("Cannot remove songs, because setVideoId is missing. Do you own this playlist?") raise YTMusicUserError(
"Cannot remove songs, because setVideoId is missing. Do you own this playlist?"
)
body: dict[str, Any] = {"playlistId": validate_playlist_id(playlistId), "actions": []} body: dict[str, Any] = {"playlistId": validate_playlist_id(playlistId), "actions": []}
for video in videos: for video in videos:

View file

@ -1,6 +1,7 @@
from typing import Any, Optional, Union from typing import Any, Optional, Union
from ytmusicapi.continuations import get_continuations from ytmusicapi.continuations import get_continuations
from ytmusicapi.exceptions import YTMusicUserError
from ytmusicapi.mixins._protocol import MixinProtocol from ytmusicapi.mixins._protocol import MixinProtocol
from ytmusicapi.parsers.search import * from ytmusicapi.parsers.search import *
@ -150,26 +151,26 @@ class SearchMixin(MixinProtocol):
"episodes", "episodes",
] ]
if filter and filter not in filters: if filter and filter not in filters:
raise Exception( raise YTMusicUserError(
"Invalid filter provided. Please use one of the following filters or leave out the parameter: " "Invalid filter provided. Please use one of the following filters or leave out the parameter: "
+ ", ".join(filters) + ", ".join(filters)
) )
scopes = ["library", "uploads"] scopes = ["library", "uploads"]
if scope and scope not in scopes: if scope and scope not in scopes:
raise Exception( raise YTMusicUserError(
"Invalid scope provided. Please use one of the following scopes or leave out the parameter: " "Invalid scope provided. Please use one of the following scopes or leave out the parameter: "
+ ", ".join(scopes) + ", ".join(scopes)
) )
if scope == scopes[1] and filter: if scope == scopes[1] and filter:
raise Exception( raise YTMusicUserError(
"No filter can be set when searching uploads. Please unset the filter parameter when scope is set to " "No filter can be set when searching uploads. Please unset the filter parameter when scope is set to "
"uploads. " "uploads. "
) )
if scope == scopes[0] and filter in filters[3:5]: if scope == scopes[0] and filter in filters[3:5]:
raise Exception( raise YTMusicUserError(
f"{filter} cannot be set when searching library. " f"{filter} cannot be set when searching library. "
f"Please use one of the following filters or leave out the parameter: " f"Please use one of the following filters or leave out the parameter: "
+ ", ".join(filters[0:3] + filters[5:]) + ", ".join(filters[0:3] + filters[5:])

View file

@ -18,6 +18,7 @@ from ytmusicapi.parsers.uploads import parse_uploaded_items
from ..auth.types import AuthType from ..auth.types import AuthType
from ..enums import ResponseStatus from ..enums import ResponseStatus
from ..exceptions import YTMusicUserError
from ._protocol import MixinProtocol from ._protocol import MixinProtocol
from ._utils import prepare_order_params, validate_order_parameter from ._utils import prepare_order_params, validate_order_parameter
@ -210,13 +211,13 @@ class UploadsMixin(MixinProtocol):
""" """
self._check_auth() self._check_auth()
if not self.auth_type == AuthType.BROWSER: if not self.auth_type == AuthType.BROWSER:
raise Exception("Please provide browser authentication before using this function") raise YTMusicUserError("Please provide browser authentication before using this function")
if not os.path.isfile(filepath): if not os.path.isfile(filepath):
raise Exception("The provided file does not exist.") raise YTMusicUserError("The provided file does not exist.")
supported_filetypes = ["mp3", "m4a", "wma", "flac", "ogg"] supported_filetypes = ["mp3", "m4a", "wma", "flac", "ogg"]
if os.path.splitext(filepath)[1][1:] not in supported_filetypes: if os.path.splitext(filepath)[1][1:] not in supported_filetypes:
raise Exception( raise YTMusicUserError(
"The provided file type is not supported by YouTube Music. Supported file types are " "The provided file type is not supported by YouTube Music. Supported file types are "
+ ", ".join(supported_filetypes) + ", ".join(supported_filetypes)
) )

View file

@ -1,6 +1,7 @@
from typing import Optional, Union from typing import Optional, Union
from ytmusicapi.continuations import get_continuations from ytmusicapi.continuations import get_continuations
from ytmusicapi.exceptions import YTMusicServerError, YTMusicUserError
from ytmusicapi.mixins._protocol import MixinProtocol from ytmusicapi.mixins._protocol import MixinProtocol
from ytmusicapi.parsers.playlists import validate_playlist_id from ytmusicapi.parsers.playlists import validate_playlist_id
from ytmusicapi.parsers.watch import * from ytmusicapi.parsers.watch import *
@ -109,7 +110,7 @@ class WatchMixin(MixinProtocol):
"tunerSettingValue": "AUTOMIX_SETTING_NORMAL", "tunerSettingValue": "AUTOMIX_SETTING_NORMAL",
} }
if not videoId and not playlistId: if not videoId and not playlistId:
raise Exception("You must provide either a video id, a playlist id, or both") raise YTMusicUserError("You must provide either a video id, a playlist id, or both")
if videoId: if videoId:
body["videoId"] = videoId body["videoId"] = videoId
if not playlistId: if not playlistId:
@ -153,7 +154,7 @@ class WatchMixin(MixinProtocol):
msg = "No content returned by the server." msg = "No content returned by the server."
if playlistId: if playlistId:
msg += f"\nEnsure you have access to {playlistId} - a private playlist may cause this." msg += f"\nEnsure you have access to {playlistId} - a private playlist may cause this."
raise Exception(msg) raise YTMusicServerError(msg)
playlist = next( playlist = next(
filter( filter(

View file

@ -37,6 +37,7 @@ from ytmusicapi.parsers.i18n import Parser
from .auth.oauth import OAuthCredentials, OAuthToken, RefreshingToken from .auth.oauth import OAuthCredentials, OAuthToken, RefreshingToken
from .auth.oauth.token import Token from .auth.oauth.token import Token
from .auth.types import AuthType from .auth.types import AuthType
from .exceptions import YTMusicServerError, YTMusicUserError
class YTMusicBase: class YTMusicBase:
@ -145,11 +146,11 @@ class YTMusicBase:
if location: if location:
if location not in SUPPORTED_LOCATIONS: if location not in SUPPORTED_LOCATIONS:
raise Exception("Location not supported. Check the FAQ for supported locations.") raise YTMusicUserError("Location not supported. Check the FAQ for supported locations.")
self.context["context"]["client"]["gl"] = location self.context["context"]["client"]["gl"] = location
if language not in SUPPORTED_LANGUAGES: if language not in SUPPORTED_LANGUAGES:
raise Exception( raise YTMusicUserError(
"Language not supported. Supported languages are " + (", ".join(SUPPORTED_LANGUAGES)) + "." "Language not supported. Supported languages are " + (", ".join(SUPPORTED_LANGUAGES)) + "."
) )
self.context["context"]["client"]["hl"] = language self.context["context"]["client"]["hl"] = language
@ -183,7 +184,7 @@ class YTMusicBase:
self.sapisid = sapisid_from_cookie(cookie) self.sapisid = sapisid_from_cookie(cookie)
self.origin = self.base_headers.get("origin", self.base_headers.get("x-origin")) self.origin = self.base_headers.get("origin", self.base_headers.get("x-origin"))
except KeyError: except KeyError:
raise Exception("Your cookie is missing the required value __Secure-3PAPISID") raise YTMusicUserError("Your cookie is missing the required value __Secure-3PAPISID")
@property @property
def base_headers(self): def base_headers(self):
@ -238,7 +239,7 @@ class YTMusicBase:
if response.status_code >= 400: if response.status_code >= 400:
message = "Server returned HTTP " + str(response.status_code) + ": " + response.reason + ".\n" message = "Server returned HTTP " + str(response.status_code) + ": " + response.reason + ".\n"
error = response_text.get("error", {}).get("message") error = response_text.get("error", {}).get("message")
raise Exception(message + error) raise YTMusicServerError(message + error)
return response_text return response_text
def _send_get_request(self, url: str, params: Optional[dict] = None) -> Response: def _send_get_request(self, url: str, params: Optional[dict] = None) -> Response:
@ -254,7 +255,7 @@ class YTMusicBase:
def _check_auth(self): def _check_auth(self):
if not self.auth: if not self.auth:
raise Exception("Please provide authentication before using this function") raise YTMusicUserError("Please provide authentication before using this function")
def __enter__(self): def __enter__(self):
return self return self