rtve.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290
  1. # coding: utf-8
  2. from __future__ import unicode_literals
  3. import base64
  4. import io
  5. import re
  6. import sys
  7. from .common import InfoExtractor
  8. from ..compat import (
  9. compat_b64decode,
  10. compat_struct_unpack,
  11. )
  12. from ..utils import (
  13. determine_ext,
  14. ExtractorError,
  15. float_or_none,
  16. qualities,
  17. remove_end,
  18. remove_start,
  19. std_headers,
  20. )
  21. _bytes_to_chr = (lambda x: x) if sys.version_info[0] == 2 else (lambda x: map(chr, x))
  22. class RTVEALaCartaIE(InfoExtractor):
  23. IE_NAME = 'rtve.es:alacarta'
  24. IE_DESC = 'RTVE a la carta'
  25. _VALID_URL = r'https?://(?:www\.)?rtve\.es/(m/)?((alacarta|playz?)/videos|filmoteca)/[^/]+/[^/]+/(?P<id>\d+)'
  26. _TESTS = [{
  27. 'url': 'http://www.rtve.es/alacarta/videos/balonmano/o-swiss-cup-masculina-final-espana-suecia/2491869/',
  28. 'md5': '1d49b7e1ca7a7502c56a4bf1b60f1b43',
  29. 'info_dict': {
  30. 'id': '2491869',
  31. 'ext': 'mp4',
  32. 'title': 'Balonmano - Swiss Cup masculina. Final: España-Suecia',
  33. 'duration': 5024.566,
  34. 'series': 'Balonmano',
  35. },
  36. 'expected_warnings': ['Failed to download MPD manifest', 'Failed to download m3u8 information'],
  37. }, {
  38. 'url': 'http://www.rtve.es/play/videos/balonmano/o-swiss-cup-masculina-final-espana-suecia/2491869/',
  39. 'md5': '1d49b7e1ca7a7502c56a4bf1b60f1b43',
  40. 'info_dict': {
  41. 'id': '2491869',
  42. 'ext': 'mp4',
  43. 'title': 'Balonmano - Swiss Cup masculina. Final: España-Suecia',
  44. 'duration': 5024.566,
  45. 'series': 'Balonmano',
  46. },
  47. 'expected_warnings': ['Failed to download MPD manifest', 'Failed to download m3u8 information'],
  48. }, {
  49. 'url': 'http://www.rtve.es/playz/videos/balonmano/o-swiss-cup-masculina-final-espana-suecia/2491869/',
  50. 'md5': '1d49b7e1ca7a7502c56a4bf1b60f1b43',
  51. 'info_dict': {
  52. 'id': '2491869',
  53. 'ext': 'mp4',
  54. 'title': 'Balonmano - Swiss Cup masculina. Final: España-Suecia',
  55. 'duration': 5024.566,
  56. 'series': 'Balonmano',
  57. },
  58. 'expected_warnings': ['Failed to download MPD manifest', 'Failed to download m3u8 information'],
  59. }, {
  60. 'note': 'Live stream',
  61. 'url': 'http://www.rtve.es/alacarta/videos/television/24h-live/1694255/',
  62. 'info_dict': {
  63. 'id': '1694255',
  64. 'ext': 'mp4',
  65. 'title': 're:^24H LIVE [0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}$',
  66. 'is_live': True,
  67. },
  68. 'params': {
  69. 'skip_download': 'live stream',
  70. },
  71. }, {
  72. 'url': 'http://www.rtve.es/alacarta/videos/servir-y-proteger/servir-proteger-capitulo-104/4236788/',
  73. 'md5': 'd850f3c8731ea53952ebab489cf81cbf',
  74. 'info_dict': {
  75. 'id': '4236788',
  76. 'ext': 'mp4',
  77. 'title': 'Servir y proteger - Capítulo 104',
  78. 'duration': 3222.0,
  79. },
  80. 'expected_warnings': ['Failed to download MPD manifest', 'Failed to download m3u8 information'],
  81. }, {
  82. 'url': 'http://www.rtve.es/m/alacarta/videos/cuentame-como-paso/cuentame-como-paso-t16-ultimo-minuto-nuestra-vida-capitulo-276/2969138/?media=tve',
  83. 'only_matching': True,
  84. }, {
  85. 'url': 'http://www.rtve.es/filmoteca/no-do/not-1-introduccion-primer-noticiario-espanol/1465256/',
  86. 'only_matching': True,
  87. }]
  88. def _real_initialize(self):
  89. user_agent_b64 = base64.b64encode(std_headers['User-Agent'].encode('utf-8')).decode('utf-8')
  90. self._manager = self._download_json(
  91. 'http://www.rtve.es/odin/loki/' + user_agent_b64,
  92. None, 'Fetching manager info')['manager']
  93. @staticmethod
  94. def _decrypt_url(png):
  95. encrypted_data = io.BytesIO(compat_b64decode(png)[8:])
  96. while True:
  97. length = compat_struct_unpack('!I', encrypted_data.read(4))[0]
  98. chunk_type = encrypted_data.read(4)
  99. if chunk_type == b'IEND':
  100. break
  101. data = encrypted_data.read(length)
  102. if chunk_type == b'tEXt':
  103. alphabet_data, text = data.split(b'\0')
  104. quality, url_data = text.split(b'%%')
  105. alphabet = []
  106. e = 0
  107. d = 0
  108. for l in _bytes_to_chr(alphabet_data):
  109. if d == 0:
  110. alphabet.append(l)
  111. d = e = (e + 1) % 4
  112. else:
  113. d -= 1
  114. url = ''
  115. f = 0
  116. e = 3
  117. b = 1
  118. for letter in _bytes_to_chr(url_data):
  119. if f == 0:
  120. l = int(letter) * 10
  121. f = 1
  122. else:
  123. if e == 0:
  124. l += int(letter)
  125. url += alphabet[l]
  126. e = (b + 3) % 4
  127. f = 0
  128. b += 1
  129. else:
  130. e -= 1
  131. yield quality.decode(), url
  132. encrypted_data.read(4) # CRC
  133. def _extract_png_formats(self, video_id):
  134. png = self._download_webpage(
  135. 'http://www.rtve.es/ztnr/movil/thumbnail/%s/videos/%s.png' % (self._manager, video_id),
  136. video_id, 'Downloading url information', query={'q': 'v2'})
  137. q = qualities(['Media', 'Alta', 'HQ', 'HD_READY', 'HD_FULL'])
  138. formats = []
  139. for quality, video_url in self._decrypt_url(png):
  140. ext = determine_ext(video_url)
  141. if ext == 'm3u8':
  142. formats.extend(self._extract_m3u8_formats(
  143. video_url, video_id, 'mp4', 'm3u8_native',
  144. m3u8_id='hls', fatal=False))
  145. elif ext == 'mpd':
  146. formats.extend(self._extract_mpd_formats(
  147. video_url, video_id, 'dash', fatal=False))
  148. else:
  149. formats.append({
  150. 'format_id': quality,
  151. 'quality': q(quality),
  152. 'url': video_url,
  153. })
  154. self._sort_formats(formats)
  155. return formats
  156. def _real_extract(self, url):
  157. video_id = self._match_id(url)
  158. info = self._download_json(
  159. 'http://www.rtve.es/api/videos/%s/config/alacarta_videos.json' % video_id,
  160. video_id)['page']['items'][0]
  161. if info['state'] == 'DESPU':
  162. raise ExtractorError('The video is no longer available', expected=True)
  163. title = info['title'].strip()
  164. formats = self._extract_png_formats(video_id)
  165. subtitles = None
  166. sbt_file = info.get('sbtFile')
  167. if sbt_file:
  168. subtitles = self.extract_subtitles(video_id, sbt_file)
  169. is_live = info.get('live') is True
  170. return {
  171. 'id': video_id,
  172. 'title': self._live_title(title) if is_live else title,
  173. 'formats': formats,
  174. 'thumbnail': info.get('image'),
  175. 'subtitles': subtitles,
  176. 'duration': float_or_none(info.get('duration'), 1000),
  177. 'is_live': is_live,
  178. 'series': info.get('programTitle'),
  179. }
  180. def _get_subtitles(self, video_id, sub_file):
  181. subs = self._download_json(
  182. sub_file + '.json', video_id,
  183. 'Downloading subtitles info')['page']['items']
  184. return dict(
  185. (s['lang'], [{'ext': 'vtt', 'url': s['src']}])
  186. for s in subs)
  187. class RTVEInfantilIE(RTVEALaCartaIE):
  188. IE_NAME = 'rtve.es:infantil'
  189. IE_DESC = 'RTVE infantil'
  190. _VALID_URL = r'https?://(?:www\.)?rtve\.es/infantil/serie/[^/]+/video/[^/]+/(?P<id>[0-9]+)/'
  191. _TESTS = [{
  192. 'url': 'http://www.rtve.es/infantil/serie/cleo/video/maneras-vivir/3040283/',
  193. 'md5': '5747454717aedf9f9fdf212d1bcfc48d',
  194. 'info_dict': {
  195. 'id': '3040283',
  196. 'ext': 'mp4',
  197. 'title': 'Maneras de vivir',
  198. 'thumbnail': r're:https?://.+/1426182947956\.JPG',
  199. 'duration': 357.958,
  200. },
  201. 'expected_warnings': ['Failed to download MPD manifest', 'Failed to download m3u8 information'],
  202. }]
  203. class RTVELiveIE(RTVEALaCartaIE):
  204. IE_NAME = 'rtve.es:live'
  205. IE_DESC = 'RTVE.es live streams'
  206. _VALID_URL = r'https?://(?:www\.)?rtve\.es/directo/(?P<id>[a-zA-Z0-9-]+)'
  207. _TESTS = [{
  208. 'url': 'http://www.rtve.es/directo/la-1/',
  209. 'info_dict': {
  210. 'id': 'la-1',
  211. 'ext': 'mp4',
  212. 'title': 're:^La 1 [0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}$',
  213. },
  214. 'params': {
  215. 'skip_download': 'live stream',
  216. }
  217. }]
  218. def _real_extract(self, url):
  219. mobj = re.match(self._VALID_URL, url)
  220. video_id = mobj.group('id')
  221. webpage = self._download_webpage(url, video_id)
  222. title = remove_end(self._og_search_title(webpage), ' en directo en RTVE.es')
  223. title = remove_start(title, 'Estoy viendo ')
  224. vidplayer_id = self._search_regex(
  225. (r'playerId=player([0-9]+)',
  226. r'class=["\'].*?\blive_mod\b.*?["\'][^>]+data-assetid=["\'](\d+)',
  227. r'data-id=["\'](\d+)'),
  228. webpage, 'internal video ID')
  229. return {
  230. 'id': video_id,
  231. 'title': self._live_title(title),
  232. 'formats': self._extract_png_formats(vidplayer_id),
  233. 'is_live': True,
  234. }
  235. class RTVETelevisionIE(InfoExtractor):
  236. IE_NAME = 'rtve.es:television'
  237. _VALID_URL = r'https?://(?:www\.)?rtve\.es/television/[^/]+/[^/]+/(?P<id>\d+).shtml'
  238. _TEST = {
  239. 'url': 'http://www.rtve.es/television/20160628/revolucion-del-movil/1364141.shtml',
  240. 'info_dict': {
  241. 'id': '3069778',
  242. 'ext': 'mp4',
  243. 'title': 'Documentos TV - La revolución del móvil',
  244. 'duration': 3496.948,
  245. },
  246. 'params': {
  247. 'skip_download': True,
  248. },
  249. }
  250. def _real_extract(self, url):
  251. page_id = self._match_id(url)
  252. webpage = self._download_webpage(url, page_id)
  253. alacarta_url = self._search_regex(
  254. r'data-location="alacarta_videos"[^<]+url&quot;:&quot;(http://www\.rtve\.es/alacarta.+?)&',
  255. webpage, 'alacarta url', default=None)
  256. if alacarta_url is None:
  257. raise ExtractorError(
  258. 'The webpage doesn\'t contain any video', expected=True)
  259. return self.url_result(alacarta_url, ie=RTVEALaCartaIE.ie_key())