refactor search parsing to work with new top result (closes #360)

This commit is contained in:
sigma67 2023-03-22 22:33:56 +01:00
commit 19ad424e0e
No known key found for this signature in database
GPG key ID: 1C314227DF0103D0
12 changed files with 354 additions and 290 deletions

View file

@ -3,6 +3,7 @@ import unittest.mock
import configparser
import time
import sys
sys.path.insert(0, '..')
from ytmusicapi.ytmusic import YTMusic # noqa: E402
@ -15,6 +16,7 @@ sample_playlist = "PL6bPxvf5dW5clc3y9wAoslzqUrmkZ5c-u" # very large playlist
class TestYTMusic(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.yt = YTMusic(requests_session=False)

View file

@ -5,9 +5,11 @@ from ytmusicapi.parsers.browsing import *
from ytmusicapi.parsers.albums import parse_album_header
from ytmusicapi.parsers.playlists import parse_playlist_items
from ytmusicapi.parsers.library import parse_albums
from typing import List, Dict
class BrowsingMixin:
def get_home(self, limit=3) -> List[Dict]:
"""
Get the home page.
@ -99,14 +101,14 @@ class BrowsingMixin:
response = self._send_request(endpoint, body)
results = nav(response, SINGLE_COLUMN_TAB + SECTION_LIST)
home = []
home.extend(self.parser.parse_mixed_content(results))
home.extend(parse_mixed_content(results))
section_list = nav(response, SINGLE_COLUMN_TAB + ['sectionListRenderer'])
if 'continuations' in section_list:
request_func = lambda additionalParams: self._send_request(
endpoint, body, additionalParams)
parse_func = lambda contents: self.parser.parse_mixed_content(contents)
parse_func = lambda contents: parse_mixed_content(contents)
home.extend(
get_continuations(section_list, 'sectionListContinuation', limit - len(home),
@ -329,7 +331,7 @@ class BrowsingMixin:
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
@ -691,7 +693,7 @@ class BrowsingMixin:
response = self._send_request('browse', {'browseId': browseId})
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:
"""

View file

@ -1,7 +1,9 @@
from ytmusicapi.parsers.explore import *
from typing import List, Dict
class ExploreMixin:
def get_mood_categories(self) -> Dict:
"""
Fetch "Moods & Genres" categories from YouTube Music.

View file

@ -3,9 +3,11 @@ from ytmusicapi.continuations import *
from ._utils import *
from ytmusicapi.parsers.browsing import *
from ytmusicapi.parsers.library import *
from typing import List, Dict
class LibraryMixin:
def get_library_playlists(self, limit: int = 25) -> List[Dict]:
"""
Retrieves the playlists in the user's library.

View file

@ -10,7 +10,12 @@ from ytmusicapi.parsers.browsing import parse_content_list, parse_playlist
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
@ -119,11 +124,11 @@ class PlaylistsMixin:
playlist['title'] = nav(header, TITLE_TEXT)
playlist['thumbnails'] = nav(header, THUMBNAIL_CROPPED)
playlist["description"] = nav(header, DESCRIPTION, True)
run_count = len(header['subtitle']['runs'])
run_count = len(nav(header, SUBTITLE_RUNS))
if run_count > 1:
playlist['author'] = {
'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:
playlist['year'] = nav(header, SUBTITLE3)
@ -135,7 +140,8 @@ class PlaylistsMixin:
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
section_list = nav(response, SINGLE_COLUMN_TAB + ['sectionListRenderer'])
@ -150,19 +156,20 @@ class PlaylistsMixin:
playlist['suggestions'] = get_continuation_contents(suggestions_shelf, parse_func)
parse_func = lambda results: parse_playlist_items(results)
playlist['suggestions'].extend(get_continuations(suggestions_shelf,
'musicShelfContinuation',
suggestions_limit - len(playlist['suggestions']),
request_func,
parse_func,
reloadable=True))
playlist['suggestions'].extend(
get_continuations(suggestions_shelf,
'musicShelfContinuation',
suggestions_limit - len(playlist['suggestions']),
request_func,
parse_func,
reloadable=True))
if related:
response = request_func(additionalParams)
continuation = nav(response, SECTION_LIST_CONTINUATION)
parse_func = lambda results: parse_content_list(results, parse_playlist)
playlist['related'] = get_continuation_contents(nav(continuation, CONTENT + CAROUSEL),
parse_func)
playlist['related'] = get_continuation_contents(
nav(continuation, CONTENT + CAROUSEL), parse_func)
if song_count > 0:
playlist['tracks'] = parse_playlist_items(results['contents'])

View file

@ -1,10 +1,10 @@
from typing import List, Dict
from ytmusicapi.navigation import *
from ytmusicapi.continuations import get_continuations
from ytmusicapi.parsers.search_params import *
from ytmusicapi.parsers.search import *
class SearchMixin:
def search(self,
query: str,
filter: str = None,
@ -141,8 +141,7 @@ class SearchMixin:
if scope == scopes[1] and filter:
raise Exception(
"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)
if params:
@ -174,26 +173,39 @@ class SearchMixin:
filter = scopes[1]
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']
original_filter = filter
type_filter = filter
category = nav(res, MUSIC_SHELF + TITLE_TEXT, True)
if not filter and scope == scopes[0]:
filter = category
if not type_filter and scope == scopes[0]:
type_filter = category
type = filter[:-1].lower() if filter else None
search_results.extend(self.parser.parse_search_results(results, type, category))
filter = original_filter
type = type_filter[:-1].lower() if type_filter else None
if 'continuations' in res['musicShelfRenderer']:
request_func = lambda additionalParams: self._send_request(
endpoint, body, additionalParams)
else:
continue
parse_func = lambda contents: self.parser.parse_search_results(
contents, type, category)
search_results.extend(
parse_search_results(results, self.parser.get_search_result_types(), type,
category))
search_results.extend(
get_continuations(res['musicShelfRenderer'], 'musicShelfContinuation',
limit - len(search_results), request_func, parse_func))
if filter: # if filter is set, there are continuations
request_func = lambda additionalParams: self._send_request(
endpoint, body, additionalParams)
parse_func = lambda contents: 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

View file

@ -31,22 +31,15 @@ NAVIGATION_VIDEO_TYPE = [
'watchEndpoint', 'watchEndpointMusicSupportedConfigs', 'watchEndpointMusicConfig',
'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_TEXT = ['title'] + RUN_TEXT
TEXT_RUNS = ['text', 'runs']
TEXT_RUN = TEXT_RUNS + [0]
TEXT_RUN_TEXT = TEXT_RUN + ['text']
SUBTITLE = ['subtitle'] + RUN_TEXT
SUBTITLE2 = ['subtitle', 'runs', 2, 'text']
SUBTITLE3 = ['subtitle', 'runs', 4, 'text']
SUBTITLE_RUNS = ['subtitle', 'runs']
SUBTITLE2 = SUBTITLE_RUNS + [2, 'text']
SUBTITLE3 = SUBTITLE_RUNS + [4, 'text']
THUMBNAIL = ['thumbnail', 'thumbnails']
THUMBNAILS = ['thumbnail', 'musicThumbnailRenderer'] + THUMBNAIL
THUMBNAIL_RENDERER = ['thumbnailRenderer', 'musicThumbnailRenderer'] + THUMBNAIL
@ -63,6 +56,15 @@ TASTE_PROFILE_ITEMS = ["contents", "tastebuilderRenderer", "contents"]
TASTE_PROFILE_ARTIST = ["title", "runs"]
SECTION_LIST_CONTINUATION = ['continuationContents', 'sectionListContinuation']
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):

View file

@ -1,195 +1,44 @@
from typing import List, Dict
from .songs import *
from ._utils import *
class Parser:
def __init__(self, language):
self.lang = language
def parse_mixed_content(self, rows):
items = []
for row in rows:
if DESCRIPTION_SHELF[0] in row:
results = nav(row, DESCRIPTION_SHELF)
title = nav(results, ['header'] + RUN_TEXT)
contents = nav(results, DESCRIPTION)
else:
results = next(iter(row.values()))
if 'contents' not in results:
continue
title = nav(results, CAROUSEL_TITLE + ['text'])
contents = []
for result in results['contents']:
data = nav(result, [MTRIR], True)
content = None
if data:
page_type = nav(data, TITLE + NAVIGATION_BROWSE + PAGE_TYPE, True)
if page_type is None: # song or watch_playlist
if nav(data, NAVIGATION_WATCH_PLAYLIST_ID, True) is not None:
content = parse_watch_playlist(data)
else:
content = parse_song(data)
elif page_type == "MUSIC_PAGE_TYPE_ALBUM":
content = parse_album(data)
elif page_type == "MUSIC_PAGE_TYPE_ARTIST":
content = parse_related_artist(data)
elif page_type == "MUSIC_PAGE_TYPE_PLAYLIST":
content = parse_playlist(data)
else:
data = nav(result, [MRLIR])
content = parse_song_flat(data)
contents.append(content)
items.append({'title': title, 'contents': contents})
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'
def parse_mixed_content(rows):
items = []
for row in rows:
if DESCRIPTION_SHELF[0] in row:
results = nav(row, DESCRIPTION_SHELF)
title = nav(results, ['header'] + RUN_TEXT)
contents = nav(results, DESCRIPTION)
else:
results = next(iter(row.values()))
if 'contents' not in results:
continue
title = nav(results, CAROUSEL_TITLE + ['text'])
contents = []
for result in results['contents']:
data = nav(result, [MTRIR], True)
content = None
if data:
page_type = nav(data, TITLE + NAVIGATION_BROWSE + PAGE_TYPE, True)
if page_type is None: # song or watch_playlist
if nav(data, NAVIGATION_WATCH_PLAYLIST_ID, True) is not None:
content = parse_watch_playlist(data)
else:
content = parse_song(data)
elif page_type == "MUSIC_PAGE_TYPE_ALBUM":
content = parse_album(data)
elif page_type == "MUSIC_PAGE_TYPE_ARTIST":
content = parse_related_artist(data)
elif page_type == "MUSIC_PAGE_TYPE_PLAYLIST":
content = parse_playlist(data)
else:
resultType = result_types[result_types_local.index(resultType)]
data = nav(result, [MRLIR])
content = parse_song_flat(data)
search_result['resultType'] = resultType
contents.append(content)
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
items.append({'title': title, 'contents': contents})
return items
def parse_content_list(results, parse_func, key=MTRIR):
@ -226,7 +75,7 @@ def parse_song(result):
'playlistId': nav(result, NAVIGATION_PLAYLIST_ID, True),
'thumbnails': nav(result, THUMBNAIL_RENDERER)
}
song.update(parse_song_runs(result['subtitle']['runs']))
song.update(parse_song_runs(nav(result, SUBTITLE_RUNS)))
return song
@ -252,7 +101,7 @@ def parse_song_flat(data):
def parse_video(result):
runs = result['subtitle']['runs']
runs = nav(result, SUBTITLE_RUNS)
artists_len = get_dot_separator_index(runs)
return {
'title': nav(result, TITLE_TEXT),

View 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

View 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]

View file

@ -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]

View file

@ -5,8 +5,9 @@ from requests.structures import CaseInsensitiveDict
from functools import partial
from contextlib import suppress
from typing import Dict
from ytmusicapi.parsers.i18n import Parser
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
@ -24,6 +25,7 @@ class YTMusic(BrowsingMixin, SearchMixin, WatchMixin, ExploreMixin, LibraryMixin
Permits both authenticated and non-authenticated requests.
Authentication header data must be provided on initialization.
"""
def __init__(self,
auth: str = None,
user: str = None,
@ -113,7 +115,7 @@ class YTMusic(BrowsingMixin, SearchMixin, WatchMixin, ExploreMixin, LibraryMixin
with suppress(locale.Error):
locale.setlocale(locale.LC_ALL, 'en_US.UTF-8')
self.lang = gettext.translation('base', localedir=locale_dir, languages=[language])
self.parser = browsing.Parser(self.lang)
self.parser = Parser(self.lang)
if user:
self.context['context']['user']['onBehalfOfUser'] = user