[cleanup] Make more playlist entries lazy (#11763)
[yt-dlp.git] / yt_dlp / extractor / francetv.py
blobab08f1c6bf14c8385d566114797321cc6e9e340c
1 import re
2 import urllib.parse
4 from .common import InfoExtractor
5 from .dailymotion import DailymotionIE
6 from ..networking import HEADRequest
7 from ..utils import (
8 clean_html,
9 determine_ext,
10 filter_dict,
11 format_field,
12 int_or_none,
13 join_nonempty,
14 parse_iso8601,
15 smuggle_url,
16 unsmuggle_url,
17 url_or_none,
19 from ..utils.traversal import traverse_obj
22 class FranceTVBaseInfoExtractor(InfoExtractor):
23 def _make_url_result(self, video_id, url=None):
24 video_id = video_id.split('@')[0] # for compat with old @catalog IDs
25 full_id = f'francetv:{video_id}'
26 if url:
27 full_id = smuggle_url(full_id, {'hostname': urllib.parse.urlparse(url).hostname})
28 return self.url_result(full_id, FranceTVIE, video_id)
31 class FranceTVIE(InfoExtractor):
32 _VALID_URL = r'francetv:(?P<id>[^@#]+)'
33 _GEO_COUNTRIES = ['FR']
34 _GEO_BYPASS = False
36 _TESTS = [{
37 # tokenized url is in dinfo['video']['token']
38 'url': 'francetv:ec217ecc-0733-48cf-ac06-af1347b849d1',
39 'info_dict': {
40 'id': 'ec217ecc-0733-48cf-ac06-af1347b849d1',
41 'ext': 'mp4',
42 'title': '13h15, le dimanche... - Les mystères de Jésus',
43 'timestamp': 1502623500,
44 'duration': 2580,
45 'thumbnail': r're:^https?://.*\.jpg$',
46 'upload_date': '20170813',
48 'params': {'skip_download': 'm3u8'},
49 }, {
50 # tokenized url is in dinfo['video']['token']['akamai']
51 'url': 'francetv:c5bda21d-2c6f-4470-8849-3d8327adb2ba',
52 'info_dict': {
53 'id': 'c5bda21d-2c6f-4470-8849-3d8327adb2ba',
54 'ext': 'mp4',
55 'title': '13h15, le dimanche... - Les mystères de Jésus',
56 'timestamp': 1514118300,
57 'duration': 2880,
58 'thumbnail': r're:^https?://.*\.jpg$',
59 'upload_date': '20171224',
61 'params': {'skip_download': 'm3u8'},
62 }, {
63 'url': 'francetv:162311093',
64 'only_matching': True,
65 }, {
66 'url': 'francetv:NI_1004933@Zouzous',
67 'only_matching': True,
68 }, {
69 'url': 'francetv:NI_983319@Info-web',
70 'only_matching': True,
71 }, {
72 'url': 'francetv:NI_983319',
73 'only_matching': True,
74 }, {
75 'url': 'francetv:NI_657393@Regions',
76 'only_matching': True,
77 }, {
78 # france-3 live
79 'url': 'francetv:SIM_France3',
80 'only_matching': True,
83 def _extract_video(self, video_id, hostname=None):
84 is_live = None
85 videos = []
86 drm_formats = False
87 title = None
88 subtitle = None
89 episode_number = None
90 season_number = None
91 image = None
92 duration = None
93 timestamp = None
94 spritesheets = None
96 # desktop+chrome returns dash; mobile+safari returns hls
97 for device_type, browser in [('desktop', 'chrome'), ('mobile', 'safari')]:
98 dinfo = self._download_json(
99 f'https://k7.ftven.fr/videos/{video_id}', video_id,
100 f'Downloading {device_type} {browser} video JSON', query=filter_dict({
101 'device_type': device_type,
102 'browser': browser,
103 'domain': hostname,
104 }), fatal=False, expected_status=422) # 422 json gives detailed error code/message
106 if not dinfo:
107 continue
109 if video := traverse_obj(dinfo, ('video', {dict})):
110 videos.append(video)
111 if duration is None:
112 duration = video.get('duration')
113 if is_live is None:
114 is_live = video.get('is_live')
115 if spritesheets is None:
116 spritesheets = video.get('spritesheets')
117 elif code := traverse_obj(dinfo, ('code', {int})):
118 if code == 2009:
119 self.raise_geo_restricted(countries=self._GEO_COUNTRIES)
120 elif code in (2015, 2017):
121 # 2015: L'accès à cette vidéo est impossible. (DRM-only)
122 # 2017: Cette vidéo n'est pas disponible depuis le site web mobile (b/c DRM)
123 drm_formats = True
124 continue
125 self.report_warning(
126 f'{self.IE_NAME} said: {code} "{clean_html(dinfo.get("message"))}"')
127 continue
129 if meta := traverse_obj(dinfo, ('meta', {dict})):
130 if title is None:
131 title = meta.get('title')
132 # meta['pre_title'] contains season and episode number for series in format "S<ID> E<ID>"
133 season_number, episode_number = self._search_regex(
134 r'S(\d+)\s*E(\d+)', meta.get('pre_title'), 'episode info', group=(1, 2), default=(None, None))
135 if subtitle is None:
136 subtitle = meta.get('additional_title')
137 if image is None:
138 image = meta.get('image_url')
139 if timestamp is None:
140 timestamp = parse_iso8601(meta.get('broadcasted_at'))
142 if not videos and drm_formats:
143 self.report_drm(video_id)
145 formats, subtitles, video_url = [], {}, None
146 for video in traverse_obj(videos, lambda _, v: url_or_none(v['url'])):
147 video_url = video['url']
148 format_id = video.get('format')
150 if token_url := traverse_obj(video, ('token', (None, 'akamai'), {url_or_none}, any)):
151 tokenized_url = traverse_obj(self._download_json(
152 token_url, video_id, f'Downloading signed {format_id} manifest URL',
153 fatal=False, query={
154 'format': 'json',
155 'url': video_url,
156 }), ('url', {url_or_none}))
157 if tokenized_url:
158 video_url = tokenized_url
160 ext = determine_ext(video_url)
161 if ext == 'f4m':
162 formats.extend(self._extract_f4m_formats(
163 video_url, video_id, f4m_id=format_id or ext, fatal=False))
164 elif ext == 'm3u8':
165 format_id = format_id or 'hls'
166 fmts, subs = self._extract_m3u8_formats_and_subtitles(
167 video_url, video_id, 'mp4', m3u8_id=format_id, fatal=False)
168 for f in traverse_obj(fmts, lambda _, v: v['vcodec'] == 'none' and v.get('tbr') is None):
169 if mobj := re.match(rf'{format_id}-[Aa]udio-\w+-(?P<bitrate>\d+)', f['format_id']):
170 f.update({
171 'tbr': int_or_none(mobj.group('bitrate')),
172 'acodec': 'mp4a',
174 formats.extend(fmts)
175 self._merge_subtitles(subs, target=subtitles)
176 elif ext == 'mpd':
177 fmts, subs = self._extract_mpd_formats_and_subtitles(
178 video_url, video_id, mpd_id=format_id or 'dash', fatal=False)
179 formats.extend(fmts)
180 self._merge_subtitles(subs, target=subtitles)
181 elif video_url.startswith('rtmp'):
182 formats.append({
183 'url': video_url,
184 'format_id': join_nonempty('rtmp', format_id),
185 'ext': 'flv',
187 else:
188 if self._is_valid_url(video_url, video_id, format_id):
189 formats.append({
190 'url': video_url,
191 'format_id': format_id,
194 # XXX: what is video['captions']?
196 if not formats and video_url:
197 urlh = self._request_webpage(
198 HEADRequest(video_url), video_id, 'Checking for geo-restriction',
199 fatal=False, expected_status=403)
200 if urlh and urlh.headers.get('x-errortype') == 'geo':
201 self.raise_geo_restricted(countries=self._GEO_COUNTRIES, metadata_available=True)
203 for f in formats:
204 if f.get('acodec') != 'none' and f.get('language') in ('qtz', 'qad'):
205 f['language_preference'] = -10
206 f['format_note'] = 'audio description{}'.format(format_field(f, 'format_note', ', %s'))
208 if spritesheets:
209 formats.append({
210 'format_id': 'spritesheets',
211 'format_note': 'storyboard',
212 'acodec': 'none',
213 'vcodec': 'none',
214 'ext': 'mhtml',
215 'protocol': 'mhtml',
216 'url': 'about:invalid',
217 'fragments': [{
218 'url': sheet,
219 # XXX: not entirely accurate; each spritesheet seems to be
220 # a 10x10 grid of thumbnails corresponding to approximately
221 # 2 seconds of the video; the last spritesheet may be shorter
222 'duration': 200,
223 } for sheet in traverse_obj(spritesheets, (..., {url_or_none}))],
226 return {
227 'id': video_id,
228 'title': join_nonempty(title, subtitle, delim=' - ').strip(),
229 'thumbnail': image,
230 'duration': duration,
231 'timestamp': timestamp,
232 'is_live': is_live,
233 'formats': formats,
234 'subtitles': subtitles,
235 'episode': subtitle if episode_number else None,
236 'series': title if episode_number else None,
237 'episode_number': int_or_none(episode_number),
238 'season_number': int_or_none(season_number),
239 '_format_sort_fields': ('res', 'tbr', 'proto'), # prioritize m3u8 over dash
242 def _real_extract(self, url):
243 url, smuggled_data = unsmuggle_url(url, {})
244 video_id = self._match_id(url)
245 hostname = smuggled_data.get('hostname') or 'www.france.tv'
247 return self._extract_video(video_id, hostname=hostname)
250 class FranceTVSiteIE(FranceTVBaseInfoExtractor):
251 _VALID_URL = r'https?://(?:(?:www\.)?france\.tv|mobile\.france\.tv)/(?:[^/]+/)*(?P<id>[^/]+)\.html'
253 _TESTS = [{
254 'url': 'https://www.france.tv/france-2/13h15-le-dimanche/140921-les-mysteres-de-jesus.html',
255 'info_dict': {
256 'id': 'c5bda21d-2c6f-4470-8849-3d8327adb2ba',
257 'ext': 'mp4',
258 'title': '13h15, le dimanche... - Les mystères de Jésus',
259 'timestamp': 1514118300,
260 'duration': 2880,
261 'thumbnail': r're:^https?://.*\.jpg$',
262 'upload_date': '20171224',
264 'params': {
265 'skip_download': True,
267 'add_ie': [FranceTVIE.ie_key()],
268 }, {
269 # geo-restricted
270 'url': 'https://www.france.tv/enfants/six-huit-ans/foot2rue/saison-1/3066387-duel-au-vieux-port.html',
271 'info_dict': {
272 'id': 'a9050959-eedd-4b4a-9b0d-de6eeaa73e44',
273 'ext': 'mp4',
274 'title': 'Foot2Rue - Duel au vieux port',
275 'episode': 'Duel au vieux port',
276 'series': 'Foot2Rue',
277 'episode_number': 1,
278 'season_number': 1,
279 'timestamp': 1642761360,
280 'upload_date': '20220121',
281 'season': 'Season 1',
282 'thumbnail': r're:^https?://.*\.jpg$',
283 'duration': 1441,
285 }, {
286 # geo-restricted livestream (workflow == 'token-akamai')
287 'url': 'https://www.france.tv/france-4/direct.html',
288 'info_dict': {
289 'id': '9a6a7670-dde9-4264-adbc-55b89558594b',
290 'ext': 'mp4',
291 'title': r're:France 4 en direct .+',
292 'live_status': 'is_live',
294 'skip': 'geo-restricted livestream',
295 }, {
296 # livestream (workflow == 'dai')
297 'url': 'https://www.france.tv/france-2/direct.html',
298 'info_dict': {
299 'id': '006194ea-117d-4bcf-94a9-153d999c59ae',
300 'ext': 'mp4',
301 'title': r're:France 2 en direct .+',
302 'live_status': 'is_live',
304 'params': {'skip_download': 'livestream'},
305 }, {
306 # france3
307 'url': 'https://www.france.tv/france-3/des-chiffres-et-des-lettres/139063-emission-du-mardi-9-mai-2017.html',
308 'only_matching': True,
309 }, {
310 # france4
311 'url': 'https://www.france.tv/france-4/hero-corp/saison-1/134151-apres-le-calme.html',
312 'only_matching': True,
313 }, {
314 # france5
315 'url': 'https://www.france.tv/france-5/c-a-dire/saison-10/137013-c-a-dire.html',
316 'only_matching': True,
317 }, {
318 # franceo
319 'url': 'https://www.france.tv/france-o/archipels/132249-mon-ancetre-l-esclave.html',
320 'only_matching': True,
321 }, {
322 'url': 'https://www.france.tv/documentaires/histoire/136517-argentine-les-500-bebes-voles-de-la-dictature.html',
323 'only_matching': True,
324 }, {
325 'url': 'https://www.france.tv/jeux-et-divertissements/divertissements/133965-le-web-contre-attaque.html',
326 'only_matching': True,
327 }, {
328 'url': 'https://mobile.france.tv/france-5/c-dans-l-air/137347-emission-du-vendredi-12-mai-2017.html',
329 'only_matching': True,
330 }, {
331 'url': 'https://www.france.tv/142749-rouge-sang.html',
332 'only_matching': True,
333 }, {
334 # france-3 live
335 'url': 'https://www.france.tv/france-3/direct.html',
336 'only_matching': True,
339 def _real_extract(self, url):
340 display_id = self._match_id(url)
342 webpage = self._download_webpage(url, display_id)
344 video_id = self._search_regex(
345 r'(?:data-main-video\s*=|videoId["\']?\s*[:=])\s*(["\'])(?P<id>(?:(?!\1).)+)\1',
346 webpage, 'video id', default=None, group='id')
348 if not video_id:
349 video_id = self._html_search_regex(
350 r'(?:href=|player\.setVideo\(\s*)"http://videos?\.francetv\.fr/video/([^@"]+@[^"]+)"',
351 webpage, 'video ID')
353 return self._make_url_result(video_id, url=url)
356 class FranceTVInfoIE(FranceTVBaseInfoExtractor):
357 IE_NAME = 'francetvinfo.fr'
358 _VALID_URL = r'https?://(?:www|mobile|france3-regions)\.francetvinfo\.fr/(?:[^/]+/)*(?P<id>[^/?#&.]+)'
360 _TESTS = [{
361 'url': 'https://www.francetvinfo.fr/replay-jt/france-3/soir-3/jt-grand-soir-3-jeudi-22-aout-2019_3561461.html',
362 'info_dict': {
363 'id': 'd12458ee-5062-48fe-bfdd-a30d6a01b793',
364 'ext': 'mp4',
365 'title': 'Soir 3',
366 'upload_date': '20190822',
367 'timestamp': 1566510730,
368 'thumbnail': r're:^https?://.*\.jpe?g$',
369 'duration': 1637,
370 'subtitles': {
371 'fr': 'mincount:2',
374 'params': {
375 'skip_download': True,
377 'add_ie': [FranceTVIE.ie_key()],
378 }, {
379 'note': 'Only an image exists in initial webpage instead of the video',
380 'url': 'https://www.francetvinfo.fr/sante/maladie/coronavirus/covid-19-en-inde-une-situation-catastrophique-a-new-dehli_4381095.html',
381 'info_dict': {
382 'id': '7d204c9e-a2d3-11eb-9e4c-000d3a23d482',
383 'ext': 'mp4',
384 'title': 'Covid-19 : une situation catastrophique à New Dehli - Édition du mercredi 21 avril 2021',
385 'thumbnail': r're:^https?://.*\.jpe?g$',
386 'duration': 76,
387 'timestamp': 1619028518,
388 'upload_date': '20210421',
390 'params': {
391 'skip_download': True,
393 'add_ie': [FranceTVIE.ie_key()],
394 }, {
395 'url': 'http://www.francetvinfo.fr/elections/europeennes/direct-europeennes-regardez-le-debat-entre-les-candidats-a-la-presidence-de-la-commission_600639.html',
396 'only_matching': True,
397 }, {
398 'url': 'http://www.francetvinfo.fr/economie/entreprises/les-entreprises-familiales-le-secret-de-la-reussite_933271.html',
399 'only_matching': True,
400 }, {
401 'url': 'http://france3-regions.francetvinfo.fr/bretagne/cotes-d-armor/thalassa-echappee-breizh-ce-venredi-dans-les-cotes-d-armor-954961.html',
402 'only_matching': True,
403 }, {
404 # Dailymotion embed
405 'url': 'http://www.francetvinfo.fr/politique/notre-dame-des-landes/video-sur-france-inter-cecile-duflot-denonce-le-regard-meprisant-de-patrick-cohen_1520091.html',
406 'md5': 'ee7f1828f25a648addc90cb2687b1f12',
407 'info_dict': {
408 'id': 'x4iiko0',
409 'ext': 'mp4',
410 'title': 'NDDL, référendum, Brexit : Cécile Duflot répond à Patrick Cohen',
411 'description': 'md5:fdcb582c370756293a65cdfbc6ecd90e',
412 'timestamp': 1467011958,
413 'uploader': 'France Inter',
414 'uploader_id': 'x2q2ez',
415 'upload_date': '20160627',
416 'view_count': int,
417 'tags': ['Politique', 'France Inter', '27 juin 2016', 'Linvité de 8h20', 'Cécile Duflot', 'Patrick Cohen'],
418 'age_limit': 0,
419 'duration': 640,
420 'like_count': int,
421 'thumbnail': r're:https://[^/?#]+/v/[^/?#]+/x1080',
423 'add_ie': ['Dailymotion'],
424 }, {
425 'url': 'http://france3-regions.francetvinfo.fr/limousin/emissions/jt-1213-limousin',
426 'only_matching': True,
427 }, {
428 # "<figure id=" pattern (#28792)
429 'url': 'https://www.francetvinfo.fr/culture/patrimoine/incendie-de-notre-dame-de-paris/notre-dame-de-paris-de-l-incendie-de-la-cathedrale-a-sa-reconstruction_4372291.html',
430 'only_matching': True,
433 def _real_extract(self, url):
434 display_id = self._match_id(url)
436 webpage = self._download_webpage(url, display_id)
438 dailymotion_urls = tuple(DailymotionIE._extract_embed_urls(url, webpage))
439 if dailymotion_urls:
440 return self.playlist_result([
441 self.url_result(dailymotion_url, DailymotionIE.ie_key())
442 for dailymotion_url in dailymotion_urls])
444 video_id = self._search_regex(
445 (r'player\.load[^;]+src:\s*["\']([^"\']+)',
446 r'id-video=([^@]+@[^"]+)',
447 r'<a[^>]+href="(?:https?:)?//videos\.francetv\.fr/video/([^@]+@[^"]+)"',
448 r'(?:data-id|<figure[^<]+\bid)=["\']([\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12})'),
449 webpage, 'video id')
451 return self._make_url_result(video_id, url=url)