refactor helpers and utils, extract SearchMixin from BrowsingMixin
This commit is contained in:
parent
1d30910e23
commit
f4ff4ba287
19 changed files with 400 additions and 378 deletions
|
|
@ -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
|
||||
|
|
@ -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']
|
||||
])
|
||||
|
|
|
|||
40
ytmusicapi/mixins/_utils.py
Normal file
40
ytmusicapi/mixins/_utils.py
Normal file
|
|
@ -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
|
||||
|
|
@ -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,
|
||||
|
|
|
|||
|
|
@ -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:
|
||||
|
|
|
|||
|
|
@ -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 *
|
||||
|
||||
|
||||
|
|
|
|||
192
ytmusicapi/mixins/search.py
Normal file
192
ytmusicapi/mixins/search.py
Normal file
|
|
@ -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
|
||||
|
|
@ -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)
|
||||
|
|
|
|||
|
|
@ -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 *
|
||||
|
||||
|
||||
|
|
|
|||
|
|
@ -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
|
||||
80
ytmusicapi/parsers/_utils.py
Normal file
80
ytmusicapi/parsers/_utils.py
Normal 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
|
||||
|
|
@ -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)
|
||||
|
|
|
|||
|
|
@ -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
|
||||
|
|
|
|||
|
|
@ -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'] = []
|
||||
|
|
|
|||
|
|
@ -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:]
|
||||
|
|
|
|||
|
|
@ -1,5 +1,4 @@
|
|||
from .utils import *
|
||||
from ..helpers import parse_duration
|
||||
from ._utils import *
|
||||
import re
|
||||
|
||||
|
||||
|
|
|
|||
|
|
@ -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):
|
||||
|
|
|
|||
|
|
@ -1,4 +1,4 @@
|
|||
from .utils import *
|
||||
from ._utils import *
|
||||
from .songs import *
|
||||
|
||||
|
||||
|
|
|
|||
|
|
@ -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.
|
||||
|
|
|
|||
Loading…
Reference in a new issue