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