rtve.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342
  1. import base64
  2. import io
  3. import struct
  4. from .common import InfoExtractor
  5. from ..utils import (
  6. ExtractorError,
  7. determine_ext,
  8. float_or_none,
  9. qualities,
  10. remove_end,
  11. remove_start,
  12. try_get,
  13. )
  14. class RTVEALaCartaIE(InfoExtractor):
  15. IE_NAME = 'rtve.es:alacarta'
  16. IE_DESC = 'RTVE a la carta'
  17. _VALID_URL = r'https?://(?:www\.)?rtve\.es/(m/)?(alacarta/videos|filmoteca)/[^/]+/[^/]+/(?P<id>\d+)'
  18. _TESTS = [{
  19. 'url': 'http://www.rtve.es/alacarta/videos/balonmano/o-swiss-cup-masculina-final-espana-suecia/2491869/',
  20. 'md5': '1d49b7e1ca7a7502c56a4bf1b60f1b43',
  21. 'info_dict': {
  22. 'id': '2491869',
  23. 'ext': 'mp4',
  24. 'title': 'Balonmano - Swiss Cup masculina. Final: España-Suecia',
  25. 'duration': 5024.566,
  26. 'series': 'Balonmano',
  27. },
  28. 'expected_warnings': ['Failed to download MPD manifest', 'Failed to download m3u8 information'],
  29. }, {
  30. 'note': 'Live stream',
  31. 'url': 'http://www.rtve.es/alacarta/videos/television/24h-live/1694255/',
  32. 'info_dict': {
  33. 'id': '1694255',
  34. 'ext': 'mp4',
  35. 'title': 're:^24H LIVE [0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}$',
  36. 'is_live': True,
  37. },
  38. 'params': {
  39. 'skip_download': 'live stream',
  40. },
  41. }, {
  42. 'url': 'http://www.rtve.es/alacarta/videos/servir-y-proteger/servir-proteger-capitulo-104/4236788/',
  43. 'md5': 'd850f3c8731ea53952ebab489cf81cbf',
  44. 'info_dict': {
  45. 'id': '4236788',
  46. 'ext': 'mp4',
  47. 'title': 'Servir y proteger - Capítulo 104',
  48. 'duration': 3222.0,
  49. },
  50. 'expected_warnings': ['Failed to download MPD manifest', 'Failed to download m3u8 information'],
  51. }, {
  52. 'url': 'http://www.rtve.es/m/alacarta/videos/cuentame-como-paso/cuentame-como-paso-t16-ultimo-minuto-nuestra-vida-capitulo-276/2969138/?media=tve',
  53. 'only_matching': True,
  54. }, {
  55. 'url': 'http://www.rtve.es/filmoteca/no-do/not-1-introduccion-primer-noticiario-espanol/1465256/',
  56. 'only_matching': True,
  57. }]
  58. def _real_initialize(self):
  59. user_agent_b64 = base64.b64encode(self.get_param('http_headers')['User-Agent'].encode()).decode('utf-8')
  60. self._manager = self._download_json(
  61. 'http://www.rtve.es/odin/loki/' + user_agent_b64,
  62. None, 'Fetching manager info')['manager']
  63. @staticmethod
  64. def _decrypt_url(png):
  65. encrypted_data = io.BytesIO(base64.b64decode(png)[8:])
  66. while True:
  67. length = struct.unpack('!I', encrypted_data.read(4))[0]
  68. chunk_type = encrypted_data.read(4)
  69. if chunk_type == b'IEND':
  70. break
  71. data = encrypted_data.read(length)
  72. if chunk_type == b'tEXt':
  73. alphabet_data, text = data.split(b'\0')
  74. quality, url_data = text.split(b'%%')
  75. alphabet = []
  76. e = 0
  77. d = 0
  78. for l in alphabet_data.decode('iso-8859-1'):
  79. if d == 0:
  80. alphabet.append(l)
  81. d = e = (e + 1) % 4
  82. else:
  83. d -= 1
  84. url = ''
  85. f = 0
  86. e = 3
  87. b = 1
  88. for letter in url_data.decode('iso-8859-1'):
  89. if f == 0:
  90. l = int(letter) * 10
  91. f = 1
  92. else:
  93. if e == 0:
  94. l += int(letter)
  95. url += alphabet[l]
  96. e = (b + 3) % 4
  97. f = 0
  98. b += 1
  99. else:
  100. e -= 1
  101. yield quality.decode(), url
  102. encrypted_data.read(4) # CRC
  103. def _extract_png_formats(self, video_id):
  104. png = self._download_webpage(
  105. f'http://www.rtve.es/ztnr/movil/thumbnail/{self._manager}/videos/{video_id}.png',
  106. video_id, 'Downloading url information', query={'q': 'v2'})
  107. q = qualities(['Media', 'Alta', 'HQ', 'HD_READY', 'HD_FULL'])
  108. formats = []
  109. for quality, video_url in self._decrypt_url(png):
  110. ext = determine_ext(video_url)
  111. if ext == 'm3u8':
  112. formats.extend(self._extract_m3u8_formats(
  113. video_url, video_id, 'mp4', 'm3u8_native',
  114. m3u8_id='hls', fatal=False))
  115. elif ext == 'mpd':
  116. formats.extend(self._extract_mpd_formats(
  117. video_url, video_id, 'dash', fatal=False))
  118. else:
  119. formats.append({
  120. 'format_id': quality,
  121. 'quality': q(quality),
  122. 'url': video_url,
  123. })
  124. return formats
  125. def _real_extract(self, url):
  126. video_id = self._match_id(url)
  127. info = self._download_json(
  128. f'http://www.rtve.es/api/videos/{video_id}/config/alacarta_videos.json',
  129. video_id)['page']['items'][0]
  130. if info['state'] == 'DESPU':
  131. raise ExtractorError('The video is no longer available', expected=True)
  132. title = info['title'].strip()
  133. formats = self._extract_png_formats(video_id)
  134. subtitles = None
  135. sbt_file = info.get('sbtFile')
  136. if sbt_file:
  137. subtitles = self.extract_subtitles(video_id, sbt_file)
  138. is_live = info.get('live') is True
  139. return {
  140. 'id': video_id,
  141. 'title': title,
  142. 'formats': formats,
  143. 'thumbnail': info.get('image'),
  144. 'subtitles': subtitles,
  145. 'duration': float_or_none(info.get('duration'), 1000),
  146. 'is_live': is_live,
  147. 'series': info.get('programTitle'),
  148. }
  149. def _get_subtitles(self, video_id, sub_file):
  150. subs = self._download_json(
  151. sub_file + '.json', video_id,
  152. 'Downloading subtitles info')['page']['items']
  153. return dict(
  154. (s['lang'], [{'ext': 'vtt', 'url': s['src']}])
  155. for s in subs)
  156. class RTVEAudioIE(RTVEALaCartaIE): # XXX: Do not subclass from concrete IE
  157. IE_NAME = 'rtve.es:audio'
  158. IE_DESC = 'RTVE audio'
  159. _VALID_URL = r'https?://(?:www\.)?rtve\.es/(alacarta|play)/audios/[^/]+/[^/]+/(?P<id>[0-9]+)'
  160. _TESTS = [{
  161. 'url': 'https://www.rtve.es/alacarta/audios/a-hombros-de-gigantes/palabra-ingeniero-codigos-informaticos-27-04-21/5889192/',
  162. 'md5': 'ae06d27bff945c4e87a50f89f6ce48ce',
  163. 'info_dict': {
  164. 'id': '5889192',
  165. 'ext': 'mp3',
  166. 'title': 'Códigos informáticos',
  167. 'thumbnail': r're:https?://.+/1598856591583.jpg',
  168. 'duration': 349.440,
  169. 'series': 'A hombros de gigantes',
  170. },
  171. }, {
  172. 'url': 'https://www.rtve.es/play/audios/en-radio-3/ignatius-farray/5791165/',
  173. 'md5': '072855ab89a9450e0ba314c717fa5ebc',
  174. 'info_dict': {
  175. 'id': '5791165',
  176. 'ext': 'mp3',
  177. 'title': 'Ignatius Farray',
  178. 'thumbnail': r're:https?://.+/1613243011863.jpg',
  179. 'duration': 3559.559,
  180. 'series': 'En Radio 3',
  181. },
  182. }, {
  183. 'url': 'https://www.rtve.es/play/audios/frankenstein-o-el-moderno-prometeo/capitulo-26-ultimo-muerte-victor-juan-jose-plans-mary-shelley/6082623/',
  184. 'md5': '0eadab248cc8dd193fa5765712e84d5c',
  185. 'info_dict': {
  186. 'id': '6082623',
  187. 'ext': 'mp3',
  188. 'title': 'Capítulo 26 y último: La muerte de Victor',
  189. 'thumbnail': r're:https?://.+/1632147445707.jpg',
  190. 'duration': 3174.086,
  191. 'series': 'Frankenstein o el moderno Prometeo',
  192. },
  193. }]
  194. def _extract_png_formats(self, audio_id):
  195. """
  196. This function retrieves media related png thumbnail which obfuscate
  197. valuable information about the media. This information is decrypted
  198. via base class _decrypt_url function providing media quality and
  199. media url
  200. """
  201. png = self._download_webpage(
  202. f'http://www.rtve.es/ztnr/movil/thumbnail/{self._manager}/audios/{audio_id}.png',
  203. audio_id, 'Downloading url information', query={'q': 'v2'})
  204. q = qualities(['Media', 'Alta', 'HQ', 'HD_READY', 'HD_FULL'])
  205. formats = []
  206. for quality, audio_url in self._decrypt_url(png):
  207. ext = determine_ext(audio_url)
  208. if ext == 'm3u8':
  209. formats.extend(self._extract_m3u8_formats(
  210. audio_url, audio_id, 'mp4', 'm3u8_native',
  211. m3u8_id='hls', fatal=False))
  212. elif ext == 'mpd':
  213. formats.extend(self._extract_mpd_formats(
  214. audio_url, audio_id, 'dash', fatal=False))
  215. else:
  216. formats.append({
  217. 'format_id': quality,
  218. 'quality': q(quality),
  219. 'url': audio_url,
  220. })
  221. return formats
  222. def _real_extract(self, url):
  223. audio_id = self._match_id(url)
  224. info = self._download_json(
  225. f'https://www.rtve.es/api/audios/{audio_id}.json',
  226. audio_id)['page']['items'][0]
  227. return {
  228. 'id': audio_id,
  229. 'title': info['title'].strip(),
  230. 'thumbnail': info.get('thumbnail'),
  231. 'duration': float_or_none(info.get('duration'), 1000),
  232. 'series': try_get(info, lambda x: x['programInfo']['title']),
  233. 'formats': self._extract_png_formats(audio_id),
  234. }
  235. class RTVEInfantilIE(RTVEALaCartaIE): # XXX: Do not subclass from concrete IE
  236. IE_NAME = 'rtve.es:infantil'
  237. IE_DESC = 'RTVE infantil'
  238. _VALID_URL = r'https?://(?:www\.)?rtve\.es/infantil/serie/[^/]+/video/[^/]+/(?P<id>[0-9]+)/'
  239. _TESTS = [{
  240. 'url': 'http://www.rtve.es/infantil/serie/cleo/video/maneras-vivir/3040283/',
  241. 'md5': '5747454717aedf9f9fdf212d1bcfc48d',
  242. 'info_dict': {
  243. 'id': '3040283',
  244. 'ext': 'mp4',
  245. 'title': 'Maneras de vivir',
  246. 'thumbnail': r're:https?://.+/1426182947956\.JPG',
  247. 'duration': 357.958,
  248. },
  249. 'expected_warnings': ['Failed to download MPD manifest', 'Failed to download m3u8 information'],
  250. }]
  251. class RTVELiveIE(RTVEALaCartaIE): # XXX: Do not subclass from concrete IE
  252. IE_NAME = 'rtve.es:live'
  253. IE_DESC = 'RTVE.es live streams'
  254. _VALID_URL = r'https?://(?:www\.)?rtve\.es/directo/(?P<id>[a-zA-Z0-9-]+)'
  255. _TESTS = [{
  256. 'url': 'http://www.rtve.es/directo/la-1/',
  257. 'info_dict': {
  258. 'id': 'la-1',
  259. 'ext': 'mp4',
  260. 'title': 're:^La 1 [0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}$',
  261. },
  262. 'params': {
  263. 'skip_download': 'live stream',
  264. },
  265. }]
  266. def _real_extract(self, url):
  267. mobj = self._match_valid_url(url)
  268. video_id = mobj.group('id')
  269. webpage = self._download_webpage(url, video_id)
  270. title = remove_end(self._og_search_title(webpage), ' en directo en RTVE.es')
  271. title = remove_start(title, 'Estoy viendo ')
  272. vidplayer_id = self._search_regex(
  273. (r'playerId=player([0-9]+)',
  274. r'class=["\'].*?\blive_mod\b.*?["\'][^>]+data-assetid=["\'](\d+)',
  275. r'data-id=["\'](\d+)'),
  276. webpage, 'internal video ID')
  277. return {
  278. 'id': video_id,
  279. 'title': title,
  280. 'formats': self._extract_png_formats(vidplayer_id),
  281. 'is_live': True,
  282. }
  283. class RTVETelevisionIE(InfoExtractor):
  284. IE_NAME = 'rtve.es:television'
  285. _VALID_URL = r'https?://(?:www\.)?rtve\.es/television/[^/]+/[^/]+/(?P<id>\d+).shtml'
  286. _TEST = {
  287. 'url': 'http://www.rtve.es/television/20160628/revolucion-del-movil/1364141.shtml',
  288. 'info_dict': {
  289. 'id': '3069778',
  290. 'ext': 'mp4',
  291. 'title': 'Documentos TV - La revolución del móvil',
  292. 'duration': 3496.948,
  293. },
  294. 'params': {
  295. 'skip_download': True,
  296. },
  297. }
  298. def _real_extract(self, url):
  299. page_id = self._match_id(url)
  300. webpage = self._download_webpage(url, page_id)
  301. alacarta_url = self._search_regex(
  302. r'data-location="alacarta_videos"[^<]+url&quot;:&quot;(http://www\.rtve\.es/alacarta.+?)&',
  303. webpage, 'alacarta url', default=None)
  304. if alacarta_url is None:
  305. raise ExtractorError(
  306. 'The webpage doesn\'t contain any video', expected=True)
  307. return self.url_result(alacarta_url, ie=RTVEALaCartaIE.ie_key())