rai.py 18 KB

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