[extractor/rai] Rewrite extractors (#5940)

Authored by: nixxo, danog
Closes #5672, closes #6341

Co-authored-by: Daniil Gentili <daniil@daniil.it>
This commit is contained in:
nixxo 2023-05-29 06:20:03 +02:00 committed by GitHub
parent aed945e1b9
commit c6d3f81a40
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 271 additions and 307 deletions

View File

@ -1548,6 +1548,8 @@
RadLiveSeasonIE, RadLiveSeasonIE,
) )
from .rai import ( from .rai import (
RaiIE,
RaiCulturaIE,
RaiPlayIE, RaiPlayIE,
RaiPlayLiveIE, RaiPlayLiveIE,
RaiPlayPlaylistIE, RaiPlayPlaylistIE,
@ -1556,7 +1558,6 @@
RaiPlaySoundPlaylistIE, RaiPlaySoundPlaylistIE,
RaiNewsIE, RaiNewsIE,
RaiSudtirolIE, RaiSudtirolIE,
RaiIE,
) )
from .raywenderlich import ( from .raywenderlich import (
RayWenderlichIE, RayWenderlichIE,

View File

@ -1,19 +1,12 @@
import re import re
from .common import InfoExtractor from .common import InfoExtractor
from ..compat import (
compat_str,
compat_urlparse,
)
from ..utils import ( from ..utils import (
clean_html, clean_html,
determine_ext, determine_ext,
ExtractorError, ExtractorError,
filter_dict, filter_dict,
find_xpath_attr,
fix_xml_ampersands,
GeoRestrictedError, GeoRestrictedError,
HEADRequest,
int_or_none, int_or_none,
join_nonempty, join_nonempty,
parse_duration, parse_duration,
@ -35,82 +28,70 @@ class RaiBaseIE(InfoExtractor):
_GEO_BYPASS = False _GEO_BYPASS = False
def _extract_relinker_info(self, relinker_url, video_id, audio_only=False): def _extract_relinker_info(self, relinker_url, video_id, audio_only=False):
def fix_cdata(s):
# remove \r\n\t before and after <![CDATA[ ]]> to avoid
# polluted text with xpath_text
s = re.sub(r'(\]\]>)[\r\n\t]+(</)', '\\1\\2', s)
return re.sub(r'(>)[\r\n\t]+(<!\[CDATA\[)', '\\1\\2', s)
if not re.match(r'https?://', relinker_url): if not re.match(r'https?://', relinker_url):
return {'formats': [{'url': relinker_url}]} return {'formats': [{'url': relinker_url}]}
formats = [] # set User-Agent to generic 'Rai' to avoid quality filtering from
geoprotection = None # the media server and get the maximum qualities available
is_live = None
duration = None
for platform in ('mon', 'flash', 'native'):
relinker = self._download_xml( relinker = self._download_xml(
relinker_url, video_id, relinker_url, video_id, note='Downloading XML metadata',
note=f'Downloading XML metadata for platform {platform}', transform_source=fix_cdata, query={'output': 64},
transform_source=fix_xml_ampersands, headers={**self.geo_verification_headers(), 'User-Agent': 'Rai'})
query={'output': 45, 'pl': platform},
headers=self.geo_verification_headers())
if xpath_text(relinker, './license_url', default='{}') != '{}': if xpath_text(relinker, './license_url', default='{}') != '{}':
self.report_drm(video_id) self.report_drm(video_id)
if not geoprotection: is_live = xpath_text(relinker, './is_live', default='N') == 'Y'
geoprotection = xpath_text( duration = parse_duration(xpath_text(relinker, './duration', default=None))
relinker, './geoprotection', default=None) == 'Y' media_url = xpath_text(relinker, './url[@type="content"]', default=None)
if not is_live: if not media_url:
is_live = xpath_text( self.raise_no_formats('The relinker returned no media url')
relinker, './is_live', default=None) == 'Y'
if not duration:
duration = parse_duration(xpath_text(
relinker, './duration', default=None))
url_elem = find_xpath_attr(relinker, './url', 'type', 'content') # geo flag is a bit unreliable and not properly set all the time
if url_elem is None: geoprotection = xpath_text(relinker, './geoprotection', default='N') == 'Y'
continue
media_url = url_elem.text
# This does not imply geo restriction (e.g.
# http://www.raisport.rai.it/dl/raiSport/media/rassegna-stampa-04a9f4bd-b563-40cf-82a6-aad3529cb4a9.html)
if '/video_no_available.mp4' in media_url:
continue
ext = determine_ext(media_url) ext = determine_ext(media_url)
if (ext == 'm3u8' and platform != 'mon') or (ext == 'f4m' and platform != 'flash'): formats = []
continue
if ext == 'mp3': if ext == 'mp3':
formats.append({ formats.append({
'url': media_url, 'url': media_url,
'vcodec': 'none', 'vcodec': 'none',
'acodec': 'mp3', 'acodec': 'mp3',
'format_id': 'http-mp3', 'format_id': 'https-mp3',
}) })
break elif ext == 'm3u8' or 'format=m3u8' in media_url:
elif ext == 'm3u8' or 'format=m3u8' in media_url or platform == 'mon':
formats.extend(self._extract_m3u8_formats( formats.extend(self._extract_m3u8_formats(
media_url, video_id, 'mp4', 'm3u8_native', media_url, video_id, 'mp4', m3u8_id='hls', fatal=False))
m3u8_id='hls', fatal=False)) elif ext == 'f4m':
elif ext == 'f4m' or platform == 'flash': # very likely no longer needed. Cannot find any url that uses it.
manifest_url = update_url_query( manifest_url = update_url_query(
media_url.replace('manifest#live_hds.f4m', 'manifest.f4m'), media_url.replace('manifest#live_hds.f4m', 'manifest.f4m'),
{'hdcore': '3.7.0', 'plugin': 'aasp-3.7.0.39.44'}) {'hdcore': '3.7.0', 'plugin': 'aasp-3.7.0.39.44'})
formats.extend(self._extract_f4m_formats( formats.extend(self._extract_f4m_formats(
manifest_url, video_id, f4m_id='hds', fatal=False)) manifest_url, video_id, f4m_id='hds', fatal=False))
else: elif ext == 'mp4':
bitrate = int_or_none(xpath_text(relinker, 'bitrate')) bitrate = int_or_none(xpath_text(relinker, './bitrate'))
formats.append({ formats.append({
'url': media_url, 'url': media_url,
'tbr': bitrate if bitrate > 0 else None, 'tbr': bitrate if bitrate > 0 else None,
'format_id': f'http-{bitrate if bitrate > 0 else "http"}', 'format_id': join_nonempty('https', bitrate, delim='-'),
}) })
else:
raise ExtractorError('Unrecognized media file found')
if not formats and geoprotection is True: if (not formats and geoprotection is True) or '/video_no_available.mp4' in media_url:
self.raise_geo_restricted(countries=self._GEO_COUNTRIES, metadata_available=True) self.raise_geo_restricted(countries=self._GEO_COUNTRIES, metadata_available=True)
if not audio_only: if not audio_only and not is_live:
formats.extend(self._create_http_urls(relinker_url, formats)) formats.extend(self._create_http_urls(media_url, relinker_url, formats))
return filter_dict({ return filter_dict({
'is_live': is_live, 'is_live': is_live,
@ -118,38 +99,31 @@ def _extract_relinker_info(self, relinker_url, video_id, audio_only=False):
'formats': formats, 'formats': formats,
}) })
def _create_http_urls(self, relinker_url, fmts): def _create_http_urls(self, manifest_url, relinker_url, fmts):
_RELINKER_REG = r'https?://(?P<host>[^/]+?)/(?:i/)?(?P<extra>[^/]+?)/(?P<path>.+?)/(?P<id>\w+)(?:_(?P<quality>[\d\,]+))?(?:\.mp4|/playlist\.m3u8).+?' _MANIFEST_REG = r'/(?P<id>\w+)(?:_(?P<quality>[\d\,]+))?(?:\.mp4)?(?:\.csmil)?/playlist\.m3u8'
_MP4_TMPL = '%s&overrideUserAgentRule=mp4-%s' _MP4_TMPL = '%s&overrideUserAgentRule=mp4-%s'
_QUALITY = { _QUALITY = {
# tbr: w, h # tbr: w, h
'250': [352, 198], 250: [352, 198],
'400': [512, 288], 400: [512, 288],
'700': [512, 288], 600: [512, 288],
'800': [700, 394], 700: [512, 288],
'1200': [736, 414], 800: [700, 394],
'1800': [1024, 576], 1200: [736, 414],
'2400': [1280, 720], 1500: [920, 518],
'3200': [1440, 810], 1800: [1024, 576],
'3600': [1440, 810], 2400: [1280, 720],
'5000': [1920, 1080], 3200: [1440, 810],
'10000': [1920, 1080], 3600: [1440, 810],
5000: [1920, 1080],
10000: [1920, 1080],
} }
def test_url(url): def percentage(number, target, pc=20, roof=125):
resp = self._request_webpage( '''check if the target is in the range of number +/- percent'''
HEADRequest(url), None, headers={'User-Agent': 'Rai'}, if not number or number < 0:
fatal=False, errnote=False, note=False)
if resp is False:
return False return False
return abs(target - number) < min(float(number) * float(pc) / 100.0, roof)
if resp.code == 200:
return False if resp.url == url else resp.url
return None
# filter out audio-only formats
fmts = [f for f in fmts if not f.get('vcodec') == 'none']
def get_format_info(tbr): def get_format_info(tbr):
import math import math
@ -157,67 +131,78 @@ def get_format_info(tbr):
if len(fmts) == 1 and not br: if len(fmts) == 1 and not br:
br = fmts[0].get('tbr') br = fmts[0].get('tbr')
if br and br > 300: if br and br > 300:
tbr = compat_str(math.floor(br / 100) * 100) tbr = math.floor(br / 100) * 100
else: else:
tbr = '250' tbr = 250
# try extracting info from available m3u8 formats # try extracting info from available m3u8 formats
format_copy = None format_copy = [None, None]
for f in fmts: for f in fmts:
if f.get('tbr'): if f.get('tbr'):
br_limit = math.floor(br / 100) if percentage(tbr, f['tbr']):
if br_limit - 1 <= math.floor(f['tbr'] / 100) <= br_limit + 1: format_copy[0] = f.copy()
format_copy = f.copy() if [f.get('width'), f.get('height')] == _QUALITY.get(tbr):
format_copy[1] = f.copy()
format_copy[1]['tbr'] = tbr
# prefer format with similar bitrate because there might be
# multiple video with the same resolution but different bitrate
format_copy = format_copy[0] or format_copy[1] or {}
return { return {
'format_id': f'https-{tbr}',
'width': format_copy.get('width'), 'width': format_copy.get('width'),
'height': format_copy.get('height'), 'height': format_copy.get('height'),
'tbr': format_copy.get('tbr'), 'tbr': format_copy.get('tbr'),
'vcodec': format_copy.get('vcodec'), 'vcodec': format_copy.get('vcodec'),
'acodec': format_copy.get('acodec'), 'acodec': format_copy.get('acodec'),
'fps': format_copy.get('fps'), 'fps': format_copy.get('fps'),
'format_id': f'https-{tbr}',
} if format_copy else { } if format_copy else {
'format_id': f'https-{tbr}',
'width': _QUALITY[tbr][0], 'width': _QUALITY[tbr][0],
'height': _QUALITY[tbr][1], 'height': _QUALITY[tbr][1],
'format_id': f'https-{tbr}', 'tbr': tbr,
'tbr': int(tbr), 'vcodec': 'avc1',
'acodec': 'mp4a',
'fps': 25,
} }
loc = test_url(_MP4_TMPL % (relinker_url, '*')) # filter out single-stream formats
if not isinstance(loc, compat_str): fmts = [f for f in fmts
return [] if not f.get('vcodec') == 'none' and not f.get('acodec') == 'none']
mobj = re.match( mobj = re.search(_MANIFEST_REG, manifest_url)
_RELINKER_REG,
test_url(relinker_url) or '')
if not mobj: if not mobj:
return [] return []
available_qualities = mobj.group('quality').split(',') if mobj.group('quality') else ['*'] available_qualities = mobj.group('quality').split(',') if mobj.group('quality') else ['*']
available_qualities = [i for i in available_qualities if i]
formats = [] formats = []
for q in available_qualities: for q in filter(None, available_qualities):
fmt = { self.write_debug(f'Creating https format for quality {q}')
formats.append({
'url': _MP4_TMPL % (relinker_url, q), 'url': _MP4_TMPL % (relinker_url, q),
'protocol': 'https', 'protocol': 'https',
'ext': 'mp4', 'ext': 'mp4',
**get_format_info(q) **get_format_info(q)
} })
formats.append(fmt)
return formats return formats
@staticmethod
def _get_thumbnails_list(thumbs, url):
return [{
'url': urljoin(url, thumb_url),
} for thumb_url in (thumbs or {}).values() if thumb_url]
@staticmethod @staticmethod
def _extract_subtitles(url, video_data): def _extract_subtitles(url, video_data):
STL_EXT = 'stl' STL_EXT = 'stl'
SRT_EXT = 'srt' SRT_EXT = 'srt'
subtitles = {} subtitles = {}
subtitles_array = video_data.get('subtitlesArray') or [] subtitles_array = video_data.get('subtitlesArray') or video_data.get('subtitleList') or []
for k in ('subtitles', 'subtitlesUrl'): for k in ('subtitles', 'subtitlesUrl'):
subtitles_array.append({'url': video_data.get(k)}) subtitles_array.append({'url': video_data.get(k)})
for subtitle in subtitles_array: for subtitle in subtitles_array:
sub_url = subtitle.get('url') sub_url = subtitle.get('url')
if sub_url and isinstance(sub_url, compat_str): if sub_url and isinstance(sub_url, str):
sub_lang = subtitle.get('language') or 'it' sub_lang = subtitle.get('language') or 'it'
sub_url = urljoin(url, sub_url) sub_url = urljoin(url, sub_url)
sub_ext = determine_ext(sub_url, SRT_EXT) sub_ext = determine_ext(sub_url, SRT_EXT)
@ -236,7 +221,7 @@ def _extract_subtitles(url, video_data):
class RaiPlayIE(RaiBaseIE): class RaiPlayIE(RaiBaseIE):
_VALID_URL = rf'(?P<base>https?://(?:www\.)?raiplay\.it/.+?-(?P<id>{RaiBaseIE._UUID_RE}))\.(?:html|json)' _VALID_URL = rf'(?P<base>https?://(?:www\.)?raiplay\.it/.+?-(?P<id>{RaiBaseIE._UUID_RE}))\.(?:html|json)'
_TESTS = [{ _TESTS = [{
'url': 'http://www.raiplay.it/video/2014/04/Report-del-07042014-cb27157f-9dd0-4aee-b788-b1f67643a391.html', 'url': 'https://www.raiplay.it/video/2014/04/Report-del-07042014-cb27157f-9dd0-4aee-b788-b1f67643a391.html',
'md5': '8970abf8caf8aef4696e7b1f2adfc696', 'md5': '8970abf8caf8aef4696e7b1f2adfc696',
'info_dict': { 'info_dict': {
'id': 'cb27157f-9dd0-4aee-b788-b1f67643a391', 'id': 'cb27157f-9dd0-4aee-b788-b1f67643a391',
@ -244,22 +229,20 @@ class RaiPlayIE(RaiBaseIE):
'title': 'Report del 07/04/2014', 'title': 'Report del 07/04/2014',
'alt_title': 'St 2013/14 - Report - Espresso nel caffè - 07/04/2014', 'alt_title': 'St 2013/14 - Report - Espresso nel caffè - 07/04/2014',
'description': 'md5:d730c168a58f4bb35600fc2f881ec04e', 'description': 'md5:d730c168a58f4bb35600fc2f881ec04e',
'thumbnail': r're:^https?://.*\.jpg$', 'thumbnail': r're:^https?://www\.raiplay\.it/.+\.jpg',
'uploader': 'Rai Gulp', 'uploader': 'Rai 3',
'creator': 'Rai 3',
'duration': 6160, 'duration': 6160,
'series': 'Report', 'series': 'Report',
'season': '2013/14', 'season': '2013/14',
'subtitles': { 'subtitles': {'it': 'count:4'},
'it': 'count:4',
},
'release_year': 2022, 'release_year': 2022,
'episode': 'Espresso nel caffè - 07/04/2014', 'episode': 'Espresso nel caffè - 07/04/2014',
'timestamp': 1396919880, 'timestamp': 1396919880,
'upload_date': '20140408', 'upload_date': '20140408',
'formats': 'count:4',
}, },
'params': { 'params': {'skip_download': True},
'skip_download': True,
},
}, { }, {
# 1080p direct mp4 url # 1080p direct mp4 url
'url': 'https://www.raiplay.it/video/2021/11/Blanca-S1E1-Senza-occhi-b1255a4a-8e72-4a2f-b9f3-fc1308e00736.html', 'url': 'https://www.raiplay.it/video/2021/11/Blanca-S1E1-Senza-occhi-b1255a4a-8e72-4a2f-b9f3-fc1308e00736.html',
@ -270,8 +253,9 @@ class RaiPlayIE(RaiBaseIE):
'title': 'Blanca - S1E1 - Senza occhi', 'title': 'Blanca - S1E1 - Senza occhi',
'alt_title': 'St 1 Ep 1 - Blanca - Senza occhi', 'alt_title': 'St 1 Ep 1 - Blanca - Senza occhi',
'description': 'md5:75f95d5c030ec8bac263b1212322e28c', 'description': 'md5:75f95d5c030ec8bac263b1212322e28c',
'thumbnail': r're:^https?://.*\.jpg$', 'thumbnail': r're:^https://www\.raiplay\.it/dl/img/.+\.jpg',
'uploader': 'Rai 1', 'uploader': 'Rai Premium',
'creator': 'Rai Fiction',
'duration': 6493, 'duration': 6493,
'series': 'Blanca', 'series': 'Blanca',
'season': 'Season 1', 'season': 'Season 1',
@ -281,6 +265,30 @@ class RaiPlayIE(RaiBaseIE):
'episode': 'Senza occhi', 'episode': 'Senza occhi',
'timestamp': 1637318940, 'timestamp': 1637318940,
'upload_date': '20211119', 'upload_date': '20211119',
'formats': 'count:12',
},
'params': {'skip_download': True},
'expected_warnings': ['Video not available. Likely due to geo-restriction.']
}, {
# 1500 quality
'url': 'https://www.raiplay.it/video/2012/09/S1E11---Tutto-cio-che-luccica-0cab3323-732e-45d6-8e86-7704acab6598.html',
'md5': 'a634d20e8ab2d43724c273563f6bf87a',
'info_dict': {
'id': '0cab3323-732e-45d6-8e86-7704acab6598',
'ext': 'mp4',
'title': 'Mia and Me - S1E11 - Tutto ciò che luccica',
'alt_title': 'St 1 Ep 11 - Mia and Me - Tutto ciò che luccica',
'description': 'md5:4969e594184b1920c4c1f2b704da9dea',
'thumbnail': r're:^https?://.*\.jpg$',
'uploader': 'Rai Gulp',
'series': 'Mia and Me',
'season': 'Season 1',
'episode_number': 11,
'release_year': 2015,
'season_number': 1,
'episode': 'Tutto ciò che luccica',
'timestamp': 1348495020,
'upload_date': '20120924',
}, },
}, { }, {
'url': 'http://www.raiplay.it/video/2016/11/gazebotraindesi-efebe701-969c-4593-92f3-285f0d1ce750.html?', 'url': 'http://www.raiplay.it/video/2016/11/gazebotraindesi-efebe701-969c-4593-92f3-285f0d1ce750.html?',
@ -299,57 +307,40 @@ def _real_extract(self, url):
base, video_id = self._match_valid_url(url).groups() base, video_id = self._match_valid_url(url).groups()
media = self._download_json( media = self._download_json(
base + '.json', video_id, 'Downloading video JSON') f'{base}.json', video_id, 'Downloading video JSON')
if not self.get_param('allow_unplayable_formats'): if not self.get_param('allow_unplayable_formats'):
if try_get( if traverse_obj(media, (('program_info', None), 'rights_management', 'rights', 'drm')):
media,
(lambda x: x['rights_management']['rights']['drm'],
lambda x: x['program_info']['rights_management']['rights']['drm']),
dict):
self.report_drm(video_id) self.report_drm(video_id)
title = media['name']
video = media['video'] video = media['video']
relinker_info = self._extract_relinker_info(video['content_url'], video_id) relinker_info = self._extract_relinker_info(video['content_url'], video_id)
date_published = join_nonempty(
thumbnails = [] media.get('date_published'), media.get('time_published'), delim=' ')
for _, value in media.get('images', {}).items():
if value:
thumbnails.append({
'url': urljoin(url, value),
})
date_published = media.get('date_published')
time_published = media.get('time_published')
if date_published and time_published:
date_published += ' ' + time_published
subtitles = self._extract_subtitles(url, video)
program_info = media.get('program_info') or {}
season = media.get('season') season = media.get('season')
alt_title = join_nonempty(media.get('subtitle'), media.get('toptitle'), delim=' - ') alt_title = join_nonempty(media.get('subtitle'), media.get('toptitle'), delim=' - ')
return { return {
'id': remove_start(media.get('id'), 'ContentItem-') or video_id, 'id': remove_start(media.get('id'), 'ContentItem-') or video_id,
'display_id': video_id, 'display_id': video_id,
'title': title, 'title': media.get('name'),
'alt_title': strip_or_none(alt_title or None), 'alt_title': strip_or_none(alt_title or None),
'description': media.get('description'), 'description': media.get('description'),
'uploader': strip_or_none(media.get('channel') or None), 'uploader': strip_or_none(
'creator': strip_or_none(media.get('editor') or None), traverse_obj(media, ('program_info', 'channel'))
or media.get('channel') or None),
'creator': strip_or_none(
traverse_obj(media, ('program_info', 'editor'))
or media.get('editor') or None),
'duration': parse_duration(video.get('duration')), 'duration': parse_duration(video.get('duration')),
'timestamp': unified_timestamp(date_published), 'timestamp': unified_timestamp(date_published),
'thumbnails': thumbnails, 'thumbnails': self._get_thumbnails_list(media.get('images'), url),
'series': program_info.get('name'), 'series': traverse_obj(media, ('program_info', 'name')),
'season_number': int_or_none(season), 'season_number': int_or_none(season),
'season': season if (season and not season.isdigit()) else None, 'season': season if (season and not season.isdigit()) else None,
'episode': media.get('episode_title'), 'episode': media.get('episode_title'),
'episode_number': int_or_none(media.get('episode')), 'episode_number': int_or_none(media.get('episode')),
'subtitles': subtitles, 'subtitles': self._extract_subtitles(url, video),
'release_year': int_or_none(traverse_obj(media, ('track_info', 'edit_year'))), 'release_year': int_or_none(traverse_obj(media, ('track_info', 'edit_year'))),
**relinker_info **relinker_info
} }
@ -371,38 +362,39 @@ class RaiPlayLiveIE(RaiPlayIE): # XXX: Do not subclass from concrete IE
'live_status': 'is_live', 'live_status': 'is_live',
'upload_date': '20090502', 'upload_date': '20090502',
'timestamp': 1241276220, 'timestamp': 1241276220,
'formats': 'count:3',
}, },
'params': { 'params': {'skip_download': True},
'skip_download': True,
},
}] }]
class RaiPlayPlaylistIE(InfoExtractor): class RaiPlayPlaylistIE(InfoExtractor):
_VALID_URL = r'(?P<base>https?://(?:www\.)?raiplay\.it/programmi/(?P<id>[^/?#&]+))(?:/(?P<extra_id>[^?#&]+))?' _VALID_URL = r'(?P<base>https?://(?:www\.)?raiplay\.it/programmi/(?P<id>[^/?#&]+))(?:/(?P<extra_id>[^?#&]+))?'
_TESTS = [{ _TESTS = [{
# entire series episodes + extras...
'url': 'https://www.raiplay.it/programmi/nondirloalmiocapo/', 'url': 'https://www.raiplay.it/programmi/nondirloalmiocapo/',
'info_dict': { 'info_dict': {
'id': 'nondirloalmiocapo', 'id': 'nondirloalmiocapo',
'title': 'Non dirlo al mio capo', 'title': 'Non dirlo al mio capo',
'description': 'md5:98ab6b98f7f44c2843fd7d6f045f153b', 'description': 'md5:98ab6b98f7f44c2843fd7d6f045f153b',
}, },
'playlist_mincount': 12, 'playlist_mincount': 30,
}, { }, {
# single season
'url': 'https://www.raiplay.it/programmi/nondirloalmiocapo/episodi/stagione-2/', 'url': 'https://www.raiplay.it/programmi/nondirloalmiocapo/episodi/stagione-2/',
'info_dict': { 'info_dict': {
'id': 'nondirloalmiocapo', 'id': 'nondirloalmiocapo',
'title': 'Non dirlo al mio capo - Stagione 2', 'title': 'Non dirlo al mio capo - Stagione 2',
'description': 'md5:98ab6b98f7f44c2843fd7d6f045f153b', 'description': 'md5:98ab6b98f7f44c2843fd7d6f045f153b',
}, },
'playlist_mincount': 12, 'playlist_count': 12,
}] }]
def _real_extract(self, url): def _real_extract(self, url):
base, playlist_id, extra_id = self._match_valid_url(url).groups() base, playlist_id, extra_id = self._match_valid_url(url).groups()
program = self._download_json( program = self._download_json(
base + '.json', playlist_id, 'Downloading program JSON') f'{base}.json', playlist_id, 'Downloading program JSON')
if extra_id: if extra_id:
extra_id = extra_id.upper().rstrip('/') extra_id = extra_id.upper().rstrip('/')
@ -450,7 +442,7 @@ class RaiPlaySoundIE(RaiBaseIE):
'title': 'Il Ruggito del Coniglio del 10/12/2021', 'title': 'Il Ruggito del Coniglio del 10/12/2021',
'alt_title': 'md5:0e6476cd57858bb0f3fcc835d305b455', 'alt_title': 'md5:0e6476cd57858bb0f3fcc835d305b455',
'description': 'md5:2a17d2107e59a4a8faa0e18334139ee2', 'description': 'md5:2a17d2107e59a4a8faa0e18334139ee2',
'thumbnail': r're:^https?://.*\.jpg$', 'thumbnail': r're:^https?://.+\.jpg$',
'uploader': 'rai radio 2', 'uploader': 'rai radio 2',
'duration': 5685, 'duration': 5685,
'series': 'Il Ruggito del Coniglio', 'series': 'Il Ruggito del Coniglio',
@ -459,9 +451,7 @@ class RaiPlaySoundIE(RaiBaseIE):
'timestamp': 1638346620, 'timestamp': 1638346620,
'upload_date': '20211201', 'upload_date': '20211201',
}, },
'params': { 'params': {'skip_download': True},
'skip_download': True,
},
}] }]
def _real_extract(self, url): def _real_extract(self, url):
@ -480,9 +470,6 @@ def _real_extract(self, url):
lambda x: x['live']['create_date'])) lambda x: x['live']['create_date']))
podcast_info = traverse_obj(media, 'podcast_info', ('live', 'cards', 0)) or {} podcast_info = traverse_obj(media, 'podcast_info', ('live', 'cards', 0)) or {}
thumbnails = [{
'url': urljoin(url, thumb_url),
} for thumb_url in (podcast_info.get('images') or {}).values() if thumb_url]
return { return {
**info, **info,
@ -494,7 +481,7 @@ def _real_extract(self, url):
'uploader': traverse_obj(media, ('track_info', 'channel'), expected_type=strip_or_none), 'uploader': traverse_obj(media, ('track_info', 'channel'), expected_type=strip_or_none),
'creator': traverse_obj(media, ('track_info', 'editor'), expected_type=strip_or_none), 'creator': traverse_obj(media, ('track_info', 'editor'), expected_type=strip_or_none),
'timestamp': unified_timestamp(date_published), 'timestamp': unified_timestamp(date_published),
'thumbnails': thumbnails, 'thumbnails': self._get_thumbnails_list(podcast_info.get('images'), url),
'series': podcast_info.get('title'), 'series': podcast_info.get('title'),
'season_number': int_or_none(media.get('season')), 'season_number': int_or_none(media.get('season')),
'episode': media.get('episode_title'), 'episode': media.get('episode_title'),
@ -512,30 +499,30 @@ class RaiPlaySoundLiveIE(RaiPlaySoundIE): # XXX: Do not subclass from concrete
'display_id': 'radio2', 'display_id': 'radio2',
'ext': 'mp4', 'ext': 'mp4',
'title': r're:Rai Radio 2 \d+-\d+-\d+ \d+:\d+', 'title': r're:Rai Radio 2 \d+-\d+-\d+ \d+:\d+',
'thumbnail': r're:https://www.raiplaysound.it/dl/img/.+?png', 'thumbnail': r're:^https://www\.raiplaysound\.it/dl/img/.+\.png',
'uploader': 'rai radio 2', 'uploader': 'rai radio 2',
'series': 'Rai Radio 2', 'series': 'Rai Radio 2',
'creator': 'raiplaysound', 'creator': 'raiplaysound',
'is_live': True, 'is_live': True,
'live_status': 'is_live', 'live_status': 'is_live',
}, },
'params': { 'params': {'skip_download': True},
'skip_download': 'live',
},
}] }]
class RaiPlaySoundPlaylistIE(InfoExtractor): class RaiPlaySoundPlaylistIE(InfoExtractor):
_VALID_URL = r'(?P<base>https?://(?:www\.)?raiplaysound\.it/(?:programmi|playlist|audiolibri)/(?P<id>[^/?#&]+))(?:/(?P<extra_id>[^?#&]+))?' _VALID_URL = r'(?P<base>https?://(?:www\.)?raiplaysound\.it/(?:programmi|playlist|audiolibri)/(?P<id>[^/?#&]+))(?:/(?P<extra_id>[^?#&]+))?'
_TESTS = [{ _TESTS = [{
# entire show
'url': 'https://www.raiplaysound.it/programmi/ilruggitodelconiglio', 'url': 'https://www.raiplaysound.it/programmi/ilruggitodelconiglio',
'info_dict': { 'info_dict': {
'id': 'ilruggitodelconiglio', 'id': 'ilruggitodelconiglio',
'title': 'Il Ruggito del Coniglio', 'title': 'Il Ruggito del Coniglio',
'description': 'md5:1bbaf631245a7ab1ec4d9fbb3c7aa8f3', 'description': 'md5:48cff6972435964284614d70474132e6',
}, },
'playlist_mincount': 65, 'playlist_mincount': 65,
}, { }, {
# single season
'url': 'https://www.raiplaysound.it/programmi/ilruggitodelconiglio/puntate/prima-stagione-1995', 'url': 'https://www.raiplaysound.it/programmi/ilruggitodelconiglio/puntate/prima-stagione-1995',
'info_dict': { 'info_dict': {
'id': 'ilruggitodelconiglio_puntate_prima-stagione-1995', 'id': 'ilruggitodelconiglio_puntate_prima-stagione-1995',
@ -568,22 +555,19 @@ def _real_extract(self, url):
class RaiIE(RaiBaseIE): class RaiIE(RaiBaseIE):
_VALID_URL = rf'https?://[^/]+\.(?:rai\.(?:it|tv))/.+?-(?P<id>{RaiBaseIE._UUID_RE})(?:-.+?)?\.html' _VALID_URL = rf'https?://[^/]+\.(?:rai\.(?:it|tv))/.+?-(?P<id>{RaiBaseIE._UUID_RE})(?:-.+?)?\.html'
_TESTS = [{ _TESTS = [{
# var uniquename = "ContentItem-..."
# data-id="ContentItem-..."
'url': 'https://www.raisport.rai.it/dl/raiSport/media/rassegna-stampa-04a9f4bd-b563-40cf-82a6-aad3529cb4a9.html', 'url': 'https://www.raisport.rai.it/dl/raiSport/media/rassegna-stampa-04a9f4bd-b563-40cf-82a6-aad3529cb4a9.html',
'info_dict': { 'info_dict': {
'id': '04a9f4bd-b563-40cf-82a6-aad3529cb4a9', 'id': '04a9f4bd-b563-40cf-82a6-aad3529cb4a9',
'ext': 'mp4', 'ext': 'mp4',
'title': 'TG PRIMO TEMPO', 'title': 'TG PRIMO TEMPO',
'thumbnail': r're:^https?://.*\.jpg$', 'thumbnail': r're:^https?://.*\.jpg',
'duration': 1758, 'duration': 1758,
'upload_date': '20140612', 'upload_date': '20140612',
}, },
'skip': 'This content is available only in Italy', 'params': {'skip_download': True},
'expected_warnings': ['Video not available. Likely due to geo-restriction.']
}, { }, {
# with ContentItem in og:url
'url': 'https://www.rai.it/dl/RaiTV/programmi/media/ContentItem-efb17665-691c-45d5-a60c-5301333cbb0c.html', 'url': 'https://www.rai.it/dl/RaiTV/programmi/media/ContentItem-efb17665-691c-45d5-a60c-5301333cbb0c.html',
'md5': '06345bd97c932f19ffb129973d07a020',
'info_dict': { 'info_dict': {
'id': 'efb17665-691c-45d5-a60c-5301333cbb0c', 'id': 'efb17665-691c-45d5-a60c-5301333cbb0c',
'ext': 'mp4', 'ext': 'mp4',
@ -592,123 +576,51 @@ class RaiIE(RaiBaseIE):
'thumbnail': r're:^https?://.*\.jpg$', 'thumbnail': r're:^https?://.*\.jpg$',
'duration': 2214, 'duration': 2214,
'upload_date': '20161103' 'upload_date': '20161103'
} },
'params': {'skip_download': True},
}, { }, {
# Direct MMS URL # Direct MMS: Media URL no longer works.
'url': 'http://www.rai.it/dl/RaiTV/programmi/media/ContentItem-b63a4089-ac28-48cf-bca5-9f5b5bc46df5.html', 'url': 'http://www.rai.it/dl/RaiTV/programmi/media/ContentItem-b63a4089-ac28-48cf-bca5-9f5b5bc46df5.html',
'only_matching': True, 'only_matching': True,
}] }]
def _extract_from_content_id(self, content_id, url): def _real_extract(self, url):
content_id = self._match_id(url)
media = self._download_json( media = self._download_json(
f'https://www.rai.tv/dl/RaiTV/programmi/media/ContentItem-{content_id}.html?json', f'https://www.rai.tv/dl/RaiTV/programmi/media/ContentItem-{content_id}.html?json',
content_id, 'Downloading video JSON') content_id, 'Downloading video JSON', fatal=False, expected_status=404)
title = media['name'].strip() if media is None:
return None
media_type = media['type'] if 'Audio' in media['type']:
if 'Audio' in media_type:
relinker_info = { relinker_info = {
'formats': [{ 'formats': [{
'format_id': media.get('formatoAudio'), 'format_id': join_nonempty('https', media.get('formatoAudio'), delim='-'),
'url': media['audioUrl'], 'url': media['audioUrl'],
'ext': media.get('formatoAudio'), 'ext': media.get('formatoAudio'),
'vcodec': 'none',
'acodec': media.get('formatoAudio'),
}] }]
} }
elif 'Video' in media_type: elif 'Video' in media['type']:
relinker_info = self._extract_relinker_info(media['mediaUri'], content_id) relinker_info = self._extract_relinker_info(media['mediaUri'], content_id)
else: else:
raise ExtractorError('not a media file') raise ExtractorError('not a media file')
thumbnails = [] thumbnails = self._get_thumbnails_list(
for image_type in ('image', 'image_medium', 'image_300'): {image_type: media.get(image_type) for image_type in (
thumbnail_url = media.get(image_type) 'image', 'image_medium', 'image_300')}, url)
if thumbnail_url:
thumbnails.append({
'url': compat_urlparse.urljoin(url, thumbnail_url),
})
subtitles = self._extract_subtitles(url, media)
return { return {
'id': content_id, 'id': content_id,
'title': title, 'title': strip_or_none(media.get('name') or media.get('title')),
'description': strip_or_none(media.get('desc') or None), 'description': strip_or_none(media.get('desc')) or None,
'thumbnails': thumbnails, 'thumbnails': thumbnails,
'uploader': strip_or_none(media.get('author') or None), 'uploader': strip_or_none(media.get('author')) or None,
'upload_date': unified_strdate(media.get('date')), 'upload_date': unified_strdate(media.get('date')),
'duration': parse_duration(media.get('length')), 'duration': parse_duration(media.get('length')),
'subtitles': subtitles, 'subtitles': self._extract_subtitles(url, media),
**relinker_info
}
def _real_extract(self, url):
video_id = self._match_id(url)
webpage = self._download_webpage(url, video_id)
content_item_id = None
content_item_url = self._html_search_meta(
('og:url', 'og:video', 'og:video:secure_url', 'twitter:url',
'twitter:player', 'jsonlink'), webpage, default=None)
if content_item_url:
content_item_id = self._search_regex(
rf'ContentItem-({self._UUID_RE})', content_item_url,
'content item id', default=None)
if not content_item_id:
content_item_id = self._search_regex(
rf'''(?x)
(?:
(?:initEdizione|drawMediaRaiTV)\(|
<(?:[^>]+\bdata-id|var\s+uniquename)=|
<iframe[^>]+\bsrc=
)
(["\'])
(?:(?!\1).)*\bContentItem-(?P<id>{self._UUID_RE})
''',
webpage, 'content item id', default=None, group='id')
content_item_ids = set()
if content_item_id:
content_item_ids.add(content_item_id)
if video_id not in content_item_ids:
content_item_ids.add(video_id)
for content_item_id in content_item_ids:
try:
return self._extract_from_content_id(content_item_id, url)
except GeoRestrictedError:
raise
except ExtractorError:
pass
relinker_url = self._proto_relative_url(self._search_regex(
r'''(?x)
(?:
var\s+videoURL|
mediaInfo\.mediaUri
)\s*=\s*
([\'"])
(?P<url>
(?:https?:)?
//mediapolis(?:vod)?\.rai\.it/relinker/relinkerServlet\.htm\?
(?:(?!\1).)*\bcont=(?:(?!\1).)+)\1
''',
webpage, 'relinker URL', group='url'))
relinker_info = self._extract_relinker_info(
urljoin(url, relinker_url), video_id)
title = self._search_regex(
r'var\s+videoTitolo\s*=\s*([\'"])(?P<title>[^\'"]+)\1',
webpage, 'title', group='title',
default=None) or self._og_search_title(webpage)
return {
'id': video_id,
'title': title,
**relinker_info **relinker_info
} }
@ -726,7 +638,8 @@ class RaiNewsIE(RaiIE): # XXX: Do not subclass from concrete IE
'duration': 1589, 'duration': 1589,
'upload_date': '20220529', 'upload_date': '20220529',
'uploader': 'rainews', 'uploader': 'rainews',
} },
'params': {'skip_download': True},
}, { }, {
# old content with fallback method to extract media urls # old content with fallback method to extract media urls
'url': 'https://www.rainews.it/dl/rainews/media/Weekend-al-cinema-da-Hollywood-arriva-il-thriller-di-Tate-Taylor-La-ragazza-del-treno-1632c009-c843-4836-bb65-80c33084a64b.html', 'url': 'https://www.rainews.it/dl/rainews/media/Weekend-al-cinema-da-Hollywood-arriva-il-thriller-di-Tate-Taylor-La-ragazza-del-treno-1632c009-c843-4836-bb65-80c33084a64b.html',
@ -739,12 +652,14 @@ class RaiNewsIE(RaiIE): # XXX: Do not subclass from concrete IE
'duration': 833, 'duration': 833,
'upload_date': '20161103' 'upload_date': '20161103'
}, },
'params': {'skip_download': True},
'expected_warnings': ['unable to extract player_data'], 'expected_warnings': ['unable to extract player_data'],
}, { }, {
# iframe + drm # iframe + drm
'url': 'https://www.rainews.it/iframe/video/2022/07/euro2022-europei-calcio-femminile-italia-belgio-gol-0-1-video-4de06a69-de75-4e32-a657-02f0885f8118.html', 'url': 'https://www.rainews.it/iframe/video/2022/07/euro2022-europei-calcio-femminile-italia-belgio-gol-0-1-video-4de06a69-de75-4e32-a657-02f0885f8118.html',
'only_matching': True, 'only_matching': True,
}] }]
_PLAYER_TAG = 'news'
def _real_extract(self, url): def _real_extract(self, url):
video_id = self._match_id(url) video_id = self._match_id(url)
@ -752,8 +667,8 @@ def _real_extract(self, url):
webpage = self._download_webpage(url, video_id) webpage = self._download_webpage(url, video_id)
player_data = self._search_json( player_data = self._search_json(
r'<rainews-player\s*data=\'', webpage, 'player_data', video_id, rf'<rai{self._PLAYER_TAG}-player\s*data=\'', webpage, 'player_data', video_id,
transform_source=clean_html, fatal=False) transform_source=clean_html, default={})
track_info = player_data.get('track_info') track_info = player_data.get('track_info')
relinker_url = traverse_obj(player_data, 'mediapolis', 'content_url') relinker_url = traverse_obj(player_data, 'mediapolis', 'content_url')
@ -770,16 +685,36 @@ def _real_extract(self, url):
return { return {
'id': video_id, 'id': video_id,
'title': track_info.get('title') or self._og_search_title(webpage), 'title': player_data.get('title') or track_info.get('title') or self._og_search_title(webpage),
'upload_date': unified_strdate(track_info.get('date')), 'upload_date': unified_strdate(track_info.get('date')),
'uploader': strip_or_none(track_info.get('editor') or None), 'uploader': strip_or_none(track_info.get('editor') or None),
**relinker_info **relinker_info
} }
class RaiSudtirolIE(RaiBaseIE): class RaiCulturaIE(RaiNewsIE): # XXX: Do not subclass from concrete IE
_VALID_URL = r'https?://raisudtirol\.rai\.it/.+?media=(?P<id>[TP]tv\d+)' _VALID_URL = rf'https?://(www\.)?raicultura\.it/(?!articoli)[^?#]+-(?P<id>{RaiBaseIE._UUID_RE})(?:-[^/?#]+)?\.html'
_EMBED_REGEX = [rf'<iframe[^>]+data-src="(?P<url>/iframe/[^?#]+?{RaiBaseIE._UUID_RE}\.html)']
_TESTS = [{ _TESTS = [{
'url': 'https://www.raicultura.it/letteratura/articoli/2018/12/Alberto-Asor-Rosa-Letteratura-e-potere-05ba8775-82b5-45c5-a89d-dd955fbde1fb.html',
'info_dict': {
'id': '05ba8775-82b5-45c5-a89d-dd955fbde1fb',
'ext': 'mp4',
'title': 'Alberto Asor Rosa: Letteratura e potere',
'duration': 1756,
'upload_date': '20181206',
'uploader': 'raicultura',
'formats': 'count:2',
},
'params': {'skip_download': True},
}]
_PLAYER_TAG = 'cultura'
class RaiSudtirolIE(RaiBaseIE):
_VALID_URL = r'https?://raisudtirol\.rai\.it/.+media=(?P<id>\w+)'
_TESTS = [{
# mp4 file
'url': 'https://raisudtirol.rai.it/la/index.php?media=Ptv1619729460', 'url': 'https://raisudtirol.rai.it/la/index.php?media=Ptv1619729460',
'info_dict': { 'info_dict': {
'id': 'Ptv1619729460', 'id': 'Ptv1619729460',
@ -787,34 +722,62 @@ class RaiSudtirolIE(RaiBaseIE):
'title': 'Euro: trasmisciun d\'economia - 29-04-2021 20:51', 'title': 'Euro: trasmisciun d\'economia - 29-04-2021 20:51',
'series': 'Euro: trasmisciun d\'economia', 'series': 'Euro: trasmisciun d\'economia',
'upload_date': '20210429', 'upload_date': '20210429',
'thumbnail': r're:https://raisudtirol\.rai\.it/img/.+?\.jpg', 'thumbnail': r're:https://raisudtirol\.rai\.it/img/.+\.jpg',
'uploader': 'raisudtirol', 'uploader': 'raisudtirol',
} 'formats': 'count:1',
},
'params': {'skip_download': True},
}, {
# m3u manifest
'url': 'https://raisudtirol.rai.it/it/kidsplayer.php?lang=it&media=GUGGUG_P1.smil',
'info_dict': {
'id': 'GUGGUG_P1',
'ext': 'mp4',
'title': 'GUGGUG! La Prospettiva - Die Perspektive',
'uploader': 'raisudtirol',
'formats': 'count:6',
},
'params': {'skip_download': True},
}] }]
def _real_extract(self, url): def _real_extract(self, url):
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)
video_date = self._html_search_regex(r'<span class="med_data">(.+?)</span>', webpage, 'video_date', fatal=False) video_date = self._html_search_regex(
video_title = self._html_search_regex(r'<span class="med_title">(.+?)</span>', webpage, 'video_title', fatal=False) r'<span class="med_data">(.+?)</span>', webpage, 'video_date', default=None)
video_url = self._html_search_regex(r'sources:\s*\[\{file:\s*"(.+?)"\}\]', webpage, 'video_url') video_title = self._html_search_regex([
video_thumb = self._html_search_regex(r'image: \'(.+?)\'', webpage, 'video_thumb', fatal=False) r'<span class="med_title">(.+?)</span>', r'title: \'(.+?)\','],
webpage, 'video_title', default=None)
video_url = self._html_search_regex([
r'sources:\s*\[\{file:\s*"(.+?)"\}\]',
r'<source\s+src="(.+?)"\s+type="application/x-mpegURL"'],
webpage, 'video_url', default=None)
return { ext = determine_ext(video_url)
'id': video_id, if ext == 'm3u8':
'title': join_nonempty(video_title, video_date, delim=' - '), formats = self._extract_m3u8_formats(video_url, video_id)
'series': video_title, elif ext == 'mp4':
'upload_date': unified_strdate(video_date), formats = [{
'thumbnail': urljoin('https://raisudtirol.rai.it/', video_thumb),
'uploader': 'raisudtirol',
'formats': [{
'format_id': 'https-mp4', 'format_id': 'https-mp4',
'url': self._proto_relative_url(video_url), 'url': self._proto_relative_url(video_url),
'width': 1024, 'width': 1024,
'height': 576, 'height': 576,
'fps': 25, 'fps': 25,
'vcodec': 'h264', 'vcodec': 'avc1',
'acodec': 'aac', 'acodec': 'mp4a',
}], }]
else:
formats = []
self.raise_no_formats(f'Unrecognized media file: {video_url}')
return {
'id': video_id,
'title': join_nonempty(video_title, video_date, delim=' - '),
'series': video_title if video_date else None,
'upload_date': unified_strdate(video_date),
'thumbnail': urljoin('https://raisudtirol.rai.it/', self._html_search_regex(
r'image: \'(.+?)\'', webpage, 'video_thumb', default=None)),
'uploader': 'raisudtirol',
'formats': formats,
} }