diff --git a/ytmusicapi/parsers/utils.py b/ytmusicapi/continuations.py similarity index 52% rename from ytmusicapi/parsers/utils.py rename to ytmusicapi/continuations.py index 5f46f68..aedd8d5 100644 --- a/ytmusicapi/parsers/utils.py +++ b/ytmusicapi/continuations.py @@ -1,55 +1,4 @@ -from . import * - - -def parse_menu_playlists(data, result): - watch_menu = find_objects_by_key(nav(data, MENU_ITEMS), 'menuNavigationItemRenderer') - for item in [_x['menuNavigationItemRenderer'] for _x in watch_menu]: - icon = nav(item, ['icon', 'iconType']) - if icon == 'MUSIC_SHUFFLE': - watch_key = 'shuffleId' - elif icon == 'MIX': - watch_key = 'radioId' - else: - continue - - watch_id = nav(item, ['navigationEndpoint', 'watchPlaylistEndpoint', 'playlistId'], True) - if not watch_id: - watch_id = nav(item, ['navigationEndpoint', 'watchEndpoint', 'playlistId'], True) - if watch_id: - result[watch_key] = watch_id - - -def get_item_text(item, index, run_index=0, none_if_absent=False): - column = get_flex_column_item(item, index) - if not column: - return None - if none_if_absent and len(column['text']['runs']) < run_index + 1: - return None - return column['text']['runs'][run_index]['text'] - - -def get_flex_column_item(item, index): - if len(item['flexColumns']) <= index or \ - 'text' not in item['flexColumns'][index]['musicResponsiveListItemFlexColumnRenderer'] or \ - 'runs' not in item['flexColumns'][index]['musicResponsiveListItemFlexColumnRenderer']['text']: - return None - - return item['flexColumns'][index]['musicResponsiveListItemFlexColumnRenderer'] - - -def get_fixed_column_item(item, index): - if 'text' not in item['fixedColumns'][index]['musicResponsiveListItemFixedColumnRenderer'] or \ - 'runs' not in item['fixedColumns'][index]['musicResponsiveListItemFixedColumnRenderer']['text']: - return None - - return item['fixedColumns'][index]['musicResponsiveListItemFixedColumnRenderer'] - - -def get_browse_id(item, index): - if 'navigationEndpoint' not in item['text']['runs'][index]: - return None - else: - return nav(item['text']['runs'][index], NAVIGATION_BROWSE_ID) +from ytmusicapi.navigation import nav def get_continuations(results, continuation_type, limit, request_func, parse_func, ctoken_path=""): @@ -136,48 +85,3 @@ def validate_response(response, per_page, limit, current_count): # response is invalid, if it has less items then minimal expected count return len(response['parsed']) >= expected_items_count - - -def validate_playlist_id(playlistId): - return playlistId if not playlistId.startswith("VL") else playlistId[2:] - - -def nav(root, items, none_if_absent=False): - """Access a nested object in root by item sequence.""" - try: - for k in items: - root = root[k] - return root - except Exception as err: - if none_if_absent: - return None - else: - raise err - - -def find_object_by_key(object_list, key, nested=None, is_key=False): - for item in object_list: - if nested: - item = item[nested] - if key in item: - return item[key] if is_key else item - return None - - -def find_objects_by_key(object_list, key, nested=None): - objects = [] - for item in object_list: - if nested: - item = item[nested] - if key in item: - objects.append(item) - return objects - - -def get_dot_separator_index(runs): - index = len(runs) - try: - index = runs.index({'text': ' • '}) - except ValueError: - len(runs) - return index diff --git a/ytmusicapi/helpers.py b/ytmusicapi/helpers.py index ac6c015..03d43ef 100644 --- a/ytmusicapi/helpers.py +++ b/ytmusicapi/helpers.py @@ -3,39 +3,10 @@ import json from http.cookies import SimpleCookie from hashlib import sha1 import time -from datetime import date -from functools import wraps import locale from ytmusicapi.constants import * -def prepare_like_endpoint(rating): - if rating == 'LIKE': - return 'like/like' - elif rating == 'DISLIKE': - return 'like/dislike' - elif rating == 'INDIFFERENT': - return 'like/removelike' - else: - return None - - -def validate_order_parameter(order): - orders = ['a_to_z', 'z_to_a', 'recently_added'] - if order and order not in orders: - raise Exception( - "Invalid order provided. Please use one of the following orders or leave out the parameter: " - + ', '.join(orders)) - - -def prepare_order_params(order): - orders = ['a_to_z', 'z_to_a', 'recently_added'] - if order is not None: - # determine order_params via `.contents.singleColumnBrowseResultsRenderer.tabs[0].tabRenderer.content.sectionListRenderer.contents[1].itemSectionRenderer.header.itemSectionTabbedHeaderRenderer.endItems[1].dropdownRenderer.entries[].dropdownItemRenderer.onSelectCommand.browseEndpoint.params` of `/youtubei/v1/browse` response - order_params = ['ggMGKgQIARAA', 'ggMGKgQIARAB', 'ggMGKgQIABAB'] - return order_params[orders.index(order)] - - def initialize_headers(): return { "user-agent": USER_AGENT, @@ -69,13 +40,6 @@ def get_visitor_id(request_func): return {'X-Goog-Visitor-Id': visitor_id} -def html_to_txt(html_text): - tags = re.findall("<[^>]+>", html_text) - for tag in tags: - html_text = html_text.replace(tag, '') - return html_text - - def sapisid_from_cookie(raw_cookie): cookie = SimpleCookie() cookie.load(raw_cookie) @@ -91,10 +55,6 @@ def get_authorization(auth): return "SAPISIDHASH " + unix_timestamp + "_" + sha_1.hexdigest() -def get_datestamp(): - return (date.today() - date.fromtimestamp(0)).days - - def to_int(string): number_string = re.sub('[^\\d]', '', string) try: @@ -105,24 +65,7 @@ def to_int(string): return int_value -def parse_duration(duration): - if duration is None: - return duration - mapped_increments = zip([1, 60, 3600], reversed(duration.split(":"))) - seconds = sum(multiplier * int(time) for multiplier, time in mapped_increments) - return seconds - - def sum_total_duration(item): - return sum( - [track['duration_seconds'] if 'duration_seconds' in track else 0 for track in item['tracks']] - ) - - -def i18n(method): - @wraps(method) - def _impl(self, *method_args, **method_kwargs): - method.__globals__['_'] = self.lang.gettext - return method(self, *method_args, **method_kwargs) - - return _impl + return sum([ + track['duration_seconds'] if 'duration_seconds' in track else 0 for track in item['tracks'] + ]) diff --git a/ytmusicapi/mixins/_utils.py b/ytmusicapi/mixins/_utils.py new file mode 100644 index 0000000..a0c6d4c --- /dev/null +++ b/ytmusicapi/mixins/_utils.py @@ -0,0 +1,40 @@ +import re +from datetime import date + + +def prepare_like_endpoint(rating): + if rating == 'LIKE': + return 'like/like' + elif rating == 'DISLIKE': + return 'like/dislike' + elif rating == 'INDIFFERENT': + return 'like/removelike' + else: + return None + + +def validate_order_parameter(order): + orders = ['a_to_z', 'z_to_a', 'recently_added'] + if order and order not in orders: + raise Exception( + "Invalid order provided. Please use one of the following orders or leave out the parameter: " + + ', '.join(orders)) + + +def prepare_order_params(order): + orders = ['a_to_z', 'z_to_a', 'recently_added'] + if order is not None: + # determine order_params via `.contents.singleColumnBrowseResultsRenderer.tabs[0].tabRenderer.content.sectionListRenderer.contents[1].itemSectionRenderer.header.itemSectionTabbedHeaderRenderer.endItems[1].dropdownRenderer.entries[].dropdownItemRenderer.onSelectCommand.browseEndpoint.params` of `/youtubei/v1/browse` response + order_params = ['ggMGKgQIARAA', 'ggMGKgQIARAB', 'ggMGKgQIABAB'] + return order_params[orders.index(order)] + + +def html_to_txt(html_text): + tags = re.findall("<[^>]+>", html_text) + for tag in tags: + html_text = html_text.replace(tag, '') + return html_text + + +def get_datestamp(): + return (date.today() - date.fromtimestamp(0)).days diff --git a/ytmusicapi/mixins/browsing.py b/ytmusicapi/mixins/browsing.py index 2a66646..c5c0ce0 100644 --- a/ytmusicapi/mixins/browsing.py +++ b/ytmusicapi/mixins/browsing.py @@ -1,8 +1,9 @@ -from ytmusicapi.helpers import * +from ._utils import get_datestamp +from ytmusicapi.continuations import get_continuations +from ytmusicapi.helpers import YTM_DOMAIN, sum_total_duration from ytmusicapi.parsers.browsing import * -from ytmusicapi.parsers.search_params import * -from ytmusicapi.parsers.albums import * -from ytmusicapi.parsers.playlists import * +from ytmusicapi.parsers.albums import parse_album_header +from ytmusicapi.parsers.playlists import parse_playlist_items from ytmusicapi.parsers.library import parse_albums @@ -113,192 +114,6 @@ class BrowsingMixin: return home - def search(self, - query: str, - filter: str = None, - scope: str = None, - limit: int = 20, - ignore_spelling: bool = False) -> List[Dict]: - """ - Search YouTube music - Returns results within the provided category. - - :param query: Query string, i.e. 'Oasis Wonderwall' - :param filter: Filter for item types. Allowed values: ``songs``, ``videos``, ``albums``, ``artists``, ``playlists``, ``community_playlists``, ``featured_playlists``, ``uploads``. - Default: Default search, including all types of items. - :param scope: Search scope. Allowed values: ``library``, ``uploads``. - Default: Search the public YouTube Music catalogue. - :param limit: Number of search results to return - Default: 20 - :param ignore_spelling: Whether to ignore YTM spelling suggestions. - If True, the exact search term will be searched for, and will not be corrected. - This does not have any effect when the filter is set to ``uploads``. - Default: False, will use YTM's default behavior of autocorrecting the search. - :return: List of results depending on filter. - resultType specifies the type of item (important for default search). - albums, artists and playlists additionally contain a browseId, corresponding to - albumId, channelId and playlistId (browseId=``VL``+playlistId) - - Example list for default search with one result per resultType for brevity. Normally - there are 3 results per resultType and an additional ``thumbnails`` key:: - - [ - { - "category": "Top result", - "resultType": "video", - "videoId": "vU05Eksc_iM", - "title": "Wonderwall", - "artists": [ - { - "name": "Oasis", - "id": "UCmMUZbaYdNH0bEd1PAlAqsA" - } - ], - "views": "1.4M", - "videoType": "MUSIC_VIDEO_TYPE_OMV", - "duration": "4:38", - "duration_seconds": 278 - }, - { - "category": "Songs", - "resultType": "song", - "videoId": "ZrOKjDZOtkA", - "title": "Wonderwall", - "artists": [ - { - "name": "Oasis", - "id": "UCmMUZbaYdNH0bEd1PAlAqsA" - } - ], - "album": { - "name": "(What's The Story) Morning Glory? (Remastered)", - "id": "MPREb_9nqEki4ZDpp" - }, - "duration": "4:19", - "duration_seconds": 259 - "isExplicit": false, - "feedbackTokens": { - "add": null, - "remove": null - } - }, - { - "category": "Albums", - "resultType": "album", - "browseId": "MPREb_9nqEki4ZDpp", - "title": "(What's The Story) Morning Glory? (Remastered)", - "type": "Album", - "artist": "Oasis", - "year": "1995", - "isExplicit": false - }, - { - "category": "Community playlists", - "resultType": "playlist", - "browseId": "VLPLK1PkWQlWtnNfovRdGWpKffO1Wdi2kvDx", - "title": "Wonderwall - Oasis", - "author": "Tate Henderson", - "itemCount": "174" - }, - { - "category": "Videos", - "resultType": "video", - "videoId": "bx1Bh8ZvH84", - "title": "Wonderwall", - "artists": [ - { - "name": "Oasis", - "id": "UCmMUZbaYdNH0bEd1PAlAqsA" - } - ], - "views": "386M", - "duration": "4:38", - "duration_seconds": 278 - }, - { - "category": "Artists", - "resultType": "artist", - "browseId": "UCmMUZbaYdNH0bEd1PAlAqsA", - "artist": "Oasis", - "shuffleId": "RDAOkjHYJjL1a3xspEyVkhHAsg", - "radioId": "RDEMkjHYJjL1a3xspEyVkhHAsg" - } - ] - - - """ - body = {'query': query} - endpoint = 'search' - search_results = [] - filters = [ - 'albums', 'artists', 'playlists', 'community_playlists', 'featured_playlists', 'songs', - 'videos' - ] - if filter and filter not in filters: - raise Exception( - "Invalid filter provided. Please use one of the following filters or leave out the parameter: " - + ', '.join(filters)) - - scopes = ['library', 'uploads'] - if scope and scope not in scopes: - raise Exception( - "Invalid scope provided. Please use one of the following scopes or leave out the parameter: " - + ', '.join(scopes)) - - params = get_search_params(filter, scope, ignore_spelling) - if params: - body['params'] = params - - response = self._send_request(endpoint, body) - - # no results - if 'contents' not in response: - return search_results - - if 'tabbedSearchResultsRenderer' in response['contents']: - tab_index = 0 if not scope or filter else scopes.index(scope) + 1 - results = response['contents']['tabbedSearchResultsRenderer']['tabs'][tab_index][ - 'tabRenderer']['content'] - else: - results = response['contents'] - - results = nav(results, SECTION_LIST) - - # no results - if len(results) == 1 and 'itemSectionRenderer' in results: - return search_results - - # set filter for parser - if filter and 'playlists' in filter: - filter = 'playlists' - elif scope == scopes[1]: - filter = scopes[1] - - for res in results: - if 'musicShelfRenderer' in res: - results = res['musicShelfRenderer']['contents'] - original_filter = filter - category = nav(res, MUSIC_SHELF + TITLE_TEXT, True) - if not filter and scope == scopes[0]: - filter = category - - type = filter[:-1].lower() if filter else None - search_results.extend(self.parser.parse_search_results(results, type, category)) - filter = original_filter - - if 'continuations' in res['musicShelfRenderer']: - request_func = lambda additionalParams: self._send_request( - endpoint, body, additionalParams) - - parse_func = lambda contents: self.parser.parse_search_results( - contents, type, category) - - search_results.extend( - get_continuations(res['musicShelfRenderer'], 'musicShelfContinuation', - limit - len(search_results), request_func, parse_func)) - - return search_results - def get_artist(self, channelId: str) -> Dict: """ Get information about an artist and their top releases (songs, diff --git a/ytmusicapi/mixins/library.py b/ytmusicapi/mixins/library.py index 7005047..212601d 100644 --- a/ytmusicapi/mixins/library.py +++ b/ytmusicapi/mixins/library.py @@ -1,7 +1,7 @@ -from ytmusicapi.helpers import * +from ytmusicapi.continuations import * +from ._utils import * from ytmusicapi.parsers.browsing import * from ytmusicapi.parsers.library import * -from ytmusicapi.parsers.playlists import * class LibraryMixin: diff --git a/ytmusicapi/mixins/playlists.py b/ytmusicapi/mixins/playlists.py index 5fa976c..6fb0c53 100644 --- a/ytmusicapi/mixins/playlists.py +++ b/ytmusicapi/mixins/playlists.py @@ -1,7 +1,10 @@ import unicodedata -from typing import List, Dict, Union, Tuple -from ytmusicapi.helpers import * -from ytmusicapi.parsers.utils import * +from typing import Dict, Union, Tuple +from ._utils import * + +from ytmusicapi.continuations import get_continuations, get_continuation_string +from ytmusicapi.navigation import * +from ytmusicapi.helpers import to_int, sum_total_duration from ytmusicapi.parsers.playlists import * diff --git a/ytmusicapi/mixins/search.py b/ytmusicapi/mixins/search.py new file mode 100644 index 0000000..9164c1d --- /dev/null +++ b/ytmusicapi/mixins/search.py @@ -0,0 +1,192 @@ +from typing import List, Dict +from ytmusicapi.navigation import * +from ytmusicapi.continuations import get_continuations +from ytmusicapi.parsers.search_params import * + + +class SearchMixin: + def search(self, + query: str, + filter: str = None, + scope: str = None, + limit: int = 20, + ignore_spelling: bool = False) -> List[Dict]: + """ + Search YouTube music + Returns results within the provided category. + + :param query: Query string, i.e. 'Oasis Wonderwall' + :param filter: Filter for item types. Allowed values: ``songs``, ``videos``, ``albums``, ``artists``, ``playlists``, ``community_playlists``, ``featured_playlists``, ``uploads``. + Default: Default search, including all types of items. + :param scope: Search scope. Allowed values: ``library``, ``uploads``. + Default: Search the public YouTube Music catalogue. + :param limit: Number of search results to return + Default: 20 + :param ignore_spelling: Whether to ignore YTM spelling suggestions. + If True, the exact search term will be searched for, and will not be corrected. + This does not have any effect when the filter is set to ``uploads``. + Default: False, will use YTM's default behavior of autocorrecting the search. + :return: List of results depending on filter. + resultType specifies the type of item (important for default search). + albums, artists and playlists additionally contain a browseId, corresponding to + albumId, channelId and playlistId (browseId=``VL``+playlistId) + + Example list for default search with one result per resultType for brevity. Normally + there are 3 results per resultType and an additional ``thumbnails`` key:: + + [ + { + "category": "Top result", + "resultType": "video", + "videoId": "vU05Eksc_iM", + "title": "Wonderwall", + "artists": [ + { + "name": "Oasis", + "id": "UCmMUZbaYdNH0bEd1PAlAqsA" + } + ], + "views": "1.4M", + "videoType": "MUSIC_VIDEO_TYPE_OMV", + "duration": "4:38", + "duration_seconds": 278 + }, + { + "category": "Songs", + "resultType": "song", + "videoId": "ZrOKjDZOtkA", + "title": "Wonderwall", + "artists": [ + { + "name": "Oasis", + "id": "UCmMUZbaYdNH0bEd1PAlAqsA" + } + ], + "album": { + "name": "(What's The Story) Morning Glory? (Remastered)", + "id": "MPREb_9nqEki4ZDpp" + }, + "duration": "4:19", + "duration_seconds": 259 + "isExplicit": false, + "feedbackTokens": { + "add": null, + "remove": null + } + }, + { + "category": "Albums", + "resultType": "album", + "browseId": "MPREb_9nqEki4ZDpp", + "title": "(What's The Story) Morning Glory? (Remastered)", + "type": "Album", + "artist": "Oasis", + "year": "1995", + "isExplicit": false + }, + { + "category": "Community playlists", + "resultType": "playlist", + "browseId": "VLPLK1PkWQlWtnNfovRdGWpKffO1Wdi2kvDx", + "title": "Wonderwall - Oasis", + "author": "Tate Henderson", + "itemCount": "174" + }, + { + "category": "Videos", + "resultType": "video", + "videoId": "bx1Bh8ZvH84", + "title": "Wonderwall", + "artists": [ + { + "name": "Oasis", + "id": "UCmMUZbaYdNH0bEd1PAlAqsA" + } + ], + "views": "386M", + "duration": "4:38", + "duration_seconds": 278 + }, + { + "category": "Artists", + "resultType": "artist", + "browseId": "UCmMUZbaYdNH0bEd1PAlAqsA", + "artist": "Oasis", + "shuffleId": "RDAOkjHYJjL1a3xspEyVkhHAsg", + "radioId": "RDEMkjHYJjL1a3xspEyVkhHAsg" + } + ] + + + """ + body = {'query': query} + endpoint = 'search' + search_results = [] + filters = [ + 'albums', 'artists', 'playlists', 'community_playlists', 'featured_playlists', 'songs', + 'videos' + ] + if filter and filter not in filters: + raise Exception( + "Invalid filter provided. Please use one of the following filters or leave out the parameter: " + + ', '.join(filters)) + + scopes = ['library', 'uploads'] + if scope and scope not in scopes: + raise Exception( + "Invalid scope provided. Please use one of the following scopes or leave out the parameter: " + + ', '.join(scopes)) + + params = get_search_params(filter, scope, ignore_spelling) + if params: + body['params'] = params + + response = self._send_request(endpoint, body) + + # no results + if 'contents' not in response: + return search_results + + if 'tabbedSearchResultsRenderer' in response['contents']: + tab_index = 0 if not scope or filter else scopes.index(scope) + 1 + results = response['contents']['tabbedSearchResultsRenderer']['tabs'][tab_index][ + 'tabRenderer']['content'] + else: + results = response['contents'] + + results = nav(results, SECTION_LIST) + + # no results + if len(results) == 1 and 'itemSectionRenderer' in results: + return search_results + + # set filter for parser + if filter and 'playlists' in filter: + filter = 'playlists' + elif scope == scopes[1]: + filter = scopes[1] + + for res in results: + if 'musicShelfRenderer' in res: + results = res['musicShelfRenderer']['contents'] + original_filter = filter + category = nav(res, MUSIC_SHELF + TITLE_TEXT, True) + if not filter and scope == scopes[0]: + filter = category + + type = filter[:-1].lower() if filter else None + search_results.extend(self.parser.parse_search_results(results, type, category)) + filter = original_filter + + if 'continuations' in res['musicShelfRenderer']: + request_func = lambda additionalParams: self._send_request( + endpoint, body, additionalParams) + + parse_func = lambda contents: self.parser.parse_search_results( + contents, type, category) + + search_results.extend( + get_continuations(res['musicShelfRenderer'], 'musicShelfContinuation', + limit - len(search_results), request_func, parse_func)) + + return search_results diff --git a/ytmusicapi/mixins/uploads.py b/ytmusicapi/mixins/uploads.py index a71f246..7eb3e12 100644 --- a/ytmusicapi/mixins/uploads.py +++ b/ytmusicapi/mixins/uploads.py @@ -2,10 +2,14 @@ import requests import ntpath import os from typing import List, Dict, Union + +from ._utils import validate_order_parameter, prepare_order_params from ytmusicapi.helpers import * -from ytmusicapi.parsers.library import * -from ytmusicapi.parsers.albums import * -from ytmusicapi.parsers.uploads import * +from ytmusicapi.navigation import * +from ytmusicapi.continuations import get_continuations +from ytmusicapi.parsers.library import parse_library_albums, parse_library_artists +from ytmusicapi.parsers.albums import parse_album_header +from ytmusicapi.parsers.uploads import parse_uploaded_items class UploadsMixin: @@ -205,7 +209,8 @@ class UploadsMixin: + ', '.join(supported_filetypes)) headers = self.headers.copy() - upload_url = "https://upload.youtube.com/upload/usermusic/http?authuser=%s" % headers['x-goog-authuser'] + upload_url = "https://upload.youtube.com/upload/usermusic/http?authuser=%s" % headers[ + 'x-goog-authuser'] filesize = os.path.getsize(filepath) body = ("filename=" + ntpath.basename(filepath)).encode('utf-8') headers.pop('content-encoding', None) diff --git a/ytmusicapi/mixins/watch.py b/ytmusicapi/mixins/watch.py index 6bfe4e1..67452ee 100644 --- a/ytmusicapi/mixins/watch.py +++ b/ytmusicapi/mixins/watch.py @@ -1,4 +1,7 @@ from typing import List, Dict, Union + +from ytmusicapi.continuations import get_continuations +from ytmusicapi.parsers.playlists import validate_playlist_id from ytmusicapi.parsers.watch import * diff --git a/ytmusicapi/parsers/__init__.py b/ytmusicapi/navigation.py similarity index 77% rename from ytmusicapi/parsers/__init__.py rename to ytmusicapi/navigation.py index e991279..4323ac1 100644 --- a/ytmusicapi/parsers/__init__.py +++ b/ytmusicapi/navigation.py @@ -25,7 +25,8 @@ NAVIGATION_VIDEO_ID = ['navigationEndpoint', 'watchEndpoint', 'videoId'] NAVIGATION_PLAYLIST_ID = ['navigationEndpoint', 'watchEndpoint', 'playlistId'] NAVIGATION_WATCH_PLAYLIST_ID = ['navigationEndpoint', 'watchPlaylistEndpoint', 'playlistId'] NAVIGATION_VIDEO_TYPE = [ - 'watchEndpoint', 'watchEndpointMusicSupportedConfigs', 'watchEndpointMusicConfig', 'musicVideoType' + 'watchEndpoint', 'watchEndpointMusicSupportedConfigs', 'watchEndpointMusicConfig', + 'musicVideoType' ] HEADER_DETAIL = ['header', 'musicDetailHeaderRenderer'] DESCRIPTION = ['description'] + RUN_TEXT @@ -54,3 +55,35 @@ CATEGORY_TITLE = ['musicNavigationButtonRenderer', 'buttonText'] + RUN_TEXT CATEGORY_PARAMS = ['musicNavigationButtonRenderer', 'clickCommand', 'browseEndpoint', 'params'] MRLIR = 'musicResponsiveListItemRenderer' MTRIR = 'musicTwoRowItemRenderer' + + +def nav(root, items, none_if_absent=False): + """Access a nested object in root by item sequence.""" + try: + for k in items: + root = root[k] + return root + except Exception as err: + if none_if_absent: + return None + else: + raise err + + +def find_object_by_key(object_list, key, nested=None, is_key=False): + for item in object_list: + if nested: + item = item[nested] + if key in item: + return item[key] if is_key else item + return None + + +def find_objects_by_key(object_list, key, nested=None): + objects = [] + for item in object_list: + if nested: + item = item[nested] + if key in item: + objects.append(item) + return objects diff --git a/ytmusicapi/parsers/_utils.py b/ytmusicapi/parsers/_utils.py new file mode 100644 index 0000000..1200cd5 --- /dev/null +++ b/ytmusicapi/parsers/_utils.py @@ -0,0 +1,80 @@ +from functools import wraps + +from ytmusicapi.navigation import * + + +def parse_menu_playlists(data, result): + watch_menu = find_objects_by_key(nav(data, MENU_ITEMS), 'menuNavigationItemRenderer') + for item in [_x['menuNavigationItemRenderer'] for _x in watch_menu]: + icon = nav(item, ['icon', 'iconType']) + if icon == 'MUSIC_SHUFFLE': + watch_key = 'shuffleId' + elif icon == 'MIX': + watch_key = 'radioId' + else: + continue + + watch_id = nav(item, ['navigationEndpoint', 'watchPlaylistEndpoint', 'playlistId'], True) + if not watch_id: + watch_id = nav(item, ['navigationEndpoint', 'watchEndpoint', 'playlistId'], True) + if watch_id: + result[watch_key] = watch_id + + +def get_item_text(item, index, run_index=0, none_if_absent=False): + column = get_flex_column_item(item, index) + if not column: + return None + if none_if_absent and len(column['text']['runs']) < run_index + 1: + return None + return column['text']['runs'][run_index]['text'] + + +def get_flex_column_item(item, index): + if len(item['flexColumns']) <= index or \ + 'text' not in item['flexColumns'][index]['musicResponsiveListItemFlexColumnRenderer'] or \ + 'runs' not in item['flexColumns'][index]['musicResponsiveListItemFlexColumnRenderer']['text']: + return None + + return item['flexColumns'][index]['musicResponsiveListItemFlexColumnRenderer'] + + +def get_fixed_column_item(item, index): + if 'text' not in item['fixedColumns'][index]['musicResponsiveListItemFixedColumnRenderer'] or \ + 'runs' not in item['fixedColumns'][index]['musicResponsiveListItemFixedColumnRenderer']['text']: + return None + + return item['fixedColumns'][index]['musicResponsiveListItemFixedColumnRenderer'] + + +def get_browse_id(item, index): + if 'navigationEndpoint' not in item['text']['runs'][index]: + return None + else: + return nav(item['text']['runs'][index], NAVIGATION_BROWSE_ID) + + +def get_dot_separator_index(runs): + index = len(runs) + try: + index = runs.index({'text': ' • '}) + except ValueError: + len(runs) + return index + + +def parse_duration(duration): + if duration is None: + return duration + mapped_increments = zip([1, 60, 3600], reversed(duration.split(":"))) + seconds = sum(multiplier * int(time) for multiplier, time in mapped_increments) + return seconds + + +def i18n(method): + @wraps(method) + def _impl(self, *method_args, **method_kwargs): + method.__globals__['_'] = self.lang.gettext + return method(self, *method_args, **method_kwargs) + + return _impl diff --git a/ytmusicapi/parsers/albums.py b/ytmusicapi/parsers/albums.py index 84c35cf..3c9201d 100644 --- a/ytmusicapi/parsers/albums.py +++ b/ytmusicapi/parsers/albums.py @@ -1,4 +1,4 @@ -from .utils import * +from ._utils import * from ytmusicapi.helpers import to_int from .songs import parse_song_runs, parse_like_status @@ -25,9 +25,11 @@ def parse_album_header(response): # add to library/uploaded menu = nav(header, MENU) toplevel = menu['topLevelButtons'] - album['audioPlaylistId'] = nav(toplevel, [0, 'buttonRenderer'] + NAVIGATION_WATCH_PLAYLIST_ID, True) + album['audioPlaylistId'] = nav(toplevel, [0, 'buttonRenderer'] + NAVIGATION_WATCH_PLAYLIST_ID, + True) if not album['audioPlaylistId']: - album['audioPlaylistId'] = nav(toplevel, [0, 'buttonRenderer'] + NAVIGATION_PLAYLIST_ID, True) + album['audioPlaylistId'] = nav(toplevel, [0, 'buttonRenderer'] + NAVIGATION_PLAYLIST_ID, + True) service = nav(toplevel, [1, 'buttonRenderer', 'defaultServiceEndpoint'], True) if service: album['likeStatus'] = parse_like_status(service) diff --git a/ytmusicapi/parsers/browsing.py b/ytmusicapi/parsers/browsing.py index cdfa545..6cb4054 100644 --- a/ytmusicapi/parsers/browsing.py +++ b/ytmusicapi/parsers/browsing.py @@ -1,7 +1,6 @@ from typing import List, Dict -from .utils import * from .songs import * -from ytmusicapi.helpers import i18n +from ._utils import * class Parser: @@ -145,8 +144,7 @@ class Parser: data, PLAY_BUTTON + ['playNavigationEndpoint', 'watchEndpoint', 'videoId'], True) search_result['videoType'] = nav( - data, PLAY_BUTTON + ['playNavigationEndpoint'] + NAVIGATION_VIDEO_TYPE, - True) + data, PLAY_BUTTON + ['playNavigationEndpoint'] + NAVIGATION_VIDEO_TYPE, True) if resultType in ['song', 'video', 'album']: search_result['duration'] = None diff --git a/ytmusicapi/parsers/library.py b/ytmusicapi/parsers/library.py index 8e32b60..e1e5162 100644 --- a/ytmusicapi/parsers/library.py +++ b/ytmusicapi/parsers/library.py @@ -1,5 +1,6 @@ from .playlists import parse_playlist_items -from .utils import * +from ._utils import * +from ytmusicapi.continuations import get_continuations def parse_artists(results, uploaded=False): @@ -48,7 +49,7 @@ def parse_albums(results): album['browseId'] = nav(data, TITLE + NAVIGATION_BROWSE_ID) album['title'] = nav(data, TITLE_TEXT) album['thumbnails'] = nav(data, THUMBNAIL_RENDERER) - + if 'runs' in data['subtitle']: run_count = len(data['subtitle']['runs']) has_artists = False @@ -56,17 +57,17 @@ def parse_albums(results): album['year'] = nav(data, SUBTITLE) else: album['type'] = nav(data, SUBTITLE) - + if run_count == 3: if nav(data, SUBTITLE2).isdigit(): album['year'] = nav(data, SUBTITLE2) else: has_artists = True - + elif run_count > 3: album['year'] = nav(data, SUBTITLE3) has_artists = True - + if has_artists: subtitle = data['subtitle']['runs'][2] album['artists'] = [] diff --git a/ytmusicapi/parsers/playlists.py b/ytmusicapi/parsers/playlists.py index 45b5baf..c538e63 100644 --- a/ytmusicapi/parsers/playlists.py +++ b/ytmusicapi/parsers/playlists.py @@ -1,7 +1,6 @@ -from .utils import * -from ..helpers import parse_duration -from .songs import * from typing import List +from .songs import * +from ._utils import * def parse_playlist_items(results, menu_entries: List[List] = None): @@ -94,3 +93,7 @@ def parse_playlist_items(results, menu_entries: List[List] = None): print("Item " + str(count) + ": " + str(e)) return songs + + +def validate_playlist_id(playlistId): + return playlistId if not playlistId.startswith("VL") else playlistId[2:] diff --git a/ytmusicapi/parsers/songs.py b/ytmusicapi/parsers/songs.py index e54dbbb..a8cfc15 100644 --- a/ytmusicapi/parsers/songs.py +++ b/ytmusicapi/parsers/songs.py @@ -1,5 +1,4 @@ -from .utils import * -from ..helpers import parse_duration +from ._utils import * import re diff --git a/ytmusicapi/parsers/uploads.py b/ytmusicapi/parsers/uploads.py index b51fac1..2c7e11a 100644 --- a/ytmusicapi/parsers/uploads.py +++ b/ytmusicapi/parsers/uploads.py @@ -1,5 +1,5 @@ -from .utils import * -from .songs import * +from ._utils import * +from .songs import parse_song_artists, parse_song_album def parse_uploaded_items(results): diff --git a/ytmusicapi/parsers/watch.py b/ytmusicapi/parsers/watch.py index c27f9f6..dbd3a03 100644 --- a/ytmusicapi/parsers/watch.py +++ b/ytmusicapi/parsers/watch.py @@ -1,4 +1,4 @@ -from .utils import * +from ._utils import * from .songs import * diff --git a/ytmusicapi/ytmusic.py b/ytmusicapi/ytmusic.py index b34d407..ec5cd1b 100644 --- a/ytmusicapi/ytmusic.py +++ b/ytmusicapi/ytmusic.py @@ -9,6 +9,7 @@ from ytmusicapi.helpers import * from ytmusicapi.parsers import browsing from ytmusicapi.setup import setup from ytmusicapi.mixins.browsing import BrowsingMixin +from ytmusicapi.mixins.search import SearchMixin from ytmusicapi.mixins.watch import WatchMixin from ytmusicapi.mixins.explore import ExploreMixin from ytmusicapi.mixins.library import LibraryMixin @@ -16,7 +17,7 @@ from ytmusicapi.mixins.playlists import PlaylistsMixin from ytmusicapi.mixins.uploads import UploadsMixin -class YTMusic(BrowsingMixin, WatchMixin, ExploreMixin, LibraryMixin, PlaylistsMixin, UploadsMixin): +class YTMusic(BrowsingMixin, SearchMixin, WatchMixin, ExploreMixin, LibraryMixin, PlaylistsMixin, UploadsMixin): """ Allows automated interactions with YouTube Music by emulating the YouTube web client's requests. Permits both authenticated and non-authenticated requests.