rai.py 17 KB

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