summaryrefslogtreecommitdiff
path: root/youtube_dl/extractor/rtve.py
blob: fa60ffd5e3fbadc013513c3e22d421f2c2c7a0bb (plain)
    1 # coding: utf-8
    2 from __future__ import unicode_literals
    3 
    4 import base64
    5 import re
    6 import time
    7 
    8 from .common import InfoExtractor
    9 from ..compat import (
   10     compat_struct_unpack,
   11 )
   12 from ..utils import (
   13     determine_ext,
   14     ExtractorError,
   15     float_or_none,
   16     remove_end,
   17     remove_start,
   18     sanitized_Request,
   19     std_headers,
   20 )
   21 
   22 
   23 def _decrypt_url(png):
   24     encrypted_data = base64.b64decode(png.encode('utf-8'))
   25     text_index = encrypted_data.find(b'tEXt')
   26     text_chunk = encrypted_data[text_index - 4:]
   27     length = compat_struct_unpack('!I', text_chunk[:4])[0]
   28     # Use bytearray to get integers when iterating in both python 2.x and 3.x
   29     data = bytearray(text_chunk[8:8 + length])
   30     data = [chr(b) for b in data if b != 0]
   31     hash_index = data.index('#')
   32     alphabet_data = data[:hash_index]
   33     url_data = data[hash_index + 1:]
   34     if url_data[0] == 'H' and url_data[3] == '%':
   35         # remove useless HQ%% at the start
   36         url_data = url_data[4:]
   37 
   38     alphabet = []
   39     e = 0
   40     d = 0
   41     for l in alphabet_data:
   42         if d == 0:
   43             alphabet.append(l)
   44             d = e = (e + 1) % 4
   45         else:
   46             d -= 1
   47     url = ''
   48     f = 0
   49     e = 3
   50     b = 1
   51     for letter in url_data:
   52         if f == 0:
   53             l = int(letter) * 10
   54             f = 1
   55         else:
   56             if e == 0:
   57                 l += int(letter)
   58                 url += alphabet[l]
   59                 e = (b + 3) % 4
   60                 f = 0
   61                 b += 1
   62             else:
   63                 e -= 1
   64 
   65     return url
   66 
   67 
   68 class RTVEALaCartaIE(InfoExtractor):
   69     IE_NAME = 'rtve.es:alacarta'
   70     IE_DESC = 'RTVE a la carta'
   71     _VALID_URL = r'https?://(?:www\.)?rtve\.es/(m/)?(alacarta/videos|filmoteca)/[^/]+/[^/]+/(?P<id>\d+)'
   72 
   73     _TESTS = [{
   74         'url': 'http://www.rtve.es/alacarta/videos/balonmano/o-swiss-cup-masculina-final-espana-suecia/2491869/',
   75         'md5': '1d49b7e1ca7a7502c56a4bf1b60f1b43',
   76         'info_dict': {
   77             'id': '2491869',
   78             'ext': 'mp4',
   79             'title': 'Balonmano - Swiss Cup masculina. Final: España-Suecia',
   80             'duration': 5024.566,
   81         },
   82     }, {
   83         'note': 'Live stream',
   84         'url': 'http://www.rtve.es/alacarta/videos/television/24h-live/1694255/',
   85         'info_dict': {
   86             'id': '1694255',
   87             'ext': 'flv',
   88             'title': 'TODO',
   89         },
   90         'skip': 'The f4m manifest can\'t be used yet',
   91     }, {
   92         'url': 'http://www.rtve.es/alacarta/videos/servir-y-proteger/servir-proteger-capitulo-104/4236788/',
   93         'md5': 'e55e162379ad587e9640eda4f7353c0f',
   94         'info_dict': {
   95             'id': '4236788',
   96             'ext': 'mp4',
   97             'title': 'Servir y proteger - Capítulo 104 ',
   98             'duration': 3222.0,
   99         },
  100         'params': {
  101             'skip_download': True,  # requires ffmpeg
  102         },
  103     }, {
  104         'url': 'http://www.rtve.es/m/alacarta/videos/cuentame-como-paso/cuentame-como-paso-t16-ultimo-minuto-nuestra-vida-capitulo-276/2969138/?media=tve',
  105         'only_matching': True,
  106     }, {
  107         'url': 'http://www.rtve.es/filmoteca/no-do/not-1-introduccion-primer-noticiario-espanol/1465256/',
  108         'only_matching': True,
  109     }]
  110 
  111     def _real_initialize(self):
  112         user_agent_b64 = base64.b64encode(std_headers['User-Agent'].encode('utf-8')).decode('utf-8')
  113         manager_info = self._download_json(
  114             'http://www.rtve.es/odin/loki/' + user_agent_b64,
  115             None, 'Fetching manager info')
  116         self._manager = manager_info['manager']
  117 
  118     def _real_extract(self, url):
  119         mobj = re.match(self._VALID_URL, url)
  120         video_id = mobj.group('id')
  121         info = self._download_json(
  122             'http://www.rtve.es/api/videos/%s/config/alacarta_videos.json' % video_id,
  123             video_id)['page']['items'][0]
  124         if info['state'] == 'DESPU':
  125             raise ExtractorError('The video is no longer available', expected=True)
  126         title = info['title']
  127         png_url = 'http://www.rtve.es/ztnr/movil/thumbnail/%s/videos/%s.png' % (self._manager, video_id)
  128         png_request = sanitized_Request(png_url)
  129         png_request.add_header('Referer', url)
  130         png = self._download_webpage(png_request, video_id, 'Downloading url information')
  131         video_url = _decrypt_url(png)
  132         ext = determine_ext(video_url)
  133 
  134         formats = []
  135         if not video_url.endswith('.f4m') and ext != 'm3u8':
  136             if '?' not in video_url:
  137                 video_url = video_url.replace('resources/', 'auth/resources/')
  138             video_url = video_url.replace('.net.rtve', '.multimedia.cdn.rtve')
  139 
  140         if ext == 'm3u8':
  141             formats.extend(self._extract_m3u8_formats(
  142                 video_url, video_id, ext='mp4', entry_protocol='m3u8_native',
  143                 m3u8_id='hls', fatal=False))
  144         elif ext == 'f4m':
  145             formats.extend(self._extract_f4m_formats(
  146                 video_url, video_id, f4m_id='hds', fatal=False))
  147         else:
  148             formats.append({
  149                 'url': video_url,
  150             })
  151         self._sort_formats(formats)
  152 
  153         subtitles = None
  154         if info.get('sbtFile') is not None:
  155             subtitles = self.extract_subtitles(video_id, info['sbtFile'])
  156 
  157         return {
  158             'id': video_id,
  159             'title': title,
  160             'formats': formats,
  161             'thumbnail': info.get('image'),
  162             'page_url': url,
  163             'subtitles': subtitles,
  164             'duration': float_or_none(info.get('duration'), scale=1000),
  165         }
  166 
  167     def _get_subtitles(self, video_id, sub_file):
  168         subs = self._download_json(
  169             sub_file + '.json', video_id,
  170             'Downloading subtitles info')['page']['items']
  171         return dict(
  172             (s['lang'], [{'ext': 'vtt', 'url': s['src']}])
  173             for s in subs)
  174 
  175 
  176 class RTVEInfantilIE(InfoExtractor):
  177     IE_NAME = 'rtve.es:infantil'
  178     IE_DESC = 'RTVE infantil'
  179     _VALID_URL = r'https?://(?:www\.)?rtve\.es/infantil/serie/(?P<show>[^/]*)/video/(?P<short_title>[^/]*)/(?P<id>[0-9]+)/'
  180 
  181     _TESTS = [{
  182         'url': 'http://www.rtve.es/infantil/serie/cleo/video/maneras-vivir/3040283/',
  183         'md5': '915319587b33720b8e0357caaa6617e6',
  184         'info_dict': {
  185             'id': '3040283',
  186             'ext': 'mp4',
  187             'title': 'Maneras de vivir',
  188             'thumbnail': 'http://www.rtve.es/resources/jpg/6/5/1426182947956.JPG',
  189             'duration': 357.958,
  190         },
  191     }]
  192 
  193     def _real_extract(self, url):
  194         video_id = self._match_id(url)
  195         info = self._download_json(
  196             'http://www.rtve.es/api/videos/%s/config/alacarta_videos.json' % video_id,
  197             video_id)['page']['items'][0]
  198 
  199         webpage = self._download_webpage(url, video_id)
  200         vidplayer_id = self._search_regex(
  201             r' id="vidplayer([0-9]+)"', webpage, 'internal video ID')
  202 
  203         png_url = 'http://www.rtve.es/ztnr/movil/thumbnail/default/videos/%s.png' % vidplayer_id
  204         png = self._download_webpage(png_url, video_id, 'Downloading url information')
  205         video_url = _decrypt_url(png)
  206 
  207         return {
  208             'id': video_id,
  209             'ext': 'mp4',
  210             'title': info['title'],
  211             'url': video_url,
  212             'thumbnail': info.get('image'),
  213             'duration': float_or_none(info.get('duration'), scale=1000),
  214         }
  215 
  216 
  217 class RTVELiveIE(InfoExtractor):
  218     IE_NAME = 'rtve.es:live'
  219     IE_DESC = 'RTVE.es live streams'
  220     _VALID_URL = r'https?://(?:www\.)?rtve\.es/directo/(?P<id>[a-zA-Z0-9-]+)'
  221 
  222     _TESTS = [{
  223         'url': 'http://www.rtve.es/directo/la-1/',
  224         'info_dict': {
  225             'id': 'la-1',
  226             'ext': 'mp4',
  227             'title': 're:^La 1 [0-9]{4}-[0-9]{2}-[0-9]{2}Z[0-9]{6}$',
  228         },
  229         'params': {
  230             'skip_download': 'live stream',
  231         }
  232     }]
  233 
  234     def _real_extract(self, url):
  235         mobj = re.match(self._VALID_URL, url)
  236         start_time = time.gmtime()
  237         video_id = mobj.group('id')
  238 
  239         webpage = self._download_webpage(url, video_id)
  240         title = remove_end(self._og_search_title(webpage), ' en directo en RTVE.es')
  241         title = remove_start(title, 'Estoy viendo ')
  242         title += ' ' + time.strftime('%Y-%m-%dZ%H%M%S', start_time)
  243 
  244         vidplayer_id = self._search_regex(
  245             (r'playerId=player([0-9]+)',
  246              r'class=["\'].*?\blive_mod\b.*?["\'][^>]+data-assetid=["\'](\d+)',
  247              r'data-id=["\'](\d+)'),
  248             webpage, 'internal video ID')
  249         png_url = 'http://www.rtve.es/ztnr/movil/thumbnail/amonet/videos/%s.png' % vidplayer_id
  250         png = self._download_webpage(png_url, video_id, 'Downloading url information')
  251         m3u8_url = _decrypt_url(png)
  252         formats = self._extract_m3u8_formats(m3u8_url, video_id, ext='mp4')
  253         self._sort_formats(formats)
  254 
  255         return {
  256             'id': video_id,
  257             'title': title,
  258             'formats': formats,
  259             'is_live': True,
  260         }
  261 
  262 
  263 class RTVETelevisionIE(InfoExtractor):
  264     IE_NAME = 'rtve.es:television'
  265     _VALID_URL = r'https?://(?:www\.)?rtve\.es/television/[^/]+/[^/]+/(?P<id>\d+).shtml'
  266 
  267     _TEST = {
  268         'url': 'http://www.rtve.es/television/20160628/revolucion-del-movil/1364141.shtml',
  269         'info_dict': {
  270             'id': '3069778',
  271             'ext': 'mp4',
  272             'title': 'Documentos TV - La revolución del móvil',
  273             'duration': 3496.948,
  274         },
  275         'params': {
  276             'skip_download': True,
  277         },
  278     }
  279 
  280     def _real_extract(self, url):
  281         page_id = self._match_id(url)
  282         webpage = self._download_webpage(url, page_id)
  283 
  284         alacarta_url = self._search_regex(
  285             r'data-location="alacarta_videos"[^<]+url&quot;:&quot;(http://www\.rtve\.es/alacarta.+?)&',
  286             webpage, 'alacarta url', default=None)
  287         if alacarta_url is None:
  288             raise ExtractorError(
  289                 'The webpage doesn\'t contain any video', expected=True)
  290 
  291         return self.url_result(alacarta_url, ie=RTVEALaCartaIE.ie_key())

Generated by cgit