rai.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487
  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. def _real_extract(self, url):
  144. base, video_id = re.match(self._VALID_URL, url).groups()
  145. media = self._download_json(
  146. base + '.json', video_id, 'Downloading video JSON')
  147. title = media['name']
  148. video = media['video']
  149. relinker_info = self._extract_relinker_info(video['content_url'], video_id)
  150. self._sort_formats(relinker_info['formats'])
  151. thumbnails = []
  152. for _, value in media.get('images', {}).items():
  153. if value:
  154. thumbnails.append({
  155. 'url': urljoin(url, value),
  156. })
  157. date_published = media.get('date_published')
  158. time_published = media.get('time_published')
  159. if date_published and time_published:
  160. date_published += ' ' + time_published
  161. subtitles = self._extract_subtitles(url, video)
  162. program_info = media.get('program_info') or {}
  163. season = media.get('season')
  164. info = {
  165. 'id': remove_start(media.get('id'), 'ContentItem-') or video_id,
  166. 'display_id': video_id,
  167. 'title': self._live_title(title) if relinker_info.get(
  168. 'is_live') else title,
  169. 'alt_title': strip_or_none(media.get('subtitle')),
  170. 'description': media.get('description'),
  171. 'uploader': strip_or_none(media.get('channel')),
  172. 'creator': strip_or_none(media.get('editor') or None),
  173. 'duration': parse_duration(video.get('duration')),
  174. 'timestamp': unified_timestamp(date_published),
  175. 'thumbnails': thumbnails,
  176. 'series': program_info.get('name'),
  177. 'season_number': int_or_none(season),
  178. 'season': season if (season and not season.isdigit()) else None,
  179. 'episode': media.get('episode_title'),
  180. 'episode_number': int_or_none(media.get('episode')),
  181. 'subtitles': subtitles,
  182. }
  183. info.update(relinker_info)
  184. return info
  185. class RaiPlayLiveIE(RaiPlayIE):
  186. _VALID_URL = r'(?P<base>https?://(?:www\.)?raiplay\.it/dirette/(?P<id>[^/?#&]+))'
  187. _TESTS = [{
  188. 'url': 'http://www.raiplay.it/dirette/rainews24',
  189. 'info_dict': {
  190. 'id': 'd784ad40-e0ae-4a69-aa76-37519d238a9c',
  191. 'display_id': 'rainews24',
  192. 'ext': 'mp4',
  193. 'title': 're:^Diretta di Rai News 24 [0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}$',
  194. 'description': 'md5:4d00bcf6dc98b27c6ec480de329d1497',
  195. 'uploader': 'Rai News 24',
  196. 'creator': 'Rai News 24',
  197. 'is_live': True,
  198. },
  199. 'params': {
  200. 'skip_download': True,
  201. },
  202. }]
  203. class RaiPlayPlaylistIE(InfoExtractor):
  204. _VALID_URL = r'(?P<base>https?://(?:www\.)?raiplay\.it/programmi/(?P<id>[^/?#&]+))'
  205. _TESTS = [{
  206. 'url': 'http://www.raiplay.it/programmi/nondirloalmiocapo/',
  207. 'info_dict': {
  208. 'id': 'nondirloalmiocapo',
  209. 'title': 'Non dirlo al mio capo',
  210. 'description': 'md5:98ab6b98f7f44c2843fd7d6f045f153b',
  211. },
  212. 'playlist_mincount': 12,
  213. }]
  214. def _real_extract(self, url):
  215. base, playlist_id = re.match(self._VALID_URL, url).groups()
  216. program = self._download_json(
  217. base + '.json', playlist_id, 'Downloading program JSON')
  218. entries = []
  219. for b in (program.get('blocks') or []):
  220. for s in (b.get('sets') or []):
  221. s_id = s.get('id')
  222. if not s_id:
  223. continue
  224. medias = self._download_json(
  225. '%s/%s.json' % (base, s_id), s_id,
  226. 'Downloading content set JSON', fatal=False)
  227. if not medias:
  228. continue
  229. for m in (medias.get('items') or []):
  230. path_id = m.get('path_id')
  231. if not path_id:
  232. continue
  233. video_url = urljoin(url, path_id)
  234. entries.append(self.url_result(
  235. video_url, ie=RaiPlayIE.ie_key(),
  236. video_id=RaiPlayIE._match_id(video_url)))
  237. return self.playlist_result(
  238. entries, playlist_id, program.get('name'),
  239. try_get(program, lambda x: x['program_info']['description']))
  240. class RaiIE(RaiBaseIE):
  241. _VALID_URL = r'https?://[^/]+\.(?:rai\.(?:it|tv)|rainews\.it)/.+?-(?P<id>%s)(?:-.+?)?\.html' % RaiBaseIE._UUID_RE
  242. _TESTS = [{
  243. # var uniquename = "ContentItem-..."
  244. # data-id="ContentItem-..."
  245. 'url': 'http://www.raisport.rai.it/dl/raiSport/media/rassegna-stampa-04a9f4bd-b563-40cf-82a6-aad3529cb4a9.html',
  246. 'info_dict': {
  247. 'id': '04a9f4bd-b563-40cf-82a6-aad3529cb4a9',
  248. 'ext': 'mp4',
  249. 'title': 'TG PRIMO TEMPO',
  250. 'thumbnail': r're:^https?://.*\.jpg$',
  251. 'duration': 1758,
  252. 'upload_date': '20140612',
  253. },
  254. 'skip': 'This content is available only in Italy',
  255. }, {
  256. # with ContentItem in many metas
  257. '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',
  258. 'info_dict': {
  259. 'id': '1632c009-c843-4836-bb65-80c33084a64b',
  260. 'ext': 'mp4',
  261. 'title': 'Weekend al cinema, da Hollywood arriva il thriller di Tate Taylor "La ragazza del treno"',
  262. 'description': 'I film in uscita questa settimana.',
  263. 'thumbnail': r're:^https?://.*\.png$',
  264. 'duration': 833,
  265. 'upload_date': '20161103',
  266. }
  267. }, {
  268. # with ContentItem in og:url
  269. 'url': 'http://www.rai.it/dl/RaiTV/programmi/media/ContentItem-efb17665-691c-45d5-a60c-5301333cbb0c.html',
  270. 'md5': '6865dd00cf0bbf5772fdd89d59bd768a',
  271. 'info_dict': {
  272. 'id': 'efb17665-691c-45d5-a60c-5301333cbb0c',
  273. 'ext': 'mp4',
  274. 'title': 'TG1 ore 20:00 del 03/11/2016',
  275. 'description': 'TG1 edizione integrale ore 20:00 del giorno 03/11/2016',
  276. 'thumbnail': r're:^https?://.*\.jpg$',
  277. 'duration': 2214,
  278. 'upload_date': '20161103',
  279. }
  280. }, {
  281. # initEdizione('ContentItem-...'
  282. 'url': 'http://www.tg1.rai.it/dl/tg1/2010/edizioni/ContentSet-9b6e0cba-4bef-4aef-8cf0-9f7f665b7dfb-tg1.html?item=undefined',
  283. 'info_dict': {
  284. 'id': 'c2187016-8484-4e3a-8ac8-35e475b07303',
  285. 'ext': 'mp4',
  286. 'title': r're:TG1 ore \d{2}:\d{2} del \d{2}/\d{2}/\d{4}',
  287. 'duration': 2274,
  288. 'upload_date': '20170401',
  289. },
  290. 'skip': 'Changes daily',
  291. }, {
  292. # HLS live stream with ContentItem in og:url
  293. 'url': 'http://www.rainews.it/dl/rainews/live/ContentItem-3156f2f2-dc70-4953-8e2f-70d7489d4ce9.html',
  294. 'info_dict': {
  295. 'id': '3156f2f2-dc70-4953-8e2f-70d7489d4ce9',
  296. 'ext': 'mp4',
  297. 'title': 'La diretta di Rainews24',
  298. },
  299. 'params': {
  300. 'skip_download': True,
  301. },
  302. }, {
  303. # ContentItem in iframe (see #12652) and subtitle at 'subtitlesUrl' key
  304. 'url': 'http://www.presadiretta.rai.it/dl/portali/site/puntata/ContentItem-3ed19d13-26c2-46ff-a551-b10828262f1b.html',
  305. 'info_dict': {
  306. 'id': '1ad6dc64-444a-42a4-9bea-e5419ad2f5fd',
  307. 'ext': 'mp4',
  308. 'title': 'Partiti acchiappavoti - Presa diretta del 13/09/2015',
  309. 'description': 'md5:d291b03407ec505f95f27970c0b025f4',
  310. 'upload_date': '20150913',
  311. 'subtitles': {
  312. 'it': 'count:2',
  313. },
  314. },
  315. 'params': {
  316. 'skip_download': True,
  317. },
  318. }, {
  319. # Direct MMS URL
  320. 'url': 'http://www.rai.it/dl/RaiTV/programmi/media/ContentItem-b63a4089-ac28-48cf-bca5-9f5b5bc46df5.html',
  321. 'only_matching': True,
  322. }, {
  323. 'url': 'https://www.rainews.it/tgr/marche/notiziari/video/2019/02/ContentItem-6ba945a2-889c-4a80-bdeb-8489c70a8db9.html',
  324. 'only_matching': True,
  325. }]
  326. def _extract_from_content_id(self, content_id, url):
  327. media = self._download_json(
  328. 'http://www.rai.tv/dl/RaiTV/programmi/media/ContentItem-%s.html?json' % content_id,
  329. content_id, 'Downloading video JSON')
  330. title = media['name'].strip()
  331. media_type = media['type']
  332. if 'Audio' in media_type:
  333. relinker_info = {
  334. 'formats': [{
  335. 'format_id': media.get('formatoAudio'),
  336. 'url': media['audioUrl'],
  337. 'ext': media.get('formatoAudio'),
  338. }]
  339. }
  340. elif 'Video' in media_type:
  341. relinker_info = self._extract_relinker_info(media['mediaUri'], content_id)
  342. else:
  343. raise ExtractorError('not a media file')
  344. self._sort_formats(relinker_info['formats'])
  345. thumbnails = []
  346. for image_type in ('image', 'image_medium', 'image_300'):
  347. thumbnail_url = media.get(image_type)
  348. if thumbnail_url:
  349. thumbnails.append({
  350. 'url': compat_urlparse.urljoin(url, thumbnail_url),
  351. })
  352. subtitles = self._extract_subtitles(url, media)
  353. info = {
  354. 'id': content_id,
  355. 'title': title,
  356. 'description': strip_or_none(media.get('desc')),
  357. 'thumbnails': thumbnails,
  358. 'uploader': media.get('author'),
  359. 'upload_date': unified_strdate(media.get('date')),
  360. 'duration': parse_duration(media.get('length')),
  361. 'subtitles': subtitles,
  362. }
  363. info.update(relinker_info)
  364. return info
  365. def _real_extract(self, url):
  366. video_id = self._match_id(url)
  367. webpage = self._download_webpage(url, video_id)
  368. content_item_id = None
  369. content_item_url = self._html_search_meta(
  370. ('og:url', 'og:video', 'og:video:secure_url', 'twitter:url',
  371. 'twitter:player', 'jsonlink'), webpage, default=None)
  372. if content_item_url:
  373. content_item_id = self._search_regex(
  374. r'ContentItem-(%s)' % self._UUID_RE, content_item_url,
  375. 'content item id', default=None)
  376. if not content_item_id:
  377. content_item_id = self._search_regex(
  378. r'''(?x)
  379. (?:
  380. (?:initEdizione|drawMediaRaiTV)\(|
  381. <(?:[^>]+\bdata-id|var\s+uniquename)=|
  382. <iframe[^>]+\bsrc=
  383. )
  384. (["\'])
  385. (?:(?!\1).)*\bContentItem-(?P<id>%s)
  386. ''' % self._UUID_RE,
  387. webpage, 'content item id', default=None, group='id')
  388. content_item_ids = set()
  389. if content_item_id:
  390. content_item_ids.add(content_item_id)
  391. if video_id not in content_item_ids:
  392. content_item_ids.add(video_id)
  393. for content_item_id in content_item_ids:
  394. try:
  395. return self._extract_from_content_id(content_item_id, url)
  396. except GeoRestrictedError:
  397. raise
  398. except ExtractorError:
  399. pass
  400. relinker_url = self._proto_relative_url(self._search_regex(
  401. r'''(?x)
  402. (?:
  403. var\s+videoURL|
  404. mediaInfo\.mediaUri
  405. )\s*=\s*
  406. ([\'"])
  407. (?P<url>
  408. (?:https?:)?
  409. //mediapolis(?:vod)?\.rai\.it/relinker/relinkerServlet\.htm\?
  410. (?:(?!\1).)*\bcont=(?:(?!\1).)+)\1
  411. ''',
  412. webpage, 'relinker URL', group='url'))
  413. relinker_info = self._extract_relinker_info(
  414. urljoin(url, relinker_url), video_id)
  415. self._sort_formats(relinker_info['formats'])
  416. title = self._search_regex(
  417. r'var\s+videoTitolo\s*=\s*([\'"])(?P<title>[^\'"]+)\1',
  418. webpage, 'title', group='title',
  419. default=None) or self._og_search_title(webpage)
  420. info = {
  421. 'id': video_id,
  422. 'title': title,
  423. }
  424. info.update(relinker_info)
  425. return info