]> jfr.im git - yt-dlp.git/blob - yt_dlp/extractor/tvplay.py
[extractor] Deprecate `_sort_formats`
[yt-dlp.git] / yt_dlp / extractor / tvplay.py
1 import re
2
3 from .common import InfoExtractor
4 from ..compat import (
5 compat_HTTPError,
6 compat_urlparse,
7 )
8 from ..utils import (
9 determine_ext,
10 ExtractorError,
11 int_or_none,
12 parse_iso8601,
13 qualities,
14 traverse_obj,
15 try_get,
16 update_url_query,
17 url_or_none,
18 urljoin,
19 )
20
21
22 class TVPlayIE(InfoExtractor):
23 IE_NAME = 'mtg'
24 IE_DESC = 'MTG services'
25 _VALID_URL = r'''(?x)
26 (?:
27 mtg:|
28 https?://
29 (?:www\.)?
30 (?:
31 tvplay(?:\.skaties)?\.lv(?:/parraides)?|
32 (?:tv3play|play\.tv3)\.lt(?:/programos)?|
33 tv3play(?:\.tv3)?\.ee/sisu|
34 (?:tv(?:3|6|8|10)play)\.se/program|
35 (?:(?:tv3play|viasat4play|tv6play)\.no|(?:tv3play)\.dk)/programmer|
36 play\.nova(?:tv)?\.bg/programi
37 )
38 /(?:[^/]+/)+
39 )
40 (?P<id>\d+)
41 '''
42 _TESTS = [
43 {
44 'url': 'http://www.tvplay.lv/parraides/vinas-melo-labak/418113?autostart=true',
45 'md5': 'a1612fe0849455423ad8718fe049be21',
46 'info_dict': {
47 'id': '418113',
48 'ext': 'mp4',
49 'title': 'Kādi ir īri? - Viņas melo labāk',
50 'description': 'Baiba apsmej īrus, kādi tie ir un ko viņi dara.',
51 'series': 'Viņas melo labāk',
52 'season': '2.sezona',
53 'season_number': 2,
54 'duration': 25,
55 'timestamp': 1406097056,
56 'upload_date': '20140723',
57 },
58 },
59 {
60 'url': 'http://play.tv3.lt/programos/moterys-meluoja-geriau/409229?autostart=true',
61 'info_dict': {
62 'id': '409229',
63 'ext': 'flv',
64 'title': 'Moterys meluoja geriau',
65 'description': 'md5:9aec0fc68e2cbc992d2a140bd41fa89e',
66 'series': 'Moterys meluoja geriau',
67 'episode_number': 47,
68 'season': '1 sezonas',
69 'season_number': 1,
70 'duration': 1330,
71 'timestamp': 1403769181,
72 'upload_date': '20140626',
73 },
74 'params': {
75 # rtmp download
76 'skip_download': True,
77 },
78 },
79 {
80 'url': 'http://www.tv3play.ee/sisu/kodu-keset-linna/238551?autostart=true',
81 'info_dict': {
82 'id': '238551',
83 'ext': 'flv',
84 'title': 'Kodu keset linna 398537',
85 'description': 'md5:7df175e3c94db9e47c0d81ffa5d68701',
86 'duration': 1257,
87 'timestamp': 1292449761,
88 'upload_date': '20101215',
89 },
90 'params': {
91 # rtmp download
92 'skip_download': True,
93 },
94 },
95 {
96 'url': 'http://www.tv3play.se/program/husraddarna/395385?autostart=true',
97 'info_dict': {
98 'id': '395385',
99 'ext': 'mp4',
100 'title': 'Husräddarna S02E07',
101 'description': 'md5:f210c6c89f42d4fc39faa551be813777',
102 'duration': 2574,
103 'timestamp': 1400596321,
104 'upload_date': '20140520',
105 },
106 'params': {
107 'skip_download': True,
108 },
109 },
110 {
111 'url': 'http://www.tv6play.se/program/den-sista-dokusapan/266636?autostart=true',
112 'info_dict': {
113 'id': '266636',
114 'ext': 'mp4',
115 'title': 'Den sista dokusåpan S01E08',
116 'description': 'md5:295be39c872520221b933830f660b110',
117 'duration': 1492,
118 'timestamp': 1330522854,
119 'upload_date': '20120229',
120 'age_limit': 18,
121 },
122 'params': {
123 'skip_download': True,
124 },
125 },
126 {
127 'url': 'http://www.tv8play.se/program/antikjakten/282756?autostart=true',
128 'info_dict': {
129 'id': '282756',
130 'ext': 'mp4',
131 'title': 'Antikjakten S01E10',
132 'description': 'md5:1b201169beabd97e20c5ad0ad67b13b8',
133 'duration': 2646,
134 'timestamp': 1348575868,
135 'upload_date': '20120925',
136 },
137 'params': {
138 'skip_download': True,
139 },
140 },
141 {
142 'url': 'http://www.tv3play.no/programmer/anna-anka-soker-assistent/230898?autostart=true',
143 'info_dict': {
144 'id': '230898',
145 'ext': 'mp4',
146 'title': 'Anna Anka søker assistent - Ep. 8',
147 'description': 'md5:f80916bf5bbe1c5f760d127f8dd71474',
148 'duration': 2656,
149 'timestamp': 1277720005,
150 'upload_date': '20100628',
151 },
152 'params': {
153 'skip_download': True,
154 },
155 },
156 {
157 'url': 'http://www.viasat4play.no/programmer/budbringerne/21873?autostart=true',
158 'info_dict': {
159 'id': '21873',
160 'ext': 'mp4',
161 'title': 'Budbringerne program 10',
162 'description': 'md5:4db78dc4ec8a85bb04fd322a3ee5092d',
163 'duration': 1297,
164 'timestamp': 1254205102,
165 'upload_date': '20090929',
166 },
167 'params': {
168 'skip_download': True,
169 },
170 },
171 {
172 'url': 'http://www.tv6play.no/programmer/hotelinspektor-alex-polizzi/361883?autostart=true',
173 'info_dict': {
174 'id': '361883',
175 'ext': 'mp4',
176 'title': 'Hotelinspektør Alex Polizzi - Ep. 10',
177 'description': 'md5:3ecf808db9ec96c862c8ecb3a7fdaf81',
178 'duration': 2594,
179 'timestamp': 1393236292,
180 'upload_date': '20140224',
181 },
182 'params': {
183 'skip_download': True,
184 },
185 },
186 {
187 'url': 'http://play.novatv.bg/programi/zdravei-bulgariya/624952?autostart=true',
188 'info_dict': {
189 'id': '624952',
190 'ext': 'flv',
191 'title': 'Здравей, България (12.06.2015 г.) ',
192 'description': 'md5:99f3700451ac5bb71a260268b8daefd7',
193 'duration': 8838,
194 'timestamp': 1434100372,
195 'upload_date': '20150612',
196 },
197 'params': {
198 # rtmp download
199 'skip_download': True,
200 },
201 },
202 {
203 'url': 'https://play.nova.bg/programi/zdravei-bulgariya/764300?autostart=true',
204 'only_matching': True,
205 },
206 {
207 'url': 'http://tvplay.skaties.lv/parraides/vinas-melo-labak/418113?autostart=true',
208 'only_matching': True,
209 },
210 {
211 'url': 'https://tvplay.skaties.lv/vinas-melo-labak/418113/?autostart=true',
212 'only_matching': True,
213 },
214 {
215 # views is null
216 'url': 'http://tvplay.skaties.lv/parraides/tv3-zinas/760183',
217 'only_matching': True,
218 },
219 {
220 'url': 'http://tv3play.tv3.ee/sisu/kodu-keset-linna/238551?autostart=true',
221 'only_matching': True,
222 },
223 {
224 'url': 'mtg:418113',
225 'only_matching': True,
226 }
227 ]
228
229 def _real_extract(self, url):
230 video_id = self._match_id(url)
231 geo_country = self._search_regex(
232 r'https?://[^/]+\.([a-z]{2})', url,
233 'geo country', default=None)
234 if geo_country:
235 self._initialize_geo_bypass({'countries': [geo_country.upper()]})
236 video = self._download_json(
237 'http://playapi.mtgx.tv/v3/videos/%s' % video_id, video_id, 'Downloading video JSON')
238
239 title = video['title']
240
241 try:
242 streams = self._download_json(
243 'http://playapi.mtgx.tv/v3/videos/stream/%s' % video_id,
244 video_id, 'Downloading streams JSON')
245 except ExtractorError as e:
246 if isinstance(e.cause, compat_HTTPError) and e.cause.code == 403:
247 msg = self._parse_json(e.cause.read().decode('utf-8'), video_id)
248 raise ExtractorError(msg['msg'], expected=True)
249 raise
250
251 quality = qualities(['hls', 'medium', 'high'])
252 formats = []
253 for format_id, video_url in streams.get('streams', {}).items():
254 video_url = url_or_none(video_url)
255 if not video_url:
256 continue
257 ext = determine_ext(video_url)
258 if ext == 'f4m':
259 formats.extend(self._extract_f4m_formats(
260 update_url_query(video_url, {
261 'hdcore': '3.5.0',
262 'plugin': 'aasp-3.5.0.151.81'
263 }), video_id, f4m_id='hds', fatal=False))
264 elif ext == 'm3u8':
265 formats.extend(self._extract_m3u8_formats(
266 video_url, video_id, 'mp4', 'm3u8_native',
267 m3u8_id='hls', fatal=False))
268 else:
269 fmt = {
270 'format_id': format_id,
271 'quality': quality(format_id),
272 'ext': ext,
273 }
274 if video_url.startswith('rtmp'):
275 m = re.search(
276 r'^(?P<url>rtmp://[^/]+/(?P<app>[^/]+))/(?P<playpath>.+)$', video_url)
277 if not m:
278 continue
279 fmt.update({
280 'ext': 'flv',
281 'url': m.group('url'),
282 'app': m.group('app'),
283 'play_path': m.group('playpath'),
284 'preference': -1,
285 })
286 else:
287 fmt.update({
288 'url': video_url,
289 })
290 formats.append(fmt)
291
292 if not formats and video.get('is_geo_blocked'):
293 self.raise_geo_restricted(
294 'This content might not be available in your country due to copyright reasons',
295 metadata_available=True)
296
297 # TODO: webvtt in m3u8
298 subtitles = {}
299 sami_path = video.get('sami_path')
300 if sami_path:
301 lang = self._search_regex(
302 r'_([a-z]{2})\.xml', sami_path, 'lang',
303 default=compat_urlparse.urlparse(url).netloc.rsplit('.', 1)[-1])
304 subtitles[lang] = [{
305 'url': sami_path,
306 }]
307
308 series = video.get('format_title')
309 episode_number = int_or_none(video.get('format_position', {}).get('episode'))
310 season = video.get('_embedded', {}).get('season', {}).get('title')
311 season_number = int_or_none(video.get('format_position', {}).get('season'))
312
313 return {
314 'id': video_id,
315 'title': title,
316 'description': video.get('description'),
317 'series': series,
318 'episode_number': episode_number,
319 'season': season,
320 'season_number': season_number,
321 'duration': int_or_none(video.get('duration')),
322 'timestamp': parse_iso8601(video.get('created_at')),
323 'view_count': try_get(video, lambda x: x['views']['total'], int),
324 'age_limit': int_or_none(video.get('age_limit', 0)),
325 'formats': formats,
326 'subtitles': subtitles,
327 }
328
329
330 class ViafreeIE(InfoExtractor):
331 _VALID_URL = r'''(?x)
332 https?://
333 (?:www\.)?
334 viafree\.(?P<country>dk|no|se|fi)
335 /(?P<id>(?:program(?:mer)?|ohjelmat)?/(?:[^/]+/)+[^/?#&]+)
336 '''
337 _TESTS = [{
338 'url': 'http://www.viafree.no/programmer/underholdning/det-beste-vorspielet/sesong-2/episode-1',
339 'info_dict': {
340 'id': '757786',
341 'ext': 'mp4',
342 'title': 'Det beste vorspielet - Sesong 2 - Episode 1',
343 'description': 'md5:b632cb848331404ccacd8cd03e83b4c3',
344 'series': 'Det beste vorspielet',
345 'season_number': 2,
346 'duration': 1116,
347 'timestamp': 1471200600,
348 'upload_date': '20160814',
349 },
350 'params': {
351 'skip_download': True,
352 },
353 }, {
354 'url': 'https://www.viafree.dk/programmer/humor/comedy-central-roast-of-charlie-sheen/film/1047660',
355 'info_dict': {
356 'id': '1047660',
357 'ext': 'mp4',
358 'title': 'Comedy Central Roast of Charlie Sheen - Comedy Central Roast of Charlie Sheen',
359 'description': 'md5:ec956d941ae9fd7c65a48fd64951dc6d',
360 'series': 'Comedy Central Roast of Charlie Sheen',
361 'season_number': 1,
362 'duration': 3747,
363 'timestamp': 1608246060,
364 'upload_date': '20201217'
365 },
366 'params': {
367 'skip_download': True
368 }
369 }, {
370 # with relatedClips
371 'url': 'http://www.viafree.se/program/reality/sommaren-med-youtube-stjarnorna/sasong-1/avsnitt-1',
372 'only_matching': True,
373 }, {
374 # Different og:image URL schema
375 'url': 'http://www.viafree.se/program/reality/sommaren-med-youtube-stjarnorna/sasong-1/avsnitt-2',
376 'only_matching': True,
377 }, {
378 'url': 'http://www.viafree.se/program/livsstil/husraddarna/sasong-2/avsnitt-2',
379 'only_matching': True,
380 }, {
381 'url': 'http://www.viafree.dk/programmer/reality/paradise-hotel/saeson-7/episode-5',
382 'only_matching': True,
383 }, {
384 'url': 'http://www.viafree.se/program/underhallning/i-like-radio-live/sasong-1/676869',
385 'only_matching': True,
386 }, {
387 'url': 'https://www.viafree.fi/ohjelmat/entertainment/amazing-makeovers/kausi-7/jakso-2',
388 'only_matching': True,
389 }]
390 _GEO_BYPASS = False
391
392 def _real_extract(self, url):
393 country, path = self._match_valid_url(url).groups()
394 content = self._download_json(
395 'https://viafree-content.mtg-api.com/viafree-content/v1/%s/path/%s' % (country, path), path)
396 program = content['_embedded']['viafreeBlocks'][0]['_embedded']['program']
397 guid = program['guid']
398 meta = content['meta']
399 title = meta['title']
400
401 try:
402 stream_href = self._download_json(
403 program['_links']['streamLink']['href'], guid,
404 headers=self.geo_verification_headers())['embedded']['prioritizedStreams'][0]['links']['stream']['href']
405 except ExtractorError as e:
406 if isinstance(e.cause, compat_HTTPError) and e.cause.code == 403:
407 self.raise_geo_restricted(countries=[country])
408 raise
409
410 formats, subtitles = self._extract_m3u8_formats_and_subtitles(stream_href, guid, 'mp4')
411 episode = program.get('episode') or {}
412 return {
413 'id': guid,
414 'title': title,
415 'thumbnail': meta.get('image'),
416 'description': meta.get('description'),
417 'series': episode.get('seriesTitle'),
418 'subtitles': subtitles,
419 'episode_number': int_or_none(episode.get('episodeNumber')),
420 'season_number': int_or_none(episode.get('seasonNumber')),
421 'duration': int_or_none(try_get(program, lambda x: x['video']['duration']['milliseconds']), 1000),
422 'timestamp': parse_iso8601(try_get(program, lambda x: x['availability']['start'])),
423 'formats': formats,
424 }
425
426
427 class TVPlayHomeIE(InfoExtractor):
428 _VALID_URL = r'''(?x)
429 https?://
430 (?:tv3?)?
431 play\.(?:tv3|skaties)\.(?P<country>lv|lt|ee)/
432 (?P<live>lives/)?
433 [^?#&]+(?:episode|programme|clip)-(?P<id>\d+)
434 '''
435 _TESTS = [{
436 'url': 'https://play.tv3.lt/series/gauju-karai-karveliai,serial-2343791/serija-8,episode-2343828',
437 'info_dict': {
438 'id': '2343828',
439 'ext': 'mp4',
440 'title': 'Gaujų karai. Karveliai (2021) | S01E08: Serija 8',
441 'description': 'md5:f6fcfbb236429f05531131640dfa7c81',
442 'duration': 2710,
443 'season': 'Gaujų karai. Karveliai',
444 'season_number': 1,
445 'release_year': 2021,
446 'episode': 'Serija 8',
447 'episode_number': 8,
448 },
449 'params': {
450 'skip_download': 'm3u8',
451 },
452 }, {
453 'url': 'https://play.tv3.lt/series/moterys-meluoja-geriau-n-7,serial-2574652/serija-25,episode-3284937',
454 'info_dict': {
455 'id': '3284937',
456 'ext': 'mp4',
457 'season': 'Moterys meluoja geriau [N-7]',
458 'season_number': 14,
459 'release_year': 2021,
460 'episode': 'Serija 25',
461 'episode_number': 25,
462 'title': 'Moterys meluoja geriau [N-7] (2021) | S14|E25: Serija 25',
463 'description': 'md5:c6926e9710f1a126f028fbe121eddb79',
464 'duration': 2440,
465 },
466 'skip': '404'
467 }, {
468 'url': 'https://play.tv3.lt/lives/tv6-lt,live-2838694/optibet-a-lygos-rungtynes-marijampoles-suduva--vilniaus-riteriai,programme-3422014',
469 'only_matching': True,
470 }, {
471 'url': 'https://tv3play.skaties.lv/series/women-lie-better-lv,serial-1024464/women-lie-better-lv,episode-1038762',
472 'only_matching': True,
473 }, {
474 'url': 'https://play.tv3.ee/series/_,serial-2654462/_,episode-2654474',
475 'only_matching': True,
476 }, {
477 'url': 'https://tv3play.skaties.lv/clips/tv3-zinas-valsti-lidz-15novembrim-bus-majsede,clip-3464509',
478 'only_matching': True,
479 }]
480
481 def _real_extract(self, url):
482 country, is_live, video_id = self._match_valid_url(url).groups()
483
484 api_path = 'lives/programmes' if is_live else 'vods'
485 data = self._download_json(
486 urljoin(url, f'/api/products/{api_path}/{video_id}?platform=BROWSER&lang={country.upper()}'),
487 video_id)
488
489 video_type = 'CATCHUP' if is_live else 'MOVIE'
490 stream_id = data['programRecordingId'] if is_live else video_id
491 stream = self._download_json(
492 urljoin(url, f'/api/products/{stream_id}/videos/playlist?videoType={video_type}&platform=BROWSER'), video_id)
493 formats, subtitles = self._extract_m3u8_formats_and_subtitles(
494 stream['sources']['HLS'][0]['src'], video_id, 'mp4', 'm3u8_native', m3u8_id='hls')
495
496 thumbnails = set(traverse_obj(
497 data, (('galary', 'images', 'artworks'), ..., ..., ('miniUrl', 'mainUrl')), expected_type=url_or_none))
498
499 return {
500 'id': video_id,
501 'title': self._resolve_title(data),
502 'description': traverse_obj(data, 'description', 'lead'),
503 'duration': int_or_none(data.get('duration')),
504 'season': traverse_obj(data, ('season', 'serial', 'title')),
505 'season_number': int_or_none(traverse_obj(data, ('season', 'number'))),
506 'episode': data.get('title'),
507 'episode_number': int_or_none(data.get('episode')),
508 'release_year': int_or_none(traverse_obj(data, ('season', 'serial', 'year'))),
509 'thumbnails': [{'url': url, 'ext': 'jpg'} for url in thumbnails],
510 'formats': formats,
511 'subtitles': subtitles,
512 }
513
514 @staticmethod
515 def _resolve_title(data):
516 return try_get(data, lambda x: (
517 f'{data["season"]["serial"]["title"]} ({data["season"]["serial"]["year"]}) | '
518 f'S{data["season"]["number"]:02d}E{data["episode"]:02d}: {data["title"]}'
519 )) or data.get('title')