rai.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408
  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. 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. formats = []
  30. geoprotection = None
  31. is_live = None
  32. duration = None
  33. for platform in ('mon', 'flash', 'native'):
  34. relinker = self._download_xml(
  35. relinker_url, video_id,
  36. note='Downloading XML metadata for platform %s' % platform,
  37. transform_source=fix_xml_ampersands,
  38. query={'output': 45, 'pl': platform},
  39. headers=self.geo_verification_headers())
  40. if not geoprotection:
  41. geoprotection = xpath_text(
  42. relinker, './geoprotection', default=None) == 'Y'
  43. if not is_live:
  44. is_live = xpath_text(
  45. relinker, './is_live', default=None) == 'Y'
  46. if not duration:
  47. duration = parse_duration(xpath_text(
  48. relinker, './duration', default=None))
  49. url_elem = find_xpath_attr(relinker, './url', 'type', 'content')
  50. if url_elem is None:
  51. continue
  52. media_url = url_elem.text
  53. # This does not imply geo restriction (e.g.
  54. # http://www.raisport.rai.it/dl/raiSport/media/rassegna-stampa-04a9f4bd-b563-40cf-82a6-aad3529cb4a9.html)
  55. if media_url == 'http://download.rai.it/video_no_available.mp4':
  56. continue
  57. ext = determine_ext(media_url)
  58. if (ext == 'm3u8' and platform != 'mon') or (ext == 'f4m' and platform != 'flash'):
  59. continue
  60. if ext == 'm3u8':
  61. formats.extend(self._extract_m3u8_formats(
  62. media_url, video_id, 'mp4', 'm3u8_native',
  63. m3u8_id='hls', fatal=False))
  64. elif ext == 'f4m':
  65. manifest_url = update_url_query(
  66. media_url.replace('manifest#live_hds.f4m', 'manifest.f4m'),
  67. {'hdcore': '3.7.0', 'plugin': 'aasp-3.7.0.39.44'})
  68. formats.extend(self._extract_f4m_formats(
  69. manifest_url, video_id, f4m_id='hds', fatal=False))
  70. else:
  71. bitrate = int_or_none(xpath_text(relinker, 'bitrate'))
  72. formats.append({
  73. 'url': media_url,
  74. 'tbr': bitrate if bitrate > 0 else None,
  75. 'format_id': 'http-%d' % bitrate if bitrate > 0 else 'http',
  76. })
  77. if not formats and geoprotection is True:
  78. self.raise_geo_restricted(countries=self._GEO_COUNTRIES)
  79. return dict((k, v) for k, v in {
  80. 'is_live': is_live,
  81. 'duration': duration,
  82. 'formats': formats,
  83. }.items() if v is not None)
  84. class RaiPlayIE(RaiBaseIE):
  85. _VALID_URL = r'(?P<url>https?://(?:www\.)?raiplay\.it/.+?-(?P<id>%s)\.html)' % RaiBaseIE._UUID_RE
  86. _TESTS = [{
  87. 'url': 'http://www.raiplay.it/video/2016/10/La-Casa-Bianca-e06118bb-59a9-4636-b914-498e4cfd2c66.html?source=twitter',
  88. 'md5': '340aa3b7afb54bfd14a8c11786450d76',
  89. 'info_dict': {
  90. 'id': 'e06118bb-59a9-4636-b914-498e4cfd2c66',
  91. 'ext': 'mp4',
  92. 'title': 'La Casa Bianca',
  93. 'alt_title': 'S2016 - Puntata del 23/10/2016',
  94. 'description': 'md5:a09d45890850458077d1f68bb036e0a5',
  95. 'thumbnail': r're:^https?://.*\.jpg$',
  96. 'uploader': 'Rai 3',
  97. 'creator': 'Rai 3',
  98. 'duration': 3278,
  99. 'timestamp': 1477764300,
  100. 'upload_date': '20161029',
  101. 'series': 'La Casa Bianca',
  102. 'season': '2016',
  103. },
  104. }, {
  105. 'url': 'http://www.raiplay.it/video/2014/04/Report-del-07042014-cb27157f-9dd0-4aee-b788-b1f67643a391.html',
  106. 'md5': '8970abf8caf8aef4696e7b1f2adfc696',
  107. 'info_dict': {
  108. 'id': 'cb27157f-9dd0-4aee-b788-b1f67643a391',
  109. 'ext': 'mp4',
  110. 'title': 'Report del 07/04/2014',
  111. 'alt_title': 'S2013/14 - Puntata del 07/04/2014',
  112. 'description': 'md5:f27c544694cacb46a078db84ec35d2d9',
  113. 'thumbnail': r're:^https?://.*\.jpg$',
  114. 'uploader': 'Rai 5',
  115. 'creator': 'Rai 5',
  116. 'duration': 6160,
  117. 'series': 'Report',
  118. 'season_number': 5,
  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. url, video_id = mobj.group('url', 'id')
  131. media = self._download_json(
  132. '%s?json' % url, video_id, 'Downloading video JSON')
  133. title = media['name']
  134. video = media['video']
  135. relinker_info = self._extract_relinker_info(video['contentUrl'], video_id)
  136. self._sort_formats(relinker_info['formats'])
  137. thumbnails = []
  138. if 'images' in media:
  139. for _, value in media.get('images').items():
  140. if value:
  141. thumbnails.append({
  142. 'url': value.replace('[RESOLUTION]', '600x400')
  143. })
  144. timestamp = unified_timestamp(try_get(
  145. media, lambda x: x['availabilities'][0]['start'], compat_str))
  146. info = {
  147. 'id': video_id,
  148. 'title': title,
  149. 'alt_title': media.get('subtitle'),
  150. 'description': media.get('description'),
  151. 'uploader': media.get('channel'),
  152. 'creator': media.get('editor'),
  153. 'duration': parse_duration(video.get('duration')),
  154. 'timestamp': timestamp,
  155. 'thumbnails': thumbnails,
  156. 'series': try_get(
  157. media, lambda x: x['isPartOf']['name'], compat_str),
  158. 'season_number': int_or_none(try_get(
  159. media, lambda x: x['isPartOf']['numeroStagioni'])),
  160. 'season': media.get('stagione') or None,
  161. }
  162. info.update(relinker_info)
  163. return info
  164. class RaiIE(RaiBaseIE):
  165. _VALID_URL = r'https?://[^/]+\.(?:rai\.(?:it|tv)|rainews\.it)/dl/.+?-(?P<id>%s)(?:-.+?)?\.html' % RaiBaseIE._UUID_RE
  166. _TESTS = [{
  167. # var uniquename = "ContentItem-..."
  168. # data-id="ContentItem-..."
  169. 'url': 'http://www.raisport.rai.it/dl/raiSport/media/rassegna-stampa-04a9f4bd-b563-40cf-82a6-aad3529cb4a9.html',
  170. 'info_dict': {
  171. 'id': '04a9f4bd-b563-40cf-82a6-aad3529cb4a9',
  172. 'ext': 'mp4',
  173. 'title': 'TG PRIMO TEMPO',
  174. 'thumbnail': r're:^https?://.*\.jpg$',
  175. 'duration': 1758,
  176. 'upload_date': '20140612',
  177. }
  178. }, {
  179. # with ContentItem in many metas
  180. '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',
  181. 'info_dict': {
  182. 'id': '1632c009-c843-4836-bb65-80c33084a64b',
  183. 'ext': 'mp4',
  184. 'title': 'Weekend al cinema, da Hollywood arriva il thriller di Tate Taylor "La ragazza del treno"',
  185. 'description': 'I film in uscita questa settimana.',
  186. 'thumbnail': r're:^https?://.*\.png$',
  187. 'duration': 833,
  188. 'upload_date': '20161103',
  189. }
  190. }, {
  191. # with ContentItem in og:url
  192. 'url': 'http://www.rai.it/dl/RaiTV/programmi/media/ContentItem-efb17665-691c-45d5-a60c-5301333cbb0c.html',
  193. 'md5': '11959b4e44fa74de47011b5799490adf',
  194. 'info_dict': {
  195. 'id': 'efb17665-691c-45d5-a60c-5301333cbb0c',
  196. 'ext': 'mp4',
  197. 'title': 'TG1 ore 20:00 del 03/11/2016',
  198. 'description': 'TG1 edizione integrale ore 20:00 del giorno 03/11/2016',
  199. 'thumbnail': r're:^https?://.*\.jpg$',
  200. 'duration': 2214,
  201. 'upload_date': '20161103',
  202. }
  203. }, {
  204. # drawMediaRaiTV(...)
  205. 'url': 'http://www.report.rai.it/dl/Report/puntata/ContentItem-0c7a664b-d0f4-4b2c-8835-3f82e46f433e.html',
  206. 'md5': '2dd727e61114e1ee9c47f0da6914e178',
  207. 'info_dict': {
  208. 'id': '59d69d28-6bb6-409d-a4b5-ed44096560af',
  209. 'ext': 'mp4',
  210. 'title': 'Il pacco',
  211. 'description': 'md5:4b1afae1364115ce5d78ed83cd2e5b3a',
  212. 'thumbnail': r're:^https?://.*\.jpg$',
  213. 'upload_date': '20141221',
  214. },
  215. }, {
  216. # initEdizione('ContentItem-...'
  217. 'url': 'http://www.tg1.rai.it/dl/tg1/2010/edizioni/ContentSet-9b6e0cba-4bef-4aef-8cf0-9f7f665b7dfb-tg1.html?item=undefined',
  218. 'info_dict': {
  219. 'id': 'c2187016-8484-4e3a-8ac8-35e475b07303',
  220. 'ext': 'mp4',
  221. 'title': r're:TG1 ore \d{2}:\d{2} del \d{2}/\d{2}/\d{4}',
  222. 'duration': 2274,
  223. 'upload_date': '20170401',
  224. },
  225. 'skip': 'Changes daily',
  226. }, {
  227. # HDS live stream with only relinker URL
  228. 'url': 'http://www.rai.tv/dl/RaiTV/dirette/PublishingBlock-1912dbbf-3f96-44c3-b4cf-523681fbacbc.html?channel=EuroNews',
  229. 'info_dict': {
  230. 'id': '1912dbbf-3f96-44c3-b4cf-523681fbacbc',
  231. 'ext': 'flv',
  232. 'title': 'EuroNews',
  233. },
  234. 'params': {
  235. 'skip_download': True,
  236. },
  237. }, {
  238. # HLS live stream with ContentItem in og:url
  239. 'url': 'http://www.rainews.it/dl/rainews/live/ContentItem-3156f2f2-dc70-4953-8e2f-70d7489d4ce9.html',
  240. 'info_dict': {
  241. 'id': '3156f2f2-dc70-4953-8e2f-70d7489d4ce9',
  242. 'ext': 'mp4',
  243. 'title': 'La diretta di Rainews24',
  244. },
  245. 'params': {
  246. 'skip_download': True,
  247. },
  248. }]
  249. def _extract_from_content_id(self, content_id, url):
  250. media = self._download_json(
  251. 'http://www.rai.tv/dl/RaiTV/programmi/media/ContentItem-%s.html?json' % content_id,
  252. content_id, 'Downloading video JSON')
  253. title = media['name'].strip()
  254. media_type = media['type']
  255. if 'Audio' in media_type:
  256. relinker_info = {
  257. 'formats': {
  258. 'format_id': media.get('formatoAudio'),
  259. 'url': media['audioUrl'],
  260. 'ext': media.get('formatoAudio'),
  261. }
  262. }
  263. elif 'Video' in media_type:
  264. relinker_info = self._extract_relinker_info(media['mediaUri'], content_id)
  265. else:
  266. raise ExtractorError('not a media file')
  267. self._sort_formats(relinker_info['formats'])
  268. thumbnails = []
  269. for image_type in ('image', 'image_medium', 'image_300'):
  270. thumbnail_url = media.get(image_type)
  271. if thumbnail_url:
  272. thumbnails.append({
  273. 'url': compat_urlparse.urljoin(url, thumbnail_url),
  274. })
  275. subtitles = {}
  276. captions = media.get('subtitlesUrl')
  277. if captions:
  278. STL_EXT = '.stl'
  279. SRT_EXT = '.srt'
  280. if captions.endswith(STL_EXT):
  281. captions = captions[:-len(STL_EXT)] + SRT_EXT
  282. subtitles['it'] = [{
  283. 'ext': 'srt',
  284. 'url': captions,
  285. }]
  286. info = {
  287. 'id': content_id,
  288. 'title': title,
  289. 'description': strip_or_none(media.get('desc')),
  290. 'thumbnails': thumbnails,
  291. 'uploader': media.get('author'),
  292. 'upload_date': unified_strdate(media.get('date')),
  293. 'duration': parse_duration(media.get('length')),
  294. 'subtitles': subtitles,
  295. }
  296. info.update(relinker_info)
  297. return info
  298. def _real_extract(self, url):
  299. video_id = self._match_id(url)
  300. webpage = self._download_webpage(url, video_id)
  301. content_item_id = None
  302. content_item_url = self._html_search_meta(
  303. ('og:url', 'og:video', 'og:video:secure_url', 'twitter:url',
  304. 'twitter:player', 'jsonlink'), webpage, default=None)
  305. if content_item_url:
  306. content_item_id = self._search_regex(
  307. r'ContentItem-(%s)' % self._UUID_RE, content_item_url,
  308. 'content item id', default=None)
  309. if not content_item_id:
  310. content_item_id = self._search_regex(
  311. r'''(?x)
  312. (?:
  313. (?:initEdizione|drawMediaRaiTV)\(|
  314. <(?:[^>]+\bdata-id|var\s+uniquename)=
  315. )
  316. (["\'])
  317. (?:(?!\1).)*\bContentItem-(?P<id>%s)
  318. ''' % self._UUID_RE,
  319. webpage, 'content item id', default=None, group='id')
  320. content_item_ids = set()
  321. if content_item_id:
  322. content_item_ids.add(content_item_id)
  323. if video_id not in content_item_ids:
  324. content_item_ids.add(video_id)
  325. for content_item_id in content_item_ids:
  326. try:
  327. return self._extract_from_content_id(content_item_id, url)
  328. except GeoRestrictedError:
  329. raise
  330. except ExtractorError:
  331. pass
  332. relinker_url = self._search_regex(
  333. r'''(?x)
  334. (?:
  335. var\s+videoURL|
  336. mediaInfo\.mediaUri
  337. )\s*=\s*
  338. ([\'"])
  339. (?P<url>
  340. (?:https?:)?
  341. //mediapolis(?:vod)?\.rai\.it/relinker/relinkerServlet\.htm\?
  342. (?:(?!\1).)*\bcont=(?:(?!\1).)+)\1
  343. ''',
  344. webpage, 'relinker URL', group='url')
  345. relinker_info = self._extract_relinker_info(
  346. urljoin(url, relinker_url), video_id)
  347. self._sort_formats(relinker_info['formats'])
  348. title = self._search_regex(
  349. r'var\s+videoTitolo\s*=\s*([\'"])(?P<title>[^\'"]+)\1',
  350. webpage, 'title', group='title',
  351. default=None) or self._og_search_title(webpage)
  352. info = {
  353. 'id': video_id,
  354. 'title': title,
  355. }
  356. info.update(relinker_info)
  357. return info