rai.py 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816
  1. import re
  2. from .common import InfoExtractor
  3. from ..networking import HEADRequest
  4. from ..utils import (
  5. ExtractorError,
  6. GeoRestrictedError,
  7. clean_html,
  8. determine_ext,
  9. filter_dict,
  10. int_or_none,
  11. join_nonempty,
  12. parse_duration,
  13. remove_start,
  14. strip_or_none,
  15. traverse_obj,
  16. try_get,
  17. unified_strdate,
  18. unified_timestamp,
  19. update_url_query,
  20. urljoin,
  21. xpath_text,
  22. )
  23. class RaiBaseIE(InfoExtractor):
  24. _UUID_RE = r'[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}'
  25. _GEO_COUNTRIES = ['IT']
  26. _GEO_BYPASS = False
  27. def _fix_m3u8_formats(self, media_url, video_id):
  28. fmts = self._extract_m3u8_formats(
  29. media_url, video_id, 'mp4', m3u8_id='hls', fatal=False)
  30. # Fix malformed m3u8 manifests by setting audio-only/video-only formats
  31. for f in fmts:
  32. if not f.get('acodec'):
  33. f['acodec'] = 'mp4a'
  34. if not f.get('vcodec'):
  35. f['vcodec'] = 'avc1'
  36. man_url = f['url']
  37. if re.search(r'chunklist(?:_b\d+)*_ao[_.]', man_url): # audio only
  38. f['vcodec'] = 'none'
  39. elif re.search(r'chunklist(?:_b\d+)*_vo[_.]', man_url): # video only
  40. f['acodec'] = 'none'
  41. else: # video+audio
  42. if f['acodec'] == 'none':
  43. f['acodec'] = 'mp4a'
  44. if f['vcodec'] == 'none':
  45. f['vcodec'] = 'avc1'
  46. return fmts
  47. def _extract_relinker_info(self, relinker_url, video_id, audio_only=False):
  48. def fix_cdata(s):
  49. # remove \r\n\t before and after <![CDATA[ ]]> to avoid
  50. # polluted text with xpath_text
  51. s = re.sub(r'(\]\]>)[\r\n\t]+(</)', '\\1\\2', s)
  52. return re.sub(r'(>)[\r\n\t]+(<!\[CDATA\[)', '\\1\\2', s)
  53. if not re.match(r'https?://', relinker_url):
  54. return {'formats': [{'url': relinker_url}]}
  55. # set User-Agent to generic 'Rai' to avoid quality filtering from
  56. # the media server and get the maximum qualities available
  57. relinker = self._download_xml(
  58. relinker_url, video_id, note='Downloading XML metadata',
  59. transform_source=fix_cdata, query={'output': 64},
  60. headers={**self.geo_verification_headers(), 'User-Agent': 'Rai'})
  61. if xpath_text(relinker, './license_url', default='{}') != '{}':
  62. self.report_drm(video_id)
  63. is_live = xpath_text(relinker, './is_live', default='N') == 'Y'
  64. duration = parse_duration(xpath_text(relinker, './duration', default=None))
  65. media_url = xpath_text(relinker, './url[@type="content"]', default=None)
  66. if not media_url:
  67. self.raise_no_formats('The relinker returned no media url')
  68. # geo flag is a bit unreliable and not properly set all the time
  69. geoprotection = xpath_text(relinker, './geoprotection', default='N') == 'Y'
  70. ext = determine_ext(media_url)
  71. formats = []
  72. if ext == 'mp3':
  73. formats.append({
  74. 'url': media_url,
  75. 'vcodec': 'none',
  76. 'acodec': 'mp3',
  77. 'format_id': 'https-mp3',
  78. })
  79. elif ext == 'm3u8' or 'format=m3u8' in media_url:
  80. formats.extend(self._fix_m3u8_formats(media_url, video_id))
  81. elif ext == 'f4m':
  82. # very likely no longer needed. Cannot find any url that uses it.
  83. manifest_url = update_url_query(
  84. media_url.replace('manifest#live_hds.f4m', 'manifest.f4m'),
  85. {'hdcore': '3.7.0', 'plugin': 'aasp-3.7.0.39.44'})
  86. formats.extend(self._extract_f4m_formats(
  87. manifest_url, video_id, f4m_id='hds', fatal=False))
  88. elif ext == 'mp4':
  89. bitrate = int_or_none(xpath_text(relinker, './bitrate'))
  90. formats.append({
  91. 'url': media_url,
  92. 'tbr': bitrate if bitrate > 0 else None,
  93. 'format_id': join_nonempty('https', bitrate, delim='-'),
  94. })
  95. else:
  96. raise ExtractorError('Unrecognized media file found')
  97. if (not formats and geoprotection is True) or '/video_no_available.mp4' in media_url:
  98. self.raise_geo_restricted(countries=self._GEO_COUNTRIES, metadata_available=True)
  99. if not audio_only and not is_live:
  100. formats.extend(self._create_http_urls(media_url, relinker_url, formats, video_id))
  101. return filter_dict({
  102. 'is_live': is_live,
  103. 'duration': duration,
  104. 'formats': formats,
  105. })
  106. def _create_http_urls(self, manifest_url, relinker_url, fmts, video_id):
  107. _MANIFEST_REG = r'/(?P<id>\w+)(?:_(?P<quality>[\d\,]+))?(?:\.mp4)?(?:\.csmil)?/playlist\.m3u8'
  108. _MP4_TMPL = '%s&overrideUserAgentRule=mp4-%s'
  109. _QUALITY = {
  110. # tbr: w, h
  111. 250: [352, 198],
  112. 400: [512, 288],
  113. 600: [512, 288],
  114. 700: [512, 288],
  115. 800: [700, 394],
  116. 1200: [736, 414],
  117. 1500: [920, 518],
  118. 1800: [1024, 576],
  119. 2400: [1280, 720],
  120. 3200: [1440, 810],
  121. 3600: [1440, 810],
  122. 5000: [1920, 1080],
  123. 10000: [1920, 1080],
  124. }
  125. def percentage(number, target, pc=20, roof=125):
  126. """check if the target is in the range of number +/- percent"""
  127. if not number or number < 0:
  128. return False
  129. return abs(target - number) < min(float(number) * float(pc) / 100.0, roof)
  130. def get_format_info(tbr):
  131. import math
  132. br = int_or_none(tbr)
  133. if len(fmts) == 1 and not br:
  134. br = fmts[0].get('tbr')
  135. if br and br > 300:
  136. tbr = math.floor(br / 100) * 100
  137. else:
  138. tbr = 250
  139. # try extracting info from available m3u8 formats
  140. format_copy = [None, None]
  141. for f in fmts:
  142. if f.get('tbr'):
  143. if percentage(tbr, f['tbr']):
  144. format_copy[0] = f.copy()
  145. if [f.get('width'), f.get('height')] == _QUALITY.get(tbr):
  146. format_copy[1] = f.copy()
  147. format_copy[1]['tbr'] = tbr
  148. # prefer format with similar bitrate because there might be
  149. # multiple video with the same resolution but different bitrate
  150. format_copy = format_copy[0] or format_copy[1] or {}
  151. return {
  152. 'format_id': f'https-{tbr}',
  153. 'width': format_copy.get('width'),
  154. 'height': format_copy.get('height'),
  155. 'tbr': format_copy.get('tbr') or tbr,
  156. 'vcodec': format_copy.get('vcodec') or 'avc1',
  157. 'acodec': format_copy.get('acodec') or 'mp4a',
  158. 'fps': format_copy.get('fps') or 25,
  159. } if format_copy else {
  160. 'format_id': f'https-{tbr}',
  161. 'width': _QUALITY[tbr][0],
  162. 'height': _QUALITY[tbr][1],
  163. 'tbr': tbr,
  164. 'vcodec': 'avc1',
  165. 'acodec': 'mp4a',
  166. 'fps': 25,
  167. }
  168. # Check if MP4 download is available
  169. try:
  170. self._request_webpage(
  171. HEADRequest(_MP4_TMPL % (relinker_url, '*')), video_id, 'Checking MP4 availability')
  172. except ExtractorError as e:
  173. self.to_screen(f'{video_id}: MP4 direct download is not available: {e.cause}')
  174. return []
  175. # filter out single-stream formats
  176. fmts = [f for f in fmts
  177. if f.get('vcodec') != 'none' and f.get('acodec') != 'none']
  178. mobj = re.search(_MANIFEST_REG, manifest_url)
  179. if not mobj:
  180. return []
  181. available_qualities = mobj.group('quality').split(',') if mobj.group('quality') else ['*']
  182. formats = []
  183. for q in filter(None, available_qualities):
  184. self.write_debug(f'Creating https format for quality {q}')
  185. formats.append({
  186. 'url': _MP4_TMPL % (relinker_url, q),
  187. 'protocol': 'https',
  188. 'ext': 'mp4',
  189. **get_format_info(q),
  190. })
  191. return formats
  192. @staticmethod
  193. def _get_thumbnails_list(thumbs, url):
  194. return [{
  195. 'url': urljoin(url, thumb_url),
  196. } for thumb_url in (thumbs or {}).values() if thumb_url]
  197. @staticmethod
  198. def _extract_subtitles(url, video_data):
  199. STL_EXT = 'stl'
  200. SRT_EXT = 'srt'
  201. subtitles = {}
  202. subtitles_array = video_data.get('subtitlesArray') or video_data.get('subtitleList') or []
  203. for k in ('subtitles', 'subtitlesUrl'):
  204. subtitles_array.append({'url': video_data.get(k)})
  205. for subtitle in subtitles_array:
  206. sub_url = subtitle.get('url')
  207. if sub_url and isinstance(sub_url, str):
  208. sub_lang = subtitle.get('language') or 'it'
  209. sub_url = urljoin(url, sub_url)
  210. sub_ext = determine_ext(sub_url, SRT_EXT)
  211. subtitles.setdefault(sub_lang, []).append({
  212. 'ext': sub_ext,
  213. 'url': sub_url,
  214. })
  215. if STL_EXT == sub_ext:
  216. subtitles[sub_lang].append({
  217. 'ext': SRT_EXT,
  218. 'url': sub_url[:-len(STL_EXT)] + SRT_EXT,
  219. })
  220. return subtitles
  221. class RaiPlayIE(RaiBaseIE):
  222. _VALID_URL = rf'(?P<base>https?://(?:www\.)?raiplay\.it/.+?-(?P<id>{RaiBaseIE._UUID_RE}))\.(?:html|json)'
  223. _TESTS = [{
  224. 'url': 'https://www.raiplay.it/video/2014/04/Report-del-07042014-cb27157f-9dd0-4aee-b788-b1f67643a391.html',
  225. 'md5': '8970abf8caf8aef4696e7b1f2adfc696',
  226. 'info_dict': {
  227. 'id': 'cb27157f-9dd0-4aee-b788-b1f67643a391',
  228. 'ext': 'mp4',
  229. 'title': 'Report del 07/04/2014',
  230. 'alt_title': 'St 2013/14 - Report - Espresso nel caffè - 07/04/2014',
  231. 'description': 'md5:d730c168a58f4bb35600fc2f881ec04e',
  232. 'thumbnail': r're:^https?://www\.raiplay\.it/.+\.jpg',
  233. 'uploader': 'Rai 3',
  234. 'creator': 'Rai 3',
  235. 'duration': 6160,
  236. 'series': 'Report',
  237. 'season': '2013/14',
  238. 'subtitles': {'it': 'count:4'},
  239. 'release_year': 2024,
  240. 'episode': 'Espresso nel caffè - 07/04/2014',
  241. 'timestamp': 1396919880,
  242. 'upload_date': '20140408',
  243. 'formats': 'count:4',
  244. },
  245. 'params': {'skip_download': True},
  246. }, {
  247. # 1080p
  248. 'url': 'https://www.raiplay.it/video/2021/11/Blanca-S1E1-Senza-occhi-b1255a4a-8e72-4a2f-b9f3-fc1308e00736.html',
  249. 'md5': 'aeda7243115380b2dd5e881fd42d949a',
  250. 'info_dict': {
  251. 'id': 'b1255a4a-8e72-4a2f-b9f3-fc1308e00736',
  252. 'ext': 'mp4',
  253. 'title': 'Blanca - S1E1 - Senza occhi',
  254. 'alt_title': 'St 1 Ep 1 - Blanca - Senza occhi',
  255. 'description': 'md5:75f95d5c030ec8bac263b1212322e28c',
  256. 'thumbnail': r're:^https://www\.raiplay\.it/dl/img/.+\.jpg',
  257. 'uploader': 'Rai Premium',
  258. 'creator': 'Rai Fiction',
  259. 'duration': 6493,
  260. 'series': 'Blanca',
  261. 'season': 'Season 1',
  262. 'episode_number': 1,
  263. 'release_year': 2021,
  264. 'season_number': 1,
  265. 'episode': 'Senza occhi',
  266. 'timestamp': 1637318940,
  267. 'upload_date': '20211119',
  268. 'formats': 'count:7',
  269. },
  270. 'params': {'skip_download': True},
  271. 'expected_warnings': ['Video not available. Likely due to geo-restriction.'],
  272. }, {
  273. # 1500 quality
  274. 'url': 'https://www.raiplay.it/video/2012/09/S1E11---Tutto-cio-che-luccica-0cab3323-732e-45d6-8e86-7704acab6598.html',
  275. 'md5': 'a634d20e8ab2d43724c273563f6bf87a',
  276. 'info_dict': {
  277. 'id': '0cab3323-732e-45d6-8e86-7704acab6598',
  278. 'ext': 'mp4',
  279. 'title': 'Mia and Me - S1E11 - Tutto ciò che luccica',
  280. 'alt_title': 'St 1 Ep 11 - Mia and Me - Tutto ciò che luccica',
  281. 'description': 'md5:4969e594184b1920c4c1f2b704da9dea',
  282. 'thumbnail': r're:^https?://.*\.jpg$',
  283. 'uploader': 'Rai Gulp',
  284. 'series': 'Mia and Me',
  285. 'season': 'Season 1',
  286. 'episode_number': 11,
  287. 'release_year': 2015,
  288. 'season_number': 1,
  289. 'episode': 'Tutto ciò che luccica',
  290. 'timestamp': 1348495020,
  291. 'upload_date': '20120924',
  292. },
  293. }, {
  294. 'url': 'http://www.raiplay.it/video/2016/11/gazebotraindesi-efebe701-969c-4593-92f3-285f0d1ce750.html?',
  295. 'only_matching': True,
  296. }, {
  297. # subtitles at 'subtitlesArray' key (see #27698)
  298. 'url': 'https://www.raiplay.it/video/2020/12/Report---04-01-2021-2e90f1de-8eee-4de4-ac0e-78d21db5b600.html',
  299. 'only_matching': True,
  300. }, {
  301. # DRM protected
  302. 'url': 'https://www.raiplay.it/video/2021/06/Lo-straordinario-mondo-di-Zoey-S2E1-Lo-straordinario-ritorno-di-Zoey-3ba992de-2332-41ad-9214-73e32ab209f4.html',
  303. 'only_matching': True,
  304. }]
  305. def _real_extract(self, url):
  306. base, video_id = self._match_valid_url(url).groups()
  307. media = self._download_json(
  308. f'{base}.json', video_id, 'Downloading video JSON')
  309. if not self.get_param('allow_unplayable_formats'):
  310. if traverse_obj(media, (('program_info', None), 'rights_management', 'rights', 'drm')):
  311. self.report_drm(video_id)
  312. video = media['video']
  313. relinker_info = self._extract_relinker_info(video['content_url'], video_id)
  314. date_published = join_nonempty(
  315. media.get('date_published'), media.get('time_published'), delim=' ')
  316. season = media.get('season')
  317. alt_title = join_nonempty(media.get('subtitle'), media.get('toptitle'), delim=' - ')
  318. return {
  319. 'id': remove_start(media.get('id'), 'ContentItem-') or video_id,
  320. 'display_id': video_id,
  321. 'title': media.get('name'),
  322. 'alt_title': strip_or_none(alt_title or None),
  323. 'description': media.get('description'),
  324. 'uploader': strip_or_none(
  325. traverse_obj(media, ('program_info', 'channel'))
  326. or media.get('channel') or None),
  327. 'creator': strip_or_none(
  328. traverse_obj(media, ('program_info', 'editor'))
  329. or media.get('editor') or None),
  330. 'duration': parse_duration(video.get('duration')),
  331. 'timestamp': unified_timestamp(date_published),
  332. 'thumbnails': self._get_thumbnails_list(media.get('images'), url),
  333. 'series': traverse_obj(media, ('program_info', 'name')),
  334. 'season_number': int_or_none(season),
  335. 'season': season if (season and not season.isdigit()) else None,
  336. 'episode': media.get('episode_title'),
  337. 'episode_number': int_or_none(media.get('episode')),
  338. 'subtitles': self._extract_subtitles(url, video),
  339. 'release_year': int_or_none(traverse_obj(media, ('track_info', 'edit_year'))),
  340. **relinker_info,
  341. }
  342. class RaiPlayLiveIE(RaiPlayIE): # XXX: Do not subclass from concrete IE
  343. _VALID_URL = r'(?P<base>https?://(?:www\.)?raiplay\.it/dirette/(?P<id>[^/?#&]+))'
  344. _TESTS = [{
  345. 'url': 'http://www.raiplay.it/dirette/rainews24',
  346. 'info_dict': {
  347. 'id': 'd784ad40-e0ae-4a69-aa76-37519d238a9c',
  348. 'display_id': 'rainews24',
  349. 'ext': 'mp4',
  350. 'title': 're:^Diretta di Rai News 24 [0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}$',
  351. 'description': 'md5:4d00bcf6dc98b27c6ec480de329d1497',
  352. 'uploader': 'Rai News 24',
  353. 'creator': 'Rai News 24',
  354. 'is_live': True,
  355. 'live_status': 'is_live',
  356. 'upload_date': '20090502',
  357. 'timestamp': 1241276220,
  358. 'formats': 'count:3',
  359. },
  360. 'params': {'skip_download': True},
  361. }]
  362. class RaiPlayPlaylistIE(InfoExtractor):
  363. _VALID_URL = r'(?P<base>https?://(?:www\.)?raiplay\.it/programmi/(?P<id>[^/?#&]+))(?:/(?P<extra_id>[^?#&]+))?'
  364. _TESTS = [{
  365. # entire series episodes + extras...
  366. 'url': 'https://www.raiplay.it/programmi/nondirloalmiocapo/',
  367. 'info_dict': {
  368. 'id': 'nondirloalmiocapo',
  369. 'title': 'Non dirlo al mio capo',
  370. 'description': 'md5:98ab6b98f7f44c2843fd7d6f045f153b',
  371. },
  372. 'playlist_mincount': 30,
  373. }, {
  374. # single season
  375. 'url': 'https://www.raiplay.it/programmi/nondirloalmiocapo/episodi/stagione-2/',
  376. 'info_dict': {
  377. 'id': 'nondirloalmiocapo',
  378. 'title': 'Non dirlo al mio capo - Stagione 2',
  379. 'description': 'md5:98ab6b98f7f44c2843fd7d6f045f153b',
  380. },
  381. 'playlist_count': 12,
  382. }]
  383. def _real_extract(self, url):
  384. base, playlist_id, extra_id = self._match_valid_url(url).groups()
  385. program = self._download_json(
  386. f'{base}.json', playlist_id, 'Downloading program JSON')
  387. if extra_id:
  388. extra_id = extra_id.upper().rstrip('/')
  389. playlist_title = program.get('name')
  390. entries = []
  391. for b in (program.get('blocks') or []):
  392. for s in (b.get('sets') or []):
  393. if extra_id:
  394. if extra_id != join_nonempty(
  395. b.get('name'), s.get('name'), delim='/').replace(' ', '-').upper():
  396. continue
  397. playlist_title = join_nonempty(playlist_title, s.get('name'), delim=' - ')
  398. s_id = s.get('id')
  399. if not s_id:
  400. continue
  401. medias = self._download_json(
  402. f'{base}/{s_id}.json', s_id,
  403. 'Downloading content set JSON', fatal=False)
  404. if not medias:
  405. continue
  406. for m in (medias.get('items') or []):
  407. path_id = m.get('path_id')
  408. if not path_id:
  409. continue
  410. video_url = urljoin(url, path_id)
  411. entries.append(self.url_result(
  412. video_url, ie=RaiPlayIE.ie_key(),
  413. video_id=RaiPlayIE._match_id(video_url)))
  414. return self.playlist_result(
  415. entries, playlist_id, playlist_title,
  416. try_get(program, lambda x: x['program_info']['description']))
  417. class RaiPlaySoundIE(RaiBaseIE):
  418. _VALID_URL = rf'(?P<base>https?://(?:www\.)?raiplaysound\.it/.+?-(?P<id>{RaiBaseIE._UUID_RE}))\.(?:html|json)'
  419. _TESTS = [{
  420. 'url': 'https://www.raiplaysound.it/audio/2021/12/IL-RUGGITO-DEL-CONIGLIO-1ebae2a7-7cdb-42bb-842e-fe0d193e9707.html',
  421. 'md5': '8970abf8caf8aef4696e7b1f2adfc696',
  422. 'info_dict': {
  423. 'id': '1ebae2a7-7cdb-42bb-842e-fe0d193e9707',
  424. 'ext': 'mp3',
  425. 'title': 'Il Ruggito del Coniglio del 10/12/2021',
  426. 'alt_title': 'md5:0e6476cd57858bb0f3fcc835d305b455',
  427. 'description': 'md5:2a17d2107e59a4a8faa0e18334139ee2',
  428. 'thumbnail': r're:^https?://.+\.jpg$',
  429. 'uploader': 'rai radio 2',
  430. 'duration': 5685,
  431. 'series': 'Il Ruggito del Coniglio',
  432. 'episode': 'Il Ruggito del Coniglio del 10/12/2021',
  433. 'creator': 'rai radio 2',
  434. 'timestamp': 1638346620,
  435. 'upload_date': '20211201',
  436. },
  437. 'params': {'skip_download': True},
  438. }]
  439. def _real_extract(self, url):
  440. base, audio_id = self._match_valid_url(url).group('base', 'id')
  441. media = self._download_json(f'{base}.json', audio_id, 'Downloading audio JSON')
  442. uid = try_get(media, lambda x: remove_start(remove_start(x['uniquename'], 'ContentItem-'), 'Page-'))
  443. info = {}
  444. formats = []
  445. relinkers = set(traverse_obj(media, (('downloadable_audio', 'audio', ('live', 'cards', 0, 'audio')), 'url')))
  446. for r in relinkers:
  447. info = self._extract_relinker_info(r, audio_id, True)
  448. formats.extend(info.get('formats'))
  449. date_published = try_get(media, (lambda x: f'{x["create_date"]} {x.get("create_time") or ""}',
  450. lambda x: x['live']['create_date']))
  451. podcast_info = traverse_obj(media, 'podcast_info', ('live', 'cards', 0)) or {}
  452. return {
  453. **info,
  454. 'id': uid or audio_id,
  455. 'display_id': audio_id,
  456. 'title': traverse_obj(media, 'title', 'episode_title'),
  457. 'alt_title': traverse_obj(media, ('track_info', 'media_name'), expected_type=strip_or_none),
  458. 'description': media.get('description'),
  459. 'uploader': traverse_obj(media, ('track_info', 'channel'), expected_type=strip_or_none),
  460. 'creator': traverse_obj(media, ('track_info', 'editor'), expected_type=strip_or_none),
  461. 'timestamp': unified_timestamp(date_published),
  462. 'thumbnails': self._get_thumbnails_list(podcast_info.get('images'), url),
  463. 'series': podcast_info.get('title'),
  464. 'season_number': int_or_none(media.get('season')),
  465. 'episode': media.get('episode_title'),
  466. 'episode_number': int_or_none(media.get('episode')),
  467. 'formats': formats,
  468. }
  469. class RaiPlaySoundLiveIE(RaiPlaySoundIE): # XXX: Do not subclass from concrete IE
  470. _VALID_URL = r'(?P<base>https?://(?:www\.)?raiplaysound\.it/(?P<id>[^/?#&]+)$)'
  471. _TESTS = [{
  472. 'url': 'https://www.raiplaysound.it/radio2',
  473. 'info_dict': {
  474. 'id': 'b00a50e6-f404-4af6-8f8c-ff3b9af73a44',
  475. 'display_id': 'radio2',
  476. 'ext': 'mp4',
  477. 'title': r're:Rai Radio 2 \d+-\d+-\d+ \d+:\d+',
  478. 'thumbnail': r're:^https://www\.raiplaysound\.it/dl/img/.+\.png',
  479. 'uploader': 'rai radio 2',
  480. 'series': 'Rai Radio 2',
  481. 'creator': 'raiplaysound',
  482. 'is_live': True,
  483. 'live_status': 'is_live',
  484. },
  485. 'params': {'skip_download': True},
  486. }]
  487. class RaiPlaySoundPlaylistIE(InfoExtractor):
  488. _VALID_URL = r'(?P<base>https?://(?:www\.)?raiplaysound\.it/(?:programmi|playlist|audiolibri)/(?P<id>[^/?#&]+))(?:/(?P<extra_id>[^?#&]+))?'
  489. _TESTS = [{
  490. # entire show
  491. 'url': 'https://www.raiplaysound.it/programmi/ilruggitodelconiglio',
  492. 'info_dict': {
  493. 'id': 'ilruggitodelconiglio',
  494. 'title': 'Il Ruggito del Coniglio',
  495. 'description': 'md5:62a627b3a2d0635d08fa8b6e0a04f27e',
  496. },
  497. 'playlist_mincount': 65,
  498. }, {
  499. # single season
  500. 'url': 'https://www.raiplaysound.it/programmi/ilruggitodelconiglio/puntate/prima-stagione-1995',
  501. 'info_dict': {
  502. 'id': 'ilruggitodelconiglio_puntate_prima-stagione-1995',
  503. 'title': 'Prima Stagione 1995',
  504. },
  505. 'playlist_count': 1,
  506. }]
  507. def _real_extract(self, url):
  508. base, playlist_id, extra_id = self._match_valid_url(url).group('base', 'id', 'extra_id')
  509. url = f'{base}.json'
  510. program = self._download_json(url, playlist_id, 'Downloading program JSON')
  511. if extra_id:
  512. extra_id = extra_id.rstrip('/')
  513. playlist_id += '_' + extra_id.replace('/', '_')
  514. path = next(c['path_id'] for c in program.get('filters') or [] if extra_id in c.get('weblink'))
  515. program = self._download_json(
  516. urljoin('https://www.raiplaysound.it', path), playlist_id, 'Downloading program secondary JSON')
  517. entries = [
  518. self.url_result(urljoin(base, c['path_id']), ie=RaiPlaySoundIE.ie_key())
  519. for c in traverse_obj(program, 'cards', ('block', 'cards')) or []
  520. if c.get('path_id')]
  521. return self.playlist_result(entries, playlist_id, program.get('title'),
  522. traverse_obj(program, ('podcast_info', 'description')))
  523. class RaiIE(RaiBaseIE):
  524. _VALID_URL = rf'https?://[^/]+\.(?:rai\.(?:it|tv))/.+?-(?P<id>{RaiBaseIE._UUID_RE})(?:-.+?)?\.html'
  525. _TESTS = [{
  526. 'url': 'https://www.raisport.rai.it/dl/raiSport/media/rassegna-stampa-04a9f4bd-b563-40cf-82a6-aad3529cb4a9.html',
  527. 'info_dict': {
  528. 'id': '04a9f4bd-b563-40cf-82a6-aad3529cb4a9',
  529. 'ext': 'mp4',
  530. 'title': 'TG PRIMO TEMPO',
  531. 'thumbnail': r're:^https?://.*\.jpg',
  532. 'duration': 1758,
  533. 'upload_date': '20140612',
  534. },
  535. 'params': {'skip_download': True},
  536. 'expected_warnings': ['Video not available. Likely due to geo-restriction.'],
  537. }, {
  538. 'url': 'https://www.rai.it/dl/RaiTV/programmi/media/ContentItem-efb17665-691c-45d5-a60c-5301333cbb0c.html',
  539. 'info_dict': {
  540. 'id': 'efb17665-691c-45d5-a60c-5301333cbb0c',
  541. 'ext': 'mp4',
  542. 'title': 'TG1 ore 20:00 del 03/11/2016',
  543. 'description': 'TG1 edizione integrale ore 20:00 del giorno 03/11/2016',
  544. 'thumbnail': r're:^https?://.*\.jpg$',
  545. 'duration': 2214,
  546. 'upload_date': '20161103',
  547. },
  548. 'params': {'skip_download': True},
  549. }, {
  550. # Direct MMS: Media URL no longer works.
  551. 'url': 'http://www.rai.it/dl/RaiTV/programmi/media/ContentItem-b63a4089-ac28-48cf-bca5-9f5b5bc46df5.html',
  552. 'only_matching': True,
  553. }]
  554. def _real_extract(self, url):
  555. content_id = self._match_id(url)
  556. media = self._download_json(
  557. f'https://www.rai.tv/dl/RaiTV/programmi/media/ContentItem-{content_id}.html?json',
  558. content_id, 'Downloading video JSON', fatal=False, expected_status=404)
  559. if media is None:
  560. return None
  561. if 'Audio' in media['type']:
  562. relinker_info = {
  563. 'formats': [{
  564. 'format_id': join_nonempty('https', media.get('formatoAudio'), delim='-'),
  565. 'url': media['audioUrl'],
  566. 'ext': media.get('formatoAudio'),
  567. 'vcodec': 'none',
  568. 'acodec': media.get('formatoAudio'),
  569. }],
  570. }
  571. elif 'Video' in media['type']:
  572. relinker_info = self._extract_relinker_info(media['mediaUri'], content_id)
  573. else:
  574. raise ExtractorError('not a media file')
  575. thumbnails = self._get_thumbnails_list(
  576. {image_type: media.get(image_type) for image_type in (
  577. 'image', 'image_medium', 'image_300')}, url)
  578. return {
  579. 'id': content_id,
  580. 'title': strip_or_none(media.get('name') or media.get('title')),
  581. 'description': strip_or_none(media.get('desc')) or None,
  582. 'thumbnails': thumbnails,
  583. 'uploader': strip_or_none(media.get('author')) or None,
  584. 'upload_date': unified_strdate(media.get('date')),
  585. 'duration': parse_duration(media.get('length')),
  586. 'subtitles': self._extract_subtitles(url, media),
  587. **relinker_info,
  588. }
  589. class RaiNewsIE(RaiBaseIE):
  590. _VALID_URL = rf'https?://(www\.)?rainews\.it/(?!articoli)[^?#]+-(?P<id>{RaiBaseIE._UUID_RE})(?:-[^/?#]+)?\.html'
  591. _EMBED_REGEX = [rf'<iframe[^>]+data-src="(?P<url>/iframe/[^?#]+?{RaiBaseIE._UUID_RE}\.html)']
  592. _TESTS = [{
  593. # new rainews player (#3911)
  594. 'url': 'https://www.rainews.it/video/2024/02/membri-della-croce-rossa-evacuano-gli-abitanti-di-un-villaggio-nella-regione-ucraina-di-kharkiv-il-filmato-dallucraina--31e8017c-845c-43f5-9c48-245b43c3a079.html',
  595. 'info_dict': {
  596. 'id': '31e8017c-845c-43f5-9c48-245b43c3a079',
  597. 'ext': 'mp4',
  598. 'title': 'md5:1e81364b09de4a149042bac3c7d36f0b',
  599. 'duration': 196,
  600. 'upload_date': '20240225',
  601. 'uploader': 'rainews',
  602. 'formats': 'count:2',
  603. },
  604. 'params': {'skip_download': True},
  605. }, {
  606. # old content with fallback method to extract media urls
  607. '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',
  608. 'info_dict': {
  609. 'id': '1632c009-c843-4836-bb65-80c33084a64b',
  610. 'ext': 'mp4',
  611. 'title': 'Weekend al cinema, da Hollywood arriva il thriller di Tate Taylor "La ragazza del treno"',
  612. 'description': 'I film in uscita questa settimana.',
  613. 'thumbnail': r're:^https?://.*\.png$',
  614. 'duration': 833,
  615. 'upload_date': '20161103',
  616. 'formats': 'count:8',
  617. },
  618. 'params': {'skip_download': True},
  619. 'expected_warnings': ['unable to extract player_data'],
  620. }, {
  621. # iframe + drm
  622. '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',
  623. 'only_matching': True,
  624. }]
  625. _PLAYER_TAG = 'news'
  626. def _real_extract(self, url):
  627. video_id = self._match_id(url)
  628. webpage = self._download_webpage(url, video_id)
  629. player_data = self._search_json(
  630. rf'<rai{self._PLAYER_TAG}-player\s*data=\'', webpage, 'player_data', video_id,
  631. transform_source=clean_html, default={})
  632. track_info = player_data.get('track_info')
  633. relinker_url = traverse_obj(player_data, 'mediapolis', 'content_url')
  634. if not relinker_url:
  635. # fallback on old implementation for some old content
  636. try:
  637. return RaiIE._real_extract(self, url)
  638. except GeoRestrictedError:
  639. raise
  640. except ExtractorError as e:
  641. raise ExtractorError('Relinker URL not found', cause=e)
  642. relinker_info = self._extract_relinker_info(urljoin(url, relinker_url), video_id)
  643. return {
  644. 'id': video_id,
  645. 'title': player_data.get('title') or track_info.get('title') or self._og_search_title(webpage),
  646. 'upload_date': unified_strdate(track_info.get('date')),
  647. 'uploader': strip_or_none(track_info.get('editor') or None),
  648. **relinker_info,
  649. }
  650. class RaiCulturaIE(RaiNewsIE): # XXX: Do not subclass from concrete IE
  651. _VALID_URL = rf'https?://(www\.)?raicultura\.it/(?!articoli)[^?#]+-(?P<id>{RaiBaseIE._UUID_RE})(?:-[^/?#]+)?\.html'
  652. _EMBED_REGEX = [rf'<iframe[^>]+data-src="(?P<url>/iframe/[^?#]+?{RaiBaseIE._UUID_RE}\.html)']
  653. _TESTS = [{
  654. 'url': 'https://www.raicultura.it/letteratura/articoli/2018/12/Alberto-Asor-Rosa-Letteratura-e-potere-05ba8775-82b5-45c5-a89d-dd955fbde1fb.html',
  655. 'info_dict': {
  656. 'id': '05ba8775-82b5-45c5-a89d-dd955fbde1fb',
  657. 'ext': 'mp4',
  658. 'title': 'Alberto Asor Rosa: Letteratura e potere',
  659. 'duration': 1756,
  660. 'upload_date': '20181206',
  661. 'uploader': 'raicultura',
  662. 'formats': 'count:2',
  663. },
  664. 'params': {'skip_download': True},
  665. }]
  666. _PLAYER_TAG = 'cultura'
  667. class RaiSudtirolIE(RaiBaseIE):
  668. _VALID_URL = r'https?://raisudtirol\.rai\.it/.+media=(?P<id>\w+)'
  669. _TESTS = [{
  670. # mp4 file
  671. 'url': 'https://raisudtirol.rai.it/la/index.php?media=Ptv1619729460',
  672. 'info_dict': {
  673. 'id': 'Ptv1619729460',
  674. 'ext': 'mp4',
  675. 'title': 'Euro: trasmisciun d\'economia - 29-04-2021 20:51',
  676. 'series': 'Euro: trasmisciun d\'economia',
  677. 'upload_date': '20210429',
  678. 'thumbnail': r're:https://raisudtirol\.rai\.it/img/.+\.jpg',
  679. 'uploader': 'raisudtirol',
  680. 'formats': 'count:1',
  681. },
  682. 'params': {'skip_download': True},
  683. }, {
  684. # m3u manifest
  685. 'url': 'https://raisudtirol.rai.it/it/kidsplayer.php?lang=it&media=GUGGUG_P1.smil',
  686. 'info_dict': {
  687. 'id': 'GUGGUG_P1',
  688. 'ext': 'mp4',
  689. 'title': 'GUGGUG! La Prospettiva - Die Perspektive',
  690. 'uploader': 'raisudtirol',
  691. 'formats': 'count:6',
  692. },
  693. 'params': {'skip_download': True},
  694. }]
  695. def _real_extract(self, url):
  696. video_id = self._match_id(url)
  697. webpage = self._download_webpage(url, video_id)
  698. video_date = self._html_search_regex(
  699. r'<span class="med_data">(.+?)</span>', webpage, 'video_date', default=None)
  700. video_title = self._html_search_regex([
  701. r'<span class="med_title">(.+?)</span>', r'title: \'(.+?)\','],
  702. webpage, 'video_title', default=None)
  703. video_url = self._html_search_regex([
  704. r'sources:\s*\[\{file:\s*"(.+?)"\}\]',
  705. r'<source\s+src="(.+?)"\s+type="application/x-mpegURL"'],
  706. webpage, 'video_url', default=None)
  707. ext = determine_ext(video_url)
  708. if ext == 'm3u8':
  709. formats = self._extract_m3u8_formats(video_url, video_id)
  710. elif ext == 'mp4':
  711. formats = [{
  712. 'format_id': 'https-mp4',
  713. 'url': self._proto_relative_url(video_url),
  714. 'width': 1024,
  715. 'height': 576,
  716. 'fps': 25,
  717. 'vcodec': 'avc1',
  718. 'acodec': 'mp4a',
  719. }]
  720. else:
  721. formats = []
  722. self.raise_no_formats(f'Unrecognized media file: {video_url}')
  723. return {
  724. 'id': video_id,
  725. 'title': join_nonempty(video_title, video_date, delim=' - '),
  726. 'series': video_title if video_date else None,
  727. 'upload_date': unified_strdate(video_date),
  728. 'thumbnail': urljoin('https://raisudtirol.rai.it/', self._html_search_regex(
  729. r'image: \'(.+?)\'', webpage, 'video_thumb', default=None)),
  730. 'uploader': 'raisudtirol',
  731. 'formats': formats,
  732. }