Rewrite song/video search result parsing to be less error-prone

This commit is contained in:
sigma67 2021-02-01 12:43:25 +01:00
commit 5cbbf73c50
No known key found for this signature in database
GPG key ID: 1545A01D4474BAF0
3 changed files with 51 additions and 71 deletions

View file

@ -26,29 +26,6 @@ class Parser:
resultType = result_types[result_types_local.index(resultType)]
search_result['resultType'] = resultType
last_artist_index = default_offset
runs = []
if resultType in ['song', 'video']:
search_result['videoId'] = nav(
data, PLAY_BUTTON + ['playNavigationEndpoint', 'watchEndpoint', 'videoId'],
True)
search_result['title'] = get_item_text(data, 0)
runs = get_flex_column_item(data, 1)['text']['runs']
last_artist_index = get_last_artist_index(runs)
# unavailable song in default search
if not search_result['videoId'] and default_offset:
default_offset = 0
search_result['artists'] = parse_song_artists_runs(
runs[default_offset:last_artist_index + 1])
if resultType in ['artist', 'album', 'playlist']:
search_result['browseId'] = nav(data, NAVIGATION_BROWSE_ID, True)
if not search_result['browseId']:
continue
if resultType in ['artist']:
search_result['artist'] = get_item_text(data, 0)
@ -67,10 +44,7 @@ class Parser:
default_offset + 2).split(' ')[0]
elif resultType in ['song']:
search_result['album'] = parse_song_album_runs(runs, last_artist_index)
search_result['duration'] = None if not re.match(
r"^\d+:\d+$", runs[-1]['text']) else runs[-1]['text']
search_result['isExplicit'] = nav(data, BADGE_LABEL, True) == 'Explicit'
search_result['duration'] = None
if 'menu' in data:
toggle_menu = find_object_by_key(nav(data, MENU_ITEMS),
'toggleMenuServiceItemRenderer')
@ -78,9 +52,7 @@ class Parser:
search_result['feedbackTokens'] = parse_song_menu_tokens(toggle_menu)
elif resultType in ['video']:
search_result['views'] = get_item_text(data, 1,
2 + last_artist_index).split(' ')[0]
search_result['duration'] = get_item_text(data, 1, 4 + last_artist_index, True)
search_result['views'] = None
elif resultType in ['upload']:
search_result['title'] = get_item_text(data, 0)
@ -121,6 +93,20 @@ class Parser:
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['title'] = get_item_text(data, 0)
song_info = parse_song_runs(get_flex_column_item(data, 1)['text']['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) == 'Explicit'

View file

@ -1,4 +1,5 @@
from . import *
import re
def parse_song_artists(data, index):
@ -6,34 +7,42 @@ def parse_song_artists(data, index):
if not flex_item:
return None
else:
return parse_song_artists_runs(flex_item['text']['runs'])
runs = flex_item['text']['runs']
artists = []
for j in range(int(len(runs) / 2) + 1):
artists.append({
'name': runs[j * 2]['text'],
'id': nav(runs[j * 2], NAVIGATION_BROWSE_ID, True)
})
return artists
def parse_song_artists_runs(runs):
artists = []
for j in range(int(len(runs) / 2) + 1):
artists.append({
'name': runs[j * 2]['text'],
'id': nav(runs[j * 2], NAVIGATION_BROWSE_ID, True)
})
def parse_song_runs(runs):
parsed = {'artists': []}
for run in runs:
text = run['text']
if 'navigationEndpoint' in run: # artist or album
item = {
'name': text,
'id': nav(run, NAVIGATION_BROWSE_ID, True)
}
return artists
if item['id'] and item['id'].startswith('MPRE'): # album
parsed['album'] = item
else: # artist
parsed['artists'].append(item)
def get_last_artist_index(runs):
try:
return next(
len(runs) - i - 1 for i, run in enumerate(reversed(runs))
if 'navigationEndpoint' in run and
(nav(run, NAVIGATION_BROWSE_ID).startswith('UC') or nav(
run, NAVIGATION_BROWSE_ID).startswith('FEmusic_library_privately_owned_artist')))
except StopIteration: # try to find album if no artist IDs available
if 'navigationEndpoint' in runs[-3] or runs[-3]['text'].endswith('views'): # has album
return len(runs) - 5
elif runs[-1]['text'].endswith('views'):
return len(runs) - 3
else:
return 0
if text.endswith(' views'):
parsed['views'] = text.split(' ')[0]
elif re.match(r"^\d+:\d+$", text):
parsed['duration'] = text
elif re.match(r"^\d{4}$", text):
parsed['year'] = text
return parsed
def parse_song_album(data, index):
@ -44,17 +53,6 @@ def parse_song_album(data, index):
}
def parse_song_album_runs(runs, last_artist_index):
if len(runs) > last_artist_index + 1 and type(
runs[last_artist_index + 2]) is dict: # has album
return {
'name': runs[last_artist_index + 2]['text'],
'id': nav(runs[last_artist_index + 2], NAVIGATION_BROWSE_ID, True)
}
else:
return None
def parse_song_menu_tokens(item):
library_add_token = library_remove_token = None
toggle_menu = item['toggleMenuServiceItemRenderer']

View file

@ -20,22 +20,18 @@ def parse_watch_playlist(results):
status = ['LIKE', 'INDIFFERENT']
like_status = status[status.index(service['likeEndpoint']['status']) - 1]
runs = data['longBylineText']['runs']
last_artist_index = get_last_artist_index(runs)
artists = parse_song_artists_runs(runs[:last_artist_index + 1])
album = parse_song_album_runs(runs, last_artist_index)
song_info = parse_song_runs(data['longBylineText']['runs'])
track = {
'videoId': data['videoId'],
'title': nav(data, TITLE_TEXT),
'artists': artists,
'album': album,
'length': nav(data, ['lengthText', 'runs', 0, 'text'], True),
'playlistId': nav(data, NAVIGATION_PLAYLIST_ID),
'thumbnail': nav(data, THUMBNAIL),
'feedbackTokens': feedback_tokens,
'likeStatus': like_status
}
track.update(song_info)
tracks.append(track)
return tracks