get_podcast, get_episode
This commit is contained in:
parent
650bc24d68
commit
a3e4c26c8a
14 changed files with 311 additions and 30 deletions
26
README.rst
26
README.rst
|
|
@ -58,6 +58,11 @@ Features
|
|||
* get playlist contents
|
||||
* get playlist suggestions
|
||||
|
||||
| **Podcasts**:
|
||||
|
||||
* get podcasts
|
||||
* get episodes
|
||||
|
||||
| **Uploads**:
|
||||
|
||||
* upload songs and remove them again
|
||||
|
|
@ -73,6 +78,15 @@ If you find something missing or broken,
|
|||
check the `FAQ <https://ytmusicapi.readthedocs.io/en/stable/faq.html>`__ or
|
||||
feel free to create an `issue <https://github.com/sigma67/ytmusicapi/issues/new/choose>`__.
|
||||
|
||||
Requirements
|
||||
------------
|
||||
|
||||
- Python 3.8 or higher - https://www.python.org
|
||||
|
||||
Setup
|
||||
-----
|
||||
|
||||
See the `Documentation <https://ytmusicapi.readthedocs.io/en/stable/usage.html>`_ for detailed instructions
|
||||
|
||||
Usage
|
||||
------
|
||||
|
|
@ -89,18 +103,8 @@ The `tests <https://github.com/sigma67/ytmusicapi/blob/master/tests/>`_ are also
|
|||
|
||||
.. end-features
|
||||
|
||||
Requirements
|
||||
==============
|
||||
|
||||
- Python 3.8 or higher - https://www.python.org
|
||||
|
||||
Setup and Usage
|
||||
===============
|
||||
|
||||
See the `Documentation <https://ytmusicapi.readthedocs.io/en/latest/usage.html>`_ for detailed instructions
|
||||
|
||||
Contributing
|
||||
==============
|
||||
------------
|
||||
|
||||
Pull requests are welcome. There are still some features that are not yet implemented.
|
||||
Please, refer to `CONTRIBUTING.rst <https://github.com/sigma67/ytmusicapi/blob/master/CONTRIBUTING.rst>`_ for guidance.
|
||||
|
|
|
|||
|
|
@ -79,6 +79,26 @@ What is a browseId?
|
|||
***********************************************************************
|
||||
A ``browseId`` is an internal, globally unique identifier used by YouTube Music for browsable content.
|
||||
|
||||
In most cases you can compose it yourself:
|
||||
|
||||
+--------+------------+----------------------+
|
||||
| Prefix | Main | Content |
|
||||
+========+============+======================+
|
||||
| VM | playlistId | Playlist |
|
||||
+--------+------------+----------------------+
|
||||
| RDAMVM | playlistId | Video-based Radio |
|
||||
+--------+------------+----------------------+
|
||||
| RDAMPL | videoId | Playlist-based Radio |
|
||||
+--------+------------+----------------------+
|
||||
| MPLA | channelId | Artist |
|
||||
+--------+------------+----------------------+
|
||||
| MPRE | custom | Album |
|
||||
+--------+------------+----------------------+
|
||||
| MPSP | playlistId | Podcast |
|
||||
+--------+------------+----------------------+
|
||||
| MPED | videoId | Episode |
|
||||
+--------+------------+----------------------+
|
||||
|
||||
|
||||
Which videoTypes exist and what do they mean?
|
||||
***********************************************************************
|
||||
|
|
@ -112,14 +132,15 @@ For the list of values you can use for the ``language`` parameter, see below:
|
|||
.. raw:: html
|
||||
|
||||
<details>
|
||||
<br>
|
||||
<summary><a>Supported locations</a></summary>
|
||||
|
||||
.. container::
|
||||
|
||||
.. list-table::
|
||||
|
||||
* - Language
|
||||
- Value
|
||||
* - **Language**
|
||||
- **Value**
|
||||
* - Arabic
|
||||
- ar
|
||||
* - German
|
||||
|
|
@ -157,6 +178,7 @@ For the list of values you can use for the ``language`` parameter, see below:
|
|||
.. raw:: html
|
||||
|
||||
</details>
|
||||
</br>
|
||||
|
||||
|
||||
|
||||
|
|
@ -168,14 +190,15 @@ Pick a value from the list below for your desired location and pass it using the
|
|||
.. raw:: html
|
||||
|
||||
<details>
|
||||
<br>
|
||||
<summary><a>Supported locations</a></summary>
|
||||
|
||||
.. container::
|
||||
|
||||
.. list-table::
|
||||
|
||||
* - Location
|
||||
- Value
|
||||
* - **Location**
|
||||
- **Value**
|
||||
* - Algeria
|
||||
- DZ
|
||||
* - Argentina
|
||||
|
|
@ -398,4 +421,4 @@ Pick a value from the list below for your desired location and pass it using the
|
|||
.. raw:: html
|
||||
|
||||
</details>
|
||||
|
||||
</br>
|
||||
|
|
|
|||
|
|
@ -71,6 +71,11 @@ Playlists
|
|||
.. automethod:: YTMusic.add_playlist_items
|
||||
.. automethod:: YTMusic.remove_playlist_items
|
||||
|
||||
Podcasts
|
||||
--------
|
||||
.. automethod:: YTMusic.get_podcast
|
||||
.. automethod:: YTMusic.get_episode
|
||||
|
||||
Uploads
|
||||
-------
|
||||
.. automethod:: YTMusic.get_library_upload_songs
|
||||
|
|
|
|||
21
tests/mixins/test_podcasts.py
Normal file
21
tests/mixins/test_podcasts.py
Normal file
|
|
@ -0,0 +1,21 @@
|
|||
class TestPodcasts:
|
||||
def test_get_podcast(self, yt, yt_brand):
|
||||
podcast_id = "PLxq_lXOUlvQDgCVFj9L79kqJybW0k6OaB" # Think Fast, Talk Smart: The Podcast
|
||||
|
||||
results = yt.get_podcast(podcast_id)
|
||||
assert len(results["episodes"]) == 100
|
||||
assert not results["saved"]
|
||||
|
||||
results = yt_brand.get_podcast(podcast_id, limit=None)
|
||||
assert len(results["episodes"]) > 100
|
||||
assert results["saved"]
|
||||
|
||||
def test_get_episode(self, yt, yt_brand):
|
||||
podcast_id = "KNkyHCLOr1o" # 124. Making Meetings Meaningful, Pt. 1: How to Structure
|
||||
result = yt.get_episode(podcast_id)
|
||||
assert len(result["description"]) == 50
|
||||
assert not result["saved"]
|
||||
assert result["playlistId"] is not None
|
||||
|
||||
result = yt_brand.get_episode(podcast_id)
|
||||
assert result["saved"]
|
||||
3
tests/setup_account.py
Normal file
3
tests/setup_account.py
Normal file
|
|
@ -0,0 +1,3 @@
|
|||
from conftest import fixture_config
|
||||
|
||||
config = fixture_config()
|
||||
|
|
@ -206,6 +206,15 @@ class PlaylistsMixin(MixinProtocol):
|
|||
"""
|
||||
return self.get_playlist("LM", limit)
|
||||
|
||||
def get_saved_episodes(self, limit: int = 100) -> Dict:
|
||||
"""
|
||||
Gets playlist items for the 'Liked Songs' playlist
|
||||
|
||||
:param limit: How many items to return. Default: 100
|
||||
:return: List of playlistItem dictionaries. See :py:func:`get_playlist`
|
||||
"""
|
||||
return self.get_playlist("SE", limit)
|
||||
|
||||
def create_playlist(
|
||||
self,
|
||||
title: str,
|
||||
|
|
|
|||
73
ytmusicapi/mixins/podcasts.py
Normal file
73
ytmusicapi/mixins/podcasts.py
Normal file
|
|
@ -0,0 +1,73 @@
|
|||
from typing import Dict
|
||||
|
||||
from ytmusicapi.continuations import *
|
||||
from ytmusicapi.mixins._protocol import MixinProtocol
|
||||
from ytmusicapi.navigation import *
|
||||
from ytmusicapi.parsers.podcasts import *
|
||||
|
||||
from ._utils import *
|
||||
|
||||
|
||||
class PodcastsMixin(MixinProtocol):
|
||||
def get_podcast(self, playlistId: str, limit: Optional[int] = 100) -> Dict:
|
||||
"""
|
||||
Returns podcast metadata and episodes
|
||||
|
||||
.. note::
|
||||
|
||||
To add a podcast to your library, you need to call `rate_playlist` on it
|
||||
|
||||
:param playlistId: Playlist id
|
||||
:param limit: How many songs to return. `None` retrieves them all. Default: 100
|
||||
"""
|
||||
browseId = "MPSP" + playlistId if not playlistId.startswith("MPSP") else playlistId
|
||||
body = {"browseId": browseId}
|
||||
endpoint = "browse"
|
||||
response = self._send_request(endpoint, body)
|
||||
two_columns = nav(response, TWO_COLUMN_RENDERER)
|
||||
header = nav(two_columns, [*TAB_CONTENT, *SECTION_LIST_ITEM, *RESPONSIVE_HEADER])
|
||||
podcast = parse_podcast_header(header)
|
||||
|
||||
results = nav(two_columns, ["secondaryContents", *SECTION_LIST_ITEM, *MUSIC_SHELF])
|
||||
episodes = parse_episodes(results["contents"])
|
||||
|
||||
if "continuations" in results:
|
||||
request_func = lambda additionalParams: self._send_request(endpoint, body, additionalParams)
|
||||
parse_func = lambda contents: parse_episodes(contents)
|
||||
remaining_limit = None if limit is None else (limit - len(episodes))
|
||||
episodes.extend(
|
||||
get_continuations(
|
||||
results, "musicShelfContinuation", remaining_limit, request_func, parse_func
|
||||
)
|
||||
)
|
||||
|
||||
podcast["episodes"] = episodes
|
||||
|
||||
return podcast
|
||||
|
||||
def get_episode(self, videoId: str) -> Dict:
|
||||
"""
|
||||
Retrieve episode data for a single episode
|
||||
|
||||
.. note::
|
||||
|
||||
To save an episode, you need to call `add_playlist_items` to add
|
||||
it to the `SE` (saved episodes) playlist.
|
||||
|
||||
:param videoId: browseId (MPED..) or videoId for a single episode
|
||||
"""
|
||||
browseId = "MPED" + videoId if not videoId.startswith("MPED") else videoId
|
||||
body = {"browseId": browseId}
|
||||
endpoint = "browse"
|
||||
response = self._send_request(endpoint, body)
|
||||
|
||||
two_columns = nav(response, TWO_COLUMN_RENDERER)
|
||||
header = nav(two_columns, [*TAB_CONTENT, *SECTION_LIST_ITEM, *RESPONSIVE_HEADER])
|
||||
episode = parse_episode_header(header)
|
||||
|
||||
description_runs = nav(
|
||||
two_columns, ["secondaryContents", *SECTION_LIST_ITEM, *DESCRIPTION_SHELF, "description", "runs"]
|
||||
)
|
||||
episode["description"] = Description.from_runs(description_runs)
|
||||
|
||||
return episode
|
||||
|
|
@ -5,11 +5,13 @@ CONTENT = ["contents", 0]
|
|||
RUN_TEXT = ["runs", 0, "text"]
|
||||
TAB_CONTENT = ["tabs", 0, "tabRenderer", "content"]
|
||||
TAB_1_CONTENT = ["tabs", 1, "tabRenderer", "content"]
|
||||
TWO_COLUMN_RENDERER = ["contents", "twoColumnBrowseResultsRenderer"]
|
||||
SINGLE_COLUMN = ["contents", "singleColumnBrowseResultsRenderer"]
|
||||
SINGLE_COLUMN_TAB = SINGLE_COLUMN + TAB_CONTENT
|
||||
SECTION = ["sectionListRenderer"]
|
||||
SECTION_LIST = [*SECTION, "contents"]
|
||||
SECTION_LIST_ITEM = SECTION + CONTENT
|
||||
RESPONSIVE_HEADER = ["musicResponsiveHeaderRenderer"]
|
||||
ITEM_SECTION = ["itemSectionRenderer", *CONTENT]
|
||||
MUSIC_SHELF = ["musicShelfRenderer"]
|
||||
GRID = ["gridRenderer"]
|
||||
|
|
@ -34,6 +36,8 @@ NAVIGATION_VIDEO_TYPE = [
|
|||
"watchEndpointMusicConfig",
|
||||
"musicVideoType",
|
||||
]
|
||||
ICON_TYPE = ["icon", "iconType"]
|
||||
TOGGLED_BUTTON = ["toggleButtonRenderer", "isToggled"]
|
||||
TITLE = ["title", "runs", 0]
|
||||
TITLE_TEXT = ["title", *RUN_TEXT]
|
||||
TEXT_RUNS = ["text", "runs"]
|
||||
|
|
@ -55,10 +59,11 @@ CATEGORY_TITLE = ["musicNavigationButtonRenderer", "buttonText", *RUN_TEXT]
|
|||
CATEGORY_PARAMS = ["musicNavigationButtonRenderer", "clickCommand", "browseEndpoint", "params"]
|
||||
MRLIR = "musicResponsiveListItemRenderer"
|
||||
MTRIR = "musicTwoRowItemRenderer"
|
||||
MNIR = "menuNavigationItemRenderer"
|
||||
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]
|
||||
MENU_PLAYLIST_ID = [*MENU_ITEMS, 0, MNIR, *NAVIGATION_WATCH_PLAYLIST_ID]
|
||||
MULTI_SELECT = ["musicMultiSelectMenuItemRenderer"]
|
||||
HEADER_DETAIL = ["header", "musicDetailHeaderRenderer"]
|
||||
HEADER_SIDE = ["header", "musicSideAlignedItemRenderer"]
|
||||
|
|
|
|||
|
|
@ -4,9 +4,9 @@ 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"])
|
||||
watch_menu = find_objects_by_key(nav(data, MENU_ITEMS), MNIR)
|
||||
for item in [_x[MNIR] for _x in watch_menu]:
|
||||
icon = nav(item, ICON_TYPE)
|
||||
if icon == "MUSIC_SHUFFLE":
|
||||
watch_key = "shuffleId"
|
||||
elif icon == "MIX":
|
||||
|
|
|
|||
|
|
@ -43,7 +43,5 @@ def parse_chart_trending(data):
|
|||
def parse_ranking(data):
|
||||
return {
|
||||
"rank": nav(data, ["customIndexColumn", "musicCustomIndexColumnRenderer", *TEXT_RUN_TEXT]),
|
||||
"trend": TRENDS[
|
||||
nav(data, ["customIndexColumn", "musicCustomIndexColumnRenderer", "icon", "iconType"])
|
||||
],
|
||||
"trend": TRENDS[nav(data, ["customIndexColumn", "musicCustomIndexColumnRenderer", *ICON_TYPE])],
|
||||
}
|
||||
|
|
|
|||
|
|
@ -75,7 +75,7 @@ def parse_playlist_items(results, menu_entries: Optional[List[List]] = None, is_
|
|||
|
||||
videoType = nav(
|
||||
data,
|
||||
[*MENU_ITEMS, 0, "menuNavigationItemRenderer", "navigationEndpoint", *NAVIGATION_VIDEO_TYPE],
|
||||
[*MENU_ITEMS, 0, MNIR, "navigationEndpoint", *NAVIGATION_VIDEO_TYPE],
|
||||
True,
|
||||
)
|
||||
|
||||
|
|
|
|||
127
ytmusicapi/parsers/podcasts.py
Normal file
127
ytmusicapi/parsers/podcasts.py
Normal file
|
|
@ -0,0 +1,127 @@
|
|||
from dataclasses import dataclass
|
||||
from typing import Sequence
|
||||
|
||||
from .songs import *
|
||||
|
||||
|
||||
@dataclass
|
||||
class DescriptionElement:
|
||||
text: str
|
||||
|
||||
def __str__(self) -> str:
|
||||
return self.text
|
||||
|
||||
|
||||
@dataclass
|
||||
class Link(DescriptionElement):
|
||||
url: str
|
||||
|
||||
|
||||
@dataclass
|
||||
class Timestamp(DescriptionElement):
|
||||
seconds: int
|
||||
|
||||
|
||||
@dataclass
|
||||
class Description(Sequence):
|
||||
def __len__(self):
|
||||
return len(self.elements)
|
||||
|
||||
def __getitem__(self, index):
|
||||
return self.elements[index]
|
||||
|
||||
elements: Sequence[DescriptionElement]
|
||||
|
||||
@property
|
||||
def text(self) -> str:
|
||||
return "".join(str(element) for element in self.elements)
|
||||
|
||||
@classmethod
|
||||
def from_runs(cls, description_runs: List[Dict]) -> "Description":
|
||||
"""parse the description runs into a usable format
|
||||
|
||||
:param description_runs: the original description runs
|
||||
|
||||
:return: List of text (str), timestamp (int) and link values (Link object)
|
||||
"""
|
||||
elements = []
|
||||
for run in description_runs:
|
||||
navigationEndpoint = nav(run, ["navigationEndpoint"], True)
|
||||
if navigationEndpoint:
|
||||
element = DescriptionElement("")
|
||||
if "urlEndpoint" in navigationEndpoint:
|
||||
element = Link(text=run["text"], url=navigationEndpoint["urlEndpoint"]["url"])
|
||||
elif "watchEndpoint" in navigationEndpoint:
|
||||
element = Timestamp(
|
||||
text=run["text"],
|
||||
seconds=nav(navigationEndpoint, ["watchEndpoint", "startTimeSeconds"]),
|
||||
)
|
||||
else:
|
||||
element = DescriptionElement(text=nav(run, ["text"], True)) # type: ignore
|
||||
|
||||
elements.append(element)
|
||||
|
||||
return cls(elements=elements)
|
||||
|
||||
|
||||
def _parse_base_header(header: Dict) -> Dict:
|
||||
"""parse common left hand side (header) items of an episode or podcast page"""
|
||||
strapline = nav(header, ["straplineTextOne"])
|
||||
return {
|
||||
"author": {
|
||||
"name": nav(strapline, [*RUN_TEXT]),
|
||||
"id": nav(strapline, ["runs", 0, *NAVIGATION_BROWSE_ID]),
|
||||
},
|
||||
"title": nav(header, TITLE_TEXT),
|
||||
}
|
||||
|
||||
|
||||
def parse_podcast_header(header: Dict) -> Dict:
|
||||
metadata = _parse_base_header(header)
|
||||
metadata["description"] = nav(header, ["description", *DESCRIPTION_SHELF, *DESCRIPTION])
|
||||
metadata["saved"] = nav(header, ["buttons", 1, *TOGGLED_BUTTON])
|
||||
|
||||
return metadata
|
||||
|
||||
|
||||
def parse_episode_header(header: Dict) -> Dict:
|
||||
metadata = _parse_base_header(header)
|
||||
metadata["date"] = nav(header, [*SUBTITLE2])
|
||||
metadata["duration"] = nav(header, [*SUBTITLE3])
|
||||
metadata["saved"] = nav(header, ["buttons", 0, *TOGGLED_BUTTON], True)
|
||||
|
||||
metadata["playlistId"] = None
|
||||
menu_buttons = nav(header, ["buttons", -1, "menuRenderer", "items"])
|
||||
for button in menu_buttons:
|
||||
if nav(button, [MNIR, *ICON_TYPE], True) == "BROADCAST":
|
||||
metadata["playlistId"] = nav(button, [MNIR, *NAVIGATION_BROWSE_ID])
|
||||
|
||||
return metadata
|
||||
|
||||
|
||||
def parse_episodes(results) -> List[Dict]:
|
||||
episodes = []
|
||||
for result in results:
|
||||
data = nav(result, ["musicMultiRowListItemRenderer"])
|
||||
date = nav(data, SUBTITLE)
|
||||
duration = nav(data, SUBTITLE2)
|
||||
title = nav(data, TITLE_TEXT)
|
||||
description = nav(data, DESCRIPTION)
|
||||
videoId = nav(data, ["onTap", *WATCH_VIDEO_ID], True)
|
||||
browseId = nav(data, [*TITLE, *NAVIGATION_BROWSE_ID], True)
|
||||
videoType = nav(data, ["onTap", *NAVIGATION_VIDEO_TYPE], True)
|
||||
index = nav(data, ["onTap", "watchEndpoint", "index"])
|
||||
episodes.append(
|
||||
{
|
||||
"index": index,
|
||||
"title": title,
|
||||
"description": description,
|
||||
"duration": duration,
|
||||
"videoId": videoId,
|
||||
"browseId": browseId,
|
||||
"videoType": videoType,
|
||||
"date": date,
|
||||
}
|
||||
)
|
||||
|
||||
return episodes
|
||||
|
|
@ -8,12 +8,23 @@ def parse_uploaded_items(results):
|
|||
data = result[MRLIR]
|
||||
if "menu" not in data:
|
||||
continue
|
||||
entityId = nav(data, MENU_ITEMS)[-1]["menuNavigationItemRenderer"]["navigationEndpoint"][
|
||||
"confirmDialogEndpoint"
|
||||
]["content"]["confirmDialogRenderer"]["confirmButton"]["buttonRenderer"]["command"][
|
||||
"musicDeletePrivatelyOwnedEntityCommand"
|
||||
]["entityId"]
|
||||
|
||||
entityId = nav(
|
||||
data,
|
||||
[
|
||||
*MENU_ITEMS,
|
||||
-1,
|
||||
MNIR,
|
||||
"navigationEndpoint",
|
||||
"confirmDialogEndpoint",
|
||||
"content",
|
||||
"confirmDialogRenderer",
|
||||
"confirmButton",
|
||||
"buttonRenderer",
|
||||
"command",
|
||||
"musicDeletePrivatelyOwnedEntityCommand",
|
||||
"entityId",
|
||||
],
|
||||
)
|
||||
videoId = nav(data, [*MENU_ITEMS, 0, *MENU_SERVICE])["queueAddEndpoint"]["queueTarget"]["videoId"]
|
||||
|
||||
title = get_item_text(data, 0)
|
||||
|
|
|
|||
|
|
@ -28,6 +28,7 @@ from ytmusicapi.mixins.browsing import BrowsingMixin
|
|||
from ytmusicapi.mixins.explore import ExploreMixin
|
||||
from ytmusicapi.mixins.library import LibraryMixin
|
||||
from ytmusicapi.mixins.playlists import PlaylistsMixin
|
||||
from ytmusicapi.mixins.podcasts import PodcastsMixin
|
||||
from ytmusicapi.mixins.search import SearchMixin
|
||||
from ytmusicapi.mixins.uploads import UploadsMixin
|
||||
from ytmusicapi.mixins.watch import WatchMixin
|
||||
|
|
@ -268,6 +269,7 @@ class YTMusic(
|
|||
ExploreMixin,
|
||||
LibraryMixin,
|
||||
PlaylistsMixin,
|
||||
PodcastsMixin,
|
||||
UploadsMixin,
|
||||
):
|
||||
"""
|
||||
|
|
|
|||
Loading…
Reference in a new issue