refactor search parsing to work with new top result (closes #360)
This commit is contained in:
parent
5d7018bd97
commit
19ad424e0e
12 changed files with 354 additions and 290 deletions
|
|
@ -3,6 +3,7 @@ import unittest.mock
|
||||||
import configparser
|
import configparser
|
||||||
import time
|
import time
|
||||||
import sys
|
import sys
|
||||||
|
|
||||||
sys.path.insert(0, '..')
|
sys.path.insert(0, '..')
|
||||||
from ytmusicapi.ytmusic import YTMusic # noqa: E402
|
from ytmusicapi.ytmusic import YTMusic # noqa: E402
|
||||||
|
|
||||||
|
|
@ -15,6 +16,7 @@ sample_playlist = "PL6bPxvf5dW5clc3y9wAoslzqUrmkZ5c-u" # very large playlist
|
||||||
|
|
||||||
|
|
||||||
class TestYTMusic(unittest.TestCase):
|
class TestYTMusic(unittest.TestCase):
|
||||||
|
|
||||||
@classmethod
|
@classmethod
|
||||||
def setUpClass(cls):
|
def setUpClass(cls):
|
||||||
cls.yt = YTMusic(requests_session=False)
|
cls.yt = YTMusic(requests_session=False)
|
||||||
|
|
|
||||||
|
|
@ -5,9 +5,11 @@ from ytmusicapi.parsers.browsing import *
|
||||||
from ytmusicapi.parsers.albums import parse_album_header
|
from ytmusicapi.parsers.albums import parse_album_header
|
||||||
from ytmusicapi.parsers.playlists import parse_playlist_items
|
from ytmusicapi.parsers.playlists import parse_playlist_items
|
||||||
from ytmusicapi.parsers.library import parse_albums
|
from ytmusicapi.parsers.library import parse_albums
|
||||||
|
from typing import List, Dict
|
||||||
|
|
||||||
|
|
||||||
class BrowsingMixin:
|
class BrowsingMixin:
|
||||||
|
|
||||||
def get_home(self, limit=3) -> List[Dict]:
|
def get_home(self, limit=3) -> List[Dict]:
|
||||||
"""
|
"""
|
||||||
Get the home page.
|
Get the home page.
|
||||||
|
|
@ -99,14 +101,14 @@ class BrowsingMixin:
|
||||||
response = self._send_request(endpoint, body)
|
response = self._send_request(endpoint, body)
|
||||||
results = nav(response, SINGLE_COLUMN_TAB + SECTION_LIST)
|
results = nav(response, SINGLE_COLUMN_TAB + SECTION_LIST)
|
||||||
home = []
|
home = []
|
||||||
home.extend(self.parser.parse_mixed_content(results))
|
home.extend(parse_mixed_content(results))
|
||||||
|
|
||||||
section_list = nav(response, SINGLE_COLUMN_TAB + ['sectionListRenderer'])
|
section_list = nav(response, SINGLE_COLUMN_TAB + ['sectionListRenderer'])
|
||||||
if 'continuations' in section_list:
|
if 'continuations' in section_list:
|
||||||
request_func = lambda additionalParams: self._send_request(
|
request_func = lambda additionalParams: self._send_request(
|
||||||
endpoint, body, additionalParams)
|
endpoint, body, additionalParams)
|
||||||
|
|
||||||
parse_func = lambda contents: self.parser.parse_mixed_content(contents)
|
parse_func = lambda contents: parse_mixed_content(contents)
|
||||||
|
|
||||||
home.extend(
|
home.extend(
|
||||||
get_continuations(section_list, 'sectionListContinuation', limit - len(home),
|
get_continuations(section_list, 'sectionListContinuation', limit - len(home),
|
||||||
|
|
@ -329,7 +331,7 @@ class BrowsingMixin:
|
||||||
|
|
||||||
return user_playlists
|
return user_playlists
|
||||||
|
|
||||||
def get_album_browse_id(self, audioPlaylistId: str):
|
def get_album_browse_id(self, audioPlaylistId: str) -> str:
|
||||||
"""
|
"""
|
||||||
Get an album's browseId based on its audioPlaylistId
|
Get an album's browseId based on its audioPlaylistId
|
||||||
|
|
||||||
|
|
@ -691,7 +693,7 @@ class BrowsingMixin:
|
||||||
|
|
||||||
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)
|
||||||
return self.parser.parse_mixed_content(sections)
|
return parse_mixed_content(sections)
|
||||||
|
|
||||||
def get_lyrics(self, browseId: str) -> Dict:
|
def get_lyrics(self, browseId: str) -> Dict:
|
||||||
"""
|
"""
|
||||||
|
|
|
||||||
|
|
@ -1,7 +1,9 @@
|
||||||
from ytmusicapi.parsers.explore import *
|
from ytmusicapi.parsers.explore import *
|
||||||
|
from typing import List, Dict
|
||||||
|
|
||||||
|
|
||||||
class ExploreMixin:
|
class ExploreMixin:
|
||||||
|
|
||||||
def get_mood_categories(self) -> Dict:
|
def get_mood_categories(self) -> Dict:
|
||||||
"""
|
"""
|
||||||
Fetch "Moods & Genres" categories from YouTube Music.
|
Fetch "Moods & Genres" categories from YouTube Music.
|
||||||
|
|
|
||||||
|
|
@ -3,9 +3,11 @@ from ytmusicapi.continuations import *
|
||||||
from ._utils import *
|
from ._utils import *
|
||||||
from ytmusicapi.parsers.browsing import *
|
from ytmusicapi.parsers.browsing import *
|
||||||
from ytmusicapi.parsers.library import *
|
from ytmusicapi.parsers.library import *
|
||||||
|
from typing import List, Dict
|
||||||
|
|
||||||
|
|
||||||
class LibraryMixin:
|
class LibraryMixin:
|
||||||
|
|
||||||
def get_library_playlists(self, limit: int = 25) -> List[Dict]:
|
def get_library_playlists(self, limit: int = 25) -> List[Dict]:
|
||||||
"""
|
"""
|
||||||
Retrieves the playlists in the user's library.
|
Retrieves the playlists in the user's library.
|
||||||
|
|
|
||||||
|
|
@ -10,7 +10,12 @@ from ytmusicapi.parsers.browsing import parse_content_list, parse_playlist
|
||||||
|
|
||||||
|
|
||||||
class PlaylistsMixin:
|
class PlaylistsMixin:
|
||||||
def get_playlist(self, playlistId: str, limit: int = 100, related: bool = False, suggestions_limit: int = 0) -> Dict:
|
|
||||||
|
def get_playlist(self,
|
||||||
|
playlistId: str,
|
||||||
|
limit: int = 100,
|
||||||
|
related: bool = False,
|
||||||
|
suggestions_limit: int = 0) -> Dict:
|
||||||
"""
|
"""
|
||||||
Returns a list of playlist items
|
Returns a list of playlist items
|
||||||
|
|
||||||
|
|
@ -119,11 +124,11 @@ class PlaylistsMixin:
|
||||||
playlist['title'] = nav(header, TITLE_TEXT)
|
playlist['title'] = nav(header, TITLE_TEXT)
|
||||||
playlist['thumbnails'] = nav(header, THUMBNAIL_CROPPED)
|
playlist['thumbnails'] = nav(header, THUMBNAIL_CROPPED)
|
||||||
playlist["description"] = nav(header, DESCRIPTION, True)
|
playlist["description"] = nav(header, DESCRIPTION, True)
|
||||||
run_count = len(header['subtitle']['runs'])
|
run_count = len(nav(header, SUBTITLE_RUNS))
|
||||||
if run_count > 1:
|
if run_count > 1:
|
||||||
playlist['author'] = {
|
playlist['author'] = {
|
||||||
'name': nav(header, SUBTITLE2),
|
'name': nav(header, SUBTITLE2),
|
||||||
'id': nav(header, ['subtitle', 'runs', 2] + NAVIGATION_BROWSE_ID, True)
|
'id': nav(header, SUBTITLE_RUNS + [2] + NAVIGATION_BROWSE_ID, True)
|
||||||
}
|
}
|
||||||
if run_count == 5:
|
if run_count == 5:
|
||||||
playlist['year'] = nav(header, SUBTITLE3)
|
playlist['year'] = nav(header, SUBTITLE3)
|
||||||
|
|
@ -135,7 +140,8 @@ class PlaylistsMixin:
|
||||||
|
|
||||||
playlist['trackCount'] = song_count
|
playlist['trackCount'] = song_count
|
||||||
|
|
||||||
request_func = lambda additionalParams: self._send_request(endpoint, body, additionalParams)
|
request_func = lambda additionalParams: self._send_request(endpoint, body, additionalParams
|
||||||
|
)
|
||||||
|
|
||||||
# suggestions and related are missing e.g. on liked songs
|
# suggestions and related are missing e.g. on liked songs
|
||||||
section_list = nav(response, SINGLE_COLUMN_TAB + ['sectionListRenderer'])
|
section_list = nav(response, SINGLE_COLUMN_TAB + ['sectionListRenderer'])
|
||||||
|
|
@ -150,7 +156,8 @@ class PlaylistsMixin:
|
||||||
playlist['suggestions'] = get_continuation_contents(suggestions_shelf, parse_func)
|
playlist['suggestions'] = get_continuation_contents(suggestions_shelf, parse_func)
|
||||||
|
|
||||||
parse_func = lambda results: parse_playlist_items(results)
|
parse_func = lambda results: parse_playlist_items(results)
|
||||||
playlist['suggestions'].extend(get_continuations(suggestions_shelf,
|
playlist['suggestions'].extend(
|
||||||
|
get_continuations(suggestions_shelf,
|
||||||
'musicShelfContinuation',
|
'musicShelfContinuation',
|
||||||
suggestions_limit - len(playlist['suggestions']),
|
suggestions_limit - len(playlist['suggestions']),
|
||||||
request_func,
|
request_func,
|
||||||
|
|
@ -161,8 +168,8 @@ class PlaylistsMixin:
|
||||||
response = request_func(additionalParams)
|
response = request_func(additionalParams)
|
||||||
continuation = nav(response, SECTION_LIST_CONTINUATION)
|
continuation = nav(response, SECTION_LIST_CONTINUATION)
|
||||||
parse_func = lambda results: parse_content_list(results, parse_playlist)
|
parse_func = lambda results: parse_content_list(results, parse_playlist)
|
||||||
playlist['related'] = get_continuation_contents(nav(continuation, CONTENT + CAROUSEL),
|
playlist['related'] = get_continuation_contents(
|
||||||
parse_func)
|
nav(continuation, CONTENT + CAROUSEL), parse_func)
|
||||||
|
|
||||||
if song_count > 0:
|
if song_count > 0:
|
||||||
playlist['tracks'] = parse_playlist_items(results['contents'])
|
playlist['tracks'] = parse_playlist_items(results['contents'])
|
||||||
|
|
|
||||||
|
|
@ -1,10 +1,10 @@
|
||||||
from typing import List, Dict
|
from typing import List, Dict
|
||||||
from ytmusicapi.navigation import *
|
|
||||||
from ytmusicapi.continuations import get_continuations
|
from ytmusicapi.continuations import get_continuations
|
||||||
from ytmusicapi.parsers.search_params import *
|
from ytmusicapi.parsers.search import *
|
||||||
|
|
||||||
|
|
||||||
class SearchMixin:
|
class SearchMixin:
|
||||||
|
|
||||||
def search(self,
|
def search(self,
|
||||||
query: str,
|
query: str,
|
||||||
filter: str = None,
|
filter: str = None,
|
||||||
|
|
@ -141,8 +141,7 @@ class SearchMixin:
|
||||||
if scope == scopes[1] and filter:
|
if scope == scopes[1] and filter:
|
||||||
raise Exception(
|
raise Exception(
|
||||||
"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. ")
|
||||||
)
|
|
||||||
|
|
||||||
params = get_search_params(filter, scope, ignore_spelling)
|
params = get_search_params(filter, scope, ignore_spelling)
|
||||||
if params:
|
if params:
|
||||||
|
|
@ -174,23 +173,36 @@ class SearchMixin:
|
||||||
filter = scopes[1]
|
filter = scopes[1]
|
||||||
|
|
||||||
for res in results:
|
for res in results:
|
||||||
if 'musicShelfRenderer' in res:
|
if 'musicCardShelfRenderer' in res:
|
||||||
|
top_result = parse_top_result(res['musicCardShelfRenderer'],
|
||||||
|
self.parser.get_search_result_types())
|
||||||
|
search_results.append(top_result)
|
||||||
|
if results := nav(res, ['musicCardShelfRenderer', 'contents'], True):
|
||||||
|
category = nav(results.pop(0), ['messageRenderer'] + TEXT_RUN_TEXT, True)
|
||||||
|
type = None
|
||||||
|
else:
|
||||||
|
continue
|
||||||
|
|
||||||
|
elif 'musicShelfRenderer' in res:
|
||||||
results = res['musicShelfRenderer']['contents']
|
results = res['musicShelfRenderer']['contents']
|
||||||
original_filter = filter
|
type_filter = filter
|
||||||
category = nav(res, MUSIC_SHELF + TITLE_TEXT, True)
|
category = nav(res, MUSIC_SHELF + TITLE_TEXT, True)
|
||||||
if not filter and scope == scopes[0]:
|
if not type_filter and scope == scopes[0]:
|
||||||
filter = category
|
type_filter = category
|
||||||
|
|
||||||
type = filter[:-1].lower() if filter else None
|
type = type_filter[:-1].lower() if type_filter else None
|
||||||
search_results.extend(self.parser.parse_search_results(results, type, category))
|
|
||||||
filter = original_filter
|
|
||||||
|
|
||||||
if 'continuations' in res['musicShelfRenderer']:
|
else:
|
||||||
|
continue
|
||||||
|
|
||||||
|
search_results.extend(
|
||||||
|
parse_search_results(results, self.parser.get_search_result_types(), type,
|
||||||
|
category))
|
||||||
|
|
||||||
|
if filter: # if filter is set, there are continuations
|
||||||
request_func = lambda additionalParams: self._send_request(
|
request_func = lambda additionalParams: self._send_request(
|
||||||
endpoint, body, additionalParams)
|
endpoint, body, additionalParams)
|
||||||
|
parse_func = lambda contents: parse_search_results(contents, type, category)
|
||||||
parse_func = lambda contents: self.parser.parse_search_results(
|
|
||||||
contents, type, category)
|
|
||||||
|
|
||||||
search_results.extend(
|
search_results.extend(
|
||||||
get_continuations(res['musicShelfRenderer'], 'musicShelfContinuation',
|
get_continuations(res['musicShelfRenderer'], 'musicShelfContinuation',
|
||||||
|
|
|
||||||
|
|
@ -31,22 +31,15 @@ NAVIGATION_VIDEO_TYPE = [
|
||||||
'watchEndpoint', 'watchEndpointMusicSupportedConfigs', 'watchEndpointMusicConfig',
|
'watchEndpoint', 'watchEndpointMusicSupportedConfigs', 'watchEndpointMusicConfig',
|
||||||
'musicVideoType'
|
'musicVideoType'
|
||||||
]
|
]
|
||||||
HEADER_DETAIL = ['header', 'musicDetailHeaderRenderer']
|
|
||||||
DESCRIPTION_SHELF = ['musicDescriptionShelfRenderer']
|
|
||||||
DESCRIPTION = ['description'] + RUN_TEXT
|
|
||||||
CAROUSEL = ['musicCarouselShelfRenderer']
|
|
||||||
IMMERSIVE_CAROUSEL = ['musicImmersiveCarouselShelfRenderer']
|
|
||||||
CAROUSEL_CONTENTS = CAROUSEL + ['contents']
|
|
||||||
CAROUSEL_TITLE = ['header', 'musicCarouselShelfBasicHeaderRenderer', 'title', 'runs', 0]
|
|
||||||
FRAMEWORK_MUTATIONS = ['frameworkUpdates', 'entityBatchUpdate', 'mutations']
|
|
||||||
TITLE = ['title', 'runs', 0]
|
TITLE = ['title', 'runs', 0]
|
||||||
TITLE_TEXT = ['title'] + RUN_TEXT
|
TITLE_TEXT = ['title'] + RUN_TEXT
|
||||||
TEXT_RUNS = ['text', 'runs']
|
TEXT_RUNS = ['text', 'runs']
|
||||||
TEXT_RUN = TEXT_RUNS + [0]
|
TEXT_RUN = TEXT_RUNS + [0]
|
||||||
TEXT_RUN_TEXT = TEXT_RUN + ['text']
|
TEXT_RUN_TEXT = TEXT_RUN + ['text']
|
||||||
SUBTITLE = ['subtitle'] + RUN_TEXT
|
SUBTITLE = ['subtitle'] + RUN_TEXT
|
||||||
SUBTITLE2 = ['subtitle', 'runs', 2, 'text']
|
SUBTITLE_RUNS = ['subtitle', 'runs']
|
||||||
SUBTITLE3 = ['subtitle', 'runs', 4, 'text']
|
SUBTITLE2 = SUBTITLE_RUNS + [2, 'text']
|
||||||
|
SUBTITLE3 = SUBTITLE_RUNS + [4, 'text']
|
||||||
THUMBNAIL = ['thumbnail', 'thumbnails']
|
THUMBNAIL = ['thumbnail', 'thumbnails']
|
||||||
THUMBNAILS = ['thumbnail', 'musicThumbnailRenderer'] + THUMBNAIL
|
THUMBNAILS = ['thumbnail', 'musicThumbnailRenderer'] + THUMBNAIL
|
||||||
THUMBNAIL_RENDERER = ['thumbnailRenderer', 'musicThumbnailRenderer'] + THUMBNAIL
|
THUMBNAIL_RENDERER = ['thumbnailRenderer', 'musicThumbnailRenderer'] + THUMBNAIL
|
||||||
|
|
@ -63,6 +56,15 @@ TASTE_PROFILE_ITEMS = ["contents", "tastebuilderRenderer", "contents"]
|
||||||
TASTE_PROFILE_ARTIST = ["title", "runs"]
|
TASTE_PROFILE_ARTIST = ["title", "runs"]
|
||||||
SECTION_LIST_CONTINUATION = ['continuationContents', 'sectionListContinuation']
|
SECTION_LIST_CONTINUATION = ['continuationContents', 'sectionListContinuation']
|
||||||
MENU_PLAYLIST_ID = MENU_ITEMS + [0, 'menuNavigationItemRenderer'] + NAVIGATION_WATCH_PLAYLIST_ID
|
MENU_PLAYLIST_ID = MENU_ITEMS + [0, 'menuNavigationItemRenderer'] + NAVIGATION_WATCH_PLAYLIST_ID
|
||||||
|
HEADER_DETAIL = ['header', 'musicDetailHeaderRenderer']
|
||||||
|
DESCRIPTION_SHELF = ['musicDescriptionShelfRenderer']
|
||||||
|
DESCRIPTION = ['description'] + RUN_TEXT
|
||||||
|
CAROUSEL = ['musicCarouselShelfRenderer']
|
||||||
|
IMMERSIVE_CAROUSEL = ['musicImmersiveCarouselShelfRenderer']
|
||||||
|
CAROUSEL_CONTENTS = CAROUSEL + ['contents']
|
||||||
|
CAROUSEL_TITLE = ['header', 'musicCarouselShelfBasicHeaderRenderer'] + TITLE
|
||||||
|
CARD_SHELF_TITLE = ['header', 'musicCardShelfHeaderBasicRenderer'] + TITLE_TEXT
|
||||||
|
FRAMEWORK_MUTATIONS = ['frameworkUpdates', 'entityBatchUpdate', 'mutations']
|
||||||
|
|
||||||
|
|
||||||
def nav(root, items, none_if_absent=False):
|
def nav(root, items, none_if_absent=False):
|
||||||
|
|
|
||||||
|
|
@ -1,13 +1,8 @@
|
||||||
from typing import List, Dict
|
|
||||||
from .songs import *
|
from .songs import *
|
||||||
from ._utils import *
|
from ._utils import *
|
||||||
|
|
||||||
|
|
||||||
class Parser:
|
def parse_mixed_content(rows):
|
||||||
def __init__(self, language):
|
|
||||||
self.lang = language
|
|
||||||
|
|
||||||
def parse_mixed_content(self, rows):
|
|
||||||
items = []
|
items = []
|
||||||
for row in rows:
|
for row in rows:
|
||||||
if DESCRIPTION_SHELF[0] in row:
|
if DESCRIPTION_SHELF[0] in row:
|
||||||
|
|
@ -45,152 +40,6 @@ class Parser:
|
||||||
items.append({'title': title, 'contents': contents})
|
items.append({'title': title, 'contents': contents})
|
||||||
return items
|
return items
|
||||||
|
|
||||||
@i18n
|
|
||||||
def parse_search_results(self, results, resultType=None, category=None):
|
|
||||||
search_results = []
|
|
||||||
default_offset = (not resultType) * 2
|
|
||||||
for result in results:
|
|
||||||
data = result[MRLIR]
|
|
||||||
search_result = {'category': category}
|
|
||||||
if not resultType:
|
|
||||||
resultType = get_item_text(data, 1).lower()
|
|
||||||
result_types = ['artist', 'playlist', 'song', 'video', 'station']
|
|
||||||
result_types_local = [
|
|
||||||
_('artist'), _('playlist'),
|
|
||||||
_('song'), _('video'),
|
|
||||||
_('station')
|
|
||||||
]
|
|
||||||
# default to album since it's labeled with multiple values ('Single', 'EP', etc.)
|
|
||||||
if resultType not in result_types_local:
|
|
||||||
resultType = 'album'
|
|
||||||
else:
|
|
||||||
resultType = result_types[result_types_local.index(resultType)]
|
|
||||||
|
|
||||||
search_result['resultType'] = resultType
|
|
||||||
|
|
||||||
if resultType != 'artist':
|
|
||||||
search_result['title'] = get_item_text(data, 0)
|
|
||||||
|
|
||||||
if resultType == 'artist':
|
|
||||||
search_result['artist'] = get_item_text(data, 0)
|
|
||||||
parse_menu_playlists(data, search_result)
|
|
||||||
|
|
||||||
elif resultType == 'album':
|
|
||||||
search_result['type'] = get_item_text(data, 1)
|
|
||||||
|
|
||||||
elif resultType == 'playlist':
|
|
||||||
flex_item = get_flex_column_item(data, 1)['text']['runs']
|
|
||||||
has_author = len(flex_item) == default_offset + 3
|
|
||||||
search_result['itemCount'] = nav(
|
|
||||||
flex_item, [default_offset + has_author * 2, 'text']).split(' ')[0]
|
|
||||||
search_result['author'] = None if not has_author else nav(
|
|
||||||
flex_item, [default_offset, 'text'])
|
|
||||||
|
|
||||||
elif resultType == 'station':
|
|
||||||
search_result['videoId'] = nav(data, NAVIGATION_VIDEO_ID)
|
|
||||||
search_result['playlistId'] = nav(data, NAVIGATION_PLAYLIST_ID)
|
|
||||||
|
|
||||||
elif resultType == 'song':
|
|
||||||
search_result['album'] = None
|
|
||||||
if 'menu' in data:
|
|
||||||
toggle_menu = find_object_by_key(nav(data, MENU_ITEMS), TOGGLE_MENU)
|
|
||||||
if toggle_menu:
|
|
||||||
search_result['feedbackTokens'] = parse_song_menu_tokens(toggle_menu)
|
|
||||||
|
|
||||||
elif resultType == 'video':
|
|
||||||
search_result['views'] = None
|
|
||||||
search_result['videoType'] = nav(data, PLAY_BUTTON + NAVIGATION_VIDEO_TYPE, True)
|
|
||||||
|
|
||||||
elif resultType == 'upload':
|
|
||||||
browse_id = nav(data, NAVIGATION_BROWSE_ID, True)
|
|
||||||
if not browse_id: # song result
|
|
||||||
flex_items = [
|
|
||||||
nav(get_flex_column_item(data, i), ['text', 'runs'], True)
|
|
||||||
for i in range(2)
|
|
||||||
]
|
|
||||||
if flex_items[0]:
|
|
||||||
search_result['videoId'] = nav(flex_items[0][0], NAVIGATION_VIDEO_ID, True)
|
|
||||||
search_result['playlistId'] = nav(flex_items[0][0], NAVIGATION_PLAYLIST_ID,
|
|
||||||
True)
|
|
||||||
if flex_items[1]:
|
|
||||||
search_result.update(parse_song_runs(flex_items[1]))
|
|
||||||
search_result['resultType'] = 'song'
|
|
||||||
|
|
||||||
else: # artist or album result
|
|
||||||
search_result['browseId'] = browse_id
|
|
||||||
if 'artist' in search_result['browseId']:
|
|
||||||
search_result['resultType'] = 'artist'
|
|
||||||
else:
|
|
||||||
flex_item2 = get_flex_column_item(data, 1)
|
|
||||||
runs = [
|
|
||||||
run['text'] for i, run in enumerate(flex_item2['text']['runs'])
|
|
||||||
if i % 2 == 0
|
|
||||||
]
|
|
||||||
if len(runs) > 1:
|
|
||||||
search_result['artist'] = runs[1]
|
|
||||||
if len(runs) > 2: # date may be missing
|
|
||||||
search_result['releaseDate'] = runs[2]
|
|
||||||
search_result['resultType'] = 'album'
|
|
||||||
|
|
||||||
if resultType in ['song', 'video']:
|
|
||||||
search_result['videoId'] = nav(
|
|
||||||
data, PLAY_BUTTON + ['playNavigationEndpoint', 'watchEndpoint', 'videoId'],
|
|
||||||
True)
|
|
||||||
search_result['videoType'] = nav(
|
|
||||||
data, PLAY_BUTTON + ['playNavigationEndpoint'] + NAVIGATION_VIDEO_TYPE, True)
|
|
||||||
|
|
||||||
if resultType in ['song', 'video', 'album']:
|
|
||||||
search_result['duration'] = None
|
|
||||||
search_result['year'] = None
|
|
||||||
has_offset = resultType == 'album' or (default_offset
|
|
||||||
and bool(search_result['videoId']))
|
|
||||||
flex_item = get_flex_column_item(data, 1)
|
|
||||||
runs = flex_item['text']['runs'][2 * has_offset:]
|
|
||||||
song_info = parse_song_runs(runs)
|
|
||||||
search_result.update(song_info)
|
|
||||||
|
|
||||||
if resultType in ['artist', 'album', 'playlist']:
|
|
||||||
search_result['browseId'] = nav(data, NAVIGATION_BROWSE_ID, True)
|
|
||||||
if not search_result['browseId']:
|
|
||||||
continue
|
|
||||||
|
|
||||||
if resultType in ['song', 'album']:
|
|
||||||
search_result['isExplicit'] = nav(data, BADGE_LABEL, True) is not None
|
|
||||||
|
|
||||||
search_result['thumbnails'] = nav(data, THUMBNAILS, True)
|
|
||||||
search_results.append(search_result)
|
|
||||||
|
|
||||||
return search_results
|
|
||||||
|
|
||||||
@i18n
|
|
||||||
def parse_artist_contents(self, results: List) -> Dict:
|
|
||||||
categories = ['albums', 'singles', 'videos', 'playlists', 'related']
|
|
||||||
categories_local = [_('albums'), _('singles'), _('videos'), _('playlists'), _('related')]
|
|
||||||
categories_parser = [
|
|
||||||
parse_album, parse_single, parse_video, parse_playlist, parse_related_artist
|
|
||||||
]
|
|
||||||
artist = {}
|
|
||||||
for i, category in enumerate(categories):
|
|
||||||
data = [
|
|
||||||
r['musicCarouselShelfRenderer'] for r in results
|
|
||||||
if 'musicCarouselShelfRenderer' in r
|
|
||||||
and nav(r, CAROUSEL + CAROUSEL_TITLE)['text'].lower() == categories_local[i]
|
|
||||||
]
|
|
||||||
if len(data) > 0:
|
|
||||||
artist[category] = {'browseId': None, 'results': []}
|
|
||||||
if 'navigationEndpoint' in nav(data[0], CAROUSEL_TITLE):
|
|
||||||
artist[category]['browseId'] = nav(data[0],
|
|
||||||
CAROUSEL_TITLE + NAVIGATION_BROWSE_ID)
|
|
||||||
if category in ['albums', 'singles', 'playlists']:
|
|
||||||
artist[category]['params'] = nav(
|
|
||||||
data[0],
|
|
||||||
CAROUSEL_TITLE)['navigationEndpoint']['browseEndpoint']['params']
|
|
||||||
|
|
||||||
artist[category]['results'] = parse_content_list(data[0]['contents'],
|
|
||||||
categories_parser[i])
|
|
||||||
|
|
||||||
return artist
|
|
||||||
|
|
||||||
|
|
||||||
def parse_content_list(results, parse_func, key=MTRIR):
|
def parse_content_list(results, parse_func, key=MTRIR):
|
||||||
contents = []
|
contents = []
|
||||||
|
|
@ -226,7 +75,7 @@ def parse_song(result):
|
||||||
'playlistId': nav(result, NAVIGATION_PLAYLIST_ID, True),
|
'playlistId': nav(result, NAVIGATION_PLAYLIST_ID, True),
|
||||||
'thumbnails': nav(result, THUMBNAIL_RENDERER)
|
'thumbnails': nav(result, THUMBNAIL_RENDERER)
|
||||||
}
|
}
|
||||||
song.update(parse_song_runs(result['subtitle']['runs']))
|
song.update(parse_song_runs(nav(result, SUBTITLE_RUNS)))
|
||||||
return song
|
return song
|
||||||
|
|
||||||
|
|
||||||
|
|
@ -252,7 +101,7 @@ def parse_song_flat(data):
|
||||||
|
|
||||||
|
|
||||||
def parse_video(result):
|
def parse_video(result):
|
||||||
runs = result['subtitle']['runs']
|
runs = nav(result, SUBTITLE_RUNS)
|
||||||
artists_len = get_dot_separator_index(runs)
|
artists_len = get_dot_separator_index(runs)
|
||||||
return {
|
return {
|
||||||
'title': nav(result, TITLE_TEXT),
|
'title': nav(result, TITLE_TEXT),
|
||||||
|
|
|
||||||
45
ytmusicapi/parsers/i18n.py
Normal file
45
ytmusicapi/parsers/i18n.py
Normal file
|
|
@ -0,0 +1,45 @@
|
||||||
|
from typing import List, Dict
|
||||||
|
|
||||||
|
from ytmusicapi.navigation import nav, CAROUSEL, CAROUSEL_TITLE, NAVIGATION_BROWSE_ID
|
||||||
|
from ytmusicapi.parsers._utils import i18n
|
||||||
|
from ytmusicapi.parsers.browsing import parse_album, parse_single, parse_video, parse_playlist, parse_related_artist, \
|
||||||
|
parse_content_list
|
||||||
|
|
||||||
|
|
||||||
|
class Parser:
|
||||||
|
|
||||||
|
def __init__(self, language):
|
||||||
|
self.lang = language
|
||||||
|
|
||||||
|
@i18n
|
||||||
|
def get_search_result_types(self):
|
||||||
|
return [_('artist'), _('playlist'), _('song'), _('video'), _('station')]
|
||||||
|
|
||||||
|
@i18n
|
||||||
|
def parse_artist_contents(self, results: List) -> Dict:
|
||||||
|
categories = ['albums', 'singles', 'videos', 'playlists', 'related']
|
||||||
|
categories_local = [_('albums'), _('singles'), _('videos'), _('playlists'), _('related')]
|
||||||
|
categories_parser = [
|
||||||
|
parse_album, parse_single, parse_video, parse_playlist, parse_related_artist
|
||||||
|
]
|
||||||
|
artist = {}
|
||||||
|
for i, category in enumerate(categories):
|
||||||
|
data = [
|
||||||
|
r['musicCarouselShelfRenderer'] for r in results
|
||||||
|
if 'musicCarouselShelfRenderer' in r
|
||||||
|
and nav(r, CAROUSEL + CAROUSEL_TITLE)['text'].lower() == categories_local[i]
|
||||||
|
]
|
||||||
|
if len(data) > 0:
|
||||||
|
artist[category] = {'browseId': None, 'results': []}
|
||||||
|
if 'navigationEndpoint' in nav(data[0], CAROUSEL_TITLE):
|
||||||
|
artist[category]['browseId'] = nav(data[0],
|
||||||
|
CAROUSEL_TITLE + NAVIGATION_BROWSE_ID)
|
||||||
|
if category in ['albums', 'singles', 'playlists']:
|
||||||
|
artist[category]['params'] = nav(
|
||||||
|
data[0],
|
||||||
|
CAROUSEL_TITLE)['navigationEndpoint']['browseEndpoint']['params']
|
||||||
|
|
||||||
|
artist[category]['results'] = parse_content_list(data[0]['contents'],
|
||||||
|
categories_parser[i])
|
||||||
|
|
||||||
|
return artist
|
||||||
195
ytmusicapi/parsers/search.py
Normal file
195
ytmusicapi/parsers/search.py
Normal file
|
|
@ -0,0 +1,195 @@
|
||||||
|
from .songs import *
|
||||||
|
from ._utils import *
|
||||||
|
|
||||||
|
|
||||||
|
def get_search_result_type(result_type_local, result_types_local):
|
||||||
|
if not result_type_local:
|
||||||
|
return None
|
||||||
|
result_types = ['artist', 'playlist', 'song', 'video', 'station']
|
||||||
|
result_type_local = result_type_local.lower()
|
||||||
|
# default to album since it's labeled with multiple values ('Single', 'EP', etc.)
|
||||||
|
if result_type_local not in result_types_local:
|
||||||
|
result_type = 'album'
|
||||||
|
else:
|
||||||
|
result_type = result_types[result_types_local.index(result_type_local)]
|
||||||
|
|
||||||
|
return result_type
|
||||||
|
|
||||||
|
|
||||||
|
def parse_top_result(data, search_result_types):
|
||||||
|
search_result = {}
|
||||||
|
result_type = get_search_result_type(nav(data, SUBTITLE), search_result_types)
|
||||||
|
search_result['resultType'] = result_type
|
||||||
|
if result_type == 'artist':
|
||||||
|
subscribers = nav(data, SUBTITLE2, True)
|
||||||
|
if subscribers:
|
||||||
|
search_result['subscribers'] = subscribers.split(' ')[0]
|
||||||
|
|
||||||
|
artist_info = parse_song_runs(nav(data, ['title', 'runs']))
|
||||||
|
search_result.update(artist_info)
|
||||||
|
|
||||||
|
if result_type in ['song', 'video', 'album']:
|
||||||
|
search_result['title'] = nav(data, TITLE_TEXT)
|
||||||
|
runs = nav(data, ['subtitle', 'runs'])[2:]
|
||||||
|
song_info = parse_song_runs(runs)
|
||||||
|
search_result.update(song_info)
|
||||||
|
|
||||||
|
search_result['thumbnails'] = nav(data, THUMBNAILS, True)
|
||||||
|
return search_result
|
||||||
|
|
||||||
|
|
||||||
|
def parse_search_result(data, search_result_types, result_type, category):
|
||||||
|
default_offset = (not result_type) * 2
|
||||||
|
search_result = {'category': category}
|
||||||
|
if video_type := nav(data, PLAY_BUTTON + ['playNavigationEndpoint'] + NAVIGATION_VIDEO_TYPE,
|
||||||
|
True):
|
||||||
|
result_type = 'song' if video_type == 'MUSIC_VIDEO_TYPE_ATV' else 'video'
|
||||||
|
|
||||||
|
result_type = get_search_result_type(get_item_text(data, 1),
|
||||||
|
search_result_types) if not result_type else result_type
|
||||||
|
search_result['resultType'] = result_type
|
||||||
|
|
||||||
|
if result_type != 'artist':
|
||||||
|
search_result['title'] = get_item_text(data, 0)
|
||||||
|
|
||||||
|
if result_type == 'artist':
|
||||||
|
search_result['artist'] = get_item_text(data, 0)
|
||||||
|
parse_menu_playlists(data, search_result)
|
||||||
|
|
||||||
|
elif result_type == 'album':
|
||||||
|
search_result['type'] = get_item_text(data, 1)
|
||||||
|
|
||||||
|
elif result_type == 'playlist':
|
||||||
|
flex_item = get_flex_column_item(data, 1)['text']['runs']
|
||||||
|
has_author = len(flex_item) == default_offset + 3
|
||||||
|
search_result['itemCount'] = nav(flex_item,
|
||||||
|
[default_offset + has_author * 2, 'text']).split(' ')[0]
|
||||||
|
search_result['author'] = None if not has_author else nav(flex_item,
|
||||||
|
[default_offset, 'text'])
|
||||||
|
|
||||||
|
elif result_type == 'station':
|
||||||
|
search_result['videoId'] = nav(data, NAVIGATION_VIDEO_ID)
|
||||||
|
search_result['playlistId'] = nav(data, NAVIGATION_PLAYLIST_ID)
|
||||||
|
|
||||||
|
elif result_type == 'song':
|
||||||
|
search_result['album'] = None
|
||||||
|
if 'menu' in data:
|
||||||
|
toggle_menu = find_object_by_key(nav(data, MENU_ITEMS), TOGGLE_MENU)
|
||||||
|
if toggle_menu:
|
||||||
|
search_result['feedbackTokens'] = parse_song_menu_tokens(toggle_menu)
|
||||||
|
|
||||||
|
elif result_type == 'upload':
|
||||||
|
browse_id = nav(data, NAVIGATION_BROWSE_ID, True)
|
||||||
|
if not browse_id: # song result
|
||||||
|
flex_items = [
|
||||||
|
nav(get_flex_column_item(data, i), ['text', 'runs'], True) for i in range(2)
|
||||||
|
]
|
||||||
|
if flex_items[0]:
|
||||||
|
search_result['videoId'] = nav(flex_items[0][0], NAVIGATION_VIDEO_ID, True)
|
||||||
|
search_result['playlistId'] = nav(flex_items[0][0], NAVIGATION_PLAYLIST_ID, True)
|
||||||
|
if flex_items[1]:
|
||||||
|
search_result.update(parse_song_runs(flex_items[1]))
|
||||||
|
search_result['resultType'] = 'song'
|
||||||
|
|
||||||
|
else: # artist or album result
|
||||||
|
search_result['browseId'] = browse_id
|
||||||
|
if 'artist' in search_result['browseId']:
|
||||||
|
search_result['resultType'] = 'artist'
|
||||||
|
else:
|
||||||
|
flex_item2 = get_flex_column_item(data, 1)
|
||||||
|
runs = [
|
||||||
|
run['text'] for i, run in enumerate(flex_item2['text']['runs']) if i % 2 == 0
|
||||||
|
]
|
||||||
|
if len(runs) > 1:
|
||||||
|
search_result['artist'] = runs[1]
|
||||||
|
if len(runs) > 2: # date may be missing
|
||||||
|
search_result['releaseDate'] = runs[2]
|
||||||
|
search_result['resultType'] = 'album'
|
||||||
|
|
||||||
|
if result_type in ['song', 'video']:
|
||||||
|
search_result['videoId'] = nav(
|
||||||
|
data, PLAY_BUTTON + ['playNavigationEndpoint', 'watchEndpoint', 'videoId'], True)
|
||||||
|
search_result['videoType'] = video_type
|
||||||
|
|
||||||
|
if result_type in ['song', 'video', 'album']:
|
||||||
|
search_result['duration'] = None
|
||||||
|
search_result['year'] = None
|
||||||
|
flex_item = get_flex_column_item(data, 1)
|
||||||
|
runs = flex_item['text']['runs'][default_offset:]
|
||||||
|
song_info = parse_song_runs(runs)
|
||||||
|
search_result.update(song_info)
|
||||||
|
|
||||||
|
if result_type in ['artist', 'album', 'playlist']:
|
||||||
|
search_result['browseId'] = nav(data, NAVIGATION_BROWSE_ID, True)
|
||||||
|
if not search_result['browseId']:
|
||||||
|
return {}
|
||||||
|
|
||||||
|
if result_type in ['song', 'album']:
|
||||||
|
search_result['isExplicit'] = nav(data, BADGE_LABEL, True) is not None
|
||||||
|
|
||||||
|
search_result['thumbnails'] = nav(data, THUMBNAILS, True)
|
||||||
|
|
||||||
|
return search_result
|
||||||
|
|
||||||
|
|
||||||
|
def parse_search_results(results, search_result_types, resultType=None, category=None):
|
||||||
|
return [
|
||||||
|
parse_search_result(result[MRLIR], search_result_types, resultType, category)
|
||||||
|
for result in results
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
def get_search_params(filter, scope, ignore_spelling):
|
||||||
|
filtered_param1 = 'EgWKAQI'
|
||||||
|
params = None
|
||||||
|
if filter is None and scope is None and not ignore_spelling:
|
||||||
|
return params
|
||||||
|
|
||||||
|
if scope == 'uploads':
|
||||||
|
params = 'agIYAw%3D%3D'
|
||||||
|
|
||||||
|
if scope == 'library':
|
||||||
|
if filter:
|
||||||
|
param1 = filtered_param1
|
||||||
|
param2 = _get_param2(filter)
|
||||||
|
param3 = 'AWoKEAUQCRADEAoYBA%3D%3D'
|
||||||
|
else:
|
||||||
|
params = 'agIYBA%3D%3D'
|
||||||
|
|
||||||
|
if scope is None and filter:
|
||||||
|
if filter == 'playlists':
|
||||||
|
params = 'Eg-KAQwIABAAGAAgACgB'
|
||||||
|
if not ignore_spelling:
|
||||||
|
params += 'MABqChAEEAMQCRAFEAo%3D'
|
||||||
|
else:
|
||||||
|
params += 'MABCAggBagoQBBADEAkQBRAK'
|
||||||
|
|
||||||
|
elif 'playlists' in filter:
|
||||||
|
param1 = 'EgeKAQQoA'
|
||||||
|
if filter == 'featured_playlists':
|
||||||
|
param2 = 'Dg'
|
||||||
|
else: # community_playlists
|
||||||
|
param2 = 'EA'
|
||||||
|
|
||||||
|
if not ignore_spelling:
|
||||||
|
param3 = 'BagwQDhAKEAMQBBAJEAU%3D'
|
||||||
|
else:
|
||||||
|
param3 = 'BQgIIAWoMEA4QChADEAQQCRAF'
|
||||||
|
|
||||||
|
else:
|
||||||
|
param1 = filtered_param1
|
||||||
|
param2 = _get_param2(filter)
|
||||||
|
if not ignore_spelling:
|
||||||
|
param3 = 'AWoMEA4QChADEAQQCRAF'
|
||||||
|
else:
|
||||||
|
param3 = 'AUICCAFqDBAOEAoQAxAEEAkQBQ%3D%3D'
|
||||||
|
|
||||||
|
if not scope and not filter and ignore_spelling:
|
||||||
|
params = 'EhGKAQ4IARABGAEgASgAOAFAAUICCAE%3D'
|
||||||
|
|
||||||
|
return params if params else param1 + param2 + param3
|
||||||
|
|
||||||
|
|
||||||
|
def _get_param2(filter):
|
||||||
|
filter_params = {'songs': 'I', 'videos': 'Q', 'albums': 'Y', 'artists': 'g', 'playlists': 'o'}
|
||||||
|
return filter_params[filter]
|
||||||
|
|
@ -1,56 +0,0 @@
|
||||||
FILTERED_PARAM1 = 'EgWKAQI'
|
|
||||||
|
|
||||||
|
|
||||||
def get_search_params(filter, scope, ignore_spelling):
|
|
||||||
params = None
|
|
||||||
if filter is None and scope is None and not ignore_spelling:
|
|
||||||
return params
|
|
||||||
|
|
||||||
if scope == 'uploads':
|
|
||||||
params = 'agIYAw%3D%3D'
|
|
||||||
|
|
||||||
if scope == 'library':
|
|
||||||
if filter:
|
|
||||||
param1 = FILTERED_PARAM1
|
|
||||||
param2 = _get_param2(filter)
|
|
||||||
param3 = 'AWoKEAUQCRADEAoYBA%3D%3D'
|
|
||||||
else:
|
|
||||||
params = 'agIYBA%3D%3D'
|
|
||||||
|
|
||||||
if scope is None and filter:
|
|
||||||
if filter == 'playlists':
|
|
||||||
params = 'Eg-KAQwIABAAGAAgACgB'
|
|
||||||
if not ignore_spelling:
|
|
||||||
params += 'MABqChAEEAMQCRAFEAo%3D'
|
|
||||||
else:
|
|
||||||
params += 'MABCAggBagoQBBADEAkQBRAK'
|
|
||||||
|
|
||||||
elif 'playlists' in filter:
|
|
||||||
param1 = 'EgeKAQQoA'
|
|
||||||
if filter == 'featured_playlists':
|
|
||||||
param2 = 'Dg'
|
|
||||||
else: # community_playlists
|
|
||||||
param2 = 'EA'
|
|
||||||
|
|
||||||
if not ignore_spelling:
|
|
||||||
param3 = 'BagwQDhAKEAMQBBAJEAU%3D'
|
|
||||||
else:
|
|
||||||
param3 = 'BQgIIAWoMEA4QChADEAQQCRAF'
|
|
||||||
|
|
||||||
else:
|
|
||||||
param1 = FILTERED_PARAM1
|
|
||||||
param2 = _get_param2(filter)
|
|
||||||
if not ignore_spelling:
|
|
||||||
param3 = 'AWoMEA4QChADEAQQCRAF'
|
|
||||||
else:
|
|
||||||
param3 = 'AUICCAFqDBAOEAoQAxAEEAkQBQ%3D%3D'
|
|
||||||
|
|
||||||
if not scope and not filter and ignore_spelling:
|
|
||||||
params = 'EhGKAQ4IARABGAEgASgAOAFAAUICCAE%3D'
|
|
||||||
|
|
||||||
return params if params else param1 + param2 + param3
|
|
||||||
|
|
||||||
|
|
||||||
def _get_param2(filter):
|
|
||||||
filter_params = {'songs': 'I', 'videos': 'Q', 'albums': 'Y', 'artists': 'g', 'playlists': 'o'}
|
|
||||||
return filter_params[filter]
|
|
||||||
|
|
@ -5,8 +5,9 @@ from requests.structures import CaseInsensitiveDict
|
||||||
from functools import partial
|
from functools import partial
|
||||||
from contextlib import suppress
|
from contextlib import suppress
|
||||||
from typing import Dict
|
from typing import Dict
|
||||||
|
|
||||||
|
from ytmusicapi.parsers.i18n import Parser
|
||||||
from ytmusicapi.helpers import *
|
from ytmusicapi.helpers import *
|
||||||
from ytmusicapi.parsers import browsing
|
|
||||||
from ytmusicapi.setup import setup
|
from ytmusicapi.setup import setup
|
||||||
from ytmusicapi.mixins.browsing import BrowsingMixin
|
from ytmusicapi.mixins.browsing import BrowsingMixin
|
||||||
from ytmusicapi.mixins.search import SearchMixin
|
from ytmusicapi.mixins.search import SearchMixin
|
||||||
|
|
@ -24,6 +25,7 @@ class YTMusic(BrowsingMixin, SearchMixin, WatchMixin, ExploreMixin, LibraryMixin
|
||||||
Permits both authenticated and non-authenticated requests.
|
Permits both authenticated and non-authenticated requests.
|
||||||
Authentication header data must be provided on initialization.
|
Authentication header data must be provided on initialization.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
def __init__(self,
|
def __init__(self,
|
||||||
auth: str = None,
|
auth: str = None,
|
||||||
user: str = None,
|
user: str = None,
|
||||||
|
|
@ -113,7 +115,7 @@ class YTMusic(BrowsingMixin, SearchMixin, WatchMixin, ExploreMixin, LibraryMixin
|
||||||
with suppress(locale.Error):
|
with suppress(locale.Error):
|
||||||
locale.setlocale(locale.LC_ALL, 'en_US.UTF-8')
|
locale.setlocale(locale.LC_ALL, 'en_US.UTF-8')
|
||||||
self.lang = gettext.translation('base', localedir=locale_dir, languages=[language])
|
self.lang = gettext.translation('base', localedir=locale_dir, languages=[language])
|
||||||
self.parser = browsing.Parser(self.lang)
|
self.parser = Parser(self.lang)
|
||||||
|
|
||||||
if user:
|
if user:
|
||||||
self.context['context']['user']['onBehalfOfUser'] = user
|
self.context['context']['user']['onBehalfOfUser'] = user
|
||||||
|
|
|
||||||
Loading…
Reference in a new issue