[vrv] Add new extractor
[youtube-dl] / youtube_dl / extractor / vrv.py
1 # coding: utf-8
2 from __future__ import unicode_literals
3
4 import base64
5 import json
6 import hashlib
7 import hmac
8 import random
9 import string
10 import time
11
12 from .common import InfoExtractor
13 from ..compat import (
14     compat_urllib_parse_urlencode,
15     compat_urlparse,
16 )
17 from ..utils import (
18     float_or_none,
19     int_or_none,
20 )
21
22
23 class VRVIE(InfoExtractor):
24     _VALID_URL = r'https?://(?:www\.)?vrv\.co/watch/(?P<id>[A-Z0-9]+)'
25     _TEST = {
26         'url': 'https://vrv.co/watch/GR9PNZ396/Hidden-America-with-Jonah-Ray:BOSTON-WHERE-THE-PAST-IS-THE-PRESENT',
27         'info_dict': {
28             'id': 'GR9PNZ396',
29             'ext': 'mp4',
30             'title': 'BOSTON: WHERE THE PAST IS THE PRESENT',
31             'description': 'md5:4ec8844ac262ca2df9e67c0983c6b83f',
32             'uploader_id': 'seeso',
33         },
34         'params': {
35             # m3u8 download
36             'skip_download': True,
37         },
38     }
39     _API_DOMAIN = None
40     _API_PARAMS = {}
41     _CMS_SIGNING = {}
42
43     def _call_api(self, path, video_id, note, data=None):
44         base_url = self._API_DOMAIN + '/core/' + path
45         encoded_query = compat_urllib_parse_urlencode({
46             'oauth_consumer_key': self._API_PARAMS['oAuthKey'],
47             'oauth_nonce': ''.join([random.choice(string.ascii_letters) for _ in range(32)]),
48             'oauth_signature_method': 'HMAC-SHA1',
49             'oauth_timestamp': int(time.time()),
50             'oauth_version': '1.0',
51         })
52         headers = self.geo_verification_headers()
53         if data:
54             data = json.dumps(data).encode()
55             headers['Content-Type'] = 'application/json'
56         method = 'POST' if data else 'GET'
57         base_string = '&'.join([method, compat_urlparse.quote(base_url, ''), compat_urlparse.quote(encoded_query, '')])
58         oauth_signature = base64.b64encode(hmac.new(
59             (self._API_PARAMS['oAuthSecret'] + '&').encode('ascii'),
60             base_string.encode(), hashlib.sha1).digest()).decode()
61         encoded_query += '&oauth_signature=' + compat_urlparse.quote(oauth_signature, '')
62         return self._download_json(
63             '?'.join([base_url, encoded_query]), video_id,
64             note='Downloading %s JSON metadata' % note, headers=headers, data=data)
65
66     def _call_cms(self, path, video_id, note):
67         return self._download_json(
68             self._API_DOMAIN + path, video_id, query=self._CMS_SIGNING,
69             note='Downloading %s JSON metadata' % note, headers=self.geo_verification_headers())
70
71     def _set_api_params(self, webpage, video_id):
72         if not self._API_PARAMS:
73             self._API_PARAMS = self._parse_json(self._search_regex(
74                 r'window\.__APP_CONFIG__\s*=\s*({.+?})</script>',
75                 webpage, 'api config'), video_id)['cxApiParams']
76             self._API_DOMAIN = self._API_PARAMS.get('apiDomain', 'https://api.vrv.co')
77
78     def _set_cms_signing(self, video_id):
79         if not self._CMS_SIGNING:
80             self._CMS_SIGNING = self._call_api('index', video_id, 'CMS Signing')['cms_signing']
81
82     def _real_extract(self, url):
83         video_id = self._match_id(url)
84         webpage = self._download_webpage(
85             url, video_id,
86             headers=self.geo_verification_headers())
87         media_resource = self._parse_json(self._search_regex(
88             r'window\.__INITIAL_STATE__\s*=\s*({.+?})</script>',
89             webpage, 'inital state'), video_id).get('watch', {}).get('mediaResource') or {}
90
91         video_data = media_resource.get('json')
92         if not video_data:
93             self._set_api_params(webpage, video_id)
94             episode_path = self._call_api('cms_resource', video_id, 'episode resource path', data={
95                 'resource_key': 'cms:/episodes/' + video_id,
96             })['__links__']['cms_resource']['href']
97             self._set_cms_signing(video_id)
98             video_data = self._call_cms(episode_path, video_id, 'video')
99         title = video_data['title']
100
101         streams_json = media_resource.get('streams', {}).get('json', {})
102         if not streams_json:
103             self._set_api_params(webpage, video_id)
104             streams_path = video_data['__links__']['streams']['href']
105             self._set_cms_signing(video_id)
106             streams_json = self._call_cms(streams_path, video_id, 'streams')
107
108         audio_locale = streams_json.get('audio_locale')
109         formats = []
110         for stream_id, stream in streams_json.get('streams', {}).get('adaptive_hls', {}).items():
111             stream_url = stream.get('url')
112             if not stream_url:
113                 continue
114             stream_id = stream_id or audio_locale
115             m3u8_formats = self._extract_m3u8_formats(
116                 stream_url, video_id, 'mp4', m3u8_id=stream_id,
117                 note='Downloading %s m3u8 information' % stream_id,
118                 fatal=False)
119             if audio_locale:
120                 for f in m3u8_formats:
121                     f['language'] = audio_locale
122             formats.extend(m3u8_formats)
123         self._sort_formats(formats)
124
125         thumbnails = []
126         for thumbnail in video_data.get('images', {}).get('thumbnails', []):
127             thumbnail_url = thumbnail.get('source')
128             if not thumbnail_url:
129                 continue
130             thumbnails.append({
131                 'url': thumbnail_url,
132                 'width': int_or_none(thumbnail.get('width')),
133                 'height': int_or_none(thumbnail.get('height')),
134             })
135
136         return {
137             'id': video_id,
138             'title': title,
139             'formats': formats,
140             'thumbnails': thumbnails,
141             'description': video_data.get('description'),
142             'duration': float_or_none(video_data.get('duration_ms'), 1000),
143             'uploader_id': video_data.get('channel_id'),
144             'series': video_data.get('series_title'),
145             'season': video_data.get('season_title'),
146             'season_number': int_or_none(video_data.get('season_number')),
147             'season_id': video_data.get('season_id'),
148             'episode': title,
149             'episode_number': int_or_none(video_data.get('episode_number')),
150             'episode_id': video_data.get('production_episode_id'),
151         }