rai.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498
  1. # coding: utf-8
  2. from __future__ import unicode_literals
  3. import re
  4. from .common import InfoExtractor
  5. from ..compat import (
  6. compat_urlparse,
  7. compat_str,
  8. )
  9. from ..utils import (
  10. ExtractorError,
  11. determine_ext,
  12. find_xpath_attr,
  13. fix_xml_ampersands,
  14. GeoRestrictedError,
  15. int_or_none,
  16. parse_duration,
  17. remove_start,
  18. strip_or_none,
  19. try_get,
  20. unified_strdate,
  21. unified_timestamp,
  22. update_url_query,
  23. urljoin,
  24. xpath_text,
  25. )
  26. class RaiBaseIE(InfoExtractor):
  27. _UUID_RE = r'[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}'
  28. _GEO_COUNTRIES = ['IT']
  29. _GEO_BYPASS = False
  30. def _extract_relinker_info(self, relinker_url, video_id):
  31. if not re.match(r'https?://', relinker_url):
  32. return {'formats': [{'url': relinker_url}]}
  33. formats = []
  34. geoprotection = None
  35. is_live = None
  36. duration = None
  37. for platform in ('mon', 'flash', 'native'):
  38. relinker = self._download_xml(
  39. relinker_url, video_id,
  40. note='Downloading XML metadata for platform %s' % platform,
  41. transform_source=fix_xml_ampersands,
  42. query={'output': 45, 'pl': platform},
  43. headers=self.geo_verification_headers())
  44. if not geoprotection:
  45. geoprotection = xpath_text(
  46. relinker, './geoprotection', default=None) == 'Y'
  47. if not is_live:
  48. is_live = xpath_text(
  49. relinker, './is_live', default=None) == 'Y'
  50. if not duration:
  51. duration = parse_duration(xpath_text(
  52. relinker, './duration', default=None))
  53. url_elem = find_xpath_attr(relinker, './url', 'type', 'content')
  54. if url_elem is None:
  55. continue
  56. media_url = url_elem.text
  57. # This does not imply geo restriction (e.g.
  58. # http://www.raisport.rai.it/dl/raiSport/media/rassegna-stampa-04a9f4bd-b563-40cf-82a6-aad3529cb4a9.html)
  59. if '/video_no_available.mp4' in media_url:
  60. continue
  61. ext = determine_ext(media_url)
  62. if (ext == 'm3u8' and platform != 'mon') or (ext == 'f4m' and platform != 'flash'):
  63. continue
  64. if ext == 'm3u8' or 'format=m3u8' in media_url or platform == 'mon':
  65. formats.extend(self._extract_m3u8_formats(
  66. media_url, video_id, 'mp4', 'm3u8_native',
  67. m3u8_id='hls', fatal=False))
  68. elif ext == 'f4m' or platform == 'flash':
  69. manifest_url = update_url_query(
  70. media_url.replace('manifest#live_hds.f4m', 'manifest.f4m'),
  71. {'hdcore': '3.7.0', 'plugin': 'aasp-3.7.0.39.44'})
  72. formats.extend(self._extract_f4m_formats(
  73. manifest_url, video_id, f4m_id='hds', fatal=False))
  74. else:
  75. bitrate = int_or_none(xpath_text(relinker, 'bitrate'))
  76. formats.append({
  77. 'url': media_url,
  78. 'tbr': bitrate if bitrate > 0 else None,
  79. 'format_id': 'http-%d' % bitrate if bitrate > 0 else 'http',
  80. })
  81. if not formats and geoprotection is True:
  82. self.raise_geo_restricted(countries=self._GEO_COUNTRIES)
  83. return dict((k, v) for k, v in {
  84. 'is_live': is_live,
  85. 'duration': duration,
  86. 'formats': formats,
  87. }.items() if v is not None)
  88. @staticmethod
  89. def _extract_subtitles(url, video_data):
  90. STL_EXT = 'stl'
  91. SRT_EXT = 'srt'
  92. subtitles = {}
  93. subtitles_array = video_data.get('subtitlesArray') or []
  94. for k in ('subtitles', 'subtitlesUrl'):
  95. subtitles_array.append({'url': video_data.get(k)})
  96. for subtitle in subtitles_array:
  97. sub_url = subtitle.get('url')
  98. if sub_url and isinstance(sub_url, compat_str):
  99. sub_lang = subtitle.get('language') or 'it'
  100. sub_url = urljoin(url, sub_url)
  101. sub_ext = determine_ext(sub_url, SRT_EXT)
  102. subtitles.setdefault(sub_lang, []).append({
  103. 'ext': sub_ext,
  104. 'url': sub_url,
  105. })
  106. if STL_EXT == sub_ext:
  107. subtitles[sub_lang].append({
  108. 'ext': SRT_EXT,
  109. 'url': sub_url[:-len(STL_EXT)] + SRT_EXT,
  110. })
  111. return subtitles
  112. class RaiPlayIE(RaiBaseIE):
  113. _VALID_URL = r'(?P<base>https?://(?:www\.)?raiplay\.it/.+?-(?P<id>%s))\.(?:html|json)' % RaiBaseIE._UUID_RE
  114. _TESTS = [{
  115. 'url': 'http://www.raiplay.it/video/2014/04/Report-del-07042014-cb27157f-9dd0-4aee-b788-b1f67643a391.html',
  116. 'md5': '8970abf8caf8aef4696e7b1f2adfc696',
  117. 'info_dict': {
  118. 'id': 'cb27157f-9dd0-4aee-b788-b1f67643a391',
  119. 'ext': 'mp4',
  120. 'title': 'Report del 07/04/2014',
  121. 'alt_title': 'St 2013/14 - Espresso nel caffè - 07/04/2014',
  122. 'description': 'md5:d730c168a58f4bb35600fc2f881ec04e',
  123. 'thumbnail': r're:^https?://.*\.jpg$',
  124. 'uploader': 'Rai Gulp',
  125. 'duration': 6160,
  126. 'series': 'Report',
  127. 'season': '2013/14',
  128. 'subtitles': {
  129. 'it': 'count:2',
  130. },
  131. },
  132. 'params': {
  133. 'skip_download': True,
  134. },
  135. }, {
  136. 'url': 'http://www.raiplay.it/video/2016/11/gazebotraindesi-efebe701-969c-4593-92f3-285f0d1ce750.html?',
  137. 'only_matching': True,
  138. }, {
  139. # subtitles at 'subtitlesArray' key (see #27698)
  140. 'url': 'https://www.raiplay.it/video/2020/12/Report---04-01-2021-2e90f1de-8eee-4de4-ac0e-78d21db5b600.html',
  141. 'only_matching': True,
  142. }, {
  143. # DRM protected
  144. 'url': 'https://www.raiplay.it/video/2020/09/Lo-straordinario-mondo-di-Zoey-S1E1-Lo-straordinario-potere-di-Zoey-ed493918-1d32-44b7-8454-862e473d00ff.html',
  145. 'only_matching': True,
  146. }]
  147. def _real_extract(self, url):
  148. base, video_id = re.match(self._VALID_URL, url).groups()
  149. media = self._download_json(
  150. base + '.json', video_id, 'Downloading video JSON')
  151. if try_get(
  152. media,
  153. (lambda x: x['rights_management']['rights']['drm'],
  154. lambda x: x['program_info']['rights_management']['rights']['drm']),
  155. dict):
  156. raise ExtractorError('This video is DRM protected.', expected=True)
  157. title = media['name']
  158. video = media['video']
  159. relinker_info = self._extract_relinker_info(video['content_url'], video_id)
  160. self._sort_formats(relinker_info['formats'])
  161. thumbnails = []
  162. for _, value in media.get('images', {}).items():
  163. if value:
  164. thumbnails.append({
  165. 'url': urljoin(url, value),
  166. })
  167. date_published = media.get('date_published')
  168. time_published = media.get('time_published')
  169. if date_published and time_published:
  170. date_published += ' ' + time_published
  171. subtitles = self._extract_subtitles(url, video)
  172. program_info = media.get('program_info') or {}
  173. season = media.get('season')
  174. info = {
  175. 'id': remove_start(media.get('id'), 'ContentItem-') or video_id,
  176. 'display_id': video_id,
  177. 'title': self._live_title(title) if relinker_info.get(
  178. 'is_live') else title,
  179. 'alt_title': strip_or_none(media.get('subtitle')),
  180. 'description': media.get('description'),
  181. 'uploader': strip_or_none(media.get('channel')),
  182. 'creator': strip_or_none(media.get('editor') or None),
  183. 'duration': parse_duration(video.get('duration')),
  184. 'timestamp': unified_timestamp(date_published),
  185. 'thumbnails': thumbnails,
  186. 'series': program_info.get('name'),
  187. 'season_number': int_or_none(season),
  188. 'season': season if (season and not season.isdigit()) else None,
  189. 'episode': media.get('episode_title'),
  190. 'episode_number': int_or_none(media.get('episode')),
  191. 'subtitles': subtitles,
  192. }
  193. info.update(relinker_info)
  194. return info
  195. class RaiPlayLiveIE(RaiPlayIE):
  196. _VALID_URL = r'(?P<base>https?://(?:www\.)?raiplay\.it/dirette/(?P<id>[^/?#&]+))'
  197. _TESTS = [{
  198. 'url': 'http://www.raiplay.it/dirette/rainews24',
  199. 'info_dict': {
  200. 'id': 'd784ad40-e0ae-4a69-aa76-37519d238a9c',
  201. 'display_id': 'rainews24',
  202. 'ext': 'mp4',
  203. 'title': 're:^Diretta di Rai News 24 [0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}$',
  204. 'description': 'md5:4d00bcf6dc98b27c6ec480de329d1497',
  205. 'uploader': 'Rai News 24',
  206. 'creator': 'Rai News 24',
  207. 'is_live': True,
  208. },
  209. 'params': {
  210. 'skip_download': True,
  211. },
  212. }]
  213. class RaiPlayPlaylistIE(InfoExtractor):
  214. _VALID_URL = r'(?P<base>https?://(?:www\.)?raiplay\.it/programmi/(?P<id>[^/?#&]+))'
  215. _TESTS = [{
  216. 'url': 'http://www.raiplay.it/programmi/nondirloalmiocapo/',
  217. 'info_dict': {
  218. 'id': 'nondirloalmiocapo',
  219. 'title': 'Non dirlo al mio capo',
  220. 'description': 'md5:98ab6b98f7f44c2843fd7d6f045f153b',
  221. },
  222. 'playlist_mincount': 12,
  223. }]
  224. def _real_extract(self, url):
  225. base, playlist_id = re.match(self._VALID_URL, url).groups()
  226. program = self._download_json(
  227. base + '.json', playlist_id, 'Downloading program JSON')
  228. entries = []
  229. for b in (program.get('blocks') or []):
  230. for s in (b.get('sets') or []):
  231. s_id = s.get('id')
  232. if not s_id:
  233. continue
  234. medias = self._download_json(
  235. '%s/%s.json' % (base, s_id), s_id,
  236. 'Downloading content set JSON', fatal=False)
  237. if not medias:
  238. continue
  239. for m in (medias.get('items') or []):
  240. path_id = m.get('path_id')
  241. if not path_id:
  242. continue
  243. video_url = urljoin(url, path_id)
  244. entries.append(self.url_result(
  245. video_url, ie=RaiPlayIE.ie_key(),
  246. video_id=RaiPlayIE._match_id(video_url)))
  247. return self.playlist_result(
  248. entries, playlist_id, program.get('name'),
  249. try_get(program, lambda x: x['program_info']['description']))
  250. class RaiIE(RaiBaseIE):
  251. _VALID_URL = r'https?://[^/]+\.(?:rai\.(?:it|tv)|rainews\.it)/.+?-(?P<id>%s)(?:-.+?)?\.html' % RaiBaseIE._UUID_RE
  252. _TESTS = [{
  253. # var uniquename = "ContentItem-..."
  254. # data-id="ContentItem-..."
  255. 'url': 'http://www.raisport.rai.it/dl/raiSport/media/rassegna-stampa-04a9f4bd-b563-40cf-82a6-aad3529cb4a9.html',
  256. 'info_dict': {
  257. 'id': '04a9f4bd-b563-40cf-82a6-aad3529cb4a9',
  258. 'ext': 'mp4',
  259. 'title': 'TG PRIMO TEMPO',
  260. 'thumbnail': r're:^https?://.*\.jpg$',
  261. 'duration': 1758,
  262. 'upload_date': '20140612',
  263. },
  264. 'skip': 'This content is available only in Italy',
  265. }, {
  266. # with ContentItem in many metas
  267. 'url': 'http://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',
  268. 'info_dict': {
  269. 'id': '1632c009-c843-4836-bb65-80c33084a64b',
  270. 'ext': 'mp4',
  271. 'title': 'Weekend al cinema, da Hollywood arriva il thriller di Tate Taylor "La ragazza del treno"',
  272. 'description': 'I film in uscita questa settimana.',
  273. 'thumbnail': r're:^https?://.*\.png$',
  274. 'duration': 833,
  275. 'upload_date': '20161103',
  276. }
  277. }, {
  278. # with ContentItem in og:url
  279. 'url': 'http://www.rai.it/dl/RaiTV/programmi/media/ContentItem-efb17665-691c-45d5-a60c-5301333cbb0c.html',
  280. 'md5': '6865dd00cf0bbf5772fdd89d59bd768a',
  281. 'info_dict': {
  282. 'id': 'efb17665-691c-45d5-a60c-5301333cbb0c',
  283. 'ext': 'mp4',
  284. 'title': 'TG1 ore 20:00 del 03/11/2016',
  285. 'description': 'TG1 edizione integrale ore 20:00 del giorno 03/11/2016',
  286. 'thumbnail': r're:^https?://.*\.jpg$',
  287. 'duration': 2214,
  288. 'upload_date': '20161103',
  289. }
  290. }, {
  291. # initEdizione('ContentItem-...'
  292. 'url': 'http://www.tg1.rai.it/dl/tg1/2010/edizioni/ContentSet-9b6e0cba-4bef-4aef-8cf0-9f7f665b7dfb-tg1.html?item=undefined',
  293. 'info_dict': {
  294. 'id': 'c2187016-8484-4e3a-8ac8-35e475b07303',
  295. 'ext': 'mp4',
  296. 'title': r're:TG1 ore \d{2}:\d{2} del \d{2}/\d{2}/\d{4}',
  297. 'duration': 2274,
  298. 'upload_date': '20170401',
  299. },
  300. 'skip': 'Changes daily',
  301. }, {
  302. # HLS live stream with ContentItem in og:url
  303. 'url': 'http://www.rainews.it/dl/rainews/live/ContentItem-3156f2f2-dc70-4953-8e2f-70d7489d4ce9.html',
  304. 'info_dict': {
  305. 'id': '3156f2f2-dc70-4953-8e2f-70d7489d4ce9',
  306. 'ext': 'mp4',
  307. 'title': 'La diretta di Rainews24',
  308. },
  309. 'params': {
  310. 'skip_download': True,
  311. },
  312. }, {
  313. # ContentItem in iframe (see #12652) and subtitle at 'subtitlesUrl' key
  314. 'url': 'http://www.presadiretta.rai.it/dl/portali/site/puntata/ContentItem-3ed19d13-26c2-46ff-a551-b10828262f1b.html',
  315. 'info_dict': {
  316. 'id': '1ad6dc64-444a-42a4-9bea-e5419ad2f5fd',
  317. 'ext': 'mp4',
  318. 'title': 'Partiti acchiappavoti - Presa diretta del 13/09/2015',
  319. 'description': 'md5:d291b03407ec505f95f27970c0b025f4',
  320. 'upload_date': '20150913',
  321. 'subtitles': {
  322. 'it': 'count:2',
  323. },
  324. },
  325. 'params': {
  326. 'skip_download': True,
  327. },
  328. }, {
  329. # Direct MMS URL
  330. 'url': 'http://www.rai.it/dl/RaiTV/programmi/media/ContentItem-b63a4089-ac28-48cf-bca5-9f5b5bc46df5.html',
  331. 'only_matching': True,
  332. }, {
  333. 'url': 'https://www.rainews.it/tgr/marche/notiziari/video/2019/02/ContentItem-6ba945a2-889c-4a80-bdeb-8489c70a8db9.html',
  334. 'only_matching': True,
  335. }]
  336. def _extract_from_content_id(self, content_id, url):
  337. media = self._download_json(
  338. 'http://www.rai.tv/dl/RaiTV/programmi/media/ContentItem-%s.html?json' % content_id,
  339. content_id, 'Downloading video JSON')
  340. title = media['name'].strip()
  341. media_type = media['type']
  342. if 'Audio' in media_type:
  343. relinker_info = {
  344. 'formats': [{
  345. 'format_id': media.get('formatoAudio'),
  346. 'url': media['audioUrl'],
  347. 'ext': media.get('formatoAudio'),
  348. }]
  349. }
  350. elif 'Video' in media_type:
  351. relinker_info = self._extract_relinker_info(media['mediaUri'], content_id)
  352. else:
  353. raise ExtractorError('not a media file')
  354. self._sort_formats(relinker_info['formats'])
  355. thumbnails = []
  356. for image_type in ('image', 'image_medium', 'image_300'):
  357. thumbnail_url = media.get(image_type)
  358. if thumbnail_url:
  359. thumbnails.append({
  360. 'url': compat_urlparse.urljoin(url, thumbnail_url),
  361. })
  362. subtitles = self._extract_subtitles(url, media)
  363. info = {
  364. 'id': content_id,
  365. 'title': title,
  366. 'description': strip_or_none(media.get('desc')),
  367. 'thumbnails': thumbnails,
  368. 'uploader': media.get('author'),
  369. 'upload_date': unified_strdate(media.get('date')),
  370. 'duration': parse_duration(media.get('length')),
  371. 'subtitles': subtitles,
  372. }
  373. info.update(relinker_info)
  374. return info
  375. def _real_extract(self, url):
  376. video_id = self._match_id(url)
  377. webpage = self._download_webpage(url, video_id)
  378. content_item_id = None
  379. content_item_url = self._html_search_meta(
  380. ('og:url', 'og:video', 'og:video:secure_url', 'twitter:url',
  381. 'twitter:player', 'jsonlink'), webpage, default=None)
  382. if content_item_url:
  383. content_item_id = self._search_regex(
  384. r'ContentItem-(%s)' % self._UUID_RE, content_item_url,
  385. 'content item id', default=None)
  386. if not content_item_id:
  387. content_item_id = self._search_regex(
  388. r'''(?x)
  389. (?:
  390. (?:initEdizione|drawMediaRaiTV)\(|
  391. <(?:[^>]+\bdata-id|var\s+uniquename)=|
  392. <iframe[^>]+\bsrc=
  393. )
  394. (["\'])
  395. (?:(?!\1).)*\bContentItem-(?P<id>%s)
  396. ''' % self._UUID_RE,
  397. webpage, 'content item id', default=None, group='id')
  398. content_item_ids = set()
  399. if content_item_id:
  400. content_item_ids.add(content_item_id)
  401. if video_id not in content_item_ids:
  402. content_item_ids.add(video_id)
  403. for content_item_id in content_item_ids:
  404. try:
  405. return self._extract_from_content_id(content_item_id, url)
  406. except GeoRestrictedError:
  407. raise
  408. except ExtractorError:
  409. pass
  410. relinker_url = self._proto_relative_url(self._search_regex(
  411. r'''(?x)
  412. (?:
  413. var\s+videoURL|
  414. mediaInfo\.mediaUri
  415. )\s*=\s*
  416. ([\'"])
  417. (?P<url>
  418. (?:https?:)?
  419. //mediapolis(?:vod)?\.rai\.it/relinker/relinkerServlet\.htm\?
  420. (?:(?!\1).)*\bcont=(?:(?!\1).)+)\1
  421. ''',
  422. webpage, 'relinker URL', group='url'))
  423. relinker_info = self._extract_relinker_info(
  424. urljoin(url, relinker_url), video_id)
  425. self._sort_formats(relinker_info['formats'])
  426. title = self._search_regex(
  427. r'var\s+videoTitolo\s*=\s*([\'"])(?P<title>[^\'"]+)\1',
  428. webpage, 'title', group='title',
  429. default=None) or self._og_search_title(webpage)
  430. info = {
  431. 'id': video_id,
  432. 'title': title,
  433. }
  434. info.update(relinker_info)
  435. return info