fix get_charts, add get_explore (#797)
* get_charts: move to a new class * get_charts: update * get_explore: init
This commit is contained in:
parent
7f42e8d5f0
commit
f6295e50be
6 changed files with 247 additions and 128 deletions
8
tests/mixins/test_charts.py
Normal file
8
tests/mixins/test_charts.py
Normal file
|
|
@ -0,0 +1,8 @@
|
|||
class TestCharts:
|
||||
def test_get_charts(self, yt, yt_oauth):
|
||||
charts = yt_oauth.get_charts()
|
||||
assert len(charts) >= 3
|
||||
charts = yt.get_charts(country="US")
|
||||
assert len(charts) == 4 # countries, videos, genres, artists
|
||||
charts = yt.get_charts(country="BE")
|
||||
assert len(charts) == 3 # countries, videos, artists
|
||||
|
|
@ -1,6 +1,3 @@
|
|||
import pytest
|
||||
|
||||
|
||||
class TestExplore:
|
||||
def test_get_mood_playlists(self, yt):
|
||||
categories = yt.get_mood_categories()
|
||||
|
|
@ -10,12 +7,25 @@ class TestExplore:
|
|||
playlists = yt.get_mood_playlists(categories[cat][0]["params"])
|
||||
assert len(playlists) > 0
|
||||
|
||||
@pytest.mark.skip(reason="disabled for now due to #787")
|
||||
def test_get_charts(self, yt, yt_oauth):
|
||||
charts = yt_oauth.get_charts()
|
||||
# songs section appears to be removed currently (US)
|
||||
assert len(charts) >= 3
|
||||
charts = yt.get_charts(country="US")
|
||||
assert len(charts) == 5
|
||||
charts = yt.get_charts(country="BE")
|
||||
assert len(charts) == 4
|
||||
def test_get_explore(self, yt, yt_oauth):
|
||||
assert len(yt.get_explore()) == 5
|
||||
|
||||
explore = yt_oauth.get_explore()
|
||||
assert len(explore) >= 5
|
||||
|
||||
assert all(item["audioPlaylistId"].startswith("OLA") for item in explore["new_releases"])
|
||||
|
||||
# check top_songs if present
|
||||
assert all(item["videoId"] for item in explore.get("top_songs", {"items": []})["items"])
|
||||
|
||||
assert all(
|
||||
item["videoId"] and all(artist["id"] for artist in item["artists"])
|
||||
for item in explore["trending"]["items"]
|
||||
)
|
||||
|
||||
assert all(item["videoId"] for item in explore["trending"]["items"])
|
||||
|
||||
assert all(
|
||||
item["duration"] and item["podcast"]["id"] and item["podcast"]["name"]
|
||||
for item in explore["top_episodes"]
|
||||
)
|
||||
|
|
|
|||
102
ytmusicapi/mixins/charts.py
Normal file
102
ytmusicapi/mixins/charts.py
Normal file
|
|
@ -0,0 +1,102 @@
|
|||
from ytmusicapi.mixins._protocol import MixinProtocol
|
||||
from ytmusicapi.parsers.explore import *
|
||||
from ytmusicapi.type_alias import JsonDict
|
||||
|
||||
|
||||
class ChartsMixin(MixinProtocol):
|
||||
def get_charts(self, country: str = "ZZ") -> JsonDict:
|
||||
"""
|
||||
Get latest charts data from YouTube Music: Artists and playlists of top videos.
|
||||
US charts have an extra Genres section with some Genre charts.
|
||||
|
||||
:param country: ISO 3166-1 Alpha-2 country code. Default: ``ZZ`` = Global
|
||||
:return: Dictionary containing chart video playlists (with separate daily/weekly charts if authenticated with a premium account),
|
||||
chart genres (US-only), and chart artists.
|
||||
|
||||
Example::
|
||||
|
||||
{
|
||||
"countries": {
|
||||
"selected": {
|
||||
"text": "United States"
|
||||
},
|
||||
"options": ["DE",
|
||||
"ZZ",
|
||||
"ZW"]
|
||||
},
|
||||
"videos": [
|
||||
{
|
||||
"title": "Daily Top Music Videos - United States",
|
||||
"playlistId": "PL4fGSI1pDJn61unMfmrUSz68RT8IFFnks",
|
||||
"thumbnails": []
|
||||
}
|
||||
],
|
||||
"artists": [
|
||||
{
|
||||
"title": "YoungBoy Never Broke Again",
|
||||
"browseId": "UCR28YDxjDE3ogQROaNdnRbQ",
|
||||
"subscribers": "9.62M",
|
||||
"thumbnails": [],
|
||||
"rank": "1",
|
||||
"trend": "neutral"
|
||||
}
|
||||
],
|
||||
"genres": [
|
||||
{
|
||||
"title": "Top 50 Pop Music Videos United States",
|
||||
"playlistId": "PL4fGSI1pDJn77aK7sAW2AT0oOzo5inWY8",
|
||||
"thumbnails": []
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
"""
|
||||
body: JsonDict = {"browseId": "FEmusic_charts"}
|
||||
if country:
|
||||
body["formData"] = {"selectedValues": [country]}
|
||||
|
||||
response = self._send_request("browse", body)
|
||||
results = nav(response, SINGLE_COLUMN_TAB + SECTION_LIST)
|
||||
charts: JsonDict = {"countries": {}}
|
||||
menu = nav(
|
||||
results[0],
|
||||
[
|
||||
*MUSIC_SHELF,
|
||||
"subheaders",
|
||||
0,
|
||||
"musicSideAlignedItemRenderer",
|
||||
"startItems",
|
||||
0,
|
||||
"musicSortFilterButtonRenderer",
|
||||
],
|
||||
)
|
||||
charts["countries"]["selected"] = nav(menu, TITLE)
|
||||
charts["countries"]["options"] = list(
|
||||
filter(
|
||||
None,
|
||||
[
|
||||
nav(m, ["payload", "musicFormBooleanChoice", "opaqueToken"], True)
|
||||
for m in nav(response, FRAMEWORK_MUTATIONS)
|
||||
],
|
||||
)
|
||||
)
|
||||
|
||||
charts_categories = [
|
||||
("videos", parse_chart_playlist, MTRIR),
|
||||
*([("genres", parse_chart_playlist, MTRIR)] if country == "US" else []),
|
||||
("artists", parse_chart_artist, MRLIR),
|
||||
]
|
||||
|
||||
# use result length to determine if the daily/weekly chart categories are present
|
||||
# could also be done via an is_premium attribute on YTMusic instance
|
||||
if (len(results) - 1) > len(charts_categories):
|
||||
# daily and weekly replace the "videos" playlist carousel
|
||||
charts_categories = [
|
||||
("daily", parse_chart_playlist, MTRIR),
|
||||
("weekly", parse_chart_playlist, MTRIR),
|
||||
] + charts_categories[1:]
|
||||
|
||||
for i, (name, parse_func, key) in enumerate(charts_categories):
|
||||
charts[name] = parse_content_list(nav(results[1 + i], CAROUSEL_CONTENTS), parse_func, key)
|
||||
|
||||
return charts
|
||||
|
|
@ -1,9 +1,6 @@
|
|||
from collections.abc import Callable
|
||||
from typing import Any
|
||||
|
||||
from ytmusicapi.mixins._protocol import MixinProtocol
|
||||
from ytmusicapi.parsers.explore import *
|
||||
from ytmusicapi.type_alias import JsonDict, JsonList, ParseFuncDictType
|
||||
from ytmusicapi.type_alias import JsonDict, JsonList
|
||||
|
||||
|
||||
class ExploreMixin(MixinProtocol):
|
||||
|
|
@ -90,27 +87,33 @@ class ExploreMixin(MixinProtocol):
|
|||
|
||||
return playlists
|
||||
|
||||
def get_charts(self, country: str = "ZZ") -> JsonDict:
|
||||
def get_explore(self) -> JsonDict:
|
||||
"""
|
||||
Get latest charts data from YouTube Music: Top songs, top videos, top artists and top trending videos.
|
||||
Global charts have no Trending section, US charts have an extra Genres section with some Genre charts.
|
||||
Get latest explore data from YouTube Music.
|
||||
The Top Songs chart is only returned when authenticated with a premium account.
|
||||
|
||||
:param country: ISO 3166-1 Alpha-2 country code. Default: ``ZZ`` = Global
|
||||
:return: Dictionary containing chart songs (only if authenticated with premium account),
|
||||
chart videos, chart artists and trending videos.
|
||||
:return: Dictionary containing new album releases, top songs (if authenticated with a premium account), moods & genres, popular episodes, trending tracks, and new music videos.
|
||||
|
||||
Example::
|
||||
|
||||
{
|
||||
"countries": {
|
||||
"selected": {
|
||||
"text": "United States"
|
||||
},
|
||||
"options": ["DE",
|
||||
"ZZ",
|
||||
"ZW"]
|
||||
},
|
||||
"songs": {
|
||||
"new_releases": [
|
||||
{
|
||||
"title": "Hangang",
|
||||
"type": "Album",
|
||||
"artists": [
|
||||
{
|
||||
"id": "UCpo4SbqmPXpCVA5RFj-Gq5Q",
|
||||
"name": "Dept"
|
||||
}
|
||||
],
|
||||
"browseId": "MPREb_rGl39ZNEl95",
|
||||
"audioPlaylistId": "OLAK5uy_mTZAp8a-agh1at-cVUGrwPhTJoM5GnKTk",
|
||||
"thumbnails": [...],
|
||||
"isExplicit": false
|
||||
}
|
||||
],
|
||||
"top_songs": {
|
||||
"playlist": "VLPL4fGSI1pDJn6O1LS0XSdF3RyO0Rq_LDeI",
|
||||
"items": [
|
||||
{
|
||||
|
|
@ -137,124 +140,104 @@ class ExploreMixin(MixinProtocol):
|
|||
}
|
||||
]
|
||||
},
|
||||
"videos": {
|
||||
"playlist": "VLPL4fGSI1pDJn69On1f-8NAvX_CYlx7QyZc",
|
||||
"items": [
|
||||
{
|
||||
"title": "EVERY CHANCE I GET (Official Music Video) (feat. Lil Baby & Lil Durk)",
|
||||
"videoId": "BTivsHlVcGU",
|
||||
"playlistId": "PL4fGSI1pDJn69On1f-8NAvX_CYlx7QyZc",
|
||||
"thumbnails": [],
|
||||
"views": "46M"
|
||||
}
|
||||
]
|
||||
},
|
||||
"artists": {
|
||||
"playlist": null,
|
||||
"items": [
|
||||
{
|
||||
"title": "YoungBoy Never Broke Again",
|
||||
"browseId": "UCR28YDxjDE3ogQROaNdnRbQ",
|
||||
"subscribers": "9.62M",
|
||||
"thumbnails": [],
|
||||
"rank": "1",
|
||||
"trend": "neutral"
|
||||
}
|
||||
]
|
||||
},
|
||||
"genres": [
|
||||
"moods_and_genres": [
|
||||
{
|
||||
"title": "Top 50 Pop Music Videos United States",
|
||||
"playlistId": "PL4fGSI1pDJn77aK7sAW2AT0oOzo5inWY8",
|
||||
"thumbnails": []
|
||||
"title": "Chill",
|
||||
"params": "ggMPOg1uXzVuc0dnZlhpV3Ba"
|
||||
}
|
||||
],
|
||||
"top_episodes": [
|
||||
{
|
||||
"title": "132. Lean Into Failure: How to Make Mistakes That Work | Think Fast, Talk Smart: Communication...",
|
||||
"description": "...",
|
||||
"duration": "25 min",
|
||||
"videoId": "xAEGaW2my7E",
|
||||
"browseId": "MPEDxAEGaW2my7E",
|
||||
"videoType": "MUSIC_VIDEO_TYPE_PODCAST_EPISODE",
|
||||
"date": "Mar 5, 2024",
|
||||
"thumbnails": [...],
|
||||
"podcast": {
|
||||
"id": "UCGwuxdEeCf0TIA2RbPOj-8g",
|
||||
"name: "Stanford Graduate School of Business"
|
||||
}
|
||||
}
|
||||
],
|
||||
"trending": {
|
||||
"playlist": "VLPLrEnWoR732-DtKgaDdnPkezM_nDidBU9H",
|
||||
"playlist": "VLOLAK5uy_kNWGJvgWVqlt5LsFDL9Sdluly4M8TvGkM",
|
||||
"items": [
|
||||
{
|
||||
"title": "Permission to Dance",
|
||||
"videoId": "CuklIb9d3fI",
|
||||
"playlistId": "PLrEnWoR732-DtKgaDdnPkezM_nDidBU9H",
|
||||
"playlistId": "OLAK5uy_kNWGJvgWVqlt5LsFDL9Sdluly4M8TvGkM",
|
||||
"artists": [
|
||||
{
|
||||
"name": "BTS",
|
||||
"id": "UC9vrvNSL3xcWGSkV86REBSg"
|
||||
}
|
||||
],
|
||||
"thumbnails": [],
|
||||
"thumbnails": [...],
|
||||
"isExplicit": false,
|
||||
"views": "108M"
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
"new_videos": [
|
||||
{
|
||||
"title": "EVERY CHANCE I GET (Official Music Video) (feat. Lil Baby & Lil Durk)",
|
||||
"videoId": "BTivsHlVcGU",
|
||||
"artists": [
|
||||
{
|
||||
"name": "DJ Khaled",
|
||||
"id": "UC0Kgvj5t_c9EMWpEDWJuR1Q"
|
||||
}
|
||||
],
|
||||
"playlistId": null,
|
||||
"thumbnails": [...],
|
||||
"views": "46M"
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
"""
|
||||
body: JsonDict = {"browseId": "FEmusic_charts"}
|
||||
if country:
|
||||
body["formData"] = {"selectedValues": [country]}
|
||||
body: JsonDict = {"browseId": "FEmusic_explore"}
|
||||
|
||||
response = self._send_request("browse", body)
|
||||
results = nav(response, SINGLE_COLUMN_TAB + SECTION_LIST)
|
||||
charts: JsonDict = {"countries": {}}
|
||||
menu = nav(
|
||||
results[0],
|
||||
[
|
||||
*MUSIC_SHELF,
|
||||
"subheaders",
|
||||
0,
|
||||
"musicSideAlignedItemRenderer",
|
||||
"startItems",
|
||||
0,
|
||||
"musicSortFilterButtonRenderer",
|
||||
],
|
||||
)
|
||||
charts["countries"]["selected"] = nav(menu, TITLE)
|
||||
charts["countries"]["options"] = list(
|
||||
filter(
|
||||
None,
|
||||
[
|
||||
nav(m, ["payload", "musicFormBooleanChoice", "opaqueToken"], True)
|
||||
for m in nav(response, FRAMEWORK_MUTATIONS)
|
||||
],
|
||||
)
|
||||
)
|
||||
charts_categories = ["videos", "artists"]
|
||||
|
||||
has_genres = country == "US"
|
||||
has_trending = country != "ZZ"
|
||||
explore: JsonDict = {}
|
||||
|
||||
# use result length to determine if songs category is present
|
||||
# could also be done via an is_premium attribute on YTMusic instance
|
||||
has_songs = (len(results) - 1) > (len(charts_categories) + has_genres + has_trending)
|
||||
for result in results:
|
||||
browse_id = nav(result, CAROUSEL + CAROUSEL_TITLE + NAVIGATION_BROWSE_ID, True)
|
||||
if browse_id is None:
|
||||
continue
|
||||
|
||||
if has_songs:
|
||||
charts_categories.insert(0, "songs")
|
||||
if has_genres:
|
||||
charts_categories.append("genres")
|
||||
if has_trending:
|
||||
charts_categories.append("trending")
|
||||
contents = nav(result, CAROUSEL_CONTENTS)
|
||||
match browse_id:
|
||||
case "FEmusic_new_releases_albums":
|
||||
explore["new_releases"] = parse_content_list(contents, parse_album)
|
||||
|
||||
parse_chart: Callable[[int, ParseFuncDictType, str], list[dict[str, Any]]] = (
|
||||
lambda index, parse_func, key: parse_content_list(
|
||||
nav(results[index + has_songs], CAROUSEL_CONTENTS), parse_func, key
|
||||
)
|
||||
)
|
||||
for i, c in enumerate(charts_categories):
|
||||
charts[c] = {
|
||||
"playlist": nav(results[1 + i], CAROUSEL + CAROUSEL_TITLE + NAVIGATION_BROWSE_ID, True)
|
||||
}
|
||||
case "FEmusic_moods_and_genres":
|
||||
explore["moods_and_genres"] = [
|
||||
{"title": nav(genre, CATEGORY_TITLE), "params": nav(genre, CATEGORY_PARAMS)}
|
||||
for genre in nav(result, CAROUSEL_CONTENTS)
|
||||
]
|
||||
|
||||
if has_songs:
|
||||
charts["songs"].update({"items": parse_chart(0, parse_chart_song, MRLIR)})
|
||||
case "FEmusic_top_non_music_audio_episodes":
|
||||
explore["top_episodes"] = parse_content_list(contents, parse_chart_episode, MMRIR)
|
||||
|
||||
charts["videos"]["items"] = parse_chart(1, parse_video, MTRIR)
|
||||
charts["artists"]["items"] = parse_chart(2, parse_chart_artist, MRLIR)
|
||||
case "FEmusic_new_releases_videos":
|
||||
explore["new_videos"] = parse_content_list(contents, parse_video, MTRIR)
|
||||
|
||||
if has_genres:
|
||||
charts["genres"] = parse_chart(3, parse_playlist, MTRIR)
|
||||
case playlist_id if playlist_id.startswith("VLPL"):
|
||||
explore["top_songs"] = {
|
||||
"playlist": playlist_id,
|
||||
"items": parse_content_list(contents, parse_chart_song, MRLIR),
|
||||
}
|
||||
|
||||
if has_trending:
|
||||
charts["trending"]["items"] = parse_chart(3 + has_genres, parse_chart_trending, MRLIR)
|
||||
case playlist_id if playlist_id.startswith("VLOLA"):
|
||||
explore["trending"] = {
|
||||
"playlist": playlist_id,
|
||||
"items": parse_content_list(contents, parse_trending_song, MRLIR),
|
||||
}
|
||||
|
||||
return charts
|
||||
return explore
|
||||
|
|
|
|||
|
|
@ -1,15 +1,33 @@
|
|||
from ytmusicapi.parsers.browsing import *
|
||||
from ytmusicapi.parsers.podcasts import *
|
||||
from ytmusicapi.parsers.songs import *
|
||||
from ytmusicapi.type_alias import JsonDict
|
||||
|
||||
TRENDS = {"ARROW_DROP_UP": "up", "ARROW_DROP_DOWN": "down", "ARROW_CHART_NEUTRAL": "neutral"}
|
||||
|
||||
|
||||
def parse_chart_song(data: JsonDict) -> JsonDict:
|
||||
parsed = parse_song_flat(data)
|
||||
parsed = parse_trending_song(data)
|
||||
parsed.update(parse_ranking(data))
|
||||
return parsed
|
||||
|
||||
|
||||
def parse_chart_playlist(data: JsonDict) -> JsonDict:
|
||||
return {
|
||||
"title": nav(data, TITLE_TEXT),
|
||||
"playlistId": nav(data, TITLE + NAVIGATION_BROWSE_ID)[2:],
|
||||
"thumbnails": nav(data, THUMBNAIL_RENDERER),
|
||||
}
|
||||
|
||||
|
||||
def parse_chart_episode(data: JsonDict) -> JsonDict:
|
||||
episode = parse_episode(data)
|
||||
del episode["index"]
|
||||
episode["podcast"] = parse_id_name(nav(data, ["secondTitle", "runs", 0]))
|
||||
episode["duration"] = nav(data, SUBTITLE2, True)
|
||||
return episode
|
||||
|
||||
|
||||
def parse_chart_artist(data: JsonDict) -> JsonDict:
|
||||
subscribers = get_flex_column_item(data, 1)
|
||||
if subscribers:
|
||||
|
|
@ -25,19 +43,15 @@ def parse_chart_artist(data: JsonDict) -> JsonDict:
|
|||
return parsed
|
||||
|
||||
|
||||
def parse_chart_trending(data: JsonDict) -> JsonDict:
|
||||
def parse_trending_song(data: JsonDict) -> JsonDict:
|
||||
flex_0 = get_flex_column_item(data, 0)
|
||||
artists = parse_song_artists(data, 1)
|
||||
index = get_dot_separator_index(artists)
|
||||
# last item is views for some reason
|
||||
views = None if index == len(artists) else artists.pop()["name"].split(" ")[0]
|
||||
return {
|
||||
"title": nav(flex_0, TEXT_RUN_TEXT),
|
||||
"videoId": nav(flex_0, TEXT_RUN + NAVIGATION_VIDEO_ID, True),
|
||||
**(parse_song_runs(nav(get_flex_column_item(data, 1), TEXT_RUNS))),
|
||||
"playlistId": nav(flex_0, TEXT_RUN + NAVIGATION_PLAYLIST_ID, True),
|
||||
"artists": artists,
|
||||
"thumbnails": nav(data, THUMBNAILS),
|
||||
"views": views,
|
||||
"isExplicit": nav(data, BADGE_LABEL, True) is not None,
|
||||
}
|
||||
|
||||
|
||||
|
|
|
|||
|
|
@ -27,6 +27,7 @@ from ytmusicapi.helpers import (
|
|||
sapisid_from_cookie,
|
||||
)
|
||||
from ytmusicapi.mixins.browsing import BrowsingMixin
|
||||
from ytmusicapi.mixins.charts import ChartsMixin
|
||||
from ytmusicapi.mixins.explore import ExploreMixin
|
||||
from ytmusicapi.mixins.library import LibraryMixin
|
||||
from ytmusicapi.mixins.playlists import PlaylistsMixin
|
||||
|
|
@ -280,6 +281,7 @@ class YTMusic(
|
|||
BrowsingMixin,
|
||||
SearchMixin,
|
||||
WatchMixin,
|
||||
ChartsMixin,
|
||||
ExploreMixin,
|
||||
LibraryMixin,
|
||||
PlaylistsMixin,
|
||||
|
|
|
|||
Loading…
Reference in a new issue