]> Raphaël G. Git Repositories - youtubedl/blob - youtube_dl/extractor/dplay.py
debian/{compat,control}: Update to debhelper compatibility level 12.
[youtubedl] / youtube_dl / extractor / dplay.py
1 # coding: utf-8
2 from __future__ import unicode_literals
3
4 import json
5 import re
6 import time
7
8 from .common import InfoExtractor
9 from ..compat import (
10 compat_HTTPError,
11 compat_str,
12 compat_urlparse,
13 )
14 from ..utils import (
15 determine_ext,
16 ExtractorError,
17 float_or_none,
18 int_or_none,
19 remove_end,
20 try_get,
21 unified_strdate,
22 unified_timestamp,
23 update_url_query,
24 urljoin,
25 USER_AGENTS,
26 )
27
28
29 class DPlayIE(InfoExtractor):
30 _VALID_URL = r'https?://(?P<domain>www\.(?P<host>dplay\.(?P<country>dk|se|no)))/(?:video(?:er|s)/)?(?P<id>[^/]+/[^/?#]+)'
31
32 _TESTS = [{
33 # non geo restricted, via secure api, unsigned download hls URL
34 'url': 'http://www.dplay.se/nugammalt-77-handelser-som-format-sverige/season-1-svensken-lar-sig-njuta-av-livet/',
35 'info_dict': {
36 'id': '3172',
37 'display_id': 'nugammalt-77-handelser-som-format-sverige/season-1-svensken-lar-sig-njuta-av-livet',
38 'ext': 'mp4',
39 'title': 'Svensken lär sig njuta av livet',
40 'description': 'md5:d3819c9bccffd0fe458ca42451dd50d8',
41 'duration': 2650,
42 'timestamp': 1365454320,
43 'upload_date': '20130408',
44 'creator': 'Kanal 5 (Home)',
45 'series': 'Nugammalt - 77 händelser som format Sverige',
46 'season_number': 1,
47 'episode_number': 1,
48 'age_limit': 0,
49 },
50 }, {
51 # geo restricted, via secure api, unsigned download hls URL
52 'url': 'http://www.dplay.dk/mig-og-min-mor/season-6-episode-12/',
53 'info_dict': {
54 'id': '70816',
55 'display_id': 'mig-og-min-mor/season-6-episode-12',
56 'ext': 'mp4',
57 'title': 'Episode 12',
58 'description': 'md5:9c86e51a93f8a4401fc9641ef9894c90',
59 'duration': 2563,
60 'timestamp': 1429696800,
61 'upload_date': '20150422',
62 'creator': 'Kanal 4 (Home)',
63 'series': 'Mig og min mor',
64 'season_number': 6,
65 'episode_number': 12,
66 'age_limit': 0,
67 },
68 }, {
69 # geo restricted, via direct unsigned hls URL
70 'url': 'http://www.dplay.no/pga-tour/season-1-hoydepunkter-18-21-februar/',
71 'only_matching': True,
72 }, {
73 # disco-api
74 'url': 'https://www.dplay.no/videoer/i-kongens-klr/sesong-1-episode-7',
75 'info_dict': {
76 'id': '40206',
77 'display_id': 'i-kongens-klr/sesong-1-episode-7',
78 'ext': 'mp4',
79 'title': 'Episode 7',
80 'description': 'md5:e3e1411b2b9aebeea36a6ec5d50c60cf',
81 'duration': 2611.16,
82 'timestamp': 1516726800,
83 'upload_date': '20180123',
84 'series': 'I kongens klær',
85 'season_number': 1,
86 'episode_number': 7,
87 },
88 'params': {
89 'format': 'bestvideo',
90 'skip_download': True,
91 },
92 }, {
93
94 'url': 'https://www.dplay.dk/videoer/singleliv/season-5-episode-3',
95 'only_matching': True,
96 }, {
97 'url': 'https://www.dplay.se/videos/sofias-anglar/sofias-anglar-1001',
98 'only_matching': True,
99 }]
100
101 def _get_disco_api_info(self, url, display_id, disco_host, realm):
102 disco_base = 'https://' + disco_host
103 token = self._download_json(
104 '%s/token' % disco_base, display_id, 'Downloading token',
105 query={
106 'realm': realm,
107 })['data']['attributes']['token']
108 headers = {
109 'Referer': url,
110 'Authorization': 'Bearer ' + token,
111 }
112 video = self._download_json(
113 '%s/content/videos/%s' % (disco_base, display_id), display_id,
114 headers=headers, query={
115 'include': 'show'
116 })
117 video_id = video['data']['id']
118 info = video['data']['attributes']
119 title = info['name']
120 formats = []
121 for format_id, format_dict in self._download_json(
122 '%s/playback/videoPlaybackInfo/%s' % (disco_base, video_id),
123 display_id, headers=headers)['data']['attributes']['streaming'].items():
124 if not isinstance(format_dict, dict):
125 continue
126 format_url = format_dict.get('url')
127 if not format_url:
128 continue
129 ext = determine_ext(format_url)
130 if format_id == 'dash' or ext == 'mpd':
131 formats.extend(self._extract_mpd_formats(
132 format_url, display_id, mpd_id='dash', fatal=False))
133 elif format_id == 'hls' or ext == 'm3u8':
134 formats.extend(self._extract_m3u8_formats(
135 format_url, display_id, 'mp4',
136 entry_protocol='m3u8_native', m3u8_id='hls',
137 fatal=False))
138 else:
139 formats.append({
140 'url': format_url,
141 'format_id': format_id,
142 })
143 self._sort_formats(formats)
144
145 series = None
146 try:
147 included = video.get('included')
148 if isinstance(included, list):
149 show = next(e for e in included if e.get('type') == 'show')
150 series = try_get(
151 show, lambda x: x['attributes']['name'], compat_str)
152 except StopIteration:
153 pass
154
155 return {
156 'id': video_id,
157 'display_id': display_id,
158 'title': title,
159 'description': info.get('description'),
160 'duration': float_or_none(
161 info.get('videoDuration'), scale=1000),
162 'timestamp': unified_timestamp(info.get('publishStart')),
163 'series': series,
164 'season_number': int_or_none(info.get('seasonNumber')),
165 'episode_number': int_or_none(info.get('episodeNumber')),
166 'age_limit': int_or_none(info.get('minimum_age')),
167 'formats': formats,
168 }
169
170 def _real_extract(self, url):
171 mobj = re.match(self._VALID_URL, url)
172 display_id = mobj.group('id')
173 domain = mobj.group('domain')
174
175 self._initialize_geo_bypass({
176 'countries': [mobj.group('country').upper()],
177 })
178
179 webpage = self._download_webpage(url, display_id)
180
181 video_id = self._search_regex(
182 r'data-video-id=["\'](\d+)', webpage, 'video id', default=None)
183
184 if not video_id:
185 host = mobj.group('host')
186 return self._get_disco_api_info(
187 url, display_id, 'disco-api.' + host, host.replace('.', ''))
188
189 info = self._download_json(
190 'http://%s/api/v2/ajax/videos?video_id=%s' % (domain, video_id),
191 video_id)['data'][0]
192
193 title = info['title']
194
195 PROTOCOLS = ('hls', 'hds')
196 formats = []
197
198 def extract_formats(protocol, manifest_url):
199 if protocol == 'hls':
200 m3u8_formats = self._extract_m3u8_formats(
201 manifest_url, video_id, ext='mp4',
202 entry_protocol='m3u8_native', m3u8_id=protocol, fatal=False)
203 # Sometimes final URLs inside m3u8 are unsigned, let's fix this
204 # ourselves. Also fragments' URLs are only served signed for
205 # Safari user agent.
206 query = compat_urlparse.parse_qs(compat_urlparse.urlparse(manifest_url).query)
207 for m3u8_format in m3u8_formats:
208 m3u8_format.update({
209 'url': update_url_query(m3u8_format['url'], query),
210 'http_headers': {
211 'User-Agent': USER_AGENTS['Safari'],
212 },
213 })
214 formats.extend(m3u8_formats)
215 elif protocol == 'hds':
216 formats.extend(self._extract_f4m_formats(
217 manifest_url + '&hdcore=3.8.0&plugin=flowplayer-3.8.0.0',
218 video_id, f4m_id=protocol, fatal=False))
219
220 domain_tld = domain.split('.')[-1]
221 if domain_tld in ('se', 'dk', 'no'):
222 for protocol in PROTOCOLS:
223 # Providing dsc-geo allows to bypass geo restriction in some cases
224 self._set_cookie(
225 'secure.dplay.%s' % domain_tld, 'dsc-geo',
226 json.dumps({
227 'countryCode': domain_tld.upper(),
228 'expiry': (time.time() + 20 * 60) * 1000,
229 }))
230 stream = self._download_json(
231 'https://secure.dplay.%s/secure/api/v2/user/authorization/stream/%s?stream_type=%s'
232 % (domain_tld, video_id, protocol), video_id,
233 'Downloading %s stream JSON' % protocol, fatal=False)
234 if stream and stream.get(protocol):
235 extract_formats(protocol, stream[protocol])
236
237 # The last resort is to try direct unsigned hls/hds URLs from info dictionary.
238 # Sometimes this does work even when secure API with dsc-geo has failed (e.g.
239 # http://www.dplay.no/pga-tour/season-1-hoydepunkter-18-21-februar/).
240 if not formats:
241 for protocol in PROTOCOLS:
242 if info.get(protocol):
243 extract_formats(protocol, info[protocol])
244
245 self._sort_formats(formats)
246
247 subtitles = {}
248 for lang in ('se', 'sv', 'da', 'nl', 'no'):
249 for format_id in ('web_vtt', 'vtt', 'srt'):
250 subtitle_url = info.get('subtitles_%s_%s' % (lang, format_id))
251 if subtitle_url:
252 subtitles.setdefault(lang, []).append({'url': subtitle_url})
253
254 return {
255 'id': video_id,
256 'display_id': display_id,
257 'title': title,
258 'description': info.get('video_metadata_longDescription'),
259 'duration': int_or_none(info.get('video_metadata_length'), scale=1000),
260 'timestamp': int_or_none(info.get('video_publish_date')),
261 'creator': info.get('video_metadata_homeChannel'),
262 'series': info.get('video_metadata_show'),
263 'season_number': int_or_none(info.get('season')),
264 'episode_number': int_or_none(info.get('episode')),
265 'age_limit': int_or_none(info.get('minimum_age')),
266 'formats': formats,
267 'subtitles': subtitles,
268 }
269
270
271 class DPlayItIE(InfoExtractor):
272 _VALID_URL = r'https?://it\.dplay\.com/[^/]+/[^/]+/(?P<id>[^/?#]+)'
273 _GEO_COUNTRIES = ['IT']
274 _TEST = {
275 'url': 'http://it.dplay.com/nove/biografie-imbarazzanti/luigi-di-maio-la-psicosi-di-stanislawskij/',
276 'md5': '2b808ffb00fc47b884a172ca5d13053c',
277 'info_dict': {
278 'id': '6918',
279 'display_id': 'luigi-di-maio-la-psicosi-di-stanislawskij',
280 'ext': 'mp4',
281 'title': 'Biografie imbarazzanti: Luigi Di Maio: la psicosi di Stanislawskij',
282 'description': 'md5:3c7a4303aef85868f867a26f5cc14813',
283 'thumbnail': r're:^https?://.*\.jpe?g',
284 'upload_date': '20160524',
285 'series': 'Biografie imbarazzanti',
286 'season_number': 1,
287 'episode': 'Luigi Di Maio: la psicosi di Stanislawskij',
288 'episode_number': 1,
289 },
290 }
291
292 def _real_extract(self, url):
293 display_id = self._match_id(url)
294
295 webpage = self._download_webpage(url, display_id)
296
297 title = remove_end(self._og_search_title(webpage), ' | Dplay')
298
299 video_id = None
300
301 info = self._search_regex(
302 r'playback_json\s*:\s*JSON\.parse\s*\(\s*("(?:\\.|[^"\\])+?")',
303 webpage, 'playback JSON', default=None)
304 if info:
305 for _ in range(2):
306 info = self._parse_json(info, display_id, fatal=False)
307 if not info:
308 break
309 else:
310 video_id = try_get(info, lambda x: x['data']['id'])
311
312 if not info:
313 info_url = self._search_regex(
314 (r'playback_json_url\s*:\s*(["\'])(?P<url>(?:(?!\1).)+)\1',
315 r'url\s*[:=]\s*["\'](?P<url>(?:https?:)?//[^/]+/playback/videoPlaybackInfo/\d+)'),
316 webpage, 'info url', group='url')
317
318 info_url = urljoin(url, info_url)
319 video_id = info_url.rpartition('/')[-1]
320
321 try:
322 info = self._download_json(
323 info_url, display_id, headers={
324 'Authorization': 'Bearer %s' % self._get_cookies(url).get(
325 'dplayit_token').value,
326 'Referer': url,
327 })
328 if isinstance(info, compat_str):
329 info = self._parse_json(info, display_id)
330 except ExtractorError as e:
331 if isinstance(e.cause, compat_HTTPError) and e.cause.code in (400, 403):
332 info = self._parse_json(e.cause.read().decode('utf-8'), display_id)
333 error = info['errors'][0]
334 if error.get('code') == 'access.denied.geoblocked':
335 self.raise_geo_restricted(
336 msg=error.get('detail'), countries=self._GEO_COUNTRIES)
337 raise ExtractorError(info['errors'][0]['detail'], expected=True)
338 raise
339
340 hls_url = info['data']['attributes']['streaming']['hls']['url']
341
342 formats = self._extract_m3u8_formats(
343 hls_url, display_id, ext='mp4', entry_protocol='m3u8_native',
344 m3u8_id='hls')
345 self._sort_formats(formats)
346
347 series = self._html_search_regex(
348 r'(?s)<h1[^>]+class=["\'].*?\bshow_title\b.*?["\'][^>]*>(.+?)</h1>',
349 webpage, 'series', fatal=False)
350 episode = self._search_regex(
351 r'<p[^>]+class=["\'].*?\bdesc_ep\b.*?["\'][^>]*>\s*<br/>\s*<b>([^<]+)',
352 webpage, 'episode', fatal=False)
353
354 mobj = re.search(
355 r'(?s)<span[^>]+class=["\']dates["\'][^>]*>.+?\bS\.(?P<season_number>\d+)\s+E\.(?P<episode_number>\d+)\s*-\s*(?P<upload_date>\d{2}/\d{2}/\d{4})',
356 webpage)
357 if mobj:
358 season_number = int(mobj.group('season_number'))
359 episode_number = int(mobj.group('episode_number'))
360 upload_date = unified_strdate(mobj.group('upload_date'))
361 else:
362 season_number = episode_number = upload_date = None
363
364 return {
365 'id': compat_str(video_id or display_id),
366 'display_id': display_id,
367 'title': title,
368 'description': self._og_search_description(webpage),
369 'thumbnail': self._og_search_thumbnail(webpage),
370 'series': series,
371 'season_number': season_number,
372 'episode': episode,
373 'episode_number': episode_number,
374 'upload_date': upload_date,
375 'formats': formats,
376 }