rai.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500
  1. from __future__ import unicode_literals
  2. import re
  3. from .common import InfoExtractor
  4. from ..compat import (
  5. compat_urlparse,
  6. compat_str,
  7. )
  8. from ..utils import (
  9. ExtractorError,
  10. determine_ext,
  11. find_xpath_attr,
  12. fix_xml_ampersands,
  13. GeoRestrictedError,
  14. int_or_none,
  15. parse_duration,
  16. strip_or_none,
  17. try_get,
  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':
  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':
  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. }, {
  126. 'url': 'http://www.raiplay.it/video/2014/04/Report-del-07042014-cb27157f-9dd0-4aee-b788-b1f67643a391.html',
  127. 'md5': '8970abf8caf8aef4696e7b1f2adfc696',
  128. 'info_dict': {
  129. 'id': 'cb27157f-9dd0-4aee-b788-b1f67643a391',
  130. 'ext': 'mp4',
  131. 'title': 'Report del 07/04/2014',
  132. 'alt_title': 'S2013/14 - Puntata del 07/04/2014',
  133. 'description': 'md5:f27c544694cacb46a078db84ec35d2d9',
  134. 'thumbnail': r're:^https?://.*\.jpg$',
  135. 'uploader': 'Rai 5',
  136. 'creator': 'Rai 5',
  137. 'duration': 6160,
  138. 'series': 'Report',
  139. 'season_number': 5,
  140. 'season': '2013/14',
  141. },
  142. 'params': {
  143. 'skip_download': True,
  144. },
  145. }, {
  146. 'url': 'http://www.raiplay.it/video/2016/11/gazebotraindesi-efebe701-969c-4593-92f3-285f0d1ce750.html?',
  147. 'only_matching': True,
  148. }]
  149. def _real_extract(self, url):
  150. mobj = re.match(self._VALID_URL, url)
  151. url, video_id = mobj.group('url', 'id')
  152. media = self._download_json(
  153. '%s?json' % url, video_id, 'Downloading video JSON')
  154. title = media['name']
  155. video = media['video']
  156. relinker_info = self._extract_relinker_info(video['contentUrl'], video_id)
  157. self._sort_formats(relinker_info['formats'])
  158. thumbnails = []
  159. if 'images' in media:
  160. for _, value in media.get('images').items():
  161. if value:
  162. thumbnails.append({
  163. 'url': value.replace('[RESOLUTION]', '600x400')
  164. })
  165. timestamp = unified_timestamp(try_get(
  166. media, lambda x: x['availabilities'][0]['start'], compat_str))
  167. subtitles = self._extract_subtitles(url, video.get('subtitles'))
  168. info = {
  169. 'id': video_id,
  170. 'title': self._live_title(title) if relinker_info.get(
  171. 'is_live') else title,
  172. 'alt_title': media.get('subtitle'),
  173. 'description': media.get('description'),
  174. 'uploader': strip_or_none(media.get('channel')),
  175. 'creator': strip_or_none(media.get('editor')),
  176. 'duration': parse_duration(video.get('duration')),
  177. 'timestamp': timestamp,
  178. 'thumbnails': thumbnails,
  179. 'series': try_get(
  180. media, lambda x: x['isPartOf']['name'], compat_str),
  181. 'season_number': int_or_none(try_get(
  182. media, lambda x: x['isPartOf']['numeroStagioni'])),
  183. 'season': media.get('stagione') or None,
  184. 'subtitles': subtitles,
  185. }
  186. info.update(relinker_info)
  187. return info
  188. class RaiPlayLiveIE(RaiBaseIE):
  189. _VALID_URL = r'https?://(?:www\.)?raiplay\.it/dirette/(?P<id>[^/?#&]+)'
  190. _TEST = {
  191. 'url': 'http://www.raiplay.it/dirette/rainews24',
  192. 'info_dict': {
  193. 'id': 'd784ad40-e0ae-4a69-aa76-37519d238a9c',
  194. 'display_id': 'rainews24',
  195. 'ext': 'mp4',
  196. 'title': 're:^Diretta di Rai News 24 [0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}$',
  197. 'description': 'md5:6eca31500550f9376819f174e5644754',
  198. 'uploader': 'Rai News 24',
  199. 'creator': 'Rai News 24',
  200. 'is_live': True,
  201. },
  202. 'params': {
  203. 'skip_download': True,
  204. },
  205. }
  206. def _real_extract(self, url):
  207. display_id = self._match_id(url)
  208. webpage = self._download_webpage(url, display_id)
  209. video_id = self._search_regex(
  210. r'data-uniquename=["\']ContentItem-(%s)' % RaiBaseIE._UUID_RE,
  211. webpage, 'content id')
  212. return {
  213. '_type': 'url_transparent',
  214. 'ie_key': RaiPlayIE.ie_key(),
  215. 'url': 'http://www.raiplay.it/dirette/ContentItem-%s.html' % video_id,
  216. 'id': video_id,
  217. 'display_id': display_id,
  218. }
  219. class RaiPlayPlaylistIE(InfoExtractor):
  220. _VALID_URL = r'https?://(?:www\.)?raiplay\.it/programmi/(?P<id>[^/?#&]+)'
  221. _TESTS = [{
  222. 'url': 'http://www.raiplay.it/programmi/nondirloalmiocapo/',
  223. 'info_dict': {
  224. 'id': 'nondirloalmiocapo',
  225. 'title': 'Non dirlo al mio capo',
  226. 'description': 'md5:9f3d603b2947c1c7abb098f3b14fac86',
  227. },
  228. 'playlist_mincount': 12,
  229. }]
  230. def _real_extract(self, url):
  231. playlist_id = self._match_id(url)
  232. webpage = self._download_webpage(url, playlist_id)
  233. title = self._html_search_meta(
  234. ('programma', 'nomeProgramma'), webpage, 'title')
  235. description = unescapeHTML(self._html_search_meta(
  236. ('description', 'og:description'), webpage, 'description'))
  237. print(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)/dl/.+?-(?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. }, {
  262. # with ContentItem in many metas
  263. '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',
  264. 'info_dict': {
  265. 'id': '1632c009-c843-4836-bb65-80c33084a64b',
  266. 'ext': 'mp4',
  267. 'title': 'Weekend al cinema, da Hollywood arriva il thriller di Tate Taylor "La ragazza del treno"',
  268. 'description': 'I film in uscita questa settimana.',
  269. 'thumbnail': r're:^https?://.*\.png$',
  270. 'duration': 833,
  271. 'upload_date': '20161103',
  272. }
  273. }, {
  274. # with ContentItem in og:url
  275. 'url': 'http://www.rai.it/dl/RaiTV/programmi/media/ContentItem-efb17665-691c-45d5-a60c-5301333cbb0c.html',
  276. 'md5': '11959b4e44fa74de47011b5799490adf',
  277. 'info_dict': {
  278. 'id': 'efb17665-691c-45d5-a60c-5301333cbb0c',
  279. 'ext': 'mp4',
  280. 'title': 'TG1 ore 20:00 del 03/11/2016',
  281. 'description': 'TG1 edizione integrale ore 20:00 del giorno 03/11/2016',
  282. 'thumbnail': r're:^https?://.*\.jpg$',
  283. 'duration': 2214,
  284. 'upload_date': '20161103',
  285. }
  286. }, {
  287. # drawMediaRaiTV(...)
  288. 'url': 'http://www.report.rai.it/dl/Report/puntata/ContentItem-0c7a664b-d0f4-4b2c-8835-3f82e46f433e.html',
  289. 'md5': '2dd727e61114e1ee9c47f0da6914e178',
  290. 'info_dict': {
  291. 'id': '59d69d28-6bb6-409d-a4b5-ed44096560af',
  292. 'ext': 'mp4',
  293. 'title': 'Il pacco',
  294. 'description': 'md5:4b1afae1364115ce5d78ed83cd2e5b3a',
  295. 'thumbnail': r're:^https?://.*\.jpg$',
  296. 'upload_date': '20141221',
  297. },
  298. }, {
  299. # initEdizione('ContentItem-...'
  300. 'url': 'http://www.tg1.rai.it/dl/tg1/2010/edizioni/ContentSet-9b6e0cba-4bef-4aef-8cf0-9f7f665b7dfb-tg1.html?item=undefined',
  301. 'info_dict': {
  302. 'id': 'c2187016-8484-4e3a-8ac8-35e475b07303',
  303. 'ext': 'mp4',
  304. 'title': r're:TG1 ore \d{2}:\d{2} del \d{2}/\d{2}/\d{4}',
  305. 'duration': 2274,
  306. 'upload_date': '20170401',
  307. },
  308. 'skip': 'Changes daily',
  309. }, {
  310. # HDS live stream with only relinker URL
  311. 'url': 'http://www.rai.tv/dl/RaiTV/dirette/PublishingBlock-1912dbbf-3f96-44c3-b4cf-523681fbacbc.html?channel=EuroNews',
  312. 'info_dict': {
  313. 'id': '1912dbbf-3f96-44c3-b4cf-523681fbacbc',
  314. 'ext': 'flv',
  315. 'title': 'EuroNews',
  316. },
  317. 'params': {
  318. 'skip_download': True,
  319. },
  320. }, {
  321. # HLS live stream with ContentItem in og:url
  322. 'url': 'http://www.rainews.it/dl/rainews/live/ContentItem-3156f2f2-dc70-4953-8e2f-70d7489d4ce9.html',
  323. 'info_dict': {
  324. 'id': '3156f2f2-dc70-4953-8e2f-70d7489d4ce9',
  325. 'ext': 'mp4',
  326. 'title': 'La diretta di Rainews24',
  327. },
  328. 'params': {
  329. 'skip_download': True,
  330. },
  331. }, {
  332. # Direct MMS URL
  333. 'url': 'http://www.rai.it/dl/RaiTV/programmi/media/ContentItem-b63a4089-ac28-48cf-bca5-9f5b5bc46df5.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.get('subtitlesUrl'))
  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. )
  393. (["\'])
  394. (?:(?!\1).)*\bContentItem-(?P<id>%s)
  395. ''' % self._UUID_RE,
  396. webpage, 'content item id', default=None, group='id')
  397. content_item_ids = set()
  398. if content_item_id:
  399. content_item_ids.add(content_item_id)
  400. if video_id not in content_item_ids:
  401. content_item_ids.add(video_id)
  402. for content_item_id in content_item_ids:
  403. try:
  404. return self._extract_from_content_id(content_item_id, url)
  405. except GeoRestrictedError:
  406. raise
  407. except ExtractorError:
  408. pass
  409. relinker_url = self._search_regex(
  410. r'''(?x)
  411. (?:
  412. var\s+videoURL|
  413. mediaInfo\.mediaUri
  414. )\s*=\s*
  415. ([\'"])
  416. (?P<url>
  417. (?:https?:)?
  418. //mediapolis(?:vod)?\.rai\.it/relinker/relinkerServlet\.htm\?
  419. (?:(?!\1).)*\bcont=(?:(?!\1).)+)\1
  420. ''',
  421. webpage, 'relinker URL', group='url')
  422. relinker_info = self._extract_relinker_info(
  423. urljoin(url, relinker_url), video_id)
  424. self._sort_formats(relinker_info['formats'])
  425. title = self._search_regex(
  426. r'var\s+videoTitolo\s*=\s*([\'"])(?P<title>[^\'"]+)\1',
  427. webpage, 'title', group='title',
  428. default=None) or self._og_search_title(webpage)
  429. info = {
  430. 'id': video_id,
  431. 'title': title,
  432. }
  433. info.update(relinker_info)
  434. return info