implement oauth authentication (#10)

This commit is contained in:
sigma67 2023-04-05 00:00:59 +02:00 • committed by sigma67
commit 0ee3b7fdb5
14 changed files with 280 additions and 123 deletions

View file

@ -19,11 +19,10 @@ jobs:
run: |
pip install -e .
pip install coverage
cd tests
curl -o test.mp3 https://www.kozco.com/tech/piano2-CoolEdit.mp3
cat <<< "$HEADERS_AUTH" > headers_auth.json
cat <<< "$TEST_CFG" > test.cfg
coverage run --source=../ytmusicapi -m unittest test.py
curl -o tests/test.mp3 https://www.kozco.com/tech/piano2-CoolEdit.mp3
cat <<< "$HEADERS_AUTH" > tests/headers_auth.json
cat <<< "$TEST_CFG" > tests/test.cfg
coverage run
coverage xml
- name: Upload coverage to Codecov
uses: codecov/codecov-action@v3

2
.gitignore vendored
View file

@ -1,6 +1,6 @@
.idea
.vscode
headers_auth.json
**.json
docs/build
**.cfg
**.mp3

View file

@ -38,4 +38,7 @@ include-package-data=false
[tool.yapf]
column_limit = 99
split_before_arithmetic_operator = true
split_before_arithmetic_operator = true
[tool.coverage.run]
command_line = "-m unittest discover tests"

View file

@ -1,41 +1,66 @@
import unittest
import unittest.mock
import json
import configparser
import time
import sys
import unittest
from pathlib import Path
from requests import Response
from unittest import mock
sys.path.insert(0, '..')
from ytmusicapi.setup import setup_oauth, setup # noqa: E402
from ytmusicapi.ytmusic import YTMusic # noqa: E402
def get_resource(file: str) -> str:
data_dir = Path(__file__).parent
return data_dir.joinpath(file).as_posix()
config = configparser.RawConfigParser()
config.read('./test.cfg', 'utf-8')
config.read(get_resource('test.cfg'), 'utf-8')
sample_album = "MPREb_4pL8gzRtw1p" # Eminem - Revival
sample_video = "hpSrLjc5SMs" # Oasis - Wonderwall
sample_playlist = "PL6bPxvf5dW5clc3y9wAoslzqUrmkZ5c-u" # very large playlist
headers_oauth = get_resource(config['auth']['headers_oauth'])
headers_browser = get_resource(config['auth']['headers_file'])
class TestYTMusic(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.yt = YTMusic(requests_session=False)
cls.yt_auth = YTMusic(config['auth']['headers_file'])
with YTMusic(requests_session=False) as yt:
pass
cls.yt = YTMusic()
cls.yt_oauth = YTMusic(headers_oauth)
cls.yt_auth = YTMusic(headers_browser)
cls.yt_brand = YTMusic(config['auth']['headers'], config['auth']['brand_account'])
cls.yt_empty = YTMusic(config['auth']['headers_empty'],
config['auth']['brand_account_empty'])
def test_init(self):
self.assertRaises(Exception, YTMusic, "{}")
def test_setup(self):
headers = YTMusic.setup(config['auth']['headers_file'], config['auth']['headers_raw'])
def test_setup_browser(self):
headers = setup(headers_browser, config['auth']['headers_raw'])
self.assertGreaterEqual(len(headers), 2)
headers_raw = config['auth']['headers_raw'].split('\n')
with unittest.mock.patch('builtins.input', side_effect=(headers_raw + [EOFError()])):
headers = YTMusic.setup(config['auth']['headers_file'])
with mock.patch('builtins.input', side_effect=(headers_raw + [EOFError()])):
headers = setup(headers_browser)
self.assertGreaterEqual(len(headers), 2)
# @unittest.skip("Cannot test oauth flow non-interactively")
@mock.patch('requests.Response.json')
@mock.patch('requests.Session.post')
def test_setup_oauth(self, session_mock, json_mock):
session_mock.return_value = Response()
json_mock.side_effect = [
json.loads(config['auth']['oauth_code']),
json.loads(config['auth']['oauth_token'])
]
with mock.patch('builtins.input', return_value='y'):
headers = setup_oauth(headers_oauth)
self.assertEqual(len(headers), 6)
self.assertTrue(Path(headers_oauth).exists())
###############
# BROWSING
###############
@ -50,8 +75,6 @@ class TestYTMusic(unittest.TestCase):
query = "edm playlist"
self.assertRaises(Exception, self.yt_auth.search, query, filter="song")
self.assertRaises(Exception, self.yt_auth.search, query, scope="upload")
results = self.yt.search("۳™LJĺӣՊ֬ãʸύЩЂקդӀâ")
self.assertEqual(len(results), 0)
queries = ["taylor swift", "taylor swift blank space", "taylor swift fearless"]
for q in queries:
with self.subTest():
@ -91,7 +114,7 @@ class TestYTMusic(unittest.TestCase):
self.assertGreater(len(results), 20)
def test_search_library(self):
results = self.yt_auth.search('garrix', scope='library')
results = self.yt_oauth.search('garrix', scope='library')
self.assertGreater(len(results), 5)
results = self.yt_auth.search('bergersen', filter='songs', scope='library', limit=40)
self.assertGreater(len(results), 10)
@ -244,7 +267,7 @@ class TestYTMusic(unittest.TestCase):
################
def test_get_library_playlists(self):
playlists = self.yt_auth.get_library_playlists(50)
playlists = self.yt_oauth.get_library_playlists(50)
self.assertGreater(len(playlists), 25)
playlists = self.yt_auth.get_library_playlists(None)
@ -255,7 +278,7 @@ class TestYTMusic(unittest.TestCase):
def test_get_library_songs(self):
self.assertRaises(Exception, self.yt_auth.get_library_songs, None, True)
songs = self.yt_auth.get_library_songs(100)
songs = self.yt_oauth.get_library_songs(100)
self.assertGreaterEqual(len(songs), 100)
songs = self.yt_auth.get_library_songs(200, validate_responses=True)
self.assertGreaterEqual(len(songs), config.getint('limits', 'library_songs'))
@ -265,7 +288,7 @@ class TestYTMusic(unittest.TestCase):
self.assertEqual(len(songs), 0)
def test_get_library_albums(self):
albums = self.yt_auth.get_library_albums(100)
albums = self.yt_oauth.get_library_albums(100)
self.assertGreater(len(albums), 50)
for album in albums:
self.assertIn('playlistId', album)
@ -281,7 +304,7 @@ class TestYTMusic(unittest.TestCase):
def test_get_library_artists(self):
artists = self.yt_auth.get_library_artists(50)
self.assertGreater(len(artists), 40)
artists = self.yt_brand.get_library_artists(order='a_to_z', limit=50)
artists = self.yt_oauth.get_library_artists(order='a_to_z', limit=50)
self.assertGreater(len(artists), 40)
artists = self.yt_brand.get_library_artists(limit=None)
self.assertGreater(len(artists), config.getint('limits', 'library_artists'))
@ -305,7 +328,7 @@ class TestYTMusic(unittest.TestCase):
self.assertEqual(songs['trackCount'], 0)
def test_get_history(self):
songs = self.yt_auth.get_history()
songs = self.yt_oauth.get_history()
self.assertGreater(len(songs), 0)
def test_manipulate_history_items(self):
@ -439,7 +462,7 @@ class TestYTMusic(unittest.TestCase):
def test_upload_song(self):
self.assertRaises(Exception, self.yt_auth.upload_song, 'song.wav')
response = self.yt_auth.upload_song(config['uploads']['file'])
response = self.yt_auth.upload_song(get_resource(config['uploads']['file']))
self.assertEqual(response.status_code, 409)
@unittest.skip("Do not delete uploads")

View file

@ -1,4 +1,5 @@
from ytmusicapi.ytmusic import YTMusic
from ytmusicapi.setup import setup, setup_oauth
from importlib.metadata import version, PackageNotFoundError
try:
@ -10,3 +11,4 @@ except PackageNotFoundError:
__copyright__ = 'Copyright 2022 sigma67'
__license__ = 'MIT'
__title__ = 'ytmusicapi'
__all__ = ["YTMusic", "setup_oauth", "setup"]

View file

View file

@ -0,0 +1,54 @@
import os
import platform
from ytmusicapi.helpers import *
path = os.path.dirname(os.path.realpath(__file__)) + os.sep
def setup_browser(filepath=None, headers_raw=None):
contents = []
if not headers_raw:
eof = "Ctrl-D" if platform.system() != "Windows" else "'Enter, Ctrl-Z, Enter'"
print("Please paste the request headers from Firefox and press " + eof + " to continue:")
while True:
try:
line = input()
except EOFError:
break
contents.append(line)
else:
contents = headers_raw.split('\n')
try:
user_headers = {}
for content in contents:
header = content.split(': ')
if len(header) == 1 or header[0].startswith(
":"): # nothing was split or chromium headers
continue
user_headers[header[0].lower()] = ': '.join(header[1:])
except Exception as e:
raise Exception("Error parsing your input, please try again. Full error: " + str(e))
missing_headers = {"cookie", "x-goog-authuser"} - set(k.lower() for k in user_headers.keys())
if missing_headers:
raise Exception(
"The following entries are missing in your headers: " + ", ".join(missing_headers)
+ ". Please try a different request (such as /browse) and make sure you are logged in."
)
ignore_headers = {"host", "content-length", "accept-encoding"}
for key in user_headers.copy().keys():
if key.startswith("sec") or key in ignore_headers:
user_headers.pop(key, None)
init_headers = initialize_headers()
user_headers.update(init_headers)
headers = user_headers
if filepath is not None:
with open(filepath, 'w') as file:
json.dump(headers, file, ensure_ascii=True, indent=4, sort_keys=True)
return json.dumps(headers)

View file

@ -0,0 +1,38 @@
import json
import os
from typing import Optional, Dict
import requests
from requests.structures import CaseInsensitiveDict
from ytmusicapi.auth.oauth import YTMusicOAuth
from ytmusicapi.helpers import initialize_headers
def prepare_headers(session: requests.Session,
proxies: Optional[Dict] = None,
auth: Optional[str] = None) -> Dict:
headers = {}
if auth:
try:
if os.path.isfile(auth):
with open(auth) as json_file:
input_json = json.load(json_file)
else:
input_json = json.loads(auth)
if "oauth.json" in auth:
oauth = YTMusicOAuth(session, proxies)
headers = oauth.load_headers(input_json, auth)
else:
headers = CaseInsensitiveDict(input_json)
except Exception as e:
print(
"Failed loading provided credentials. Make sure to provide a string or a file path. "
"Reason: " + str(e))
else: # no authentication
headers = initialize_headers()
return headers

71
ytmusicapi/auth/oauth.py Normal file
View file

@ -0,0 +1,71 @@
import time
from typing import Dict, Optional
import requests
import json
from ytmusicapi.constants import OAUTH_CLIENT_ID, OAUTH_CLIENT_SECRET, OAUTH_SCOPE, OAUTH_CODE_URL, OAUTH_TOKEN_URL, OAUTH_USER_AGENT
from ytmusicapi.helpers import initialize_headers
class YTMusicOAuth:
"""OAuth implementation for YouTube Music based on YouTube TV"""
def __init__(self, session: requests.Session, proxies: Dict = None):
self._session = session
if proxies:
self._session.proxies.update(proxies)
def _send_request(self, url, data) -> requests.Response:
data.update({"client_id": OAUTH_CLIENT_ID})
headers = {"User-Agent": OAUTH_USER_AGENT}
return self._session.post(url, data, headers=headers)
def get_code(self) -> Dict:
code_response = self._send_request(OAUTH_CODE_URL, data={"scope": OAUTH_SCOPE})
response_json = code_response.json()
url = f"{response_json['verification_url']}?user_code={response_json['user_code']}"
input(f"Go to {url}, finish the login flow and press Enter when done, Ctrl-C to abort")
return response_json
def get_token_from_code(self, device_code: str) -> Dict:
token_response = self._send_request(OAUTH_TOKEN_URL,
data={
"client_secret": OAUTH_CLIENT_SECRET,
"grant_type":
"http://oauth.net/grant_type/device/1.0",
"code": device_code
})
return token_response.json()
def refresh_token(self, refresh_token: str) -> Dict:
response = self._send_request(OAUTH_TOKEN_URL,
data={
"client_secret": OAUTH_CLIENT_SECRET,
"grant_type": "refresh_token",
"refresh_token": refresh_token
})
return response.json()
@staticmethod
def dump_token(token, filepath):
token["expires_at"] = int(time.time()) + int(token["expires_in"])
with open(filepath, encoding="utf8", mode="w") as file:
json.dump(token, file)
def setup(self, filepath: Optional[str] = None) -> Dict:
code = self.get_code()
token = self.get_token_from_code(code["device_code"])
if filepath:
self.dump_token(token, filepath)
return token
def load_headers(self, token: Dict, filepath: Optional[str] = None):
headers = initialize_headers()
if time.time() > token["expires_at"] - 3600:
token = self.refresh_token(token["refresh_token"])
self.dump_token(token, filepath)
headers["Authorization"] = f"{token['token_type']} {token['access_token']}"
headers["Content-Type"] = "application/json"
headers["X-Goog-Request-Time"] = str(int(time.time()))
return headers

View file

@ -1,4 +1,11 @@
YTM_DOMAIN = 'https://music.youtube.com'
YTM_BASE_API = YTM_DOMAIN + '/youtubei/v1/'
YTM_PARAMS = '?alt=json&key=AIzaSyC9XL3ZjWddXya6X74dJoCTL-WEYFDNX30'
YTM_PARAMS = '?alt=json'
YTM_PARAMS_KEY = "&key=AIzaSyC9XL3ZjWddXya6X74dJoCTL-WEYFDNX30"
USER_AGENT = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:88.0) Gecko/20100101 Firefox/88.0'
OAUTH_CLIENT_ID = "861556708454-d6dlm3lh05idd8npek18k6be8ba3oc68.apps.googleusercontent.com"
OAUTH_CLIENT_SECRET = "SboVhoG9s0rNafixCSGGKXAT"
OAUTH_SCOPE = "https://www.googleapis.com/auth/youtube"
OAUTH_CODE_URL = "https://www.youtube.com/o/oauth2/device/code"
OAUTH_TOKEN_URL = "https://oauth2.googleapis.com/token"
OAUTH_USER_AGENT = USER_AGENT + " Cobalt/Version"

View file

View file

View file

@ -1,54 +1,41 @@
import os
import platform
from ytmusicapi.helpers import *
from typing import Dict
path = os.path.dirname(os.path.realpath(__file__)) + os.sep
import requests
from ytmusicapi.auth.browser import setup_browser
from ytmusicapi.auth.oauth import YTMusicOAuth
def setup(filepath=None, headers_raw=None):
contents = []
if not headers_raw:
eof = "Ctrl-D" if platform.system() != "Windows" else "'Enter, Ctrl-Z, Enter'"
print("Please paste the request headers from Firefox and press " + eof + " to continue:")
while True:
try:
line = input()
except EOFError:
break
contents.append(line)
else:
contents = headers_raw.split('\n')
def setup(filepath: str = None, headers_raw: str = None) -> Dict:
"""
Requests browser headers from the user via command line
and returns a string that can be passed to YTMusic()
try:
user_headers = {}
for content in contents:
header = content.split(': ')
if len(header) == 1 or header[0].startswith(
":"): # nothing was split or chromium headers
continue
user_headers[header[0].lower()] = ': '.join(header[1:])
:param filepath: Optional filepath to store headers to.
:param headers_raw: Optional request headers copied from browser.
Otherwise requested from terminal
:return: configuration headers string
"""
return setup_browser(filepath, headers_raw)
except Exception as e:
raise Exception("Error parsing your input, please try again. Full error: " + str(e))
missing_headers = {"cookie", "x-goog-authuser"} - set(k.lower() for k in user_headers.keys())
if missing_headers:
raise Exception(
"The following entries are missing in your headers: " + ", ".join(missing_headers)
+ ". Please try a different request (such as /browse) and make sure you are logged in."
)
def setup_oauth(filepath: str = None,
session: requests.Session = None,
proxies: dict = None) -> Dict:
"""
Starts oauth flow from the terminal
and returns a string that can be passed to YTMusic()
ignore_headers = {"host", "content-length", "accept-encoding"}
for key in user_headers.copy().keys():
if key.startswith("sec") or key in ignore_headers:
user_headers.pop(key, None)
:param session: Session to use for authentication
:param proxies: Proxies to use for authentication
:param filepath: Optional filepath to store headers to.
:return: configuration headers string
"""
if not session:
session = requests.Session()
init_headers = initialize_headers()
user_headers.update(init_headers)
headers = user_headers
return YTMusicOAuth(session, proxies).setup(filepath)
if filepath is not None:
with open(filepath, 'w') as file:
json.dump(headers, file, ensure_ascii=True, indent=4, sort_keys=True)
return json.dumps(headers)
if __name__ == "__main__":
setup_oauth()

View file

@ -1,14 +1,13 @@
import requests
import gettext
import os
from requests.structures import CaseInsensitiveDict
from functools import partial
from contextlib import suppress
from typing import Dict
from ytmusicapi.auth.headers import prepare_headers
from ytmusicapi.parsers.i18n import Parser
from ytmusicapi.helpers import *
from ytmusicapi.setup import setup
from ytmusicapi.mixins.browsing import BrowsingMixin
from ytmusicapi.mixins.search import SearchMixin
from ytmusicapi.mixins.watch import WatchMixin
@ -37,7 +36,6 @@ class YTMusic(BrowsingMixin, SearchMixin, WatchMixin, ExploreMixin, LibraryMixin
:param auth: Optional. Provide a string or path to file.
Authentication credentials are needed to manage your library.
Should be an adjusted version of `headers_auth.json.example` in the project root.
See :py:func:`setup` for how to fill in the correct credentials.
Default: A default header is used without authentication.
:param user: Optional. Specify a user ID string to use in requests.
@ -79,23 +77,7 @@ class YTMusic(BrowsingMixin, SearchMixin, WatchMixin, ExploreMixin, LibraryMixin
self.proxies = proxies
self.cookies = {'CONSENT': 'YES+1'}
# prepare headers
if auth:
try:
if os.path.isfile(auth):
file = auth
with open(file) as json_file:
self.headers = CaseInsensitiveDict(json.load(json_file))
else:
self.headers = CaseInsensitiveDict(json.loads(auth))
except Exception as e:
print(
"Failed loading provided credentials. Make sure to provide a string or a file path. "
"Reason: " + str(e))
else: # no authentication
self.headers = initialize_headers()
self.headers = prepare_headers(self._session, proxies, auth)
if 'x-goog-visitor-id' not in self.headers:
self.headers.update(get_visitor_id(self._send_get_request))
@ -120,8 +102,9 @@ class YTMusic(BrowsingMixin, SearchMixin, WatchMixin, ExploreMixin, LibraryMixin
if user:
self.context['context']['user']['onBehalfOfUser'] = user
# verify authentication credentials work
if auth:
auth_header = self.headers.get("authorization")
self.is_browser_auth = auth_header and "SAPISIDHASH" in auth_header
if self.is_browser_auth:
try:
cookie = self.headers.get('cookie')
self.sapisid = sapisid_from_cookie(cookie)
@ -130,10 +113,13 @@ class YTMusic(BrowsingMixin, SearchMixin, WatchMixin, ExploreMixin, LibraryMixin
def _send_request(self, endpoint: str, body: Dict, additionalParams: str = "") -> Dict:
body.update(self.context)
if self.auth:
params = YTM_PARAMS
if self.is_browser_auth:
origin = self.headers.get('origin', self.headers.get('x-origin'))
self.headers["Authorization"] = get_authorization(self.sapisid + ' ' + origin)
response = self._session.post(YTM_BASE_API + endpoint + YTM_PARAMS + additionalParams,
self.headers["authorization"] = get_authorization(self.sapisid + ' ' + origin)
params += YTM_PARAMS_KEY
response = self._session.post(YTM_BASE_API + endpoint + params + additionalParams,
json=body,
headers=self.headers,
proxies=self.proxies,
@ -158,19 +144,6 @@ class YTMusic(BrowsingMixin, SearchMixin, WatchMixin, ExploreMixin, LibraryMixin
if not self.auth:
raise Exception("Please provide authentication before using this function")
@classmethod
def setup(cls, filepath: str = None, headers_raw: str = None) -> Dict:
"""
Requests browser headers from the user via command line
and returns a string that can be passed to YTMusic()
:param filepath: Optional filepath to store headers to.
:param headers_raw: Optional request headers copied from browser.
Otherwise requested from terminal
:return: configuration headers string
"""
return setup(filepath, headers_raw)
def __enter__(self):
return self