]> Raphaël G. Git Repositories - youtubedl/blob - youtube_dl/extractor/drtv.py
Merge pull request #3 from unit193/master
[youtubedl] / youtube_dl / extractor / drtv.py
1 # coding: utf-8
2 from __future__ import unicode_literals
3
4 import binascii
5 import hashlib
6 import re
7
8
9 from .common import InfoExtractor
10 from ..aes import aes_cbc_decrypt
11 from ..compat import compat_urllib_parse_unquote
12 from ..utils import (
13 bytes_to_intlist,
14 ExtractorError,
15 int_or_none,
16 intlist_to_bytes,
17 float_or_none,
18 mimetype2ext,
19 str_or_none,
20 try_get,
21 unified_timestamp,
22 update_url_query,
23 url_or_none,
24 )
25
26
27 class DRTVIE(InfoExtractor):
28 _VALID_URL = r'''(?x)
29 https?://
30 (?:
31 (?:www\.)?dr\.dk/(?:tv/se|nyheder|radio(?:/ondemand)?)/(?:[^/]+/)*|
32 (?:www\.)?(?:dr\.dk|dr-massive\.com)/drtv/(?:se|episode)/
33 )
34 (?P<id>[\da-z_-]+)
35 '''
36 _GEO_BYPASS = False
37 _GEO_COUNTRIES = ['DK']
38 IE_NAME = 'drtv'
39 _TESTS = [{
40 'url': 'https://www.dr.dk/tv/se/boern/ultra/klassen-ultra/klassen-darlig-taber-10',
41 'md5': '25e659cccc9a2ed956110a299fdf5983',
42 'info_dict': {
43 'id': 'klassen-darlig-taber-10',
44 'ext': 'mp4',
45 'title': 'Klassen - Dårlig taber (10)',
46 'description': 'md5:815fe1b7fa656ed80580f31e8b3c79aa',
47 'timestamp': 1539085800,
48 'upload_date': '20181009',
49 'duration': 606.84,
50 'series': 'Klassen',
51 'season': 'Klassen I',
52 'season_number': 1,
53 'season_id': 'urn:dr:mu:bundle:57d7e8216187a4031cfd6f6b',
54 'episode': 'Episode 10',
55 'episode_number': 10,
56 'release_year': 2016,
57 },
58 'expected_warnings': ['Unable to download f4m manifest'],
59 }, {
60 # embed
61 'url': 'https://www.dr.dk/nyheder/indland/live-christianias-rydning-af-pusher-street-er-i-gang',
62 'info_dict': {
63 'id': 'urn:dr:mu:programcard:57c926176187a50a9c6e83c6',
64 'ext': 'mp4',
65 'title': 'christiania pusher street ryddes drdkrjpo',
66 'description': 'md5:2a71898b15057e9b97334f61d04e6eb5',
67 'timestamp': 1472800279,
68 'upload_date': '20160902',
69 'duration': 131.4,
70 },
71 'params': {
72 'skip_download': True,
73 },
74 'expected_warnings': ['Unable to download f4m manifest'],
75 }, {
76 # with SignLanguage formats
77 'url': 'https://www.dr.dk/tv/se/historien-om-danmark/-/historien-om-danmark-stenalder',
78 'info_dict': {
79 'id': 'historien-om-danmark-stenalder',
80 'ext': 'mp4',
81 'title': 'Historien om Danmark: Stenalder',
82 'description': 'md5:8c66dcbc1669bbc6f873879880f37f2a',
83 'timestamp': 1546628400,
84 'upload_date': '20190104',
85 'duration': 3502.56,
86 'formats': 'mincount:20',
87 },
88 'params': {
89 'skip_download': True,
90 },
91 }, {
92 'url': 'https://www.dr.dk/radio/p4kbh/regionale-nyheder-kh4/p4-nyheder-2019-06-26-17-30-9',
93 'only_matching': True,
94 }, {
95 'url': 'https://www.dr.dk/drtv/se/bonderoeven_71769',
96 'info_dict': {
97 'id': '00951930010',
98 'ext': 'mp4',
99 'title': 'Bonderøven (1:8)',
100 'description': 'md5:3cf18fc0d3b205745d4505f896af8121',
101 'timestamp': 1546542000,
102 'upload_date': '20190103',
103 'duration': 2576.6,
104 },
105 'params': {
106 'skip_download': True,
107 },
108 }, {
109 'url': 'https://www.dr.dk/drtv/episode/bonderoeven_71769',
110 'only_matching': True,
111 }, {
112 'url': 'https://dr-massive.com/drtv/se/bonderoeven_71769',
113 'only_matching': True,
114 }]
115
116 def _real_extract(self, url):
117 video_id = self._match_id(url)
118
119 webpage = self._download_webpage(url, video_id)
120
121 if '>Programmet er ikke længere tilgængeligt' in webpage:
122 raise ExtractorError(
123 'Video %s is not available' % video_id, expected=True)
124
125 video_id = self._search_regex(
126 (r'data-(?:material-identifier|episode-slug)="([^"]+)"',
127 r'data-resource="[^>"]+mu/programcard/expanded/([^"]+)"'),
128 webpage, 'video id', default=None)
129
130 if not video_id:
131 video_id = self._search_regex(
132 r'(urn(?:%3A|:)dr(?:%3A|:)mu(?:%3A|:)programcard(?:%3A|:)[\da-f]+)',
133 webpage, 'urn', default=None)
134 if video_id:
135 video_id = compat_urllib_parse_unquote(video_id)
136
137 _PROGRAMCARD_BASE = 'https://www.dr.dk/mu-online/api/1.4/programcard'
138 query = {'expanded': 'true'}
139
140 if video_id:
141 programcard_url = '%s/%s' % (_PROGRAMCARD_BASE, video_id)
142 else:
143 programcard_url = _PROGRAMCARD_BASE
144 page = self._parse_json(
145 self._search_regex(
146 r'data\s*=\s*({.+?})\s*(?:;|</script)', webpage,
147 'data'), '1')['cache']['page']
148 page = page[list(page.keys())[0]]
149 item = try_get(
150 page, (lambda x: x['item'], lambda x: x['entries'][0]['item']),
151 dict)
152 video_id = item['customId'].split(':')[-1]
153 query['productionnumber'] = video_id
154
155 data = self._download_json(
156 programcard_url, video_id, 'Downloading video JSON', query=query)
157
158 title = str_or_none(data.get('Title')) or re.sub(
159 r'\s*\|\s*(?:TV\s*\|\s*DR|DRTV)$', '',
160 self._og_search_title(webpage))
161 description = self._og_search_description(
162 webpage, default=None) or data.get('Description')
163
164 timestamp = unified_timestamp(
165 data.get('PrimaryBroadcastStartTime') or data.get('SortDateTime'))
166
167 thumbnail = None
168 duration = None
169
170 restricted_to_denmark = False
171
172 formats = []
173 subtitles = {}
174
175 assets = []
176 primary_asset = data.get('PrimaryAsset')
177 if isinstance(primary_asset, dict):
178 assets.append(primary_asset)
179 secondary_assets = data.get('SecondaryAssets')
180 if isinstance(secondary_assets, list):
181 for secondary_asset in secondary_assets:
182 if isinstance(secondary_asset, dict):
183 assets.append(secondary_asset)
184
185 def hex_to_bytes(hex):
186 return binascii.a2b_hex(hex.encode('ascii'))
187
188 def decrypt_uri(e):
189 n = int(e[2:10], 16)
190 a = e[10 + n:]
191 data = bytes_to_intlist(hex_to_bytes(e[10:10 + n]))
192 key = bytes_to_intlist(hashlib.sha256(
193 ('%s:sRBzYNXBzkKgnjj8pGtkACch' % a).encode('utf-8')).digest())
194 iv = bytes_to_intlist(hex_to_bytes(a))
195 decrypted = aes_cbc_decrypt(data, key, iv)
196 return intlist_to_bytes(
197 decrypted[:-decrypted[-1]]).decode('utf-8').split('?')[0]
198
199 for asset in assets:
200 kind = asset.get('Kind')
201 if kind == 'Image':
202 thumbnail = url_or_none(asset.get('Uri'))
203 elif kind in ('VideoResource', 'AudioResource'):
204 duration = float_or_none(asset.get('DurationInMilliseconds'), 1000)
205 restricted_to_denmark = asset.get('RestrictedToDenmark')
206 asset_target = asset.get('Target')
207 for link in asset.get('Links', []):
208 uri = link.get('Uri')
209 if not uri:
210 encrypted_uri = link.get('EncryptedUri')
211 if not encrypted_uri:
212 continue
213 try:
214 uri = decrypt_uri(encrypted_uri)
215 except Exception:
216 self.report_warning(
217 'Unable to decrypt EncryptedUri', video_id)
218 continue
219 uri = url_or_none(uri)
220 if not uri:
221 continue
222 target = link.get('Target')
223 format_id = target or ''
224 if asset_target in ('SpokenSubtitles', 'SignLanguage', 'VisuallyInterpreted'):
225 preference = -1
226 format_id += '-%s' % asset_target
227 elif asset_target == 'Default':
228 preference = 1
229 else:
230 preference = None
231 if target == 'HDS':
232 f4m_formats = self._extract_f4m_formats(
233 uri + '?hdcore=3.3.0&plugin=aasp-3.3.0.99.43',
234 video_id, preference, f4m_id=format_id, fatal=False)
235 if kind == 'AudioResource':
236 for f in f4m_formats:
237 f['vcodec'] = 'none'
238 formats.extend(f4m_formats)
239 elif target == 'HLS':
240 formats.extend(self._extract_m3u8_formats(
241 uri, video_id, 'mp4', entry_protocol='m3u8_native',
242 preference=preference, m3u8_id=format_id,
243 fatal=False))
244 else:
245 bitrate = link.get('Bitrate')
246 if bitrate:
247 format_id += '-%s' % bitrate
248 formats.append({
249 'url': uri,
250 'format_id': format_id,
251 'tbr': int_or_none(bitrate),
252 'ext': link.get('FileFormat'),
253 'vcodec': 'none' if kind == 'AudioResource' else None,
254 'preference': preference,
255 })
256 subtitles_list = asset.get('SubtitlesList') or asset.get('Subtitleslist')
257 if isinstance(subtitles_list, list):
258 LANGS = {
259 'Danish': 'da',
260 }
261 for subs in subtitles_list:
262 if not isinstance(subs, dict):
263 continue
264 sub_uri = url_or_none(subs.get('Uri'))
265 if not sub_uri:
266 continue
267 lang = subs.get('Language') or 'da'
268 subtitles.setdefault(LANGS.get(lang, lang), []).append({
269 'url': sub_uri,
270 'ext': mimetype2ext(subs.get('MimeType')) or 'vtt'
271 })
272
273 if not formats and restricted_to_denmark:
274 self.raise_geo_restricted(
275 'Unfortunately, DR is not allowed to show this program outside Denmark.',
276 countries=self._GEO_COUNTRIES)
277
278 self._sort_formats(formats)
279
280 return {
281 'id': video_id,
282 'title': title,
283 'description': description,
284 'thumbnail': thumbnail,
285 'timestamp': timestamp,
286 'duration': duration,
287 'formats': formats,
288 'subtitles': subtitles,
289 'series': str_or_none(data.get('SeriesTitle')),
290 'season': str_or_none(data.get('SeasonTitle')),
291 'season_number': int_or_none(data.get('SeasonNumber')),
292 'season_id': str_or_none(data.get('SeasonUrn')),
293 'episode': str_or_none(data.get('EpisodeTitle')),
294 'episode_number': int_or_none(data.get('EpisodeNumber')),
295 'release_year': int_or_none(data.get('ProductionYear')),
296 }
297
298
299 class DRTVLiveIE(InfoExtractor):
300 IE_NAME = 'drtv:live'
301 _VALID_URL = r'https?://(?:www\.)?dr\.dk/(?:tv|TV)/live/(?P<id>[\da-z-]+)'
302 _GEO_COUNTRIES = ['DK']
303 _TEST = {
304 'url': 'https://www.dr.dk/tv/live/dr1',
305 'info_dict': {
306 'id': 'dr1',
307 'ext': 'mp4',
308 'title': 're:^DR1 [0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}$',
309 },
310 'params': {
311 # m3u8 download
312 'skip_download': True,
313 },
314 }
315
316 def _real_extract(self, url):
317 channel_id = self._match_id(url)
318 channel_data = self._download_json(
319 'https://www.dr.dk/mu-online/api/1.0/channel/' + channel_id,
320 channel_id)
321 title = self._live_title(channel_data['Title'])
322
323 formats = []
324 for streaming_server in channel_data.get('StreamingServers', []):
325 server = streaming_server.get('Server')
326 if not server:
327 continue
328 link_type = streaming_server.get('LinkType')
329 for quality in streaming_server.get('Qualities', []):
330 for stream in quality.get('Streams', []):
331 stream_path = stream.get('Stream')
332 if not stream_path:
333 continue
334 stream_url = update_url_query(
335 '%s/%s' % (server, stream_path), {'b': ''})
336 if link_type == 'HLS':
337 formats.extend(self._extract_m3u8_formats(
338 stream_url, channel_id, 'mp4',
339 m3u8_id=link_type, fatal=False, live=True))
340 elif link_type == 'HDS':
341 formats.extend(self._extract_f4m_formats(update_url_query(
342 '%s/%s' % (server, stream_path), {'hdcore': '3.7.0'}),
343 channel_id, f4m_id=link_type, fatal=False))
344 self._sort_formats(formats)
345
346 return {
347 'id': channel_id,
348 'title': title,
349 'thumbnail': channel_data.get('PrimaryImageUri'),
350 'formats': formats,
351 'is_live': True,
352 }