rai.py 32 KB

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