Compare commits

...

20 Commits

Author SHA1 Message Date
Cedric Nugteren
3a36416c86
Merge d893535d7b62439186353dad0da4fddb251a6a69 into 2b4fbfce25902d557b86b003cf48f738129efce4 2025-03-26 08:12:19 +00:00
dirkf
2b4fbfce25 [YouTube] Support player 4fcd6e4a
thx seproDev, bashonly: yt-dlp/yt-dlp#12748
2025-03-26 02:27:25 +00:00
dirkf
1bc45b8b6c [JSInterp] Use , for join() with null/undefined argument
Eg: [1,2,3].join(null) -> '1,2,3'
2025-03-25 22:35:06 +00:00
dirkf
b982d77d0b [YouTube] Align signature tests with yt-dlp
thx bashonly, yt-dlp/yt-dlp#12725
2025-03-25 22:35:06 +00:00
dirkf
c55dbf4838 [YouTube] Update signature extraction for players 643afba4, 363db69b 2025-03-25 22:35:06 +00:00
dirkf
087d865230 [YouTube] Support new player URL patterns 2025-03-25 22:35:06 +00:00
dirkf
a4fc1151f1 [JSInterp] Improve indexing
* catch invalid list index with `ValueError` (eg [1, 2]['ab'] -> undefined)
* allow assignment outside existing list (eg var l = [1,2]; l[9] = 0;)
2025-03-25 22:35:05 +00:00
dirkf
a464c159e6 [YouTube] Make _extract_player_info() use _search_regex() 2025-03-25 22:35:05 +00:00
dirkf
7dca08eff0 [YouTube] Also get original of translated automatic captions 2025-03-25 22:35:05 +00:00
dirkf
2239ee7965 [YouTube] Get subtitles/automatic captions from both web and API responses 2025-03-25 22:35:05 +00:00
Cedric Nugteren
d893535d7b Merge branch 'master' into fixes_for_vier_extractor 2022-03-29 21:20:16 +02:00
Cedric Nugteren
7a489eaa6d Apply improvements as suggested by 'pateik' 2022-03-29 21:17:11 +02:00
Cedric Nugteren
9a14872ffd
Update youtube_dl/extractor/vier.py
Co-authored-by: Jeroen Jacobs <github.com@jeroenj.be>
2021-05-01 14:25:01 +02:00
Cedric Nugteren
95e0844f0c Merge branch 'master' into fixes_for_vier_extractor 2021-02-06 13:27:46 +01:00
Cedric Nugteren
5f15109dff
Update youtube_dl/extractor/vier.py
Co-authored-by: Jeroen Jacobs <github.com@jeroenj.be>
2021-02-06 13:24:22 +01:00
Cedric Nugteren
56251c4d2e
Update youtube_dl/extractor/vier.py
Co-authored-by: Jeroen Jacobs <github.com@jeroenj.be>
2021-02-06 13:24:14 +01:00
Cedric Nugteren
62798011e3 Attempt to fix failing test #2 2021-01-15 12:02:34 +01:00
Cedric Nugteren
6aa0183a43 Attempt to fix failing test 2021-01-15 11:57:44 +01:00
Cedric Nugteren
96d2ecc584 Fix issue in case of a single season/episode 2021-01-15 11:57:28 +01:00
Cedric Nugteren
dc96ac5f09 [VierVijfKijkOnline] Fix extractor 2021-01-14 14:33:41 +01:00
6 changed files with 530 additions and 58 deletions

View File

@ -84,6 +84,21 @@ _SIG_TESTS = [
'2aq0aqSyOoJXtK73m-uME_jv7-pT15gOFC02RFkGMqWpzEICs69VdbwQ0LDp1v7j8xx92efCJlYFYb1sUkkBSPOlPmXgIARw8JQ0qOAOAA',
'0QJ8wRAIgXmPlOPSBkkUs1bYFYlJCfe29xxAj7v1pDL0QwbdV96sCIEzpWqMGkFR20CFOg51Tp-7vj_EMu-m37KtXJ2OySqa0q',
),
(
'https://www.youtube.com/s/player/643afba4/tv-player-ias.vflset/tv-player-ias.js',
'2aq0aqSyOoJXtK73m-uME_jv7-pT15gOFC02RFkGMqWpzEICs69VdbwQ0LDp1v7j8xx92efCJlYFYb1sUkkBSPOlPmXgIARw8JQ0qOAOAA',
'AAOAOq0QJ8wRAIgXmPlOPSBkkUs1bYFYlJCfe29xx8j7vgpDL0QwbdV06sCIEzpWqMGkFR20CFOS21Tp-7vj_EMu-m37KtXJoOy1',
),
(
'https://www.youtube.com/s/player/363db69b/player_ias.vflset/en_US/base.js',
'2aq0aqSyOoJXtK73m-uME_jv7-pT15gOFC02RFkGMqWpzEICs69VdbwQ0LDp1v7j8xx92efCJlYFYb1sUkkBSPOlPmXgIARw8JQ0qOAOAA',
'0aqSyOoJXtK73m-uME_jv7-pT15gOFC02RFkGMqWpz2ICs6EVdbwQ0LDp1v7j8xx92efCJlYFYb1sUkkBSPOlPmXgIARw8JQ0qOAOAA',
),
(
'https://www.youtube.com/s/player/4fcd6e4a/player_ias.vflset/en_US/base.js',
'2aq0aqSyOoJXtK73m-uME_jv7-pT15gOFC02RFkGMqWpzEICs69VdbwQ0LDp1v7j8xx92efCJlYFYb1sUkkBSPOlPmXgIARw8JQ0qOAOAA',
'wAOAOq0QJ8ARAIgXmPlOPSBkkUs1bYFYlJCfe29xx8q7v1pDL0QwbdV96sCIEzpWqMGkFR20CFOg51Tp-7vj_EMu-m37KtXJoOySqa0',
),
]
_NSIG_TESTS = [
@ -153,7 +168,7 @@ _NSIG_TESTS = [
),
(
'https://www.youtube.com/s/player/c57c113c/player_ias.vflset/en_US/base.js',
'-Txvy6bT5R6LqgnQNx', 'dcklJCnRUHbgSg',
'M92UUMHa8PdvPd3wyM', '3hPqLJsiNZx7yA',
),
(
'https://www.youtube.com/s/player/5a3b6271/player_ias.vflset/en_US/base.js',
@ -173,7 +188,7 @@ _NSIG_TESTS = [
),
(
'https://www.youtube.com/s/player/cfa9e7cb/player_ias.vflset/en_US/base.js',
'qO0NiMtYQ7TeJnfFG2', 'k9cuJDHNS5O7kQ',
'aCi3iElgd2kq0bxVbQ', 'QX1y8jGb2IbZ0w',
),
(
'https://www.youtube.com/s/player/8c7583ff/player_ias.vflset/en_US/base.js',
@ -231,10 +246,6 @@ _NSIG_TESTS = [
'https://www.youtube.com/s/player/f6e09c70/player_ias_tce.vflset/en_US/base.js',
'W9HJZKktxuYoDTqW', 'jHbbkcaxm54',
),
(
'https://www.youtube.com/s/player/643afba4/player_ias.vflset/en_US/base.js',
'W9HJZKktxuYoDTqW', 'larxUlagTRAcSw',
),
(
'https://www.youtube.com/s/player/e7567ecf/player_ias_tce.vflset/en_US/base.js',
'Sy4aDGc0VpYRR9ew_', '5UPOT1VhoZxNLQ',
@ -259,6 +270,22 @@ _NSIG_TESTS = [
'https://www.youtube.com/s/player/643afba4/tv-player-ias.vflset/tv-player-ias.js',
'ir9-V6cdbCiyKxhr', '2PL7ZDYAALMfmA',
),
(
'https://www.youtube.com/s/player/643afba4/player_ias.vflset/en_US/base.js',
'W9HJZKktxuYoDTqW', 'larxUlagTRAcSw',
),
(
'https://www.youtube.com/s/player/363db69b/player_ias.vflset/en_US/base.js',
'eWYu5d5YeY_4LyEDc', 'XJQqf-N7Xra3gg',
),
(
'https://www.youtube.com/s/player/4fcd6e4a/player_ias.vflset/en_US/base.js',
'o_L251jm8yhZkWtBW', 'lXoxI3XvToqn6A',
),
(
'https://www.youtube.com/s/player/4fcd6e4a/tv-player-ias.vflset/tv-player-ias.js',
'o_L251jm8yhZkWtBW', 'lXoxI3XvToqn6A',
),
]
@ -271,6 +298,8 @@ class TestPlayerInfo(unittest.TestCase):
('https://www.youtube.com/s/player/64dddad9/player-plasma-ias-phone-en_US.vflset/base.js', '64dddad9'),
('https://www.youtube.com/s/player/64dddad9/player-plasma-ias-phone-de_DE.vflset/base.js', '64dddad9'),
('https://www.youtube.com/s/player/64dddad9/player-plasma-ias-tablet-en_US.vflset/base.js', '64dddad9'),
('https://www.youtube.com/s/player/e7567ecf/player_ias_tce.vflset/en_US/base.js', 'e7567ecf'),
('https://www.youtube.com/s/player/643afba4/tv-player-ias.vflset/tv-player-ias.js', '643afba4'),
# obsolete
('https://www.youtube.com/yts/jsbin/player_ias-vfle4-e03/en_US/base.js', 'vfle4-e03'),
('https://www.youtube.com/yts/jsbin/player_ias-vfl49f_g4/en_US/base.js', 'vfl49f_g4'),
@ -280,8 +309,9 @@ class TestPlayerInfo(unittest.TestCase):
('https://s.ytimg.com/yts/jsbin/html5player-en_US-vflXGBaUN.js', 'vflXGBaUN'),
('https://s.ytimg.com/yts/jsbin/html5player-en_US-vflKjOTVq/html5player.js', 'vflKjOTVq'),
)
ie = YoutubeIE(FakeYDL({'cachedir': False}))
for player_url, expected_player_id in PLAYER_URLS:
player_id = YoutubeIE._extract_player_info(player_url)
player_id = ie._extract_player_info(player_url)
self.assertEqual(player_id, expected_player_id)
@ -301,8 +331,8 @@ class TestSignature(unittest.TestCase):
def t_factory(name, sig_func, url_pattern):
def make_tfunc(url, sig_input, expected_sig):
m = url_pattern.match(url)
assert m, '%r should follow URL format' % url
test_id = m.group('id')
assert m, '{0!r} should follow URL format'.format(url)
test_id = re.sub(r'[/.-]', '_', m.group('id') or m.group('compat_id'))
def test_func(self):
basename = 'player-{0}-{1}.js'.format(name, test_id)
@ -335,12 +365,16 @@ def n_sig(jscode, sig_input):
make_sig_test = t_factory(
'signature', signature, re.compile(r'.*(?:-|/player/)(?P<id>[a-zA-Z0-9_-]+)(?:/.+\.js|(?:/watch_as3|/html5player)?\.[a-z]+)$'))
'signature', signature,
re.compile(r'''(?x)
.+/(?P<h5>html5)?player(?(h5)(?:-en_US)?-|/)(?P<id>[a-zA-Z0-9/._-]+)
(?(h5)/(?:watch_as3|html5player))?\.js$
'''))
for test_spec in _SIG_TESTS:
make_sig_test(*test_spec)
make_nsig_test = t_factory(
'nsig', n_sig, re.compile(r'.+/player/(?P<id>[a-zA-Z0-9_-]+)/.+.js$'))
'nsig', n_sig, re.compile(r'.+/player/(?P<id>[a-zA-Z0-9_/.-]+)\.js$'))
for test_spec in _NSIG_TESTS:
make_nsig_test(*test_spec)

View File

@ -1482,7 +1482,7 @@ from .vidme import (
VidmeUserIE,
VidmeUserLikesIE,
)
from .vier import VierIE, VierVideosIE
from .vier import VierIE, VierVideosIE, VierVijfKijkOnlineIE
from .viewlift import (
ViewLiftIE,
ViewLiftEmbedIE,

View File

@ -2,8 +2,10 @@
from __future__ import unicode_literals
import re
import json
import itertools
from .vier_auth_aws import AwsIdp
from .common import InfoExtractor
from ..utils import (
urlencode_postdata,
@ -12,16 +14,116 @@ from ..utils import (
)
class VierVijfKijkOnlineIE(InfoExtractor):
IE_NAME = 'viervijfkijkonline'
IE_DESC = 'vier.be and vijf.be - Kijk Online'
_VALID_URL = r'https?://(?:www\.)?(?P<site>vier|vijf|goplay)\.be/video/(?P<series>(?!v3)[^/]+)/(?P<season>[^/]+)(/(?P<episode>[^/]+)|)'
_NETRC_MACHINE = 'vier'
_TESTS = [{
'url': 'https://www.vier.be/video/hotel-romantiek/2017/hotel-romantiek-aflevering-1',
'info_dict': {
'id': 'ebcd3c39-10a2-4730-b137-b0e7aaed247c',
'ext': 'mp4',
'title': 'Hotel Römantiek - Seizoen 1 - Aflevering 1',
'series': 'Hotel Römantiek',
'season_number': 1,
'episode_number': 1,
},
'skip': 'This video is only available for registered users'
}, {
'url': 'https://www.vier.be/video/blockbusters/in-juli-en-augustus-summer-classics',
'only_matching': True,
}, {
'url': 'https://www.vier.be/video/achter-de-rug/2017/achter-de-rug-seizoen-1-aflevering-6',
'only_matching': True,
}]
def _real_initialize(self):
self._logged_in = False
self.id_token = ''
def _login(self):
username, password = self._get_login_info()
if username is None or password is None:
self.raise_login_required()
aws = AwsIdp(pool_id='eu-west-1_dViSsKM5Y', client_id='6s1h851s8uplco5h6mqh1jac8m')
self.id_token, _ = aws.authenticate(username=username, password=password)
self._logged_in = True
def _real_extract(self, url):
if "#" in url:
url = url.split("#")[0]
if not self._logged_in:
self._login()
webpage = self._download_webpage(url, None)
title = self._html_search_regex(
r'<meta\s*property="og:title"\s*content="(.+?)"\s*/>',
webpage, 'title')
title_split = title.split(' - ')
series = title_split[0].strip()
if len(title_split) == 3:
if 'Seizoen' in title_split[1]:
season = title_split[1].split('Seizoen')[1].strip()
else:
season = title_split[1].strip()
episode = title_split[2].split('Aflevering')[1].strip()
elif len(title_split) == 1:
season = None
episode = None
else:
season = None
episode = title_split[1].split('Aflevering')[1].strip()
video_data = self._html_search_regex(
r'<div data-hero="([^"]*)"',
webpage, 'video_data')
playlists = json.loads(video_data.replace('&quot;', '"'))['data']['playlists']
wanted_playlist = [x for x in playlists if x['pageInfo']['url'] in url][0]
wanted_episode = [x for x in wanted_playlist['episodes'] if x['pageInfo']['url'] == url][0] or [x for x in wanted_playlist['episodes'] if x['pageInfo']['url'] in url][0]
video_id = wanted_episode['videoUuid']
api_url = 'https://api.viervijfzes.be/content/%s' % (video_id)
api_headers = {
'authorization': self.id_token,
}
api = self._download_json(
api_url,
None, note='Peforming API Call', errnote='API Call Failed',
headers=api_headers,
)
formats = []
formats.extend(self._extract_m3u8_formats(
api['video']['S'], video_id, 'mp4', entry_protocol='m3u8_native',
m3u8_id='HLS', fatal=False))
self._sort_formats(formats)
return {
'id': video_id,
'title': title,
'series': series,
'season_number': int_or_none(season),
'episode_number': int_or_none(episode),
'formats': formats,
}
class VierIE(InfoExtractor):
IE_NAME = 'vier'
IE_DESC = 'vier.be and vijf.be'
_VALID_URL = r'''(?x)
https?://
(?:www\.)?(?P<site>vier|vijf)\.be/
(?:www\.)?(?P<site>vier|vijf|goplay)\.be/
(?:
(?:
[^/]+/videos|
video(?:/[^/]+)*
[^/]+/videos
)/
(?P<display_id>[^/]+)(?:/(?P<id>\d+))?|
(?:
@ -100,12 +202,6 @@ class VierIE(InfoExtractor):
}, {
'url': 'https://www.vijf.be/embed/video/public/4093',
'only_matching': True,
}, {
'url': 'https://www.vier.be/video/blockbusters/in-juli-en-augustus-summer-classics',
'only_matching': True,
}, {
'url': 'https://www.vier.be/video/achter-de-rug/2017/achter-de-rug-seizoen-1-aflevering-6',
'only_matching': True,
}]
def _real_initialize(self):

View File

@ -0,0 +1,320 @@
# coding: utf-8
from __future__ import absolute_import, division, unicode_literals
# Taken from https://github.com/add-ons/plugin.video.viervijfzes/blob/master/resources/lib/viervijfzes/auth_awsidp.py
# with some small modifications (replacement of six and requests, removal of unused function, reformatting)
# This file is licensed as GPL-3 from https://github.com/add-ons/plugin.video.viervijfzes:
# https://github.com/add-ons/plugin.video.viervijfzes/blob/master/LICENSE
# Amazon Cognito implementation without external dependencies
# Based on https://github.com/retrospect-addon/plugin.video.retrospect/blob/master/channels/channel.be/vier/awsidp.py
import base64
import binascii
import datetime
import hashlib
import hmac
import json
import os
from ..compat import compat_basestring, compat_urllib_request
class InvalidLoginException(Exception):
""" The login credentials are invalid """
class AuthenticationException(Exception):
""" Something went wrong while logging in """
class AwsIdp:
""" AWS Identity Provider """
def __init__(self, pool_id, client_id):
"""
:param str pool_id: The AWS user pool to connect to (format: <region>_<poolid>).
E.g.: eu-west-1_aLkOfYN3T
:param str client_id: The client application ID (the ID of the application connecting)
"""
self.pool_id = pool_id
if "_" not in self.pool_id:
raise ValueError("Invalid pool_id format. Should be <region>_<poolid>.")
self.client_id = client_id
self.region = self.pool_id.split("_")[0]
self.url = "https://cognito-idp.%s.amazonaws.com/" % (self.region,)
# Initialize the values
# https://github.com/aws/amazon-cognito-identity-js/blob/master/src/AuthenticationHelper.js#L22
self.n_hex = 'FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD1' + \
'29024E088A67CC74020BBEA63B139B22514A08798E3404DD' + \
'EF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245' + \
'E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7ED' + \
'EE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3D' + \
'C2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F' + \
'83655D23DCA3AD961C62F356208552BB9ED529077096966D' + \
'670C354E4ABC9804F1746C08CA18217C32905E462E36CE3B' + \
'E39E772C180E86039B2783A2EC07A28FB5C55DF06F4C52C9' + \
'DE2BCBF6955817183995497CEA956AE515D2261898FA0510' + \
'15728E5A8AAAC42DAD33170D04507A33A85521ABDF1CBA64' + \
'ECFB850458DBEF0A8AEA71575D060C7DB3970F85A6E1E4C7' + \
'ABF5AE8CDB0933D71E8C94E04A25619DCEE3D2261AD2EE6B' + \
'F12FFA06D98A0864D87602733EC86A64521F2B18177B200C' + \
'BBE117577A615D6C770988C0BAD946E208E24FA074E5AB31' + \
'43DB5BFCE0FD108E4B82D120A93AD2CAFFFFFFFFFFFFFFFF'
# https://github.com/aws/amazon-cognito-identity-js/blob/master/src/AuthenticationHelper.js#L49
self.g_hex = '2'
self.info_bits = bytearray('Caldera Derived Key', 'utf-8')
self.big_n = self.__hex_to_long(self.n_hex)
self.g = self.__hex_to_long(self.g_hex) # pylint: disable=invalid-name
self.k = self.__hex_to_long(self.__hex_hash('00' + self.n_hex + '0' + self.g_hex)) # pylint: disable=invalid-name
self.small_a_value = self.__generate_random_small_a()
self.large_a_value = self.__calculate_a()
def authenticate(self, username, password):
""" Authenticate with a username and password. """
# Step 1: First initiate an authentication request
auth_data_dict = self.__get_authentication_request(username)
auth_data = json.dumps(auth_data_dict).encode("utf-8")
auth_headers = {
"X-Amz-Target": "AWSCognitoIdentityProviderService.InitiateAuth",
"Accept-Encoding": "identity",
"Content-Type": "application/x-amz-json-1.1"
}
auth_request = compat_urllib_request.Request(url=self.url, data=auth_data, headers=auth_headers)
auth_response = compat_urllib_request.urlopen(auth_request).read()
auth_response_json = json.loads(auth_response.decode("utf-8"))
challenge_parameters = auth_response_json.get("ChallengeParameters")
challenge_name = auth_response_json.get("ChallengeName")
if not challenge_name == "PASSWORD_VERIFIER":
raise AuthenticationException(auth_response_json.get("message"))
# Step 2: Respond to the Challenge with a valid ChallengeResponse
challenge_request = self.__get_challenge_response_request(challenge_parameters, password)
challenge_data = json.dumps(challenge_request).encode("utf-8")
challenge_headers = {
"X-Amz-Target": "AWSCognitoIdentityProviderService.RespondToAuthChallenge",
"Content-Type": "application/x-amz-json-1.1"
}
auth_request = compat_urllib_request.Request(url=self.url, data=challenge_data, headers=challenge_headers)
auth_response = compat_urllib_request.urlopen(auth_request).read()
auth_response_json = json.loads(auth_response.decode("utf-8"))
if "message" in auth_response_json:
raise InvalidLoginException(auth_response_json.get("message"))
id_token = auth_response_json.get("AuthenticationResult", {}).get("IdToken")
refresh_token = auth_response_json.get("AuthenticationResult", {}).get("RefreshToken")
return id_token, refresh_token
def __get_authentication_request(self, username):
"""
:param str username: The username to use
:return: A full Authorization request.
:rtype: dict
"""
auth_request = {
"AuthParameters": {
"USERNAME": username,
"SRP_A": self.__long_to_hex(self.large_a_value)
},
"AuthFlow": "USER_SRP_AUTH",
"ClientId": self.client_id
}
return auth_request
def __get_challenge_response_request(self, challenge_parameters, password):
""" Create a Challenge Response Request object.
:param dict[str,str|imt] challenge_parameters: The parameters for the challenge.
:param str password: The password.
:return: A valid and full request data object to use as a response for a challenge.
:rtype: dict
"""
user_id = challenge_parameters["USERNAME"]
user_id_for_srp = challenge_parameters["USER_ID_FOR_SRP"]
srp_b = challenge_parameters["SRP_B"]
salt = challenge_parameters["SALT"]
secret_block = challenge_parameters["SECRET_BLOCK"]
timestamp = self.__get_current_timestamp()
# Get a HKDF key for the password, SrpB and the Salt
hkdf = self.__get_hkdf_key_for_password(
user_id_for_srp,
password,
self.__hex_to_long(srp_b),
salt
)
secret_block_bytes = base64.standard_b64decode(secret_block)
# the message is a combo of the pool_id, provided SRP userId, the Secret and Timestamp
msg = \
bytearray(self.pool_id.split('_')[1], 'utf-8') + \
bytearray(user_id_for_srp, 'utf-8') + \
bytearray(secret_block_bytes) + \
bytearray(timestamp, 'utf-8')
hmac_obj = hmac.new(hkdf, msg, digestmod=hashlib.sha256)
signature_string = base64.standard_b64encode(hmac_obj.digest()).decode('utf-8')
challenge_request = {
"ChallengeResponses": {
"USERNAME": user_id,
"TIMESTAMP": timestamp,
"PASSWORD_CLAIM_SECRET_BLOCK": secret_block,
"PASSWORD_CLAIM_SIGNATURE": signature_string
},
"ChallengeName": "PASSWORD_VERIFIER",
"ClientId": self.client_id
}
return challenge_request
def __get_hkdf_key_for_password(self, username, password, server_b_value, salt):
""" Calculates the final hkdf based on computed S value, and computed U value and the key.
:param str username: Username.
:param str password: Password.
:param int server_b_value: Server B value.
:param int salt: Generated salt.
:return Computed HKDF value.
:rtype: object
"""
u_value = self.__calculate_u(self.large_a_value, server_b_value)
if u_value == 0:
raise ValueError('U cannot be zero.')
username_password = '%s%s:%s' % (self.pool_id.split('_')[1], username, password)
username_password_hash = self.__hash_sha256(username_password.encode('utf-8'))
x_value = self.__hex_to_long(self.__hex_hash(self.__pad_hex(salt) + username_password_hash))
g_mod_pow_xn = pow(self.g, x_value, self.big_n)
int_value2 = server_b_value - self.k * g_mod_pow_xn
s_value = pow(int_value2, self.small_a_value + u_value * x_value, self.big_n)
hkdf = self.__compute_hkdf(
bytearray.fromhex(self.__pad_hex(s_value)),
bytearray.fromhex(self.__pad_hex(self.__long_to_hex(u_value)))
)
return hkdf
def __compute_hkdf(self, ikm, salt):
""" Standard hkdf algorithm
:param {Buffer} ikm Input key material.
:param {Buffer} salt Salt value.
:return {Buffer} Strong key material.
"""
prk = hmac.new(salt, ikm, hashlib.sha256).digest()
info_bits_update = self.info_bits + bytearray(chr(1), 'utf-8')
hmac_hash = hmac.new(prk, info_bits_update, hashlib.sha256).digest()
return hmac_hash[:16]
def __calculate_u(self, big_a, big_b):
""" Calculate the client's value U which is the hash of A and B
:param int big_a: Large A value.
:param int big_b: Server B value.
:return Computed U value.
:rtype: int
"""
u_hex_hash = self.__hex_hash(self.__pad_hex(big_a) + self.__pad_hex(big_b))
return self.__hex_to_long(u_hex_hash)
def __generate_random_small_a(self):
""" Helper function to generate a random big integer
:return a random value.
:rtype: int
"""
random_long_int = self.__get_random(128)
return random_long_int % self.big_n
def __calculate_a(self):
""" Calculate the client's public value A = g^a%N with the generated random number a
:return Computed large A.
:rtype: int
"""
big_a = pow(self.g, self.small_a_value, self.big_n)
# safety check
if (big_a % self.big_n) == 0:
raise ValueError('Safety check for A failed')
return big_a
@staticmethod
def __long_to_hex(long_num):
return '%x' % long_num
@staticmethod
def __hex_to_long(hex_string):
return int(hex_string, 16)
@staticmethod
def __hex_hash(hex_string):
return AwsIdp.__hash_sha256(bytearray.fromhex(hex_string))
@staticmethod
def __hash_sha256(buf):
"""AuthenticationHelper.hash"""
digest = hashlib.sha256(buf).hexdigest()
return (64 - len(digest)) * '0' + digest
@staticmethod
def __pad_hex(long_int):
""" Converts a Long integer (or hex string) to hex format padded with zeroes for hashing
:param int|str long_int: Number or string to pad.
:return Padded hex string.
:rtype: str
"""
# noinspection PyTypeChecker
if not isinstance(long_int, compat_basestring):
hash_str = AwsIdp.__long_to_hex(long_int)
else:
hash_str = long_int
if len(hash_str) % 2 == 1:
hash_str = '0%s' % hash_str
elif hash_str[0] in '89ABCDEFabcdef':
hash_str = '00%s' % hash_str
return hash_str
@staticmethod
def __get_random(nbytes):
random_hex = binascii.hexlify(os.urandom(nbytes))
return AwsIdp.__hex_to_long(random_hex)
@staticmethod
def __get_current_timestamp():
""" Creates a timestamp with the correct English format.
:return: timestamp in format 'Sun Jan 27 19:00:04 UTC 2019'
:rtype: str
"""
# We need US only data, so we cannot just do a strftime:
# Sun Jan 27 19:00:04 UTC 2019
months = [None, 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
days = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
time_now = datetime.datetime.utcnow()
format_string = "{} {} {} %H:%M:%S UTC %Y".format(days[time_now.weekday()], months[time_now.month], time_now.day)
time_string = datetime.datetime.utcnow().strftime(format_string)
return time_string
def __str__(self):
return "AWS IDP Client for:\nRegion: %s\nPoolId: %s\nAppId: %s" % (
self.region, self.pool_id.split("_")[1], self.client_id
)

View File

@ -692,9 +692,9 @@ class YoutubeIE(YoutubeBaseInfoExtractor):
'invidious': '|'.join(_INVIDIOUS_SITES),
}
_PLAYER_INFO_RE = (
r'/s/player/(?P<id>[a-zA-Z0-9_-]{8,})//(?:tv-)?player',
r'/(?P<id>[a-zA-Z0-9_-]{8,})/player(?:_ias\.vflset(?:/[a-zA-Z]{2,3}_[a-zA-Z]{2,3})?|-plasma-ias-(?:phone|tablet)-[a-z]{2}_[A-Z]{2}\.vflset)/base\.js$',
r'\b(?P<id>vfl[a-zA-Z0-9_-]+)\b.*?\.js$',
r'/s/player/(?P<id>[a-zA-Z0-9_-]{8,})/(?:tv-)?player',
r'/(?P<id>[a-zA-Z0-9_-]{8,})/player(?:_ias(?:_tce)?\.vflset(?:/[a-zA-Z]{2,3}_[a-zA-Z]{2,3})?|-plasma-ias-(?:phone|tablet)-[a-z]{2}_[A-Z]{2}\.vflset)/base\.js$',
r'\b(?P<id>vfl[a-zA-Z0-9_-]{6,})\b.*?\.js$',
)
_SUBTITLE_FORMATS = ('json3', 'srv1', 'srv2', 'srv3', 'ttml', 'vtt')
@ -1626,15 +1626,13 @@ class YoutubeIE(YoutubeBaseInfoExtractor):
""" Return a string representation of a signature """
return '.'.join(compat_str(len(part)) for part in example_sig.split('.'))
@classmethod
def _extract_player_info(cls, player_url):
for player_re in cls._PLAYER_INFO_RE:
id_m = re.search(player_re, player_url)
if id_m:
break
else:
raise ExtractorError('Cannot identify player %r' % player_url)
return id_m.group('id')
def _extract_player_info(self, player_url):
try:
return self._search_regex(
self._PLAYER_INFO_RE, player_url, 'player info', group='id')
except ExtractorError as e:
raise ExtractorError(
'Cannot identify player %r' % (player_url,), cause=e)
def _load_player(self, video_id, player_url, fatal=True, player_id=None):
if not player_id:
@ -1711,6 +1709,23 @@ class YoutubeIE(YoutubeBaseInfoExtractor):
' return %s\n') % (signature_id_tuple, expr_code)
self.to_screen('Extracted signature function:\n' + code)
def _extract_sig_fn(self, jsi, funcname):
var_ay = self._search_regex(
r'''(?x)
(?:\*/|\{|\n|^)\s*(?:'[^']+'\s*;\s*)
(var\s*[\w$]+\s*=\s*(?:
('|")(?:\\\2|(?!\2).)+\2\s*\.\s*split\(\s*('|")\W+\3\s*\)|
\[\s*(?:('|")(?:\\\4|(?!\4).)*\4\s*(?:(?=\])|,\s*))+\]
))(?=\s*[,;])
''', jsi.code, 'useful values', default='')
sig_fn = jsi.extract_function_code(funcname)
if var_ay:
sig_fn = (sig_fn[0], ';\n'.join((var_ay, sig_fn[1])))
return sig_fn
def _parse_sig_js(self, jscode):
# Examples where `sig` is funcname:
# sig=function(a){a=a.split(""); ... ;return a.join("")};
@ -1736,8 +1751,12 @@ class YoutubeIE(YoutubeBaseInfoExtractor):
jscode, 'Initial JS player signature function name', group='sig')
jsi = JSInterpreter(jscode)
initial_function = jsi.extract_function(funcname)
return lambda s: initial_function([s])
initial_function = self._extract_sig_fn(jsi, funcname)
func = jsi.extract_function_from_code(*initial_function)
return lambda s: func([s])
def _cached(self, func, *cache_id):
def inner(*args, **kwargs):
@ -1856,15 +1875,9 @@ class YoutubeIE(YoutubeBaseInfoExtractor):
def _extract_n_function_code_jsi(self, video_id, jsi, player_id=None):
var_ay = self._search_regex(
r'(?:[;\s]|^)\s*(var\s*[\w$]+\s*=\s*"(?:\\"|[^"])+"\s*\.\s*split\("\W+"\))(?=\s*[,;])',
jsi.code, 'useful values', default='')
func_name = self._extract_n_function_name(jsi.code)
func_code = jsi.extract_function_code(func_name)
if var_ay:
func_code = (func_code[0], ';\n'.join((var_ay, func_code[1])))
func_code = self._extract_sig_fn(jsi, func_name)
if player_id:
self.cache.store('youtube-nsig', player_id, func_code)
@ -2136,7 +2149,8 @@ class YoutubeIE(YoutubeBaseInfoExtractor):
video_details = merge_dicts(*traverse_obj(
(player_response, api_player_response),
(Ellipsis, 'videoDetails', T(dict))))
player_response.update(api_player_response or {})
player_response.update(filter_dict(
api_player_response or {}, cndn=lambda k, _: k != 'captions'))
player_response['videoDetails'] = video_details
def is_agegated(playability):
@ -2566,8 +2580,8 @@ class YoutubeIE(YoutubeBaseInfoExtractor):
}
pctr = traverse_obj(
player_response,
('captions', 'playerCaptionsTracklistRenderer', T(dict)))
(player_response, api_player_response),
(Ellipsis, 'captions', 'playerCaptionsTracklistRenderer', T(dict)))
if pctr:
def process_language(container, base_url, lang_code, query):
lang_subs = []
@ -2584,20 +2598,21 @@ class YoutubeIE(YoutubeBaseInfoExtractor):
def process_subtitles():
subtitles = {}
for caption_track in traverse_obj(pctr, (
'captionTracks', lambda _, v: v.get('baseUrl'))):
Ellipsis, 'captionTracks', lambda _, v: (
v.get('baseUrl') and v.get('languageCode')))):
base_url = self._yt_urljoin(caption_track['baseUrl'])
if not base_url:
continue
lang_code = caption_track['languageCode']
if caption_track.get('kind') != 'asr':
lang_code = caption_track.get('languageCode')
if not lang_code:
continue
process_language(
subtitles, base_url, lang_code, {})
continue
automatic_captions = {}
process_language(
automatic_captions, base_url, lang_code, {})
for translation_language in traverse_obj(pctr, (
'translationLanguages', lambda _, v: v.get('languageCode'))):
Ellipsis, 'translationLanguages', lambda _, v: v.get('languageCode'))):
translation_language_code = translation_language['languageCode']
process_language(
automatic_captions, base_url, translation_language_code,

View File

@ -678,7 +678,7 @@ class JSInterpreter(object):
return len(obj)
try:
return obj[int(idx)] if isinstance(obj, list) else obj[compat_str(idx)]
except (TypeError, KeyError, IndexError) as e:
except (TypeError, KeyError, IndexError, ValueError) as e:
# allow_undefined is None gives correct behaviour
if allow_undefined or (
allow_undefined is None and not isinstance(e, TypeError)):
@ -1038,6 +1038,10 @@ class JSInterpreter(object):
left_val = self._index(left_val, idx)
if isinstance(idx, float):
idx = int(idx)
if isinstance(left_val, list) and len(left_val) <= int_or_none(idx, default=-1):
# JS Array is a sparsely assignable list
# TODO: handle extreme sparsity without memory bloat, eg using auxiliary dict
left_val.extend((idx - len(left_val) + 1) * [JS_Undefined])
left_val[idx] = self._operator(
m.group('op'), self._index(left_val, idx) if m.group('op') else None,
m.group('expr'), expr, local_vars, allow_recursion)
@ -1204,9 +1208,10 @@ class JSInterpreter(object):
elif member == 'join':
assertion(isinstance(obj, list), 'must be applied on a list')
assertion(len(argvals) <= 1, 'takes at most one argument')
return (',' if len(argvals) == 0 else argvals[0]).join(
('' if x in (None, JS_Undefined) else _js_toString(x))
for x in obj)
return (',' if len(argvals) == 0 or argvals[0] in (None, JS_Undefined)
else argvals[0]).join(
('' if x in (None, JS_Undefined) else _js_toString(x))
for x in obj)
elif member == 'reverse':
assertion(not argvals, 'does not take any arguments')
obj.reverse()
@ -1364,19 +1369,21 @@ class JSInterpreter(object):
code, _ = self._separate_at_paren(func_m.group('code')) # refine the match
return self.build_arglist(func_m.group('args')), code
def extract_function(self, funcname):
def extract_function(self, funcname, *global_stack):
return function_with_repr(
self.extract_function_from_code(*self.extract_function_code(funcname)),
self.extract_function_from_code(*itertools.chain(
self.extract_function_code(funcname), global_stack)),
'F<%s>' % (funcname,))
def extract_function_from_code(self, argnames, code, *global_stack):
local_vars = {}
start = None
while True:
mobj = re.search(r'function\((?P<args>[^)]*)\)\s*{', code)
mobj = re.search(r'function\((?P<args>[^)]*)\)\s*{', code[start:])
if mobj is None:
break
start, body_start = mobj.span()
start, body_start = ((start or 0) + x for x in mobj.span())
body, remaining = self._separate_at_paren(code[body_start - 1:])
name = self._named_object(local_vars, self.extract_function_from_code(
[x.strip() for x in mobj.group('args').split(',')],