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