Update docs

This commit is contained in:
sigma67 2020-02-21 14:21:52 +01:00
commit 581bbdbbd4
No known key found for this signature in database
GPG key ID: 1545A01D4474BAF0
9 changed files with 234 additions and 23 deletions

4
.gitignore vendored
View file

@ -1,2 +1,4 @@
.idea
headers_auth.json
headers_auth.json
docs/build
**.bat

20
docs/Makefile Normal file
View file

@ -0,0 +1,20 @@
# Minimal makefile for Sphinx documentation
#
# You can set these variables from the command line, and also
# from the environment for the first two.
SPHINXOPTS ?=
SPHINXBUILD ?= sphinx-build
SOURCEDIR = source
BUILDDIR = build
# Put it first so that "make" without argument is like "make help".
help:
@$(SPHINXBUILD) -M help "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O)
.PHONY: help Makefile
# Catch-all target: route all unknown targets to Sphinx using the new
# "make mode" option. $(O) is meant as a shortcut for $(SPHINXOPTS).
%: Makefile
@$(SPHINXBUILD) -M $@ "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O)

70
docs/source/conf.py Normal file
View file

@ -0,0 +1,70 @@
# Configuration file for the Sphinx documentation builder.
#
# This file only contains a selection of the most common options. For a full
# list see the documentation:
# https://www.sphinx-doc.org/en/master/usage/configuration.html
# -- Path setup --------------------------------------------------------------
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
#
import os
import sys
sys.path.insert(0, os.path.abspath('.'))
on_rtd = os.environ.get('READTHEDOCS', None) == 'True'
from ytmusicapi import __version__
# -- Project information -----------------------------------------------------
project = 'ytmusicapi'
copyright = '2020, sigma67'
author = 'sigma67'
# The full version, including alpha/beta/rc tags
version = __version__
# The full version, including alpha/beta/rc tags.
release = __version__
# -- General configuration ---------------------------------------------------
# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
# ones.
extensions = ["sphinx.ext.autodoc"]
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
# This pattern also affects html_static_path and html_extra_path.
exclude_patterns = []
# -- Options for HTML output -------------------------------------------------
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
#
if not on_rtd:
# Try to use the ReadTheDocs theme if installed.
# Default to the default alabaster theme if not.
try:
import sphinx_rtd_theme
html_theme = 'sphinx_rtd_theme'
html_theme_path = [sphinx_rtd_theme.get_html_theme_path()]
except ImportError:
html_theme = 'alabaster'
else:
# Set theme to 'default' for ReadTheDocs.
html_theme = 'default'
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['_static']

24
docs/source/index.rst Normal file
View file

@ -0,0 +1,24 @@
.. ytmusicapi documentation master file, created by
sphinx-quickstart on Fri Feb 21 12:48:31 2020.
You can adapt this file completely to your liking, but it should at least
contain the root `toctree` directive.
ytmusicapi: Unofficial API for YouTube Music
==================================================
**This project is not supported nor endorsed by Google**
Features
--------
- Library management: list, create, delete, and modify playlists and playlist items
- Search: Search for songs on YouTube Music
Contents
--------
.. toctree::
Home <self>
.. toctree::
reference

14
docs/source/reference.rst Normal file
View file

@ -0,0 +1,14 @@
Reference
==================
Reference for the YTMusic class.
.. currentmodule:: ytmusicapi
.. autoclass:: YTMusic
.. automethod:: YTMusic.__init__
.. automethod:: YTMusic.get_playlists
.. automethod:: YTMusic.get_playlist_items
.. automethod:: YTMusic.create_playlist
.. automethod:: YTMusic.edit_playlist

View file

@ -1,7 +1,18 @@
from setuptools import setup, find_packages
import re
VERSIONFILE = 'ytmusicapi/_version.py'
version_line = open(VERSIONFILE).read()
version_re = r"^__version__ = ['\"]([^'\"]*)['\"]"
match = re.search(version_re, version_line, re.M)
if match:
version = match.group(1)
else:
raise RuntimeError("Could not find version in '%s'" % VERSIONFILE)
setup(name='ytmusicapi',
version='0.3',
version=version,
description='Unofficial YTMusic API',
long_description=(open('README.md').read()),
url='https://github.com/sigma67/ytmusicapi',

View file

@ -1 +1 @@
__version__ = "0.1.0"
__version__ = "0.3.0"

View file

@ -3,21 +3,27 @@ from ytmusicapi.ytmusic import YTMusic
youtube = YTMusic()
youtube_auth = YTMusic('../headers_auth.json')
def get_playlists():
songs = youtube.get_playlists()
playlists = youtube.get_playlists()
print(playlists)
def get_foreign_playlist():
songs = youtube.get_playlist_items("PLw-VjHDlEOgs658kAHR_LAaILBXb-s6Q5")
assert (len(songs) == 200)
def get_owned_playlist():
songs = youtube_auth.get_playlist_items('PLQwVIlKxHM6oCeKLTsUx_w9CmWjHKdg68')
assert (len(songs) == 64)
def search():
results = youtube_auth.search("Oasis Wonderwall")
print(results)
#end to end test adding playlist, adding item, deleting item, deleting playlist
def end2end():
playlist = youtube_auth.create_playlist("test", "test description")
@ -31,19 +37,8 @@ def end2end():
response = youtube_auth.delete_playlist(playlist)
assert(response['command']['handlePlaylistDeletionCommand']['playlistId'] == playlist)
# youtube.add_playlist_item('PLQwVIlKxHM6p6LRH_53M7tvRXaz0eVzpa', 'y0Hhvtmv0gk')
# songs = youtube.get_playlist_items("PLw-VjHDlEOgs658kAHR_LAaILBXb-s6Q5")
# for song in songs:
# youtube.add_playlist_item('PLQwVIlKxHM6p6LRH_53M7tvRXaz0eVzpa', song['videoId'])
# songs = youtube.get_playlist_items("PLQwVIlKxHM6p6LRH_53M7tvRXaz0eVzpa")
# for song in songs:
# youtube.remove_playlist_item("PLQwVIlKxHM6p6LRH_53M7tvRXaz0eVzpa", song['removeAction'])
# id = youtube.add_playlist("test3", "test description", True)
# youtube.remove_playlist_item('PLQwVIlKxHM6rPU4UadJV7UZf9miJcK-hm', 'cilnCQMJudo')
# YTMusic.search('lione revive')
if __name__ == '__main__':
#end2end()
#search()
search()
#get_owned_playlist()
youtube_auth.get_liked_songs()

View file

@ -6,14 +6,23 @@ from ytmusicapi.helpers import parse_songs
params = '?alt=json&key=AIzaSyC9XL3ZjWddXya6X74dJoCTL-WEYFDNX30'
base_url = 'https://music.youtube.com/youtubei/v1/'
class YTMusic:
def __init__(self, auth=""):
"""
Create a new instance to interact with YouTube Music.
:param auth: Optional. Provide authentication credentials to manage your library.
Should be an adjusted version of `headers_auth.json.example` in the project root.
Default: A default header is used without authentication.
"""
self.auth = auth
file = auth if auth else pkg_resources.resource_filename('ytmusicapi', 'headers.json')
with open(file) as json_file:
self.headers = json.load(json_file)
with open(pkg_resources.resource_filename('ytmusicapi','context.json')) as json_file:
with open(pkg_resources.resource_filename('ytmusicapi', 'context.json')) as json_file:
self.body = json.load(json_file)
def __send_request(self, endpoint, additionalParams=""):
@ -25,6 +34,27 @@ class YTMusic:
raise Exception("Please provide authentication before using this function")
def search(self, query):
"""
Search for any song within YouTube music
:param query: Query string, i.e. 'Oasis Wonderwall'
:return: List of song results
Example list:
[
{
'videoId': 'ZrOKjDZOtkA',
'artist': 'Oasis',
'title': 'Wonderwall (Remastered)',
},
{
'videoId': 'Gvfgut8nAgw',
'artist': 'Oasis',
'title': 'Wonderwall',
}
]
"""
self.body['query'] = query
self.body['params'] = 'Eg-KAQwIARAAGAAgACgAMABqChAEEAMQCRAFEAo%3D'
endpoint = 'search'
@ -53,7 +83,16 @@ class YTMusic:
def get_playlists(self):
"""
Retrieves the content of the 'Library' page
:return: List of owned playlists
:return: List of owned playlists.
Each item is in the following format::
{
'playlistId': 'PLQwVIlKxHM6rz0fDJVv_0UlXGEWf-bFys',
'title': 'Playlist title'
}
"""
self.__check_auth()
self.body['browseId'] = 'FEmusic_liked_playlists'
@ -83,9 +122,23 @@ class YTMusic:
def get_playlist_items(self, playlistId, limit=1000):
"""
Returns a list of playlist items
:param playlistId: The playlist's id
:param playlistId: Playlist id
:param limit: How many songs to return. Default: 1000
:return: List of playlistItem dictionaries, containing { videoId, artist, title, setVideoId }
:return: List of playlistItem dictionaries
Each item is in the following format::
{
'videoId': 'PLQwVIlKxHM6rz0fDJVv_0UlXGEWf-bFys',
'artist': 'Artist',
'title': 'Song Title',
'setVideoId': '56B44F6D10557CC6'
}
The setVideoId is the unique id of this playlist item and
needed for moving/removing playlist items
"""
self.body['browseEndpointContextSupportedConfigs'] = {"browseEndpointContextMusicConfig": {"pageType": "MUSIC_PAGE_TYPE_PLAYLIST"}}
self.body['browseId'] = "VL" + playlistId
@ -117,6 +170,7 @@ class YTMusic:
def create_playlist(self, title, description, privacy_status="PRIVATE"):
"""
Creates a new empty playlist and returns its id.
:param title: Playlist title
:param description: Playlist description
:param privacy_status: Playlists can be 'PUBLIC', 'PRIVATE', or 'UNLISTED'. Default: 'PRIVATE'
@ -132,12 +186,13 @@ class YTMusic:
def edit_playlist(self, playlistId, title=None, description=None, privacyStatus=None):
"""
Edit title, description or privacyStatus of a playlist.
:param playlistId: Playlist ID
:param playlistId: Playlist id
:param title: Optional. New title for the playlist
:param description: Optional. New description for the playlist
:param privacyStatus: Optional. New privacy status for the playlist
:return: Request status
:return: Status String or full response
"""
self.__check_auth()
self.body['playlistId'] = playlistId
@ -157,6 +212,12 @@ class YTMusic:
return response['status'] if 'status' in response else response
def delete_playlist(self, playlistId):
"""
Delete a playlist.
:param playlistId: Playlist id
:return: Status String or full response
"""
self.__check_auth()
self.body['playlistId'] = playlistId
endpoint = 'playlist/delete'
@ -164,6 +225,13 @@ class YTMusic:
return response['status'] if 'status' in response else response
def add_playlist_item(self, playlistId, videoId):
"""
Add a song to an existing playlist
:param playlistId: Playlist id
:param videoId: Video id
:return: Status String or full response
"""
self.__check_auth()
self.body['playlistId'] = playlistId
self.body['actions'] = {'action': 'ACTION_ADD_VIDEO', 'addedVideoId': videoId}
@ -172,6 +240,13 @@ class YTMusic:
return response['status'] if 'status' in response else response
def remove_playlist_item(self, playlistId, song):
"""
Remove a song from an existing playlist
:param playlistId: Playlist id
:param song: Dictionary containing song information. Must contain videoId and setVideoId
:return: Status String or full response
"""
self.__check_auth()
if not song['setVideoId']:
print("Cannot remove this song, since you don't own this playlist.")
@ -181,4 +256,4 @@ class YTMusic:
self.body['actions'] = { 'setVideoId': song['setVideoId'], 'removedVideoId': song['videoId'], 'action': 'ACTION_REMOVE_VIDEO'}
endpoint = 'browse/edit_playlist'
response = self.__send_request(endpoint)
return response['status'] if 'status' in response else response
return response['status'] if 'status' in response else response