rtve.py 9.8 KB

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