refactor helpers and utils, extract SearchMixin from BrowsingMixin

This commit is contained in:
sigma67 2022-05-05 14:26:45 +02:00
commit f4ff4ba287
No known key found for this signature in database
GPG key ID: 1545A01D4474BAF0
19 changed files with 400 additions and 378 deletions

View file

@ -1,56 +0,0 @@
# commonly used navigation paths
RUN_TEXT = ['runs', 0, 'text']
TAB_CONTENT = ['tabs', 0, 'tabRenderer', 'content']
SINGLE_COLUMN_TAB = ['contents', 'singleColumnBrowseResultsRenderer'] + TAB_CONTENT
SECTION_LIST = ['sectionListRenderer', 'contents']
SECTION_LIST_ITEM = ['sectionListRenderer', 'contents', 0]
ITEM_SECTION = ['itemSectionRenderer', 'contents', 0]
MUSIC_SHELF = ['musicShelfRenderer']
GRID = ['gridRenderer']
GRID_ITEMS = GRID + ['items']
MENU = ['menu', 'menuRenderer']
MENU_ITEMS = MENU + ['items']
MENU_LIKE_STATUS = MENU + ['topLevelButtons', 0, 'likeButtonRenderer', 'likeStatus']
MENU_SERVICE = ['menuServiceItemRenderer', 'serviceEndpoint']
TOGGLE_MENU = 'toggleMenuServiceItemRenderer'
PLAY_BUTTON = [
'overlay', 'musicItemThumbnailOverlayRenderer', 'content', 'musicPlayButtonRenderer'
]
NAVIGATION_BROWSE = ['navigationEndpoint', 'browseEndpoint']
NAVIGATION_BROWSE_ID = NAVIGATION_BROWSE + ['browseId']
PAGE_TYPE = [
'browseEndpointContextSupportedConfigs', 'browseEndpointContextMusicConfig', 'pageType'
]
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'
]
HEADER_DETAIL = ['header', 'musicDetailHeaderRenderer']
DESCRIPTION = ['description'] + RUN_TEXT
CAROUSEL = ['musicCarouselShelfRenderer']
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']
THUMBNAIL = ['thumbnail', 'thumbnails']
THUMBNAILS = ['thumbnail', 'musicThumbnailRenderer'] + THUMBNAIL
THUMBNAIL_RENDERER = ['thumbnailRenderer', 'musicThumbnailRenderer'] + THUMBNAIL
THUMBNAIL_CROPPED = ['thumbnail', 'croppedSquareThumbnailRenderer'] + THUMBNAIL
FEEDBACK_TOKEN = ['feedbackEndpoint', 'feedbackToken']
BADGE_LABEL = [
'badges', 0, 'musicInlineBadgeRenderer', 'accessibilityData', 'accessibilityData', 'label'
]
RELOAD_CONTINUATION = ['continuations', 0, 'reloadContinuationData', 'continuation']
CATEGORY_TITLE = ['musicNavigationButtonRenderer', 'buttonText'] + RUN_TEXT
CATEGORY_PARAMS = ['musicNavigationButtonRenderer', 'clickCommand', 'browseEndpoint', 'params']
MRLIR = 'musicResponsiveListItemRenderer'
MTRIR = 'musicTwoRowItemRenderer'

View file

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

View file

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

View file

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

View file

@ -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'] = []

View file

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

View file

@ -1,5 +1,4 @@
from .utils import *
from ..helpers import parse_duration
from ._utils import *
import re

View file

@ -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):

View file

@ -1,183 +0,0 @@
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)
def get_continuations(results, continuation_type, limit, request_func, parse_func, ctoken_path=""):
items = []
while 'continuations' in results and len(items) < limit:
additionalParams = get_continuation_params(results, ctoken_path)
response = request_func(additionalParams)
if 'continuationContents' in response:
results = response['continuationContents'][continuation_type]
else:
break
contents = get_continuation_contents(results, parse_func)
if len(contents) == 0:
break
items.extend(contents)
return items
def get_validated_continuations(results,
continuation_type,
limit,
per_page,
request_func,
parse_func,
ctoken_path=""):
items = []
while 'continuations' in results and len(items) < limit:
additionalParams = get_continuation_params(results, ctoken_path)
wrapped_parse_func = lambda raw_response: get_parsed_continuation_items(
raw_response, parse_func, continuation_type)
validate_func = lambda parsed: validate_response(parsed, per_page, limit, len(items))
response = resend_request_until_parsed_response_is_valid(request_func, additionalParams,
wrapped_parse_func, validate_func,
3)
results = response['results']
items.extend(response['parsed'])
return items
def get_parsed_continuation_items(response, parse_func, continuation_type):
results = response['continuationContents'][continuation_type]
return {'results': results, 'parsed': get_continuation_contents(results, parse_func)}
def get_continuation_params(results, ctoken_path):
ctoken = nav(results,
['continuations', 0, 'next' + ctoken_path + 'ContinuationData', 'continuation'])
return get_continuation_string(ctoken)
def get_continuation_string(ctoken):
return "&ctoken=" + ctoken + "&continuation=" + ctoken
def get_continuation_contents(continuation, parse_func):
for term in ['contents', 'items']:
if term in continuation:
return parse_func(continuation[term])
return []
def resend_request_until_parsed_response_is_valid(request_func, request_additional_params,
parse_func, validate_func, max_retries):
response = request_func(request_additional_params)
parsed_object = parse_func(response)
retry_counter = 0
while not validate_func(parsed_object) and retry_counter < max_retries:
response = request_func(request_additional_params)
attempt = parse_func(response)
if len(attempt['parsed']) > len(parsed_object['parsed']):
parsed_object = attempt
retry_counter += 1
return parsed_object
def validate_response(response, per_page, limit, current_count):
remaining_items_count = limit - current_count
expected_items_count = min(per_page, remaining_items_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

View file

@ -1,4 +1,4 @@
from .utils import *
from ._utils import *
from .songs import *