Compare commits

...

6 Commits

Author SHA1 Message Date
dirkf
dd32a93aa0
Merge 97c1053ba8 into c5098961b0 2024-08-21 22:33:22 -04:00
dirkf
c5098961b0 [Youtube] Rework n function extraction pattern
Now also succeeds with player b12cc44b
2024-08-06 20:59:09 +01:00
dirkf
dbc08fba83 [jsinterp] Improve slice implementation for player b12cc44b
Partly taken from yt-dlp/yt-dlp#10664, thx seproDev
        Fixes #32896
2024-08-06 20:51:38 +01:00
Aiur Adept
71223bff39
[Youtube] Fix nsig extraction for player 20dfca59 (#32891)
* dirkf's patch for nsig extraction
* add generic search per  yt-dlp/yt-dlp/pull/10611 - thx bashonly

---------

Co-authored-by: dirkf <fieldhouse@gmx.net>
2024-08-01 19:18:34 +01:00
dirkf
97c1053ba8 Implement @dstftw review comments 2021-04-18 20:02:54 +01:00
df
13d2684263 Support BBC World (etc) pages with data in SIMORGH_DATA JSON 2021-04-18 20:02:52 +01:00
5 changed files with 196 additions and 19 deletions

View File

@ -425,6 +425,34 @@ class TestJSInterpreter(unittest.TestCase):
self._test(jsi, [''], args=['', '-'])
self._test(jsi, [], args=['', ''])
def test_slice(self):
self._test('function f(){return [0, 1, 2, 3, 4, 5, 6, 7, 8].slice()}', [0, 1, 2, 3, 4, 5, 6, 7, 8])
self._test('function f(){return [0, 1, 2, 3, 4, 5, 6, 7, 8].slice(0)}', [0, 1, 2, 3, 4, 5, 6, 7, 8])
self._test('function f(){return [0, 1, 2, 3, 4, 5, 6, 7, 8].slice(5)}', [5, 6, 7, 8])
self._test('function f(){return [0, 1, 2, 3, 4, 5, 6, 7, 8].slice(99)}', [])
self._test('function f(){return [0, 1, 2, 3, 4, 5, 6, 7, 8].slice(-2)}', [7, 8])
self._test('function f(){return [0, 1, 2, 3, 4, 5, 6, 7, 8].slice(-99)}', [0, 1, 2, 3, 4, 5, 6, 7, 8])
self._test('function f(){return [0, 1, 2, 3, 4, 5, 6, 7, 8].slice(0, 0)}', [])
self._test('function f(){return [0, 1, 2, 3, 4, 5, 6, 7, 8].slice(1, 0)}', [])
self._test('function f(){return [0, 1, 2, 3, 4, 5, 6, 7, 8].slice(0, 1)}', [0])
self._test('function f(){return [0, 1, 2, 3, 4, 5, 6, 7, 8].slice(3, 6)}', [3, 4, 5])
self._test('function f(){return [0, 1, 2, 3, 4, 5, 6, 7, 8].slice(1, -1)}', [1, 2, 3, 4, 5, 6, 7])
self._test('function f(){return [0, 1, 2, 3, 4, 5, 6, 7, 8].slice(-1, 1)}', [])
self._test('function f(){return [0, 1, 2, 3, 4, 5, 6, 7, 8].slice(-3, -1)}', [6, 7])
self._test('function f(){return "012345678".slice()}', '012345678')
self._test('function f(){return "012345678".slice(0)}', '012345678')
self._test('function f(){return "012345678".slice(5)}', '5678')
self._test('function f(){return "012345678".slice(99)}', '')
self._test('function f(){return "012345678".slice(-2)}', '78')
self._test('function f(){return "012345678".slice(-99)}', '012345678')
self._test('function f(){return "012345678".slice(0, 0)}', '')
self._test('function f(){return "012345678".slice(1, 0)}', '')
self._test('function f(){return "012345678".slice(0, 1)}', '0')
self._test('function f(){return "012345678".slice(3, 6)}', '345')
self._test('function f(){return "012345678".slice(1, -1)}', '1234567')
self._test('function f(){return "012345678".slice(-1, 1)}', '')
self._test('function f(){return "012345678".slice(-3, -1)}', '67')
if __name__ == '__main__':
unittest.main()

View File

@ -174,6 +174,14 @@ _NSIG_TESTS = [
'https://www.youtube.com/s/player/5604538d/player_ias.vflset/en_US/base.js',
'7X-he4jjvMx7BCX', 'sViSydX8IHtdWA',
),
(
'https://www.youtube.com/s/player/20dfca59/player_ias.vflset/en_US/base.js',
'-fLCxedkAk4LUTK2', 'O8kfRq1y1eyHGw',
),
(
'https://www.youtube.com/s/player/b12cc44b/player_ias.vflset/en_US/base.js',
'keLa5R2U00sR9SQK', 'N1OGyujjEwMnLw',
),
]

View File

@ -25,6 +25,7 @@ from ..utils import (
get_element_by_class,
int_or_none,
js_to_json,
parse_bitrate,
parse_duration,
parse_iso8601,
strip_or_none,
@ -647,9 +648,7 @@ class BBCIE(BBCCoUkIE):
'skip_download': True,
}
}, {
# article with single video embedded with data-playable containing XML playlist
# with direct video links as progressiveDownloadUrl (for now these are extracted)
# and playlist with f4m and m3u8 as streamingUrl
# article with single video (formerly) embedded, now using SIMORGH_DATA JSON
'url': 'http://www.bbc.com/turkce/haberler/2015/06/150615_telabyad_kentin_cogu',
'info_dict': {
'id': '150615_telabyad_kentin_cogu',
@ -661,12 +660,13 @@ class BBCIE(BBCCoUkIE):
},
'params': {
'skip_download': True,
}
},
'skip': 'Video no longer embedded, 2021',
}, {
# single video embedded with data-playable containing XML playlists (regional section)
# single video embedded, legacy media, in promo object of SIMORGH_DATA JSON
'url': 'http://www.bbc.com/mundo/video_fotos/2015/06/150619_video_honduras_militares_hospitales_corrupcion_aw',
'info_dict': {
'id': '150619_video_honduras_militares_hospitales_corrupcion_aw',
'id': '39275083',
'ext': 'mp4',
'title': 'Honduras militariza sus hospitales por nuevo escándalo de corrupción',
'description': 'md5:1525f17448c4ee262b64b8f0c9ce66c8',
@ -845,6 +845,18 @@ class BBCIE(BBCCoUkIE):
'upload_date': '20190604',
'categories': ['Psychology'],
},
}, {
# BBC World Service etc: media nested in content object of SIMORGH_DATA JSON
'url': 'http://www.bbc.co.uk/scotland/articles/cm49v4x1r9lo',
'info_dict': {
'id': 'p06p040v',
'ext': 'mp4',
'title': 'Five things ants can teach us about management',
'description': 'They may be tiny, but us humans could learn a thing or two from ants.',
'duration': 191,
'thumbnail': r're:https?://.+/p06p0qzv.jpg',
'upload_date': '20181016',
},
}]
@classmethod
@ -1107,6 +1119,99 @@ class BBCIE(BBCCoUkIE):
'subtitles': subtitles,
}
# simorgh-based playlist (see https://github.com/bbc/simorgh)
# JSON assigned to window.SIMORGH_DATA in a <script> element
simorgh_data = self._parse_json(
self._search_regex(
r'window\.SIMORGH_DATA\s*=\s*(\{[^<]+})\s*</',
webpage, 'simorgh playlist', default='{}'),
playlist_id, fatal=False)
# legacy media, video in promo object (eg, http://www.bbc.com/mundo/video_fotos/2015/06/150619_video_honduras_militares_hospitales_corrupcion_aw)
playlist = try_get(simorgh_data, lambda x: x['pageData']['promo']['media']['playlist']) or []
if playlist:
media = simorgh_data['pageData']['promo']
if media['media'].get('format') == 'video':
media.update(media['media'])
title = (dict_get(media.get('headlines') or {},
('shortHeadline', 'headline'))
or playlist_title),
programme_id = media.get('id')
if programme_id and title:
formats = []
keys = {'url', 'format', 'format_id', 'language', 'quality', 'tbr', 'resolution'}
for format in playlist:
if not (format.get('url') and format.get('format')):
continue
bitrate = format.pop('bitrate')
format['tbr'] = int_or_none(bitrate, scale=1000) or parse_bitrate(bitrate)
format['language'] = media.get('language')
# format id: penultimate item from the url split on _ and .
(fmt,) = re.split('[_.]', format['url'])[-2:][:1]
format['format_id'] = '%s_%s' % (format['format'], fmt)
# try to set resolution using any available data
aspect_ratio = re.split(r'[xX:]', media.get('aspectRatio') or '')
if len(aspect_ratio) != 2:
aspect_ratio = None
else:
aspect_ratio = float_or_none(aspect_ratio[0], scale=aspect_ratio[1])
# these may not be present, but try anyway
width = int_or_none(format.get('width'))
height = int_or_none(format.get('height'))
if (not height) and aspect_ratio:
height = int(width / aspect_ratio)
elif (not width) and aspect_ratio:
width = int(height * aspect_ratio)
format['resolution'] = ('%dx%d' % (width, height) if width and height
else dict_get(format, ('resolution', 'res'), default=fmt))
format['quality'] = -1
formats.append(dict((k, format[k]) for k in keys))
self._sort_formats(formats)
return {
'id': programme_id,
'title': title,
'description': media.get('summary') or playlist_description,
'formats': formats,
'subtitles': None,
'thumbnail': try_get(media, lambda x: x['image']['href']),
'timestamp': int_or_none(media.get('timestamp'), scale=1000)
}
# general case: media nested in content object
# test: https://www.bbc.co.uk/scotland/articles/cm49v4x1r9lo
if simorgh_data:
def extract_media_from_simorgh(model):
if not isinstance(model, dict):
return
for block in model.get('blocks') or {}:
if block.get('type') == 'aresMediaMetadata':
vpid = try_get(block, lambda x: x['model']['versions'][0]['versionId'])
if vpid:
formats, subtitles = self._download_media_selector(vpid)
self._sort_formats(formats)
model = block['model']
version = model['versions'][0]
thumbnail = model.get('imageUrl')
return {
'id': vpid,
'title': model.get('title') or 'unnamed clip',
'description': dict_get(model.get('synopses') or {}, ('long', 'medium', 'short')),
'duration': (int_or_none(version.get('duration'))
or parse_duration(version.get('durationISO8601'))),
'timestamp': version.get('availableFrom'),
'thumbnail': urljoin(url, thumbnail.replace('$recipe', 'raw')) if thumbnail else None,
'formats': formats,
'subtitles': subtitles,
}
else:
entry = extract_media_from_simorgh(block.get('model'))
if entry:
return entry
playlist = extract_media_from_simorgh(try_get(simorgh_data, lambda x: x['pageData']['content']['model']))
if playlist:
return playlist
preload_state = self._parse_json(self._search_regex(
r'window\.__PRELOADED_STATE__\s*=\s*({.+?});', webpage,
'preload state', default='{}'), playlist_id, fatal=False)

View File

@ -1659,17 +1659,46 @@ class YoutubeIE(YoutubeBaseInfoExtractor):
def _extract_n_function_name(self, jscode):
func_name, idx = self._search_regex(
# new: (b=String.fromCharCode(110),c=a.get(b))&&c=nfunc[idx](c)
# or: (b="nn"[+a.D],c=a.get(b))&&(c=nfunc[idx](c)s
# old: .get("n"))&&(b=nfunc[idx](b)
# older: .get("n"))&&(b=nfunc(b)
# or: (b="nn"[+a.D],c=a.get(b))&&(c=nfunc[idx](c)
# or: (PL(a),b=a.j.n||null)&&(b=nfunc[idx](b)
# or: (b="nn"[+a.D],vL(a),c=a.j[b]||null)&&(c=narray[idx](c),a.set(b,c),narray.length||nfunc("")
# old: (b=a.get("n"))&&(b=nfunc[idx](b)(?P<c>[a-z])\s*=\s*[a-z]\s*
# older: (b=a.get("n"))&&(b=nfunc(b)
r'''(?x)
(?:\(\s*(?P<b>[a-z])\s*=\s*(?:
String\s*\.\s*fromCharCode\s*\(\s*110\s*\)|
"n+"\[\s*\+?s*[\w$.]+\s*]
)\s*,(?P<c>[a-z])\s*=\s*[a-z]\s*)?
\.\s*get\s*\(\s*(?(b)(?P=b)|"n{1,2}")(?:\s*\)){2}\s*&&\s*\(\s*(?(c)(?P=c)|b)\s*=\s*
(?P<nfunc>[a-zA-Z_$][\w$]*)(?:\s*\[(?P<idx>\d+)\])?\s*\(\s*[\w$]+\s*\)
''', jscode, 'Initial JS player n function name', group=('nfunc', 'idx'))
\((?:[\w$()\s]+,)*?\s* # (
(?P<b>[a-z])\s*=\s* # b=
(?:
(?: # expect ,c=a.get(b) (etc)
String\s*\.\s*fromCharCode\s*\(\s*110\s*\)|
"n+"\[\s*\+?s*[\w$.]+\s*]
)\s*(?:,[\w$()\s]+(?=,))*|
(?P<old>[\w$]+) # a (old[er])
)\s*
(?(old)
# b.get("n")
(?:\.\s*[\w$]+\s*|\[\s*[\w$]+\s*]\s*)*?
(?:\.\s*n|\[\s*"n"\s*]|\.\s*get\s*\(\s*"n"\s*\))
| # ,c=a.get(b)
,\s*(?P<c>[a-z])\s*=\s*[a-z]\s*
(?:\.\s*[\w$]+\s*|\[\s*[\w$]+\s*]\s*)*?
(?:\[\s*(?P=b)\s*]|\.\s*get\s*\(\s*(?P=b)\s*\))
)
# interstitial junk
\s*(?:\|\|\s*null\s*)?(?:\)\s*)?&&\s*(?:\(\s*)?
(?(c)(?P=c)|(?P=b))\s*=\s* # [c|b]=
# nfunc|nfunc[idx]
(?P<nfunc>[a-zA-Z_$][\w$]*)(?:\s*\[(?P<idx>\d+)\])?\s*\(\s*[\w$]+\s*\)
''', jscode, 'Initial JS player n function name', group=('nfunc', 'idx'),
default=(None, None))
# thx bashonly: yt-dlp/yt-dlp/pull/10611
if not func_name:
self.report_warning('Falling back to generic n function search')
return self._search_regex(
r'''(?xs)
(?:(?<=[^\w$])|^) # instead of \b, which ignores $
(?P<name>(?!\d)[a-zA-Z\d_$]+)\s*=\s*function\((?!\d)[a-zA-Z\d_$]+\)
\s*\{(?:(?!};).)+?["']enhanced_except_
''', jscode, 'Initial JS player n function name', group='name')
if not idx:
return func_name

View File

@ -925,9 +925,16 @@ class JSInterpreter(object):
obj.reverse()
return obj
elif member == 'slice':
assertion(isinstance(obj, list), 'must be applied on a list')
assertion(len(argvals) == 1, 'takes exactly one argument')
return obj[argvals[0]:]
assertion(isinstance(obj, (list, compat_str)), 'must be applied on a list or string')
# From [1]:
# .slice() - like [:]
# .slice(n) - like [n:] (not [slice(n)]
# .slice(m, n) - like [m:n] or [slice(m, n)]
# [1] https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice
assertion(len(argvals) <= 2, 'takes between 0 and 2 arguments')
if len(argvals) < 2:
argvals += (None,)
return obj[slice(*argvals)]
elif member == 'splice':
assertion(isinstance(obj, list), 'must be applied on a list')
assertion(argvals, 'takes one or more arguments')