Compare commits

...

5 Commits

Author SHA1 Message Date
red-acid
23f88603c9
Merge 049862b803 into f2a4983df7 2024-11-13 01:47:05 +01:00
Jackson Humphrey
f2a4983df7
[ie/archive.org] Fix comments extraction (#11527)
Closes #11526
Authored by: jshumphrey
2024-11-12 23:26:18 +00:00
bashonly
bacc31b05a
[ie/facebook] Fix formats extraction (#11513)
Closes #11497
Authored by: bashonly
2024-11-12 23:23:10 +00:00
red-acid
049862b803
Apply suggestions from code review
Co-authored-by: N/Ame <173015200+grqz@users.noreply.github.com>
2024-10-23 11:11:24 +01:00
red-acid
c2b5c7025c
Update rtp.py 2024-10-14 12:36:35 +01:00
3 changed files with 184 additions and 47 deletions

View File

@ -205,6 +205,26 @@ class ArchiveOrgIE(InfoExtractor):
}, },
}, },
], ],
}, {
# The reviewbody is None for one of the reviews; just need to extract data without crashing
'url': 'https://archive.org/details/gd95-04-02.sbd.11622.sbeok.shnf/gd95-04-02d1t04.shn',
'info_dict': {
'id': 'gd95-04-02.sbd.11622.sbeok.shnf/gd95-04-02d1t04.shn',
'ext': 'mp3',
'title': 'Stuck Inside of Mobile with the Memphis Blues Again',
'creators': ['Grateful Dead'],
'duration': 338.31,
'track': 'Stuck Inside of Mobile with the Memphis Blues Again',
'description': 'md5:764348a470b986f1217ffd38d6ac7b72',
'display_id': 'gd95-04-02d1t04.shn',
'location': 'Pyramid Arena',
'uploader': 'jon@archive.org',
'album': '1995-04-02 - Pyramid Arena',
'upload_date': '20040519',
'track_number': 4,
'release_date': '19950402',
'timestamp': 1084927901,
},
}] }]
@staticmethod @staticmethod
@ -335,7 +355,7 @@ class ArchiveOrgIE(InfoExtractor):
info['comments'].append({ info['comments'].append({
'id': review.get('review_id'), 'id': review.get('review_id'),
'author': review.get('reviewer'), 'author': review.get('reviewer'),
'text': str_or_none(review.get('reviewtitle'), '') + '\n\n' + review.get('reviewbody'), 'text': join_nonempty('reviewtitle', 'reviewbody', from_dict=review, delim='\n\n'),
'timestamp': unified_timestamp(review.get('createdate')), 'timestamp': unified_timestamp(review.get('createdate')),
'parent': 'root'}) 'parent': 'root'})

View File

@ -563,13 +563,13 @@ class FacebookIE(InfoExtractor):
return extract_video_data(try_get( return extract_video_data(try_get(
js_data, lambda x: x['jsmods']['instances'], list) or []) js_data, lambda x: x['jsmods']['instances'], list) or [])
def extract_dash_manifest(video, formats): def extract_dash_manifest(vid_data, formats, mpd_url=None):
dash_manifest = traverse_obj( dash_manifest = traverse_obj(
video, 'dash_manifest', 'playlist', 'dash_manifest_xml_string', expected_type=str) vid_data, 'dash_manifest', 'playlist', 'dash_manifest_xml_string', 'manifest_xml', expected_type=str)
if dash_manifest: if dash_manifest:
formats.extend(self._parse_mpd_formats( formats.extend(self._parse_mpd_formats(
compat_etree_fromstring(urllib.parse.unquote_plus(dash_manifest)), compat_etree_fromstring(urllib.parse.unquote_plus(dash_manifest)),
mpd_url=url_or_none(video.get('dash_manifest_url')))) mpd_url=url_or_none(video.get('dash_manifest_url')) or mpd_url))
def process_formats(info): def process_formats(info):
# Downloads with browser's User-Agent are rate limited. Working around # Downloads with browser's User-Agent are rate limited. Working around
@ -619,9 +619,12 @@ class FacebookIE(InfoExtractor):
video = video['creation_story'] video = video['creation_story']
video['owner'] = traverse_obj(video, ('short_form_video_context', 'video_owner')) video['owner'] = traverse_obj(video, ('short_form_video_context', 'video_owner'))
video.update(reel_info) video.update(reel_info)
fmt_data = traverse_obj(video, ('videoDeliveryLegacyFields', {dict})) or video
formats = [] formats = []
q = qualities(['sd', 'hd']) q = qualities(['sd', 'hd'])
# Legacy formats extraction
fmt_data = traverse_obj(video, ('videoDeliveryLegacyFields', {dict})) or video
for key, format_id in (('playable_url', 'sd'), ('playable_url_quality_hd', 'hd'), for key, format_id in (('playable_url', 'sd'), ('playable_url_quality_hd', 'hd'),
('playable_url_dash', ''), ('browser_native_hd_url', 'hd'), ('playable_url_dash', ''), ('browser_native_hd_url', 'hd'),
('browser_native_sd_url', 'sd')): ('browser_native_sd_url', 'sd')):
@ -629,7 +632,7 @@ class FacebookIE(InfoExtractor):
if not playable_url: if not playable_url:
continue continue
if determine_ext(playable_url) == 'mpd': if determine_ext(playable_url) == 'mpd':
formats.extend(self._extract_mpd_formats(playable_url, video_id)) formats.extend(self._extract_mpd_formats(playable_url, video_id, fatal=False))
else: else:
formats.append({ formats.append({
'format_id': format_id, 'format_id': format_id,
@ -638,6 +641,28 @@ class FacebookIE(InfoExtractor):
'url': playable_url, 'url': playable_url,
}) })
extract_dash_manifest(fmt_data, formats) extract_dash_manifest(fmt_data, formats)
# New videoDeliveryResponse formats extraction
fmt_data = traverse_obj(video, ('videoDeliveryResponseFragment', 'videoDeliveryResponseResult'))
mpd_urls = traverse_obj(fmt_data, ('dash_manifest_urls', ..., 'manifest_url', {url_or_none}))
dash_manifests = traverse_obj(fmt_data, ('dash_manifests', lambda _, v: v['manifest_xml']))
for idx, dash_manifest in enumerate(dash_manifests):
extract_dash_manifest(dash_manifest, formats, mpd_url=traverse_obj(mpd_urls, idx))
if not dash_manifests:
# Only extract from MPD URLs if the manifests are not already provided
for mpd_url in mpd_urls:
formats.extend(self._extract_mpd_formats(mpd_url, video_id, fatal=False))
for prog_fmt in traverse_obj(fmt_data, ('progressive_urls', lambda _, v: v['progressive_url'])):
format_id = traverse_obj(prog_fmt, ('metadata', 'quality', {str.lower}))
formats.append({
'format_id': format_id,
# sd, hd formats w/o resolution info should be deprioritized below DASH
'quality': q(format_id) - 3,
'url': prog_fmt['progressive_url'],
})
for m3u8_url in traverse_obj(fmt_data, ('hls_playlist_urls', ..., 'hls_playlist_url', {url_or_none})):
formats.extend(self._extract_m3u8_formats(m3u8_url, video_id, 'mp4', fatal=False, m3u8_id='hls'))
if not formats: if not formats:
# Do not append false positive entry w/o any formats # Do not append false positive entry w/o any formats
return return

View File

@ -4,40 +4,97 @@ import re
import urllib.parse import urllib.parse
from .common import InfoExtractor from .common import InfoExtractor
from ..utils import js_to_json from ..utils import (
ExtractorError,
determine_ext,
join_nonempty,
js_to_json,
)
class RTPIE(InfoExtractor): class RTPIE(InfoExtractor):
_VALID_URL = r'https?://(?:www\.)?rtp\.pt/play/(?:(?:estudoemcasa|palco|zigzag)/)?p(?P<program_id>[0-9]+)/(?P<id>[^/?#]+)' _VALID_URL = r'https?://(?:(?:www\.)?rtp\.pt/play/(?P<subarea>.*/)?p(?P<program_id>\d+)/|arquivos\.rtp\.pt/conteudos/)(?P<id>[^/?#]+)'
_TESTS = [{ _TESTS = [{
'url': 'http://www.rtp.pt/play/p405/e174042/paixoes-cruzadas', 'url': 'https://www.rtp.pt/play/p9165/e562949/por-do-sol',
'md5': 'e736ce0c665e459ddb818546220b4ef8',
'info_dict': { 'info_dict': {
'id': 'e174042', 'id': 'e562949',
'ext': 'mp3',
'title': 'Paixões Cruzadas',
'description': 'As paixões musicais de António Cartaxo e António Macedo',
'thumbnail': r're:^https?://.*\.jpg',
},
}, {
'url': 'https://www.rtp.pt/play/zigzag/p13166/e757904/25-curiosidades-25-de-abril',
'md5': '9a81ed53f2b2197cfa7ed455b12f8ade',
'info_dict': {
'id': 'e757904',
'ext': 'mp4', 'ext': 'mp4',
'title': '25 Curiosidades, 25 de Abril', 'title': 'Pôr do Sol Episódio 1',
'description': 'Estudar ou não estudar - Em cada um dos episódios descobrimos uma curiosidade acerca de como era viver em Portugal antes da revolução do 25 de abr', 'description': 'Madalena Bourbon de Linhaça vive atormentada pelo segredo que esconde desde 1990. Matilde Bourbon de Linhaça sonha fugir com o seu amor proibido. O',
'thumbnail': r're:^https?://.*\.jpg', 'thumbnail': r're:https?://.*\.(?:jpg|png)',
}, },
}, { }, {
'url': 'http://www.rtp.pt/play/p831/a-quimica-das-coisas', 'url': 'https://www.rtp.pt/play/p12646/e738493/telejornal',
'only_matching': True, 'info_dict': {
'id': 'e738493',
'ext': 'mp4',
'title': 'Telejornal de 01 jan 2024 PARTE 1',
'description': 'A mais rigorosa seleção de notícias, todos os dias às 20h00. De segunda a domingo, João Adelino Faria, José Rodrigues dos Santos e Ana Lourenço',
'thumbnail': r're:https?://.*\.(?:jpg|png)',
},
}, { }, {
'url': 'https://www.rtp.pt/play/estudoemcasa/p7776/portugues-1-ano', 'url': 'https://www.rtp.pt/play/p6646/e457262/grande-entrevista',
'only_matching': True, 'info_dict': {
'id': 'e457262',
'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.',
'thumbnail': r're:https?://.*\.(?:jpg|png)',
},
}, { }, {
'url': 'https://www.rtp.pt/play/palco/p13785/l7nnon', 'url': 'https://www.rtp.pt/play/p1525/e738522/a-mosca',
'only_matching': True, 'info_dict': {
'id': 'e738522',
'ext': 'mp4',
'title': 'A Mosca de 02 jan 2024',
'description': 'Ano novo, vida nova - Ano novo, vida nova',
'thumbnail': r're:https?://.*\.(?:jpg|png)',
},
}, {
'url': 'https://www.rtp.pt/play/estudoemcasa/p7776/e539826/portugues-1-ano',
'info_dict': {
'id': 'e539826',
'ext': 'mp4',
'title': 'Português - 1.º ano , aula 45 - 27 abr 2021',
'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\'.',
'thumbnail': r're:https?://.*\.(?:jpg|png)',
},
}, {
'url': 'https://www.rtp.pt/play/zigzag/p13857/e794575/zig-zag-zzz-e-amigos',
'info_dict': {
'id': 'e794575',
'ext': 'mp4',
'title': 'Zig, Zag, Zzz e Amigos Episódio 1 - de 16 set 2024',
'description': 'O Brinquedo Perdido - Zig, Zag e Zzz são três amigos inseparáveis que partilham aventuras emocionantes e cheias de imaginação. Exploram o mundo <20>',
'thumbnail': r're:https?://.*\.(?:jpg|png)',
},
}, {
'url': 'https://www.rtp.pt/play/palco/p13151/premio-miguel-rovisco-2023-requiem-por-isabel',
'info_dict': {
'id': 'premio-miguel-rovisco-2023-requiem-por-isabel',
'ext': 'mp4',
'title': 'Prémio Miguel Rovisco 23: Requiem Por Isabel de 30 mar 2024',
'description': 'Lucrécia foi a atriz mais famosa e requisitada do seu tempo. Este já não é o seu tempo. A debater-se com a decrepitude física e financeira, foi o',
'thumbnail': r're:https?://.*\.(?:jpg|png)',
},
}, {
'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.',
'thumbnail': r're:https?://.*\.(?:jpg|png)',
},
}, {
'url': 'https://www.rtp.pt/play/p510/e786608/aleixo-fm',
'info_dict': {
'id': 'e786608',
'ext': 'mp3',
'title': 'Aleixo FM de 31 jul 2024',
'description': 'Melhor dia pra casar - Já o diz Joaquim de Magalhães Fernandes Barreiros, comummente conhecido como Quim Barreiros. Mas será mesmo este o melhor di',
'thumbnail': r're:https?://.*\.(?:jpg|png)',
},
}] }]
_RX_OBFUSCATION = re.compile(r'''(?xs) _RX_OBFUSCATION = re.compile(r'''(?xs)
@ -60,33 +117,69 @@ class RTPIE(InfoExtractor):
video_id = self._match_id(url) video_id = self._match_id(url)
webpage = self._download_webpage(url, video_id) webpage = self._download_webpage(url, video_id)
title = self._html_search_meta(
'twitter:title', webpage, display_name='title', fatal=True)
# Title tag includes relevant data
title = self._html_search_regex(r'<title>(.+?)</title>', webpage, 'title', default='')
# Raise error if episode is unavailable
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|Estudo Em Casa|Zig Zag Play|RTP Palco)( - RTP)?', '', title)
# Check if it's a episode split in parts
part = self._html_search_regex(r'section\-parts.*<span.*>(.+?)</span>.*</ul>', webpage, 'part', default=None)
# Add episode part identification to title if it exists
title = join_nonempty(title, part, delim=' ')
# Extract f and config from page
f, config = self._search_regex( f, config = self._search_regex(
r'''(?sx) r'''(?sx)
(?:var\s+f\s*=\s*(?P<f>".*?"|{[^;]+?});\s*)? (?:var\s+f\s*=\s*(?P<f>".*?"|{[^;]+?});\s*)?
var\s+player1\s+=\s+new\s+RTPPlayer\s*\((?P<config>{(?:(?!\*/).)+?})\);(?!\s*\*/) var\s+player1?\s+=\s+new\s+RTPPlayer\s*\((?P<config>{(?:(?!\*/).)+?})\);(?!\s*\*/)
''', webpage, ''', webpage,
'player config', group=('f', 'config')) 'player config', group=('f', 'config'))
config = self._parse_json( config = self._parse_json(
config, video_id, config, video_id,
lambda data: self.__unobfuscate(data, video_id=video_id)) lambda data: self.__unobfuscate(data, video_id=video_id))
# Estudo em Casa / Zig Zag / Palco / RTP Arquivos subareas don't include f
f = config['file'] if not f else self._parse_json( f = config['file'] if not f else self._parse_json(
f, video_id, f, video_id,
lambda data: self.__unobfuscate(data, video_id=video_id)) lambda data: self.__unobfuscate(data, video_id=video_id))
formats = [] formats = []
if isinstance(f, dict): if isinstance(f, dict):
f_hls = f.get('hls') file_hls = f.get('hls')
if f_hls is not None: file_fps = f.get('fps')
formats.extend(self._extract_m3u8_formats(
f_hls, video_id, 'mp4', 'm3u8_native', m3u8_id='hls')) if file_fps is not None:
# RTP Arquivos specific use case
if '/arquivo/' in file_fps:
file_key = config['fileKey']
split_file_key = file_key.split('/')
filename = split_file_key[-1]
del split_file_key[-1]
split_file_key.extend([f'index.m3u8?tlm=hls&streams={filename}.m3u8'])
path = '/'.join(split_file_key)
file_hls = f'https://streaming-arquivo-ondemand.rtp.pt/nas2.share{path}'
elif file_hls is None:
file_hls = file_fps.replace('drm-fps', 'hls')
formats.extend(self._extract_m3u8_formats(
file_hls, video_id, 'mp4', 'm3u8_native', m3u8_id='hls'))
else:
ext = determine_ext(f)
if ext == 'm3u8':
formats.extend(self._extract_m3u8_formats(
f, video_id, 'mp4', 'm3u8_native', m3u8_id='hls'))
f_dash = f.get('dash')
if f_dash is not None:
formats.extend(self._extract_mpd_formats(f_dash, video_id, mpd_id='dash'))
else: else:
formats.append({ formats.append({
'format_id': 'f', 'format_id': 'f',
@ -95,7 +188,6 @@ class RTPIE(InfoExtractor):
}) })
subtitles = {} subtitles = {}
vtt = config.get('vtt') vtt = config.get('vtt')
if vtt is not None: if vtt is not None:
for lcode, lname, url in vtt: for lcode, lname, url in vtt:
@ -108,7 +200,7 @@ class RTPIE(InfoExtractor):
'id': video_id, 'id': video_id,
'title': title, 'title': title,
'formats': formats, 'formats': formats,
'description': self._html_search_meta(['description', 'twitter:description'], webpage), 'description': self._html_search_meta(['og:description', 'description'], webpage),
'thumbnail': config.get('poster') or self._og_search_thumbnail(webpage), 'thumbnail': config.get('poster') or self._og_search_thumbnail(webpage),
'subtitles': subtitles, 'subtitles': subtitles,
} }