[abcnews,chilloutsoze,cracked,vice,vk] Use dedicated YouTube embeds extraction routines
[youtube-dl] / youtube_dl / extractor / vice.py
1 # coding: utf-8
2 from __future__ import unicode_literals
3
4 import re
5 import time
6 import hashlib
7 import json
8
9 from .adobepass import AdobePassIE
10 from .youtube import YoutubeIE
11 from .common import InfoExtractor
12 from ..compat import compat_HTTPError
13 from ..utils import (
14     int_or_none,
15     parse_age_limit,
16     str_or_none,
17     parse_duration,
18     ExtractorError,
19     extract_attributes,
20 )
21
22
23 class ViceBaseIE(AdobePassIE):
24     def _extract_preplay_video(self, url, locale, webpage):
25         watch_hub_data = extract_attributes(self._search_regex(
26             r'(?s)(<watch-hub\s*.+?</watch-hub>)', webpage, 'watch hub'))
27         video_id = watch_hub_data['vms-id']
28         title = watch_hub_data['video-title']
29
30         query = {}
31         is_locked = watch_hub_data.get('video-locked') == '1'
32         if is_locked:
33             resource = self._get_mvpd_resource(
34                 'VICELAND', title, video_id,
35                 watch_hub_data.get('video-rating'))
36             query['tvetoken'] = self._extract_mvpd_auth(
37                 url, video_id, 'VICELAND', resource)
38
39         # signature generation algorithm is reverse engineered from signatureGenerator in
40         # webpack:///../shared/~/vice-player/dist/js/vice-player.js in
41         # https://www.viceland.com/assets/common/js/web.vendor.bundle.js
42         exp = int(time.time()) + 14400
43         query.update({
44             'exp': exp,
45             'sign': hashlib.sha512(('%s:GET:%d' % (video_id, exp)).encode()).hexdigest(),
46         })
47
48         try:
49             host = 'www.viceland' if is_locked else self._PREPLAY_HOST
50             preplay = self._download_json(
51                 'https://%s.com/%s/preplay/%s' % (host, locale, video_id),
52                 video_id, query=query)
53         except ExtractorError as e:
54             if isinstance(e.cause, compat_HTTPError) and e.cause.code == 400:
55                 error = json.loads(e.cause.read().decode())
56                 raise ExtractorError('%s said: %s' % (
57                     self.IE_NAME, error['details']), expected=True)
58             raise
59
60         video_data = preplay['video']
61         base = video_data['base']
62         uplynk_preplay_url = preplay['preplayURL']
63         episode = video_data.get('episode', {})
64         channel = video_data.get('channel', {})
65
66         subtitles = {}
67         cc_url = preplay.get('ccURL')
68         if cc_url:
69             subtitles['en'] = [{
70                 'url': cc_url,
71             }]
72
73         return {
74             '_type': 'url_transparent',
75             'url': uplynk_preplay_url,
76             'id': video_id,
77             'title': title,
78             'description': base.get('body') or base.get('display_body'),
79             'thumbnail': watch_hub_data.get('cover-image') or watch_hub_data.get('thumbnail'),
80             'duration': int_or_none(video_data.get('video_duration')) or parse_duration(watch_hub_data.get('video-duration')),
81             'timestamp': int_or_none(video_data.get('created_at'), 1000),
82             'age_limit': parse_age_limit(video_data.get('video_rating')),
83             'series': video_data.get('show_title') or watch_hub_data.get('show-title'),
84             'episode_number': int_or_none(episode.get('episode_number') or watch_hub_data.get('episode')),
85             'episode_id': str_or_none(episode.get('id') or video_data.get('episode_id')),
86             'season_number': int_or_none(watch_hub_data.get('season')),
87             'season_id': str_or_none(episode.get('season_id')),
88             'uploader': channel.get('base', {}).get('title') or watch_hub_data.get('channel-title'),
89             'uploader_id': str_or_none(channel.get('id')),
90             'subtitles': subtitles,
91             'ie_key': 'UplynkPreplay',
92         }
93
94
95 class ViceIE(ViceBaseIE):
96     IE_NAME = 'vice'
97     _VALID_URL = r'https?://(?:.+?\.)?vice\.com/(?:(?P<locale>[^/]+)/)?videos?/(?P<id>[^/?#&]+)'
98
99     _TESTS = [{
100         'url': 'https://news.vice.com/video/experimenting-on-animals-inside-the-monkey-lab',
101         'md5': '7d3ae2f9ba5f196cdd9f9efd43657ac2',
102         'info_dict': {
103             'id': 'N2bzkydjraWDGwnt8jAttCF6Y0PDv4Zj',
104             'ext': 'flv',
105             'title': 'Monkey Labs of Holland',
106             'description': 'md5:92b3c7dcbfe477f772dd4afa496c9149',
107         },
108         'add_ie': ['Ooyala'],
109     }, {
110         'url': 'https://video.vice.com/en_us/video/the-signal-from-tolva/5816510690b70e6c5fd39a56',
111         'info_dict': {
112             'id': '5816510690b70e6c5fd39a56',
113             'ext': 'mp4',
114             'uploader': 'Waypoint',
115             'title': 'The Signal From Tölva',
116             'description': 'md5:3927e3c79f9e8094606a2b3c5b5e55d5',
117             'uploader_id': '57f7d621e05ca860fa9ccaf9',
118             'timestamp': 1477941983,
119             'upload_date': '20161031',
120         },
121         'params': {
122             # m3u8 download
123             'skip_download': True,
124         },
125         'add_ie': ['UplynkPreplay'],
126     }, {
127         'url': 'https://video.vice.com/alps/video/ulfs-wien-beruchtigste-grafitti-crew-part-1/581b12b60a0e1f4c0fb6ea2f',
128         'info_dict': {
129             'id': '581b12b60a0e1f4c0fb6ea2f',
130             'ext': 'mp4',
131             'title': 'ULFs - Wien berüchtigste Grafitti Crew - Part 1',
132             'description': '<p>Zwischen Hinterzimmer-Tattoos und U-Bahnschächten erzählen uns die Ulfs, wie es ist, "süchtig nach Sachbeschädigung" zu sein.</p>',
133             'uploader': 'VICE',
134             'uploader_id': '57a204088cb727dec794c67b',
135             'timestamp': 1485368119,
136             'upload_date': '20170125',
137             'age_limit': 14,
138         },
139         'params': {
140             # AES-encrypted m3u8
141             'skip_download': True,
142         },
143         'add_ie': ['UplynkPreplay'],
144     }, {
145         'url': 'https://video.vice.com/en_us/video/pizza-show-trailer/56d8c9a54d286ed92f7f30e4',
146         'only_matching': True,
147     }]
148     _PREPLAY_HOST = 'video.vice'
149
150     def _real_extract(self, url):
151         locale, video_id = re.match(self._VALID_URL, url).groups()
152         webpage, urlh = self._download_webpage_handle(url, video_id)
153         embed_code = self._search_regex(
154             r'embedCode=([^&\'"]+)', webpage,
155             'ooyala embed code', default=None)
156         if embed_code:
157             return self.url_result('ooyala:%s' % embed_code, 'Ooyala')
158         youtube_id = self._search_regex(
159             r'data-youtube-id="([^"]+)"', webpage, 'youtube id', default=None)
160         if youtube_id:
161             return self.url_result(youtube_id, 'Youtube')
162         return self._extract_preplay_video(urlh.geturl(), locale, webpage)
163
164
165 class ViceShowIE(InfoExtractor):
166     IE_NAME = 'vice:show'
167     _VALID_URL = r'https?://(?:.+?\.)?vice\.com/(?:[^/]+/)?show/(?P<id>[^/?#&]+)'
168
169     _TEST = {
170         'url': 'https://munchies.vice.com/en/show/fuck-thats-delicious-2',
171         'info_dict': {
172             'id': 'fuck-thats-delicious-2',
173             'title': "Fuck, That's Delicious",
174             'description': 'Follow the culinary adventures of rapper Action Bronson during his ongoing world tour.',
175         },
176         'playlist_count': 17,
177     }
178
179     def _real_extract(self, url):
180         show_id = self._match_id(url)
181         webpage = self._download_webpage(url, show_id)
182
183         entries = [
184             self.url_result(video_url, ViceIE.ie_key())
185             for video_url, _ in re.findall(
186                 r'<h2[^>]+class="article-title"[^>]+data-id="\d+"[^>]*>\s*<a[^>]+href="(%s.*?)"'
187                 % ViceIE._VALID_URL, webpage)]
188
189         title = self._search_regex(
190             r'<title>(.+?)</title>', webpage, 'title', default=None)
191         if title:
192             title = re.sub(r'(.+)\s*\|\s*.+$', r'\1', title).strip()
193         description = self._html_search_meta(
194             'description', webpage, 'description')
195
196         return self.playlist_result(entries, show_id, title, description)
197
198
199 class ViceArticleIE(InfoExtractor):
200     IE_NAME = 'vice:article'
201     _VALID_URL = r'https://www.vice.com/[^/]+/article/(?P<id>[^?#]+)'
202
203     _TESTS = [{
204         'url': 'https://www.vice.com/en_us/article/on-set-with-the-woman-making-mormon-porn-in-utah',
205         'info_dict': {
206             'id': '58dc0a3dee202d2a0ccfcbd8',
207             'ext': 'mp4',
208             'title': 'Mormon War on Porn ',
209             'description': 'md5:ad396a2481e7f8afb5ed486878421090',
210             'uploader': 'VICE',
211             'uploader_id': '57a204088cb727dec794c693',
212             'timestamp': 1489160690,
213             'upload_date': '20170310',
214         },
215         'params': {
216             # AES-encrypted m3u8
217             'skip_download': True,
218         },
219         'add_ie': ['UplynkPreplay'],
220     }, {
221         'url': 'https://www.vice.com/en_us/article/how-to-hack-a-car',
222         'md5': 'a7ecf64ee4fa19b916c16f4b56184ae2',
223         'info_dict': {
224             'id': '3jstaBeXgAs',
225             'ext': 'mp4',
226             'title': 'How to Hack a Car: Phreaked Out (Episode 2)',
227             'description': 'md5:ee95453f7ff495db8efe14ae8bf56f30',
228             'uploader_id': 'MotherboardTV',
229             'uploader': 'Motherboard',
230             'upload_date': '20140529',
231         },
232         'add_ie': ['Youtube'],
233     }, {
234         'url': 'https://www.vice.com/en_us/article/cowboy-capitalists-part-1',
235         'only_matching': True,
236     }, {
237         'url': 'https://www.vice.com/ru/article/big-night-out-ibiza-clive-martin-229',
238         'only_matching': True,
239     }]
240
241     def _real_extract(self, url):
242         display_id = self._match_id(url)
243
244         webpage = self._download_webpage(url, display_id)
245
246         prefetch_data = self._parse_json(self._search_regex(
247             r'window\.__PREFETCH_DATA\s*=\s*({.*});',
248             webpage, 'prefetch data'), display_id)
249         body = prefetch_data['body']
250
251         def _url_res(video_url, ie_key):
252             return {
253                 '_type': 'url_transparent',
254                 'url': video_url,
255                 'display_id': display_id,
256                 'ie_key': ie_key,
257             }
258
259         embed_code = self._search_regex(
260             r'embedCode=([^&\'"]+)', body,
261             'ooyala embed code', default=None)
262         if embed_code:
263             return _url_res('ooyala:%s' % embed_code, 'Ooyala')
264
265         youtube_url = YoutubeIE._extract_url(body)
266         if youtube_url:
267             return _url_res(youtube_url, YoutubeIE.ie_key())
268
269         video_url = self._html_search_regex(
270             r'data-video-url="([^"]+)"',
271             prefetch_data['embed_code'], 'video URL')
272
273         return _url_res(video_url, ViceIE.ie_key())