Compare commits

...

18 Commits

Author SHA1 Message Date
Valter Vicente
23ca8bbb7c
Merge 1058c29c74 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
vallovic
1058c29c74 Make extractor compatible with Python 2.6+ 2021-10-31 11:16:05 +00:00
vallovic
6bde4a1377 Fix 'RTP Arquivos' downloads, allow subtitles download, more tests, general cleanup 2021-08-28 21:10:18 +01:00
vallovic
89a75524e6 Merge remote-tracking branch 'upstream/master' 2021-08-28 17:33:40 +01:00
vallovic
31595de72b Merge remote-tracking branch 'upstream/master' 2021-05-13 21:33:03 +01:00
vallovic
5a7243b741 Working around new URLs 2021-05-06 23:20:20 +01:00
vallovic
d30180d4f3 Consider multi-part videos in filename output 2021-04-23 23:02:04 +01:00
vallovic
ff47d11269 Ignore EVEN more comments in RTP source code 2021-04-21 16:24:26 +01:00
vallovic
7f40887b29 Ignore more comments in RTP source code 2021-04-13 21:03:59 +01:00
vallovic
c1a696ee40 Merge remote-tracking branch 'upstream/master' 2021-04-13 13:05:15 +01:00
vallovic
b955e0a5dc RTP devs like to try out different approaches 2021-02-21 14:05:42 +00:00
vallovic
030a5713e6 Merge remote-tracking branch 'upstream/master' 2021-02-21 11:00:40 +00:00
vallovic
a85625977d 'Estudo em Casa' wasn't working since RTP has a lot of ways of dealing with their code 2021-02-20 20:42:33 +00:00
vallovic
fd733f52f5 Merge remote-tracking branch 'upstream/master' 2021-02-20 20:40:33 +00:00
vallovic
35779eda7a Dealing with RTP latest changes 2021-02-19 14:10:10 +00:00
5 changed files with 235 additions and 40 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

@ -3,25 +3,71 @@ from __future__ import unicode_literals
from .common import InfoExtractor
from ..utils import (
ExtractorError,
determine_ext,
js_to_json,
)
from ..compat import (
compat_b64decode,
compat_urllib_parse_unquote,
)
import re
class RTPIE(InfoExtractor):
_VALID_URL = r'https?://(?:www\.)?rtp\.pt/play/p(?P<program_id>[0-9]+)/(?P<id>[^/?#]+)/?'
_VALID_URL = r'https?://(?:(?:(?:www\.)?rtp\.pt/play/(?P<subarea>.*/)?p(?P<program_id>[0-9]+)/(?P<episode_id>e[0-9]+/)?)|(?:arquivos\.rtp\.pt/conteudos/))(?P<id>[^/?#]+)/?'
_TESTS = [{
'url': 'http://www.rtp.pt/play/p405/e174042/paixoes-cruzadas',
'md5': 'e736ce0c665e459ddb818546220b4ef8',
'url': 'https://www.rtp.pt/play/p117/e563265/os-contemporaneos',
'info_dict': {
'id': 'e174042',
'ext': 'mp3',
'title': 'Paixões Cruzadas',
'description': 'As paixões musicais de António Cartaxo e António Macedo',
'thumbnail': r're:^https?://.*\.jpg',
'id': 'os-contemporaneos',
'ext': 'mp4',
'title': 'Os Contemporâneos Episódio 1',
'description': 'Os Contemporâneos, um programa de humor com um olhar na sociedade portuguesa!',
'thumbnail': r're:^https?://.*\.(jpg|png)'
},
}, {
'url': 'http://www.rtp.pt/play/p831/a-quimica-das-coisas',
'url': 'https://www.rtp.pt/play/p8157/e541212/telejornal',
'info_dict': {
'id': 'telejornal',
'ext': 'mp4',
'title': 'Telejornal de 01 Mai 2021 PARTE 1',
'description': 'A mais rigorosa seleção de notícias, todos os dias às 20h00. De segunda a domingo, João Adelino Faria e José Rodrigues dos Santos mostram-lhe o que de'
},
}, {
'url': 'https://www.rtp.pt/play/p6646/e457262/grande-entrevista',
'info_dict': {
'id': 'grande-entrevista',
'ext': 'mp4',
'title': 'Grande Entrevista Episódio 7 - de 19 Fev 2020',
'description': 'Bruno Nogueira - É um dos mais originais humoristas portugueses e de maior êxito! Bruno Nogueira na Grande Entrevista com Vítor Gonçalves.'
},
}, {
'url': 'https://www.rtp.pt/play/estudoemcasa/p7776/e539826/portugues-1-ano',
'info_dict': {
'id': 'portugues-1-ano',
'ext': 'mp4',
'title': 'Português - 1.º ano , aula 45 - 27 Abr 2021 - Estudo Em Casa - RTP',
'description': 'A História do Pedrito Coelho, de Beatrix Potter. O dígrafo \'lh\' - A História do Pedrito Coelho, de Beatrix Potter. O dígrafo \'lh\'.'
},
}, {
'url': 'https://www.rtp.pt/play/zigzag/p5449/e385973/banda-zig-zag',
'info_dict': {
'id': 'banda-zig-zag',
'ext': 'mp4',
'title': 'Banda Zig Zag Episódio 1 - Zig Zag Play - RTP',
'description': 'A Amizade é o Nosso Mel - Zig: é a menina que além de tocar também canta. Adora aprender palavras novas e adora ler. Gosta de fazer palavras cruzadas'
},
}, {
'url': 'https://arquivos.rtp.pt/conteudos/liga-dos-ultimos-152/',
'info_dict': {
'id': 'liga-dos-ultimos-152',
'ext': 'mp4',
'title': 'Liga dos Últimos RTP Arquivos',
'description': 'Magazine desportivo, com apresentação de Álvaro Costa e comentários em estúdio do professor Hernâni Gonçalves e do sociólogo João Nuno Coelho. Destaque para os jogos de futebol das equipas dos escalões secundários de Portugal, com momentos dos jogos: Agrário de Lamas vs Pampilhoense e Apúlia vs Fragoso.'
},
}, {
'url': 'https://www.rtp.pt/play/p510/aleixo-fm',
'only_matching': True,
}]
@ -29,38 +75,115 @@ class RTPIE(InfoExtractor):
video_id = self._match_id(url)
webpage = self._download_webpage(url, video_id)
title = self._html_search_meta(
'twitter:title', webpage, display_name='title', fatal=True)
config = self._parse_json(self._search_regex(
r'(?s)RTPPlayer\(({.+?})\);', webpage,
'player config'), video_id, js_to_json)
file_url = config['file']
# Remove JS multi-line comments from webpage source
webpage = re.sub(r'(\/\*.*\*\/)', '', webpage, flags=re.DOTALL)
title = self._html_search_regex(r'<title>(.+?)</title>', webpage, 'title')
if 'Este episódio não se encontra disponível' in title:
raise ExtractorError('Episode unavailable', expected=True)
# Replace irrelevant text in title
title = re.sub(r' - ?RTP Play - RTP', '', title)
# Check if it's a video split in parts, if so add part number to title
part = self._html_search_regex(r'section\-parts.*<span.*>(.+?)</span>.*</ul>', webpage, 'part', default=None)
if part:
title = '{title} {part}'.format(title=title, part=part)
# Get JS object
js_object = self._search_regex(r'(?s)RTPPlayer *\( *({.+?}) *\);', webpage, 'player config')
json_string_for_config = ''
filekey_found = False
# Verify JS object since it isn't pure JSON and probably needs some fixing
for line in js_object.splitlines():
stripped_line = line.strip()
# If JS object key is 'fileKey'
if re.match('fileKey ?:', stripped_line):
filekey_found = True
if 'decodeURIComponent' in stripped_line:
# 1) The value is an encoded URL
encoded_url = re.match(r"[^[]*\[([^]]*)\]", stripped_line).groups()[0]
encoded_url = re.sub(r'[\s"\',]', '', encoded_url)
if 'atob' in stripped_line:
# Most of the times 'atob' approach is used but not always so we need to be sure
decoded_url = compat_b64decode(
compat_urllib_parse_unquote(
encoded_url)).decode('utf-8')
else:
# If no 'atob' we just need to unquote it
decoded_url = compat_urllib_parse_unquote(encoded_url)
# Insert the (relative) decoded URL in JSON
json_string_for_config += '\nfileKey: "{decoded_url}",'.format(decoded_url=decoded_url)
else:
# 2) ... or the value URL is not encoded so keep it that way
json_string_for_config += '\n{stripped_line}'.format(stripped_line=stripped_line)
elif (
not stripped_line.startswith("//")
and not re.match('.*extraSettings ?:', stripped_line)
and (not filekey_found or (filekey_found and not re.match('file ?:', stripped_line)))
):
# Ignore commented lines and 'extraSettings'. Also ignore 'file' if 'fileKey' already exists
json_string_for_config += '\n{stripped_line}'.format(stripped_line=stripped_line)
# Finally send pure JSON string for JSON parsing
config = self._parse_json(json_string_for_config, video_id, js_to_json)
if 'fileKey' in config:
# 'fileKey' has priority over 'file' on our end
file_url = config['fileKey']
elif 'file' in config:
# 'RTP Arquivos' still uses old regular non-encoded 'file' key
file_url = config['file']
else:
raise ExtractorError('No valid media source found in page')
ext = determine_ext(file_url)
if ext == 'm3u8':
file_key = config.get('fileKey')
if ext == 'mp4':
# Due to recent changes, we need to hardcode the URL like this and download it using 'm3u8'
file_url = 'https://streaming-vod.rtp.pt/hls{file_url}/index-v1-a1.m3u8'.format(file_url=file_url)
formats = self._extract_m3u8_formats(
file_url, video_id, 'mp4', 'm3u8_native',
m3u8_id='hls', fatal=file_key)
if file_key:
formats.append({
'url': 'https://cdn-ondemand.rtp.pt' + file_key,
'preference': 1,
})
self._sort_formats(formats)
m3u8_id='hls')
elif ext == 'm3u8':
# It can be downloaded without any further changes
formats = self._extract_m3u8_formats(
file_url, video_id, 'mp4', 'm3u8_native',
m3u8_id='hls')
else:
# Need to set basepath
file_url = 'https://cdn-ondemand.rtp.pt{file_url}'.format(file_url=file_url)
formats = [{
'url': file_url,
'ext': ext,
}]
if config.get('mediaType') == 'audio':
if config['mediaType'] == 'audio':
for f in formats:
f['vcodec'] = 'none'
subtitles = {}
if 'vtt' in config:
sub_lang, sub_lang_full, sub_url = config['vtt'][0]
subtitles.setdefault(sub_lang, []).append({
'url': sub_url,
'ext': 'vtt',
})
return {
'id': video_id,
'title': title,
'formats': formats,
'description': self._html_search_meta(['description', 'twitter:description'], webpage),
'thumbnail': config.get('poster') or self._og_search_thumbnail(webpage),
'subtitles': subtitles,
'description': self._html_search_meta(['og:description', 'description', 'twitter:description'], webpage),
'thumbnail': config['poster'] or self._og_search_thumbnail(webpage),
}

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')