]> jfr.im git - yt-dlp.git/blame - yt_dlp/extractor/tv2.py
[sbs] Fix for movies and livestreams
[yt-dlp.git] / yt_dlp / extractor / tv2.py
CommitLineData
dcdb292f 1# coding: utf-8
bc0f937b
S
2from __future__ import unicode_literals
3
588b82bb
S
4import re
5
bc0f937b 6from .common import InfoExtractor
8d3a3a99 7from ..compat import compat_HTTPError
bc0f937b
S
8from ..utils import (
9 determine_ext,
8d3a3a99 10 ExtractorError,
bc0f937b
S
11 int_or_none,
12 float_or_none,
481c5c51 13 js_to_json,
bc0f937b 14 parse_iso8601,
588b82bb 15 remove_end,
8d3a3a99 16 strip_or_none,
9a621ddc 17 try_get,
bc0f937b
S
18)
19
20
21class TV2IE(InfoExtractor):
5886b38d 22 _VALID_URL = r'https?://(?:www\.)?tv2\.no/v/(?P<id>\d+)'
2181983a 23 _TESTS = [{
bc0f937b 24 'url': 'http://www.tv2.no/v/916509/',
bc0f937b
S
25 'info_dict': {
26 'id': '916509',
ea81966e 27 'ext': 'mp4',
ed1a3905 28 'title': 'Se Frode Gryttens hyllest av Steven Gerrard',
bc0f937b
S
29 'description': 'TV 2 Sportens huspoet tar avskjed med Liverpools kaptein Steven Gerrard.',
30 'timestamp': 1431715610,
31 'upload_date': '20150515',
ea81966e 32 'duration': 157,
bc0f937b
S
33 'view_count': int,
34 'categories': list,
ed1a3905 35 },
2181983a 36 }]
ea81966e 37 _PROTOCOLS = ('HLS', 'DASH')
8d3a3a99 38 _GEO_COUNTRIES = ['NO']
bc0f937b
S
39
40 def _real_extract(self, url):
41 video_id = self._match_id(url)
ea81966e
A
42 asset = self._download_json('https://sumo.tv2.no/rest/assets/' + video_id, video_id,
43 'Downloading metadata JSON')
44 title = asset['title']
2181983a 45 is_live = asset.get('live') is True
46
bc0f937b
S
47 formats = []
48 format_urls = []
8d3a3a99
RA
49 for protocol in self._PROTOCOLS:
50 try:
ea81966e
A
51 data = self._download_json('https://api.sumo.tv2.no/play/%s?stream=%s' % (video_id, protocol),
52 video_id, 'Downloading playabck JSON',
53 headers={'content-type': 'application/json'},
54 data='{"device":{"id":"1-1-1","name":"Nettleser (HTML)"}}'.encode())['playback']
8d3a3a99
RA
55 except ExtractorError as e:
56 if isinstance(e.cause, compat_HTTPError) and e.cause.code == 401:
57 error = self._parse_json(e.cause.read().decode(), video_id)['error']
58 error_code = error.get('code')
59 if error_code == 'ASSET_PLAYBACK_INVALID_GEO_LOCATION':
60 self.raise_geo_restricted(countries=self._GEO_COUNTRIES)
61 elif error_code == 'SESSION_NOT_AUTHENTICATED':
62 self.raise_login_required()
63 raise ExtractorError(error['description'])
64 raise
ea81966e 65 items = data.get('streams', [])
9a621ddc 66 for item in items:
bc0f937b
S
67 video_url = item.get('url')
68 if not video_url or video_url in format_urls:
69 continue
ea81966e 70 format_id = '%s-%s' % (protocol.lower(), item.get('type'))
bc0f937b
S
71 if not self._is_valid_url(video_url, video_id, format_id):
72 continue
73 format_urls.append(video_url)
74 ext = determine_ext(video_url)
75 if ext == 'f4m':
76 formats.extend(self._extract_f4m_formats(
dbc0b39b 77 video_url, video_id, f4m_id=format_id, fatal=False))
bc0f937b 78 elif ext == 'm3u8':
0b25af9b
RA
79 if not data.get('drmProtected'):
80 formats.extend(self._extract_m3u8_formats(
2181983a 81 video_url, video_id, 'mp4',
82 'm3u8' if is_live else 'm3u8_native',
0b25af9b 83 m3u8_id=format_id, fatal=False))
8d3a3a99
RA
84 elif ext == 'mpd':
85 formats.extend(self._extract_mpd_formats(
86 video_url, video_id, format_id, fatal=False))
bc0f937b
S
87 elif ext == 'ism' or video_url.endswith('.ism/Manifest'):
88 pass
89 else:
90 formats.append({
91 'url': video_url,
92 'format_id': format_id,
bc0f937b 93 })
0b25af9b 94 if not formats and data.get('drmProtected'):
88acdbc2 95 self.report_drm(video_id)
bc0f937b
S
96 self._sort_formats(formats)
97
bc0f937b 98 thumbnails = [{
ea81966e
A
99 'id': type,
100 'url': thumb_url,
101 } for type, thumb_url in (asset.get('images') or {}).items()]
bc0f937b
S
102
103 return {
104 'id': video_id,
105 'url': video_url,
2181983a 106 'title': self._live_title(title) if is_live else title,
8d3a3a99 107 'description': strip_or_none(asset.get('description')),
bc0f937b 108 'thumbnails': thumbnails,
ea81966e 109 'timestamp': parse_iso8601(asset.get('live_broadcast_time') or asset.get('update_time')),
8d3a3a99
RA
110 'duration': float_or_none(asset.get('accurateDuration') or asset.get('duration')),
111 'view_count': int_or_none(asset.get('views')),
ea81966e 112 'categories': asset.get('tags', '').split(','),
bc0f937b 113 'formats': formats,
2181983a 114 'is_live': is_live,
bc0f937b 115 }
588b82bb
S
116
117
118class TV2ArticleIE(InfoExtractor):
5886b38d 119 _VALID_URL = r'https?://(?:www\.)?tv2\.no/(?:a|\d{4}/\d{2}/\d{2}(/[^/]+)+)/(?P<id>\d+)'
588b82bb
S
120 _TESTS = [{
121 'url': 'http://www.tv2.no/2015/05/16/nyheter/alesund/krim/pingvin/6930542',
122 'info_dict': {
123 'id': '6930542',
481c5c51 124 'title': 'Russen hetses etter pingvintyveri - innrømmer å ha åpnet luken på buret',
8d3a3a99 125 'description': 'De fire siktede nekter fortsatt for å ha stjålet pingvinbabyene, men innrømmer å ha åpnet luken til de små kyllingene.',
588b82bb
S
126 },
127 'playlist_count': 2,
128 }, {
129 'url': 'http://www.tv2.no/a/6930542',
130 'only_matching': True,
131 }]
132
133 def _real_extract(self, url):
134 playlist_id = self._match_id(url)
135
136 webpage = self._download_webpage(url, playlist_id)
137
481c5c51
S
138 # Old embed pattern (looks unused nowadays)
139 assets = re.findall(r'data-assetid=["\'](\d+)', webpage)
140
141 if not assets:
142 # New embed pattern
8d3a3a99 143 for v in re.findall(r'(?s)TV2ContentboxVideo\(({.+?})\)', webpage):
481c5c51
S
144 video = self._parse_json(
145 v, playlist_id, transform_source=js_to_json, fatal=False)
146 if not video:
147 continue
148 asset = video.get('assetId')
149 if asset:
150 assets.append(asset)
151
588b82bb 152 entries = [
481c5c51
S
153 self.url_result('http://www.tv2.no/v/%s' % asset_id, 'TV2')
154 for asset_id in assets]
588b82bb
S
155
156 title = remove_end(self._og_search_title(webpage), ' - TV2.no')
157 description = remove_end(self._og_search_description(webpage), ' - TV2.no')
158
159 return self.playlist_result(entries, playlist_id, title, description)
8d3a3a99
RA
160
161
ea81966e 162class KatsomoIE(InfoExtractor):
2181983a 163 _VALID_URL = r'https?://(?:www\.)?(?:katsomo|mtv(uutiset)?)\.fi/(?:sarja/[0-9a-z-]+-\d+/[0-9a-z-]+-|(?:#!/)?jakso/(?:\d+/[^/]+/)?|video/prog)(?P<id>\d+)'
164 _TESTS = [{
8d3a3a99
RA
165 'url': 'https://www.mtv.fi/sarja/mtv-uutiset-live-33001002003/lahden-pelicans-teki-kovan-ratkaisun-ville-nieminen-pihalle-1181321',
166 'info_dict': {
167 'id': '1181321',
168 'ext': 'mp4',
2181983a 169 'title': 'Lahden Pelicans teki kovan ratkaisun – Ville Nieminen pihalle',
8d3a3a99
RA
170 'description': 'Päätöksen teki Pelicansin hallitus.',
171 'timestamp': 1575116484,
172 'upload_date': '20191130',
173 'duration': 37.12,
174 'view_count': int,
175 'categories': list,
176 },
177 'params': {
178 # m3u8 download
179 'skip_download': True,
180 },
2181983a 181 }, {
182 'url': 'http://www.katsomo.fi/#!/jakso/33001005/studio55-fi/658521/jukka-kuoppamaki-tekee-yha-lauluja-vaikka-lentokoneessa',
183 'only_matching': True,
184 }, {
185 'url': 'https://www.mtvuutiset.fi/video/prog1311159',
186 'only_matching': True,
187 }, {
188 'url': 'https://www.katsomo.fi/#!/jakso/1311159',
189 'only_matching': True,
190 }]
8d3a3a99
RA
191 _API_DOMAIN = 'api.katsomo.fi'
192 _PROTOCOLS = ('HLS', 'MPD')
193 _GEO_COUNTRIES = ['FI']
2181983a 194
ea81966e
A
195 def _real_extract(self, url):
196 video_id = self._match_id(url)
197 api_base = 'http://%s/api/web/asset/%s' % (self._API_DOMAIN, video_id)
198
199 asset = self._download_json(
200 api_base + '.json', video_id,
201 'Downloading metadata JSON')['asset']
202 title = asset.get('subtitle') or asset['title']
203 is_live = asset.get('live') is True
204
205 formats = []
206 format_urls = []
207 for protocol in self._PROTOCOLS:
208 try:
209 data = self._download_json(
210 api_base + '/play.json?protocol=%s&videoFormat=SMIL+ISMUSP' % protocol,
211 video_id, 'Downloading play JSON')['playback']
212 except ExtractorError as e:
213 if isinstance(e.cause, compat_HTTPError) and e.cause.code == 401:
214 error = self._parse_json(e.cause.read().decode(), video_id)['error']
215 error_code = error.get('code')
216 if error_code == 'ASSET_PLAYBACK_INVALID_GEO_LOCATION':
217 self.raise_geo_restricted(countries=self._GEO_COUNTRIES)
218 elif error_code == 'SESSION_NOT_AUTHENTICATED':
219 self.raise_login_required()
220 raise ExtractorError(error['description'])
221 raise
222 items = try_get(data, lambda x: x['items']['item'])
223 if not items:
224 continue
225 if not isinstance(items, list):
226 items = [items]
227 for item in items:
228 if not isinstance(item, dict):
229 continue
230 video_url = item.get('url')
231 if not video_url or video_url in format_urls:
232 continue
233 format_id = '%s-%s' % (protocol.lower(), item.get('mediaFormat'))
234 if not self._is_valid_url(video_url, video_id, format_id):
235 continue
236 format_urls.append(video_url)
237 ext = determine_ext(video_url)
238 if ext == 'f4m':
239 formats.extend(self._extract_f4m_formats(
240 video_url, video_id, f4m_id=format_id, fatal=False))
241 elif ext == 'm3u8':
242 if not data.get('drmProtected'):
243 formats.extend(self._extract_m3u8_formats(
244 video_url, video_id, 'mp4',
245 'm3u8' if is_live else 'm3u8_native',
246 m3u8_id=format_id, fatal=False))
247 elif ext == 'mpd':
248 formats.extend(self._extract_mpd_formats(
249 video_url, video_id, format_id, fatal=False))
250 elif ext == 'ism' or video_url.endswith('.ism/Manifest'):
251 pass
252 else:
253 formats.append({
254 'url': video_url,
255 'format_id': format_id,
256 'tbr': int_or_none(item.get('bitrate')),
257 'filesize': int_or_none(item.get('fileSize')),
258 })
259 if not formats and data.get('drmProtected'):
260 self.report_drm(video_id)
261 self._sort_formats(formats)
262
263 thumbnails = [{
264 'id': thumbnail.get('@type'),
265 'url': thumbnail.get('url'),
266 } for _, thumbnail in (asset.get('imageVersions') or {}).items()]
267
268 return {
269 'id': video_id,
270 'url': video_url,
271 'title': self._live_title(title) if is_live else title,
272 'description': strip_or_none(asset.get('description')),
273 'thumbnails': thumbnails,
274 'timestamp': parse_iso8601(asset.get('createTime')),
275 'duration': float_or_none(asset.get('accurateDuration') or asset.get('duration')),
276 'view_count': int_or_none(asset.get('views')),
277 'categories': asset.get('keywords', '').split(','),
278 'formats': formats,
279 'is_live': is_live,
280 }
281
2181983a 282
283class MTVUutisetArticleIE(InfoExtractor):
284 _VALID_URL = r'https?://(?:www\.)mtvuutiset\.fi/artikkeli/[^/]+/(?P<id>\d+)'
285 _TESTS = [{
286 'url': 'https://www.mtvuutiset.fi/artikkeli/tallaisia-vaurioita-viking-amorellassa-on-useamman-osaston-alla-vetta/7931384',
287 'info_dict': {
288 'id': '1311159',
289 'ext': 'mp4',
290 'title': 'Viking Amorellan matkustajien evakuointi on alkanut – tältä operaatio näyttää laivalla',
291 'description': 'Viking Amorellan matkustajien evakuointi on alkanut – tältä operaatio näyttää laivalla',
292 'timestamp': 1600608966,
293 'upload_date': '20200920',
294 'duration': 153.7886666,
295 'view_count': int,
296 'categories': list,
297 },
298 'params': {
299 # m3u8 download
300 'skip_download': True,
301 },
302 }, {
303 # multiple Youtube embeds
304 'url': 'https://www.mtvuutiset.fi/artikkeli/50-vuotta-subarun-vastaiskua/6070962',
305 'only_matching': True,
306 }]
307
308 def _real_extract(self, url):
309 article_id = self._match_id(url)
310 article = self._download_json(
311 'http://api.mtvuutiset.fi/mtvuutiset/api/json/' + article_id,
312 article_id)
313
314 def entries():
315 for video in (article.get('videos') or []):
316 video_type = video.get('videotype')
317 video_url = video.get('url')
318 if not (video_url and video_type in ('katsomo', 'youtube')):
319 continue
320 yield self.url_result(
321 video_url, video_type.capitalize(), video.get('video_id'))
322
323 return self.playlist_result(
324 entries(), article_id, article.get('title'), article.get('description'))