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