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