]> jfr.im git - yt-dlp.git/blame - yt_dlp/extractor/archiveorg.py
[ie/youtube] Suppress "Unavailable videos are hidden" warning (#10159)
[yt-dlp.git] / yt_dlp / extractor / archiveorg.py
CommitLineData
add96eb9 1from __future__ import annotations
2
a3e26449 3import json
ac668111 4import re
5import urllib.parse
6
a4a554a7 7from .common import InfoExtractor
ac668111 8from .youtube import YoutubeBaseInfoExtractor, YoutubeIE
3d2623a8 9from ..networking import HEADRequest
10from ..networking.exceptions import HTTPError
d50aca41 11from ..utils import (
ac668111 12 KNOWN_EXTENSIONS,
13 ExtractorError,
aa4b0545 14 bug_reports_message,
d50aca41 15 clean_html,
a3e26449 16 dict_get,
879e7199 17 extract_attributes,
aa4b0545 18 get_element_by_id,
a3e26449 19 int_or_none,
1f13021e 20 join_nonempty,
217753f4 21 js_to_json,
a3e26449 22 merge_dicts,
879e7199 23 mimetype2ext,
aa4b0545 24 orderedSet,
879e7199 25 parse_duration,
4dfbf869 26 parse_qs,
879e7199 27 str_or_none,
ac668111 28 str_to_int,
aa4b0545 29 traverse_obj,
879e7199 30 try_get,
31 unified_strdate,
32 unified_timestamp,
ac668111 33 url_or_none,
aa4b0545 34 urlhandle_detect_ext,
f4f9f6d0 35 variadic,
d50aca41 36)
5fe3a3c3
PH
37
38
a4a554a7 39class ArchiveOrgIE(InfoExtractor):
5fe3a3c3 40 IE_NAME = 'archive.org'
a3e26449 41 IE_DESC = 'archive.org video and audio'
42 _VALID_URL = r'https?://(?:www\.)?archive\.org/(?:details|embed)/(?P<id>[^?#]+)(?:[?].*)?$'
e8e28989
S
43 _TESTS = [{
44 'url': 'http://archive.org/details/XD300-23_68HighlightsAResearchCntAugHumanIntellect',
3798eadc
PH
45 'md5': '8af1d4cf447933ed3c7f4871162602db',
46 'info_dict': {
e8e28989 47 'id': 'XD300-23_68HighlightsAResearchCntAugHumanIntellect',
a3e26449 48 'ext': 'ogv',
e8e28989 49 'title': '1968 Demo - FJCC Conference Presentation Reel #1',
d50aca41 50 'description': 'md5:da45c349df039f1cc8075268eb1b5c25',
a3e26449 51 'release_date': '19681210',
52 'timestamp': 1268695290,
53 'upload_date': '20100315',
f4f9f6d0 54 'creators': ['SRI International'],
a3e26449 55 'uploader': 'laura@archive.org',
871a8929 56 'thumbnail': r're:https://archive\.org/download/.*\.jpg',
871a8929 57 'display_id': 'XD300-23_68HighlightsAResearchCntAugHumanIntellect.cdr',
58 'track': 'XD300-23 68HighlightsAResearchCntAugHumanIntellect',
59
a3e26449 60 },
e8e28989
S
61 }, {
62 'url': 'https://archive.org/details/Cops1922',
c12b4b80 63 'md5': '0869000b4ce265e8ca62738b336b268a',
e8e28989
S
64 'info_dict': {
65 'id': 'Cops1922',
d50aca41 66 'ext': 'mp4',
e8e28989 67 'title': 'Buster Keaton\'s "Cops" (1922)',
871a8929 68 'description': 'md5:cd6f9910c35aedd5fc237dbc3957e2ca',
a3e26449 69 'uploader': 'yorkmba99@hotmail.com',
70 'timestamp': 1387699629,
1f13021e 71 'upload_date': '20131222',
871a8929 72 'display_id': 'Cops-v2.mp4',
73 'thumbnail': r're:https://archive\.org/download/.*\.jpg',
74 'duration': 1091.96,
a3e26449 75 },
d50aca41
RA
76 }, {
77 'url': 'http://archive.org/embed/XD300-23_68HighlightsAResearchCntAugHumanIntellect',
78 'only_matching': True,
a3e26449 79 }, {
80 'url': 'https://archive.org/details/Election_Ads',
871a8929 81 'md5': 'eec5cddebd4793c6a653b69c3b11f2e6',
a3e26449 82 'info_dict': {
83 'id': 'Election_Ads/Commercial-JFK1960ElectionAdCampaignJingle.mpg',
84 'title': 'Commercial-JFK1960ElectionAdCampaignJingle.mpg',
871a8929 85 'ext': 'mpg',
86 'thumbnail': r're:https://archive\.org/download/.*\.jpg',
87 'duration': 59.77,
88 'display_id': 'Commercial-JFK1960ElectionAdCampaignJingle.mpg',
a3e26449 89 },
90 }, {
91 'url': 'https://archive.org/details/Election_Ads/Commercial-Nixon1960ElectionAdToughonDefense.mpg',
871a8929 92 'md5': 'ea1eed8234e7d4165f38c8c769edef38',
a3e26449 93 'info_dict': {
94 'id': 'Election_Ads/Commercial-Nixon1960ElectionAdToughonDefense.mpg',
95 'title': 'Commercial-Nixon1960ElectionAdToughonDefense.mpg',
871a8929 96 'ext': 'mpg',
a3e26449 97 'timestamp': 1205588045,
98 'uploader': 'mikedavisstripmaster@yahoo.com',
99 'description': '1960 Presidential Campaign Election Commercials John F Kennedy, Richard M Nixon',
100 'upload_date': '20080315',
871a8929 101 'display_id': 'Commercial-Nixon1960ElectionAdToughonDefense.mpg',
102 'duration': 59.51,
103 'license': 'http://creativecommons.org/licenses/publicdomain/',
104 'thumbnail': r're:https://archive\.org/download/.*\.jpg',
a3e26449 105 },
106 }, {
107 'url': 'https://archive.org/details/gd1977-05-08.shure57.stevenson.29303.flac16',
108 'md5': '7d07ffb42aba6537c28e053efa4b54c9',
109 'info_dict': {
110 'id': 'gd1977-05-08.shure57.stevenson.29303.flac16/gd1977-05-08d01t01.flac',
111 'title': 'Turning',
112 'ext': 'flac',
871a8929 113 'track': 'Turning',
f4f9f6d0 114 'creators': ['Grateful Dead'],
871a8929 115 'display_id': 'gd1977-05-08d01t01.flac',
116 'track_number': 1,
117 'album': '1977-05-08 - Barton Hall - Cornell University',
118 'duration': 39.8,
a3e26449 119 },
120 }, {
121 'url': 'https://archive.org/details/gd1977-05-08.shure57.stevenson.29303.flac16/gd1977-05-08d01t07.flac',
122 'md5': 'a07cd8c6ab4ee1560f8a0021717130f3',
123 'info_dict': {
124 'id': 'gd1977-05-08.shure57.stevenson.29303.flac16/gd1977-05-08d01t07.flac',
125 'title': 'Deal',
126 'ext': 'flac',
127 'timestamp': 1205895624,
128 'uploader': 'mvernon54@yahoo.com',
871a8929 129 'description': 'md5:6c921464414814720c6593810a5c7e3d',
a3e26449 130 'upload_date': '20080319',
131 'location': 'Barton Hall - Cornell University',
871a8929 132 'duration': 438.68,
133 'track': 'Deal',
f4f9f6d0 134 'creators': ['Grateful Dead'],
871a8929 135 'album': '1977-05-08 - Barton Hall - Cornell University',
136 'release_date': '19770508',
137 'display_id': 'gd1977-05-08d01t07.flac',
871a8929 138 'track_number': 7,
a3e26449 139 },
140 }, {
871a8929 141 # FIXME: give a better error message than just IndexError when all available formats are restricted
a3e26449 142 'url': 'https://archive.org/details/lp_the-music-of-russia_various-artists-a-askaryan-alexander-melik',
143 'md5': '7cb019baa9b332e82ea7c10403acd180',
144 'info_dict': {
145 'id': 'lp_the-music-of-russia_various-artists-a-askaryan-alexander-melik/disc1/01.01. Bells Of Rostov.mp3',
146 'title': 'Bells Of Rostov',
147 'ext': 'mp3',
148 },
add96eb9 149 'skip': 'restricted',
a3e26449 150 }, {
151 'url': 'https://archive.org/details/lp_the-music-of-russia_various-artists-a-askaryan-alexander-melik/disc1/02.02.+Song+And+Chorus+In+The+Polovetsian+Camp+From+%22Prince+Igor%22+(Act+2%2C+Scene+1).mp3',
152 'md5': '1d0aabe03edca83ca58d9ed3b493a3c3',
153 'info_dict': {
154 'id': 'lp_the-music-of-russia_various-artists-a-askaryan-alexander-melik/disc1/02.02. Song And Chorus In The Polovetsian Camp From "Prince Igor" (Act 2, Scene 1).mp3',
155 'title': 'Song And Chorus In The Polovetsian Camp From "Prince Igor" (Act 2, Scene 1)',
156 'ext': 'mp3',
157 'timestamp': 1569662587,
158 'uploader': 'associate-joygen-odiongan@archive.org',
159 'description': 'md5:012b2d668ae753be36896f343d12a236',
160 'upload_date': '20190928',
161 },
add96eb9 162 'skip': 'restricted',
871a8929 163 }, {
164 # Original formats are private
165 'url': 'https://archive.org/details/irelandthemakingofarepublic',
166 'info_dict': {
167 'id': 'irelandthemakingofarepublic',
168 'title': 'Ireland: The Making of a Republic',
169 'upload_date': '20160610',
170 'description': 'md5:f70956a156645a658a0dc9513d9e78b7',
171 'uploader': 'dimitrios@archive.org',
f4f9f6d0 172 'creators': ['British Broadcasting Corporation', 'Time-Life Films'],
871a8929 173 'timestamp': 1465594947,
174 },
175 'playlist': [
176 {
177 'md5': '0b211261b26590d49df968f71b90690d',
178 'info_dict': {
179 'id': 'irelandthemakingofarepublic/irelandthemakingofarepublicreel1_01.mov',
180 'ext': 'mp4',
181 'title': 'irelandthemakingofarepublicreel1_01.mov',
182 'duration': 130.46,
183 'thumbnail': 'https://archive.org/download/irelandthemakingofarepublic/irelandthemakingofarepublic.thumbs/irelandthemakingofarepublicreel1_01_000117.jpg',
184 'display_id': 'irelandthemakingofarepublicreel1_01.mov',
185 },
186 }, {
187 'md5': '67335ee3b23a0da930841981c1e79b02',
188 'info_dict': {
189 'id': 'irelandthemakingofarepublic/irelandthemakingofarepublicreel1_02.mov',
190 'ext': 'mp4',
191 'duration': 1395.13,
192 'title': 'irelandthemakingofarepublicreel1_02.mov',
193 'display_id': 'irelandthemakingofarepublicreel1_02.mov',
194 'thumbnail': 'https://archive.org/download/irelandthemakingofarepublic/irelandthemakingofarepublic.thumbs/irelandthemakingofarepublicreel1_02_001374.jpg',
195 },
196 }, {
197 'md5': 'e470e86787893603f4a341a16c281eb5',
198 'info_dict': {
199 'id': 'irelandthemakingofarepublic/irelandthemakingofarepublicreel2.mov',
200 'ext': 'mp4',
201 'duration': 1602.67,
202 'title': 'irelandthemakingofarepublicreel2.mov',
203 'thumbnail': 'https://archive.org/download/irelandthemakingofarepublic/irelandthemakingofarepublic.thumbs/irelandthemakingofarepublicreel2_001554.jpg',
204 'display_id': 'irelandthemakingofarepublicreel2.mov',
205 },
add96eb9 206 },
207 ],
e8e28989 208 }]
ff7a07d5 209
a3e26449 210 @staticmethod
211 def _playlist_data(webpage):
212 element = re.findall(r'''(?xs)
213 <input
214 (?:\s+[a-zA-Z0-9:._-]+(?:=[a-zA-Z0-9:._-]*|="[^"]*"|='[^']*'|))*?
215 \s+class=['"]?js-play8-playlist['"]?
216 (?:\s+[a-zA-Z0-9:._-]+(?:=[a-zA-Z0-9:._-]*|="[^"]*"|='[^']*'|))*?
217 \s*/>
218 ''', webpage)[0]
219
220 return json.loads(extract_attributes(element)['value'])
221
5fe3a3c3 222 def _real_extract(self, url):
ac668111 223 video_id = urllib.parse.unquote_plus(self._match_id(url))
add96eb9 224 identifier, _, entry_id = video_id.partition('/')
a3e26449 225
226 # Archive.org metadata API doesn't clearly demarcate playlist entries
227 # or subtitle tracks, so we get them from the embeddable player.
1f13021e 228 embed_page = self._download_webpage(f'https://archive.org/embed/{identifier}', identifier)
a3e26449 229 playlist = self._playlist_data(embed_page)
230
231 entries = {}
232 for p in playlist:
233 # If the user specified a playlist entry in the URL, ignore the
234 # rest of the playlist.
235 if entry_id and p['orig'] != entry_id:
236 continue
237
238 entries[p['orig']] = {
239 'formats': [],
240 'thumbnails': [],
241 'artist': p.get('artist'),
242 'track': p.get('title'),
1f13021e 243 'subtitles': {},
244 }
a3e26449 245
246 for track in p.get('tracks', []):
247 if track['kind'] != 'subtitles':
248 continue
a3e26449 249 entries[p['orig']][track['label']] = {
add96eb9 250 'url': 'https://archive.org/' + track['file'].lstrip('/'),
1f13021e 251 }
5fe3a3c3 252
1f13021e 253 metadata = self._download_json('http://archive.org/metadata/' + identifier, identifier)
a3e26449 254 m = metadata['metadata']
255 identifier = m['identifier']
256
257 info = {
258 'id': identifier,
259 'title': m['title'],
260 'description': clean_html(m.get('description')),
261 'uploader': dict_get(m, ['uploader', 'adder']),
f4f9f6d0 262 'creators': traverse_obj(m, ('creator', {variadic}, {lambda x: x[0] and list(x)})),
a3e26449 263 'license': m.get('licenseurl'),
264 'release_date': unified_strdate(m.get('date')),
265 'timestamp': unified_timestamp(dict_get(m, ['publicdate', 'addeddate'])),
1f13021e 266 'webpage_url': f'https://archive.org/details/{identifier}',
a3e26449 267 'location': m.get('venue'),
268 'release_year': int_or_none(m.get('year'))}
269
270 for f in metadata['files']:
271 if f['name'] in entries:
272 entries[f['name']] = merge_dicts(entries[f['name']], {
273 'id': identifier + '/' + f['name'],
274 'title': f.get('title') or f['name'],
275 'display_id': f['name'],
276 'description': clean_html(f.get('description')),
f4f9f6d0 277 'creators': traverse_obj(f, ('creator', {variadic}, {lambda x: x[0] and list(x)})),
a3e26449 278 'duration': parse_duration(f.get('length')),
279 'track_number': int_or_none(f.get('track')),
280 'album': f.get('album'),
281 'discnumber': int_or_none(f.get('disc')),
282 'release_year': int_or_none(f.get('year'))})
283 entry = entries[f['name']]
e612f66c 284 elif traverse_obj(f, 'original', expected_type=str) in entries:
a3e26449 285 entry = entries[f['original']]
286 else:
287 continue
288
289 if f.get('format') == 'Thumbnail':
290 entry['thumbnails'].append({
291 'id': f['name'],
292 'url': 'https://archive.org/download/' + identifier + '/' + f['name'],
293 'width': int_or_none(f.get('width')),
294 'height': int_or_none(f.get('width')),
295 'filesize': int_or_none(f.get('size'))})
296
add96eb9 297 _, has_ext, extension = f['name'].rpartition('.')
298 if not has_ext:
299 extension = None
871a8929 300
301 # We don't want to skip private formats if the user has access to them,
302 # however without access to an account with such privileges we can't implement/test this.
303 # For now to be safe, we will only skip them if there is no user logged in.
304 is_logged_in = bool(self._get_cookies('https://archive.org').get('logged-in-sig'))
305 if extension in KNOWN_EXTENSIONS and (not f.get('private') or is_logged_in):
a3e26449 306 entry['formats'].append({
3894ab95 307 'url': 'https://archive.org/download/' + identifier + '/' + urllib.parse.quote(f['name']),
a3e26449 308 'format': f.get('format'),
309 'width': int_or_none(f.get('width')),
310 'height': int_or_none(f.get('height')),
311 'filesize': int_or_none(f.get('size')),
871a8929 312 'protocol': 'https',
313 'source_preference': 0 if f.get('source') == 'original' else -1,
add96eb9 314 'format_note': f.get('source'),
871a8929 315 })
a3e26449 316
a3e26449 317 for entry in entries.values():
9f14daf2 318 entry['_format_sort_fields'] = ('source', )
a3e26449 319
320 if len(entries) == 1:
321 # If there's only one item, use it as the main info dict
1f13021e 322 only_video = next(iter(entries.values()))
a3e26449 323 if entry_id:
324 info = merge_dicts(only_video, info)
325 else:
326 info = merge_dicts(info, only_video)
327 else:
328 # Otherwise, we have a playlist.
329 info['_type'] = 'playlist'
330 info['entries'] = list(entries.values())
331
332 if metadata.get('reviews'):
333 info['comments'] = []
334 for review in metadata['reviews']:
335 info['comments'].append({
336 'id': review.get('review_id'),
337 'author': review.get('reviewer'),
338 'text': str_or_none(review.get('reviewtitle'), '') + '\n\n' + review.get('reviewbody'),
339 'timestamp': unified_timestamp(review.get('createdate')),
340 'parent': 'root'})
341
84bc23b4 342 return info
879e7199 343
344
345class YoutubeWebArchiveIE(InfoExtractor):
346 IE_NAME = 'web.archive:youtube'
1f13021e 347 IE_DESC = 'web.archive.org saved youtube videos, "ytarchive:" prefix'
348 _VALID_URL = r'''(?x)(?:(?P<prefix>ytarchive:)|
349 (?:https?://)?web\.archive\.org/
350 (?:web/)?(?:(?P<date>[0-9]{14})?[0-9A-Za-z_*]*/)? # /web and the version index is optional
351 (?:https?(?::|%3[Aa])//)?(?:
352 (?:\w+\.)?youtube\.com(?::(?:80|443))?/watch(?:\.php)?(?:\?|%3[fF])(?:[^\#]+(?:&|%26))?v(?:=|%3[dD]) # Youtube URL
353 |(?:wayback-fakeurl\.archive\.org/yt/) # Or the internal fake url
354 )
355 )(?P<id>[0-9A-Za-z_-]{11})
356 (?(prefix)
357 (?::(?P<date2>[0-9]{14}))?$|
358 (?:%26|[#&]|$)
359 )'''
879e7199 360
361 _TESTS = [
362 {
363 'url': 'https://web.archive.org/web/20150415002341/https://www.youtube.com/watch?v=aYAGB11YrSs',
364 'info_dict': {
365 'id': 'aYAGB11YrSs',
366 'ext': 'webm',
aa4b0545 367 'title': 'Team Fortress 2 - Sandviches!',
368 'description': 'md5:4984c0f9a07f349fc5d8e82ab7af4eaf',
369 'upload_date': '20110926',
370 'uploader': 'Zeurel',
371 'channel_id': 'UCukCyHaD-bK3in_pKpfH9Eg',
372 'duration': 32,
373 'uploader_id': 'Zeurel',
217753f4
M
374 'uploader_url': 'https://www.youtube.com/user/Zeurel',
375 'thumbnail': r're:https?://.*\.(jpg|webp)',
376 'channel_url': 'https://www.youtube.com/channel/UCukCyHaD-bK3in_pKpfH9Eg',
add96eb9 377 },
aa4b0545 378 }, {
879e7199 379 # Internal link
380 'url': 'https://web.archive.org/web/2oe/http://wayback-fakeurl.archive.org/yt/97t7Xj_iBv0',
381 'info_dict': {
382 'id': '97t7Xj_iBv0',
383 'ext': 'mp4',
aa4b0545 384 'title': 'Why Machines That Bend Are Better',
385 'description': 'md5:00404df2c632d16a674ff8df1ecfbb6c',
386 'upload_date': '20190312',
387 'uploader': 'Veritasium',
388 'channel_id': 'UCHnyfMqiRRG1u-2MsSQLbXA',
389 'duration': 771,
390 'uploader_id': '1veritasium',
217753f4
M
391 'uploader_url': 'https://www.youtube.com/user/1veritasium',
392 'thumbnail': r're:https?://.*\.(jpg|webp)',
393 'channel_url': 'https://www.youtube.com/channel/UCHnyfMqiRRG1u-2MsSQLbXA',
add96eb9 394 },
aa4b0545 395 }, {
396 # Video from 2012, webm format itag 45. Newest capture is deleted video, with an invalid description.
397 # Should use the date in the link. Title ends with '- Youtube'. Capture has description in eow-description
879e7199 398 'url': 'https://web.archive.org/web/20120712231619/http://www.youtube.com/watch?v=AkhihxRKcrs&gl=US&hl=en',
399 'info_dict': {
400 'id': 'AkhihxRKcrs',
401 'ext': 'webm',
aa4b0545 402 'title': 'Limited Run: Mondo\'s Modern Classic 1 of 3 (SDCC 2012)',
403 'upload_date': '20120712',
404 'duration': 398,
405 'description': 'md5:ff4de6a7980cb65d951c2f6966a4f2f3',
406 'uploader_id': 'machinima',
217753f4
M
407 'uploader_url': 'https://www.youtube.com/user/machinima',
408 'thumbnail': r're:https?://.*\.(jpg|webp)',
add96eb9 409 'uploader': 'machinima',
410 },
aa4b0545 411 }, {
412 # FLV video. Video file URL does not provide itag information
879e7199 413 'url': 'https://web.archive.org/web/20081211103536/http://www.youtube.com/watch?v=jNQXAC9IVRw',
414 'info_dict': {
415 'id': 'jNQXAC9IVRw',
aa4b0545 416 'ext': 'flv',
417 'title': 'Me at the zoo',
418 'upload_date': '20050423',
419 'channel_id': 'UC4QobU6STFB0P71PMvOGN5A',
420 'duration': 19,
421 'description': 'md5:10436b12e07ac43ff8df65287a56efb4',
422 'uploader_id': 'jawed',
217753f4
M
423 'uploader_url': 'https://www.youtube.com/user/jawed',
424 'channel_url': 'https://www.youtube.com/channel/UC4QobU6STFB0P71PMvOGN5A',
425 'thumbnail': r're:https?://.*\.(jpg|webp)',
426 'uploader': 'jawed',
add96eb9 427 },
aa4b0545 428 }, {
879e7199 429 'url': 'https://web.archive.org/web/20110712231407/http://www.youtube.com/watch?v=lTx3G6h2xyA',
430 'info_dict': {
431 'id': 'lTx3G6h2xyA',
432 'ext': 'flv',
aa4b0545 433 'title': 'Madeon - Pop Culture (live mashup)',
434 'upload_date': '20110711',
435 'uploader': 'Madeon',
436 'channel_id': 'UCqMDNf3Pn5L7pcNkuSEeO3w',
437 'duration': 204,
438 'description': 'md5:f7535343b6eda34a314eff8b85444680',
439 'uploader_id': 'itsmadeon',
217753f4
M
440 'uploader_url': 'https://www.youtube.com/user/itsmadeon',
441 'channel_url': 'https://www.youtube.com/channel/UCqMDNf3Pn5L7pcNkuSEeO3w',
442 'thumbnail': r're:https?://.*\.(jpg|webp)',
add96eb9 443 },
aa4b0545 444 }, {
445 # First capture is of dead video, second is the oldest from CDX response.
446 'url': 'https://web.archive.org/https://www.youtube.com/watch?v=1JYutPM8O6E',
879e7199 447 'info_dict': {
aa4b0545 448 'id': '1JYutPM8O6E',
879e7199 449 'ext': 'mp4',
aa4b0545 450 'title': 'Fake Teen Doctor Strikes AGAIN! - Weekly Weird News',
451 'upload_date': '20160218',
452 'channel_id': 'UCdIaNUarhzLSXGoItz7BHVA',
217753f4 453 'duration': 1235,
aa4b0545 454 'description': 'md5:21032bae736421e89c2edf36d1936947',
455 'uploader_id': 'MachinimaETC',
217753f4
M
456 'uploader_url': 'https://www.youtube.com/user/MachinimaETC',
457 'channel_url': 'https://www.youtube.com/channel/UCdIaNUarhzLSXGoItz7BHVA',
458 'thumbnail': r're:https?://.*\.(jpg|webp)',
459 'uploader': 'ETC News',
add96eb9 460 },
aa4b0545 461 }, {
462 # First capture of dead video, capture date in link links to dead capture.
463 'url': 'https://web.archive.org/web/20180803221945/https://www.youtube.com/watch?v=6FPhZJGvf4E',
879e7199 464 'info_dict': {
aa4b0545 465 'id': '6FPhZJGvf4E',
879e7199 466 'ext': 'mp4',
aa4b0545 467 'title': 'WTF: Video Games Still Launch BROKEN?! - T.U.G.S.',
468 'upload_date': '20160219',
469 'channel_id': 'UCdIaNUarhzLSXGoItz7BHVA',
217753f4 470 'duration': 797,
aa4b0545 471 'description': 'md5:a1dbf12d9a3bd7cb4c5e33b27d77ffe7',
472 'uploader_id': 'MachinimaETC',
217753f4
M
473 'uploader_url': 'https://www.youtube.com/user/MachinimaETC',
474 'channel_url': 'https://www.youtube.com/channel/UCdIaNUarhzLSXGoItz7BHVA',
475 'thumbnail': r're:https?://.*\.(jpg|webp)',
476 'uploader': 'ETC News',
879e7199 477 },
478 'expected_warnings': [
add96eb9 479 r'unable to download capture webpage \(it may not be archived\)',
480 ],
aa4b0545 481 }, { # Very old YouTube page, has - YouTube in title.
482 'url': 'http://web.archive.org/web/20070302011044/http://youtube.com/watch?v=-06-KB9XTzg',
483 'info_dict': {
484 'id': '-06-KB9XTzg',
485 'ext': 'flv',
add96eb9 486 'title': 'New Coin Hack!! 100% Safe!!',
487 },
aa4b0545 488 }, {
489 'url': 'web.archive.org/https://www.youtube.com/watch?v=dWW7qP423y8',
490 'info_dict': {
491 'id': 'dWW7qP423y8',
492 'ext': 'mp4',
493 'title': 'It\'s Bootleg AirPods Time.',
494 'upload_date': '20211021',
495 'channel_id': 'UC7Jwj9fkrf1adN4fMmTkpug',
217753f4 496 'channel_url': 'https://www.youtube.com/channel/UC7Jwj9fkrf1adN4fMmTkpug',
aa4b0545 497 'duration': 810,
498 'description': 'md5:7b567f898d8237b256f36c1a07d6d7bc',
217753f4 499 'thumbnail': r're:https?://.*\.(jpg|webp)',
aa4b0545 500 'uploader': 'DankPods',
add96eb9 501 },
aa4b0545 502 }, {
503 # player response contains '};' See: https://github.com/ytdl-org/youtube-dl/issues/27093
504 'url': 'https://web.archive.org/web/20200827003909if_/http://www.youtube.com/watch?v=6Dh-RL__uN4',
505 'info_dict': {
506 'id': '6Dh-RL__uN4',
507 'ext': 'mp4',
508 'title': 'bitch lasagna',
509 'upload_date': '20181005',
510 'channel_id': 'UC-lHJZR3Gqxm24_Vd_AJ5Yw',
217753f4 511 'channel_url': 'https://www.youtube.com/channel/UC-lHJZR3Gqxm24_Vd_AJ5Yw',
aa4b0545 512 'duration': 135,
513 'description': 'md5:2dbe4051feeff2dab5f41f82bb6d11d0',
514 'uploader': 'PewDiePie',
515 'uploader_id': 'PewDiePie',
217753f4
M
516 'uploader_url': 'https://www.youtube.com/user/PewDiePie',
517 'thumbnail': r're:https?://.*\.(jpg|webp)',
add96eb9 518 },
217753f4
M
519 }, {
520 # ~June 2010 Capture. swfconfig
521 'url': 'https://web.archive.org/web/0/https://www.youtube.com/watch?v=8XeW5ilk-9Y',
522 'info_dict': {
523 'id': '8XeW5ilk-9Y',
524 'ext': 'flv',
525 'title': 'Story of Stuff, The Critique Part 4 of 4',
526 'duration': 541,
527 'description': 'md5:28157da06f2c5e94c97f7f3072509972',
528 'uploader': 'HowTheWorldWorks',
529 'uploader_id': 'HowTheWorldWorks',
530 'thumbnail': r're:https?://.*\.(jpg|webp)',
531 'uploader_url': 'https://www.youtube.com/user/HowTheWorldWorks',
532 'upload_date': '20090520',
add96eb9 533 },
217753f4
M
534 }, {
535 # Jan 2011: watch-video-date/eow-date surrounded by whitespace
536 'url': 'https://web.archive.org/web/20110126141719/http://www.youtube.com/watch?v=Q_yjX80U7Yc',
537 'info_dict': {
538 'id': 'Q_yjX80U7Yc',
539 'ext': 'flv',
540 'title': 'Spray Paint Art by Clay Butler: Purple Fantasy Forest',
541 'uploader_id': 'claybutlermusic',
542 'description': 'md5:4595264559e3d0a0ceb3f011f6334543',
543 'upload_date': '20090803',
544 'uploader': 'claybutlermusic',
545 'thumbnail': r're:https?://.*\.(jpg|webp)',
546 'duration': 132,
547 'uploader_url': 'https://www.youtube.com/user/claybutlermusic',
add96eb9 548 },
217753f4
M
549 }, {
550 # ~May 2009 swfArgs. ytcfg is spread out over various vars
551 'url': 'https://web.archive.org/web/0/https://www.youtube.com/watch?v=c5uJgG05xUY',
552 'info_dict': {
553 'id': 'c5uJgG05xUY',
554 'ext': 'webm',
555 'title': 'Story of Stuff, The Critique Part 1 of 4',
556 'uploader_id': 'HowTheWorldWorks',
557 'uploader': 'HowTheWorldWorks',
558 'uploader_url': 'https://www.youtube.com/user/HowTheWorldWorks',
559 'upload_date': '20090513',
560 'description': 'md5:4ca77d79538064e41e4cc464e93f44f0',
561 'thumbnail': r're:https?://.*\.(jpg|webp)',
562 'duration': 754,
add96eb9 563 },
217753f4
M
564 }, {
565 # ~June 2012. Upload date is in another lang so cannot extract.
566 'url': 'https://web.archive.org/web/20120607174520/http://www.youtube.com/watch?v=xWTLLl-dQaA',
567 'info_dict': {
568 'id': 'xWTLLl-dQaA',
569 'ext': 'mp4',
570 'title': 'Black Nerd eHarmony Video Bio Parody (SPOOF)',
571 'uploader_url': 'https://www.youtube.com/user/BlackNerdComedy',
572 'description': 'md5:e25f0133aaf9e6793fb81c18021d193e',
573 'uploader_id': 'BlackNerdComedy',
574 'uploader': 'BlackNerdComedy',
575 'duration': 182,
576 'thumbnail': r're:https?://.*\.(jpg|webp)',
add96eb9 577 },
217753f4
M
578 }, {
579 # ~July 2013
580 'url': 'https://web.archive.org/web/*/https://www.youtube.com/watch?v=9eO1aasHyTM',
581 'info_dict': {
582 'id': '9eO1aasHyTM',
583 'ext': 'mp4',
584 'title': 'Polar-oid',
585 'description': 'Cameras and bears are dangerous!',
586 'uploader_url': 'https://www.youtube.com/user/punkybird',
587 'uploader_id': 'punkybird',
588 'duration': 202,
589 'channel_id': 'UC62R2cBezNBOqxSerfb1nMQ',
590 'channel_url': 'https://www.youtube.com/channel/UC62R2cBezNBOqxSerfb1nMQ',
591 'upload_date': '20060428',
592 'uploader': 'punkybird',
add96eb9 593 },
217753f4
M
594 }, {
595 # April 2020: Player response in player config
596 'url': 'https://web.archive.org/web/20200416034815/https://www.youtube.com/watch?v=Cf7vS8jc7dY&gl=US&hl=en',
597 'info_dict': {
598 'id': 'Cf7vS8jc7dY',
599 'ext': 'mp4',
600 'title': 'A Dramatic Pool Story (by Jamie Spicer-Lewis) - Game Grumps Animated',
601 'duration': 64,
602 'upload_date': '20200408',
603 'uploader_id': 'GameGrumps',
604 'uploader': 'GameGrumps',
605 'channel_url': 'https://www.youtube.com/channel/UC9CuvdOVfMPvKCiwdGKL3cQ',
606 'channel_id': 'UC9CuvdOVfMPvKCiwdGKL3cQ',
607 'thumbnail': r're:https?://.*\.(jpg|webp)',
608 'description': 'md5:c625bb3c02c4f5fb4205971e468fa341',
609 'uploader_url': 'https://www.youtube.com/user/GameGrumps',
add96eb9 610 },
217753f4
M
611 }, {
612 # watch7-user-header with yt-user-info
613 'url': 'ytarchive:kbh4T_b4Ixw:20160307085057',
614 'info_dict': {
615 'id': 'kbh4T_b4Ixw',
616 'ext': 'mp4',
617 'title': 'Shovel Knight OST - Strike the Earth! Plains of Passage 16 bit SNES style remake / remix',
618 'channel_url': 'https://www.youtube.com/channel/UCnTaGvsHmMy792DWeT6HbGA',
619 'uploader': 'Nelward music',
620 'duration': 213,
621 'description': 'md5:804b4a9ce37b050a5fefdbb23aeba54d',
622 'thumbnail': r're:https?://.*\.(jpg|webp)',
623 'upload_date': '20150503',
624 'channel_id': 'UCnTaGvsHmMy792DWeT6HbGA',
add96eb9 625 },
217753f4
M
626 }, {
627 # April 2012
628 'url': 'https://web.archive.org/web/0/https://www.youtube.com/watch?v=SOm7mPoPskU',
629 'info_dict': {
630 'id': 'SOm7mPoPskU',
631 'ext': 'mp4',
632 'title': 'Boyfriend - Justin Bieber Parody',
633 'uploader_url': 'https://www.youtube.com/user/thecomputernerd01',
634 'uploader': 'thecomputernerd01',
635 'thumbnail': r're:https?://.*\.(jpg|webp)',
636 'description': 'md5:dd7fa635519c2a5b4d566beaecad7491',
637 'duration': 200,
638 'upload_date': '20120407',
639 'uploader_id': 'thecomputernerd01',
add96eb9 640 },
aa4b0545 641 }, {
642 'url': 'https://web.archive.org/web/http://www.youtube.com/watch?v=kH-G_aIBlFw',
add96eb9 643 'only_matching': True,
aa4b0545 644 }, {
645 'url': 'https://web.archive.org/web/20050214000000_if/http://www.youtube.com/watch?v=0altSZ96U4M',
add96eb9 646 'only_matching': True,
aa4b0545 647 }, {
879e7199 648 # Video not archived, only capture is unavailable video page
649 'url': 'https://web.archive.org/web/20210530071008/https://www.youtube.com/watch?v=lHJTf93HL1s&spfreload=10',
add96eb9 650 'only_matching': True,
aa4b0545 651 }, { # Encoded url
879e7199 652 'url': 'https://web.archive.org/web/20120712231619/http%3A//www.youtube.com/watch%3Fgl%3DUS%26v%3DAkhihxRKcrs%26hl%3Den',
add96eb9 653 'only_matching': True,
aa4b0545 654 }, {
879e7199 655 'url': 'https://web.archive.org/web/20120712231619/http%3A//www.youtube.com/watch%3Fv%3DAkhihxRKcrs%26gl%3DUS%26hl%3Den',
add96eb9 656 'only_matching': True,
aa4b0545 657 }, {
658 'url': 'https://web.archive.org/web/20060527081937/http://www.youtube.com:80/watch.php?v=ELTFsLT73fA&amp;search=soccer',
add96eb9 659 'only_matching': True,
aa4b0545 660 }, {
661 'url': 'https://web.archive.org/http://www.youtube.com:80/watch?v=-05VVye-ffg',
add96eb9 662 'only_matching': True,
1f13021e 663 }, {
664 'url': 'ytarchive:BaW_jenozKc:20050214000000',
add96eb9 665 'only_matching': True,
88f23a18 666 }, {
1f13021e 667 'url': 'ytarchive:BaW_jenozKc',
add96eb9 668 'only_matching': True,
1f13021e 669 },
879e7199 670 ]
b7c47b74 671 _YT_INITIAL_DATA_RE = YoutubeBaseInfoExtractor._YT_INITIAL_DATA_RE
19b4e59a 672 _YT_INITIAL_PLAYER_RESPONSE_RE = fr'''(?x:
b7c47b74 673 (?:window\s*\[\s*["\']ytInitialPlayerResponse["\']\s*\]|ytInitialPlayerResponse)\s*=[(\s]*|
19b4e59a 674 {YoutubeBaseInfoExtractor._YT_INITIAL_PLAYER_RESPONSE_RE}
675 )'''
aa4b0545 676
677 _YT_DEFAULT_THUMB_SERVERS = ['i.ytimg.com'] # thumbnails most likely archived on these servers
678 _YT_ALL_THUMB_SERVERS = orderedSet(
add96eb9 679 [*_YT_DEFAULT_THUMB_SERVERS, 'img.youtube.com', *[f'{c}{n or ""}.ytimg.com' for c in ('i', 's') for n in (*range(5), 9)]])
aa4b0545 680
681 _WAYBACK_BASE_URL = 'https://web.archive.org/web/%sif_/'
682 _OLDEST_CAPTURE_DATE = 20050214000000
683 _NEWEST_CAPTURE_DATE = 20500101000000
684
add96eb9 685 def _call_cdx_api(self, item_id, url, filters: list | None = None, collapse: list | None = None, query: dict | None = None, note=None, fatal=False):
aa4b0545 686 # CDX docs: https://github.com/internetarchive/wayback/blob/master/wayback-cdx-server/README.md
687 query = {
688 'url': url,
689 'output': 'json',
690 'fl': 'original,mimetype,length,timestamp',
691 'limit': 500,
692 'filter': ['statuscode:200'] + (filters or []),
693 'collapse': collapse or [],
add96eb9 694 **(query or {}),
aa4b0545 695 }
c8e856a5 696 res = self._download_json(
697 'https://web.archive.org/cdx/search/cdx', item_id,
698 note or 'Downloading CDX API JSON', query=query, fatal=fatal)
aa4b0545 699 if isinstance(res, list) and len(res) >= 2:
700 # format response to make it easier to use
add96eb9 701 return [dict(zip(res[0], v)) for v in res[1:]]
aa4b0545 702 elif not isinstance(res, list) or len(res) != 0:
703 self.report_warning('Error while parsing CDX API response' + bug_reports_message())
704
aa4b0545 705 def _extract_webpage_title(self, webpage):
04f3fd2c 706 page_title = self._html_extract_title(webpage, default='')
aa4b0545 707 # YouTube video pages appear to always have either 'YouTube -' as prefix or '- YouTube' as suffix.
708 return self._html_search_regex(
709 r'(?:YouTube\s*-\s*(.*)$)|(?:(.*)\s*-\s*YouTube$)',
710 page_title, 'title', default='')
711
712 def _extract_metadata(self, video_id, webpage):
aa4b0545 713 search_meta = ((lambda x: self._html_search_meta(x, webpage, default=None)) if webpage else (lambda x: None))
b7c47b74 714 player_response = self._search_json(
715 self._YT_INITIAL_PLAYER_RESPONSE_RE, webpage, 'initial player response',
f0bc6e20 716 video_id, default={})
b7c47b74 717 initial_data = self._search_json(
f0bc6e20 718 self._YT_INITIAL_DATA_RE, webpage, 'initial data', video_id, default={})
aa4b0545 719
217753f4
M
720 ytcfg = {}
721 for j in re.findall(r'yt\.setConfig\(\s*(?P<json>{\s*(?s:.+?)\s*})\s*\);', webpage): # ~June 2010
722 ytcfg.update(self._parse_json(j, video_id, fatal=False, ignore_extra=True, transform_source=js_to_json, errnote='') or {})
723
724 # XXX: this also may contain a 'ptchn' key
725 player_config = (
726 self._search_json(
727 r'(?:yt\.playerConfig|ytplayer\.config|swfConfig)\s*=',
728 webpage, 'player config', video_id, default=None)
729 or ytcfg.get('PLAYER_CONFIG') or {})
730
731 # XXX: this may also contain a 'creator' key.
732 swf_args = self._search_json(r'swfArgs\s*=', webpage, 'swf config', video_id, default={})
733 if swf_args and not traverse_obj(player_config, ('args',)):
734 player_config['args'] = swf_args
735
736 if not player_response:
737 # April 2020
738 player_response = self._parse_json(
739 traverse_obj(player_config, ('args', 'player_response')) or '{}', video_id, fatal=False)
740
aa4b0545 741 initial_data_video = traverse_obj(
742 initial_data, ('contents', 'twoColumnWatchNextResults', 'results', 'results', 'contents', ..., 'videoPrimaryInfoRenderer'),
743 expected_type=dict, get_all=False, default={})
744
745 video_details = traverse_obj(
746 player_response, 'videoDetails', expected_type=dict, get_all=False, default={})
747
748 microformats = traverse_obj(
749 player_response, ('microformat', 'playerMicroformatRenderer'), expected_type=dict, get_all=False, default={})
750
751 video_title = (
752 video_details.get('title')
753 or YoutubeBaseInfoExtractor._get_text(microformats, 'title')
754 or YoutubeBaseInfoExtractor._get_text(initial_data_video, 'title')
217753f4 755 or traverse_obj(player_config, ('args', 'title'))
aa4b0545 756 or self._extract_webpage_title(webpage)
757 or search_meta(['og:title', 'twitter:title', 'title']))
758
217753f4
M
759 def id_from_url(url, type_):
760 return self._search_regex(
761 rf'(?:{type_})/([^/#&?]+)', url or '', f'{type_} id', default=None)
762
763 # XXX: would the get_elements_by_... functions be better suited here?
764 _CHANNEL_URL_HREF_RE = r'href="[^"]*(?P<url>https?://www\.youtube\.com/(?:user|channel)/[^"]+)"'
765 uploader_or_channel_url = self._search_regex(
766 [fr'<(?:link\s*itemprop=\"url\"|a\s*id=\"watch-username\").*?\b{_CHANNEL_URL_HREF_RE}>', # @fd05024
767 fr'<div\s*id=\"(?:watch-channel-stats|watch-headline-user-info)\"[^>]*>\s*<a[^>]*\b{_CHANNEL_URL_HREF_RE}'], # ~ May 2009, ~June 2012
768 webpage, 'uploader or channel url', default=None)
769
770 owner_profile_url = url_or_none(microformats.get('ownerProfileUrl')) # @a6211d2
771
772 # Uploader refers to the /user/ id ONLY
773 uploader_id = (
774 id_from_url(owner_profile_url, 'user')
775 or id_from_url(uploader_or_channel_url, 'user')
776 or ytcfg.get('VIDEO_USERNAME'))
777 uploader_url = f'https://www.youtube.com/user/{uploader_id}' if uploader_id else None
778
779 # XXX: do we want to differentiate uploader and channel?
780 uploader = (
781 self._search_regex(
782 [r'<a\s*id="watch-username"[^>]*>\s*<strong>([^<]+)</strong>', # June 2010
783 r'var\s*watchUsername\s*=\s*\'(.+?)\';', # ~May 2009
784 r'<div\s*\bid=\"watch-channel-stats"[^>]*>\s*<a[^>]*>\s*(.+?)\s*</a', # ~May 2009
785 r'<a\s*id="watch-userbanner"[^>]*title="\s*(.+?)\s*"'], # ~June 2012
786 webpage, 'uploader', default=None)
787 or self._html_search_regex(
788 [r'(?s)<div\s*class="yt-user-info".*?<a[^>]*[^>]*>\s*(.*?)\s*</a', # March 2016
789 r'(?s)<a[^>]*yt-user-name[^>]*>\s*(.*?)\s*</a'], # july 2013
790 get_element_by_id('watch7-user-header', webpage), 'uploader', default=None)
791 or self._html_search_regex(
792 r'<button\s*href="/user/[^>]*>\s*<span[^>]*>\s*(.+?)\s*<', # April 2012
793 get_element_by_id('watch-headline-user-info', webpage), 'uploader', default=None)
794 or traverse_obj(player_config, ('args', 'creator'))
795 or video_details.get('author'))
796
aa4b0545 797 channel_id = str_or_none(
798 video_details.get('channelId')
799 or microformats.get('externalChannelId')
800 or search_meta('channelId')
801 or self._search_regex(
802 r'data-channel-external-id=(["\'])(?P<id>(?:(?!\1).)+)\1', # @b45a9e6
217753f4
M
803 webpage, 'channel id', default=None, group='id')
804 or id_from_url(owner_profile_url, 'channel')
805 or id_from_url(uploader_or_channel_url, 'channel')
806 or traverse_obj(player_config, ('args', 'ucid')))
aa4b0545 807
217753f4 808 channel_url = f'https://www.youtube.com/channel/{channel_id}' if channel_id else None
aa4b0545 809 duration = int_or_none(
810 video_details.get('lengthSeconds')
811 or microformats.get('lengthSeconds')
217753f4 812 or traverse_obj(player_config, ('args', ('length_seconds', 'l')), get_all=False)
aa4b0545 813 or parse_duration(search_meta('duration')))
814 description = (
815 video_details.get('shortDescription')
816 or YoutubeBaseInfoExtractor._get_text(microformats, 'description')
817 or clean_html(get_element_by_id('eow-description', webpage)) # @9e6dd23
818 or search_meta(['description', 'og:description', 'twitter:description']))
819
aa4b0545 820 upload_date = unified_strdate(
821 dict_get(microformats, ('uploadDate', 'publishDate'))
822 or search_meta(['uploadDate', 'datePublished'])
823 or self._search_regex(
217753f4
M
824 [r'(?s)id="eow-date.*?>\s*(.*?)\s*</span>',
825 r'(?:id="watch-uploader-info".*?>.*?|["\']simpleText["\']\s*:\s*["\'])(?:Published|Uploaded|Streamed live|Started) on (.+?)[<"\']', # @7998520
826 r'class\s*=\s*"(?:watch-video-date|watch-video-added post-date)"[^>]*>\s*([^<]+?)\s*<'], # ~June 2010, ~Jan 2009 (respectively)
aa4b0545 827 webpage, 'upload date', default=None))
828
829 return {
830 'title': video_title,
831 'description': description,
832 'upload_date': upload_date,
833 'uploader': uploader,
834 'channel_id': channel_id,
835 'channel_url': channel_url,
836 'duration': duration,
837 'uploader_url': uploader_url,
838 'uploader_id': uploader_id,
839 }
840
841 def _extract_thumbnails(self, video_id):
842 try_all = 'thumbnails' in self._configuration_arg('check_all')
843 thumbnail_base_urls = ['http://{server}/vi{webp}/{video_id}'.format(
844 webp='_webp' if ext == 'webp' else '', video_id=video_id, server=server)
845 for server in (self._YT_ALL_THUMB_SERVERS if try_all else self._YT_DEFAULT_THUMB_SERVERS) for ext in (('jpg', 'webp') if try_all else ('jpg',))]
846
847 thumbnails = []
848 for url in thumbnail_base_urls:
849 response = self._call_cdx_api(
850 video_id, url, filters=['mimetype:image/(?:webp|jpeg)'],
851 collapse=['urlkey'], query={'matchType': 'prefix'})
852 if not response:
853 continue
854 thumbnails.extend(
855 {
856 'url': (self._WAYBACK_BASE_URL % (int_or_none(thumbnail_dict.get('timestamp')) or self._OLDEST_CAPTURE_DATE)) + thumbnail_dict.get('original'),
857 'filesize': int_or_none(thumbnail_dict.get('length')),
add96eb9 858 'preference': int_or_none(thumbnail_dict.get('length')),
aa4b0545 859 } for thumbnail_dict in response)
860 if not try_all:
861 break
862
863 self._remove_duplicate_formats(thumbnails)
864 return thumbnails
865
866 def _get_capture_dates(self, video_id, url_date):
867 capture_dates = []
868 # Note: CDX API will not find watch pages with extra params in the url.
869 response = self._call_cdx_api(
870 video_id, f'https://www.youtube.com/watch?v={video_id}',
871 filters=['mimetype:text/html'], collapse=['timestamp:6', 'digest'], query={'matchType': 'prefix'}) or []
86e5f3ed 872 all_captures = sorted(int_or_none(r['timestamp']) for r in response if int_or_none(r['timestamp']) is not None)
aa4b0545 873
874 # Prefer the new polymer UI captures as we support extracting more metadata from them
875 # WBM captures seem to all switch to this layout ~July 2020
1f13021e 876 modern_captures = [x for x in all_captures if x >= 20200701000000]
aa4b0545 877 if modern_captures:
878 capture_dates.append(modern_captures[0])
879 capture_dates.append(url_date)
880 if all_captures:
881 capture_dates.append(all_captures[0])
882
883 if 'captures' in self._configuration_arg('check_all'):
884 capture_dates.extend(modern_captures + all_captures)
885
886 # Fallbacks if any of the above fail
887 capture_dates.extend([self._OLDEST_CAPTURE_DATE, self._NEWEST_CAPTURE_DATE])
1f13021e 888 return orderedSet(filter(None, capture_dates))
879e7199 889
890 def _real_extract(self, url):
1f13021e 891 video_id, url_date, url_date_2 = self._match_valid_url(url).group('id', 'date', 'date2')
892 url_date = url_date or url_date_2
aa4b0545 893
894 urlh = None
217753f4
M
895 retry_manager = self.RetryManager(fatal=False)
896 for retry in retry_manager:
897 try:
898 urlh = self._request_webpage(
add96eb9 899 HEADRequest(f'https://web.archive.org/web/2oe_/http://wayback-fakeurl.archive.org/yt/{video_id}'),
217753f4
M
900 video_id, note='Fetching archived video file url', expected_status=True)
901 except ExtractorError as e:
902 # HTTP Error 404 is expected if the video is not saved.
3d2623a8 903 if isinstance(e.cause, HTTPError) and e.cause.status == 404:
217753f4
M
904 self.raise_no_formats(
905 'The requested video is not archived, indexed, or there is an issue with web.archive.org (try again later)', expected=True)
906 else:
907 retry.error = e
908
909 if retry_manager.error:
910 self.raise_no_formats(retry_manager.error, expected=True, video_id=video_id)
aa4b0545 911
912 capture_dates = self._get_capture_dates(video_id, int_or_none(url_date))
1f13021e 913 self.write_debug('Captures to try: ' + join_nonempty(*capture_dates, delim=', '))
aa4b0545 914 info = {'id': video_id}
915 for capture in capture_dates:
aa4b0545 916 webpage = self._download_webpage(
917 (self._WAYBACK_BASE_URL + 'http://www.youtube.com/watch?v=%s') % (capture, video_id),
918 video_id=video_id, fatal=False, errnote='unable to download capture webpage (it may not be archived)',
919 note='Downloading capture webpage')
920 current_info = self._extract_metadata(video_id, webpage or '')
921 # Try avoid getting deleted video metadata
922 if current_info.get('title'):
923 info = merge_dicts(info, current_info)
924 if 'captures' not in self._configuration_arg('check_all'):
925 break
926
927 info['thumbnails'] = self._extract_thumbnails(video_id)
928
929 if urlh:
add96eb9 930 url = urllib.parse.unquote(urlh.url)
aa4b0545 931 video_file_url_qs = parse_qs(url)
932 # Attempt to recover any ext & format info from playback url & response headers
add96eb9 933 fmt = {'url': url, 'filesize': int_or_none(urlh.headers.get('x-archive-orig-content-length'))}
aa4b0545 934 itag = try_get(video_file_url_qs, lambda x: x['itag'][0])
935 if itag and itag in YoutubeIE._formats:
add96eb9 936 fmt.update(YoutubeIE._formats[itag])
937 fmt.update({'format_id': itag})
aa4b0545 938 else:
939 mime = try_get(video_file_url_qs, lambda x: x['mime'][0])
940 ext = (mimetype2ext(mime)
941 or urlhandle_detect_ext(urlh)
942 or mimetype2ext(urlh.headers.get('x-archive-guessed-content-type')))
add96eb9 943 fmt.update({'ext': ext})
944 info['formats'] = [fmt]
aa4b0545 945 if not info.get('duration'):
946 info['duration'] = str_to_int(try_get(video_file_url_qs, lambda x: x['dur'][0]))
947
948 if not info.get('title'):
949 info['title'] = video_id
950 return info