rai.py 17 KB

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