[vice] add support for uplynk preplay videos(#11101)
[youtube-dl] / youtube_dl / extractor / vice.py
1 from __future__ import unicode_literals
2
3 import re
4 import time
5 import hashlib
6 import json
7
8 from .adobepass import AdobePassIE
9 from .common import InfoExtractor
10 from ..compat import compat_HTTPError
11 from ..utils import (
12     int_or_none,
13     parse_age_limit,
14     str_or_none,
15     parse_duration,
16     ExtractorError,
17     extract_attributes,
18 )
19
20
21 class ViceBaseIE(AdobePassIE):
22     def _extract_preplay_video(self, url, webpage):
23         watch_hub_data = extract_attributes(self._search_regex(
24             r'(?s)(<watch-hub\s*.+?</watch-hub>)', webpage, 'watch hub'))
25         video_id = watch_hub_data['vms-id']
26         title = watch_hub_data['video-title']
27
28         query = {}
29         is_locked = watch_hub_data.get('video-locked') == '1'
30         if is_locked:
31             resource = self._get_mvpd_resource(
32                 'VICELAND', title, video_id,
33                 watch_hub_data.get('video-rating'))
34             query['tvetoken'] = self._extract_mvpd_auth(url, video_id, 'VICELAND', resource)
35
36         # signature generation algorithm is reverse engineered from signatureGenerator in
37         # webpack:///../shared/~/vice-player/dist/js/vice-player.js in
38         # https://www.viceland.com/assets/common/js/web.vendor.bundle.js
39         exp = int(time.time()) + 14400
40         query.update({
41             'exp': exp,
42             'sign': hashlib.sha512(('%s:GET:%d' % (video_id, exp)).encode()).hexdigest(),
43         })
44
45         try:
46             host = 'www.viceland' if is_locked else self._PREPLAY_HOST
47             preplay = self._download_json('https://%s.com/en_us/preplay/%s' % (host, video_id), video_id, query=query)
48         except ExtractorError as e:
49             if isinstance(e.cause, compat_HTTPError) and e.cause.code == 400:
50                 error = json.loads(e.cause.read().decode())
51                 raise ExtractorError('%s said: %s' % (self.IE_NAME, error['details']), expected=True)
52             raise
53
54         video_data = preplay['video']
55         base = video_data['base']
56         uplynk_preplay_url = preplay['preplayURL']
57         episode = video_data.get('episode', {})
58         channel = video_data.get('channel', {})
59
60         subtitles = {}
61         cc_url = preplay.get('ccURL')
62         if cc_url:
63             subtitles['en'] = [{
64                 'url': cc_url,
65             }]
66
67         return {
68             '_type': 'url_transparent',
69             'url': uplynk_preplay_url,
70             'id': video_id,
71             'title': title,
72             'description': base.get('body'),
73             'thumbnail': watch_hub_data.get('cover-image') or watch_hub_data.get('thumbnail'),
74             'duration': parse_duration(video_data.get('video_duration') or watch_hub_data.get('video-duration')),
75             'timestamp': int_or_none(video_data.get('created_at')),
76             'age_limit': parse_age_limit(video_data.get('video_rating')),
77             'series': video_data.get('show_title') or watch_hub_data.get('show-title'),
78             'episode_number': int_or_none(episode.get('episode_number') or watch_hub_data.get('episode')),
79             'episode_id': str_or_none(episode.get('id') or video_data.get('episode_id')),
80             'season_number': int_or_none(watch_hub_data.get('season')),
81             'season_id': str_or_none(episode.get('season_id')),
82             'uploader': channel.get('base', {}).get('title') or watch_hub_data.get('channel-title'),
83             'uploader_id': str_or_none(channel.get('id')),
84             'subtitles': subtitles,
85             'ie_key': 'UplynkPreplay',
86         }
87
88
89 class ViceIE(ViceBaseIE):
90     _VALID_URL = r'https?://(?:.+?\.)?vice\.com/(?:[^/]+/)?videos?/(?P<id>[^/?#&]+)'
91
92     _TESTS = [{
93         'url': 'http://www.vice.com/video/cowboy-capitalists-part-1',
94         'md5': 'e9d77741f9e42ba583e683cd170660f7',
95         'info_dict': {
96             'id': '43cW1mYzpia9IlestBjVpd23Yu3afAfp',
97             'ext': 'flv',
98             'title': 'VICE_COWBOYCAPITALISTS_PART01_v1_VICE_WM_1080p.mov',
99             'duration': 725.983,
100         },
101         'add_ie': ['Ooyala'],
102     }, {
103         'url': 'http://www.vice.com/video/how-to-hack-a-car',
104         'md5': 'a7ecf64ee4fa19b916c16f4b56184ae2',
105         'info_dict': {
106             'id': '3jstaBeXgAs',
107             'ext': 'mp4',
108             'title': 'How to Hack a Car: Phreaked Out (Episode 2)',
109             'description': 'md5:ee95453f7ff495db8efe14ae8bf56f30',
110             'uploader_id': 'MotherboardTV',
111             'uploader': 'Motherboard',
112             'upload_date': '20140529',
113         },
114         'add_ie': ['Youtube'],
115     }, {
116         'url': 'https://video.vice.com/en_us/video/the-signal-from-tolva/5816510690b70e6c5fd39a56',
117         'md5': '',
118         'info_dict': {
119             'id': '5816510690b70e6c5fd39a56',
120             'ext': 'mp4',
121             'uploader': 'Waypoint',
122             'title': 'The Signal From Tölva',
123             'uploader_id': '57f7d621e05ca860fa9ccaf9',
124             'timestamp': 1477941983938,
125         },
126         'params': {
127             # m3u8 download
128             'skip_download': True,
129         },
130         'add_ie': ['UplynkPreplay'],
131     }, {
132         'url': 'https://news.vice.com/video/experimenting-on-animals-inside-the-monkey-lab',
133         'only_matching': True,
134     }, {
135         'url': 'http://www.vice.com/ru/video/big-night-out-ibiza-clive-martin-229',
136         'only_matching': True,
137     }, {
138         'url': 'https://munchies.vice.com/en/videos/watch-the-trailer-for-our-new-series-the-pizza-show',
139         'only_matching': True,
140     }]
141     _PREPLAY_HOST = 'video.vice'
142
143     def _real_extract(self, url):
144         video_id = self._match_id(url)
145         webpage, urlh = self._download_webpage_handle(url, video_id)
146         embed_code = self._search_regex(
147             r'embedCode=([^&\'"]+)', webpage,
148             'ooyala embed code', default=None)
149         if embed_code:
150             return self.url_result('ooyala:%s' % embed_code, 'Ooyala')
151         youtube_id = self._search_regex(
152             r'data-youtube-id="([^"]+)"', webpage, 'youtube id', default=None)
153         if youtube_id:
154             return self.url_result(youtube_id, 'Youtube')
155         return self._extract_preplay_video(urlh.geturl(), webpage)
156
157
158 class ViceShowIE(InfoExtractor):
159     _VALID_URL = r'https?://(?:.+?\.)?vice\.com/(?:[^/]+/)?show/(?P<id>[^/?#&]+)'
160
161     _TEST = {
162         'url': 'https://munchies.vice.com/en/show/fuck-thats-delicious-2',
163         'info_dict': {
164             'id': 'fuck-thats-delicious-2',
165             'title': "Fuck, That's Delicious",
166             'description': 'Follow the culinary adventures of rapper Action Bronson during his ongoing world tour.',
167         },
168         'playlist_count': 17,
169     }
170
171     def _real_extract(self, url):
172         show_id = self._match_id(url)
173         webpage = self._download_webpage(url, show_id)
174
175         entries = [
176             self.url_result(video_url, ViceIE.ie_key())
177             for video_url, _ in re.findall(
178                 r'<h2[^>]+class="article-title"[^>]+data-id="\d+"[^>]*>\s*<a[^>]+href="(%s.*?)"'
179                 % ViceIE._VALID_URL, webpage)]
180
181         title = self._search_regex(
182             r'<title>(.+?)</title>', webpage, 'title', default=None)
183         if title:
184             title = re.sub(r'(.+)\s*\|\s*.+$', r'\1', title).strip()
185         description = self._html_search_meta('description', webpage, 'description')
186
187         return self.playlist_result(entries, show_id, title, description)