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

Generated by cgit