1 from __future__
import annotations
7 from .common
import InfoExtractor
8 from .youtube
import YoutubeBaseInfoExtractor
, YoutubeIE
9 from ..networking
import HEADRequest
10 from ..networking
.exceptions
import HTTPError
39 class ArchiveOrgIE(InfoExtractor
):
40 IE_NAME
= 'archive.org'
41 IE_DESC
= 'archive.org video and audio'
42 _VALID_URL
= r
'https?://(?:www\.)?archive\.org/(?:details|embed)/(?P<id>[^?#]+)(?:[?].*)?$'
44 'url': 'http://archive.org/details/XD300-23_68HighlightsAResearchCntAugHumanIntellect',
45 'md5': '8af1d4cf447933ed3c7f4871162602db',
47 'id': 'XD300-23_68HighlightsAResearchCntAugHumanIntellect',
49 'title': '1968 Demo - FJCC Conference Presentation Reel #1',
50 'description': 'md5:da45c349df039f1cc8075268eb1b5c25',
51 'release_date': '19681210',
52 'timestamp': 1268695290,
53 'upload_date': '20100315',
54 'creators': ['SRI International'],
55 'uploader': 'laura@archive.org',
56 'thumbnail': r
're:https://archive\.org/download/.*\.jpg',
57 'display_id': 'XD300-23_68HighlightsAResearchCntAugHumanIntellect.cdr',
58 'track': 'XD300-23 68HighlightsAResearchCntAugHumanIntellect',
62 'url': 'https://archive.org/details/Cops1922',
63 'md5': '0869000b4ce265e8ca62738b336b268a',
67 'title': 'Buster Keaton\'s "Cops" (1922)',
68 'description': 'md5:cd6f9910c35aedd5fc237dbc3957e2ca',
69 'uploader': 'yorkmba99@hotmail.com',
70 'timestamp': 1387699629,
71 'upload_date': '20131222',
72 'display_id': 'Cops-v2.mp4',
73 'thumbnail': r
're:https://archive\.org/download/.*\.jpg',
77 'url': 'http://archive.org/embed/XD300-23_68HighlightsAResearchCntAugHumanIntellect',
78 'only_matching': True,
80 'url': 'https://archive.org/details/Election_Ads',
81 'md5': 'eec5cddebd4793c6a653b69c3b11f2e6',
83 'id': 'Election_Ads/Commercial-JFK1960ElectionAdCampaignJingle.mpg',
84 'title': 'Commercial-JFK1960ElectionAdCampaignJingle.mpg',
86 'thumbnail': r
're:https://archive\.org/download/.*\.jpg',
88 'display_id': 'Commercial-JFK1960ElectionAdCampaignJingle.mpg',
91 'url': 'https://archive.org/details/Election_Ads/Commercial-Nixon1960ElectionAdToughonDefense.mpg',
92 'md5': 'ea1eed8234e7d4165f38c8c769edef38',
94 'id': 'Election_Ads/Commercial-Nixon1960ElectionAdToughonDefense.mpg',
95 'title': 'Commercial-Nixon1960ElectionAdToughonDefense.mpg',
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',
101 'display_id': 'Commercial-Nixon1960ElectionAdToughonDefense.mpg',
103 'license': 'http://creativecommons.org/licenses/publicdomain/',
104 'thumbnail': r
're:https://archive\.org/download/.*\.jpg',
107 'url': 'https://archive.org/details/gd1977-05-08.shure57.stevenson.29303.flac16',
108 'md5': '7d07ffb42aba6537c28e053efa4b54c9',
110 'id': 'gd1977-05-08.shure57.stevenson.29303.flac16/gd1977-05-08d01t01.flac',
114 'creators': ['Grateful Dead'],
115 'display_id': 'gd1977-05-08d01t01.flac',
117 'album': '1977-05-08 - Barton Hall - Cornell University',
121 'url': 'https://archive.org/details/gd1977-05-08.shure57.stevenson.29303.flac16/gd1977-05-08d01t07.flac',
122 'md5': 'a07cd8c6ab4ee1560f8a0021717130f3',
124 'id': 'gd1977-05-08.shure57.stevenson.29303.flac16/gd1977-05-08d01t07.flac',
127 'timestamp': 1205895624,
128 'uploader': 'mvernon54@yahoo.com',
129 'description': 'md5:6c921464414814720c6593810a5c7e3d',
130 'upload_date': '20080319',
131 'location': 'Barton Hall - Cornell University',
134 'creators': ['Grateful Dead'],
135 'album': '1977-05-08 - Barton Hall - Cornell University',
136 'release_date': '19770508',
137 'display_id': 'gd1977-05-08d01t07.flac',
141 # FIXME: give a better error message than just IndexError when all available formats are restricted
142 'url': 'https://archive.org/details/lp_the-music-of-russia_various-artists-a-askaryan-alexander-melik',
143 'md5': '7cb019baa9b332e82ea7c10403acd180',
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',
149 'skip': 'restricted',
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',
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)',
157 'timestamp': 1569662587,
158 'uploader': 'associate-joygen-odiongan@archive.org',
159 'description': 'md5:012b2d668ae753be36896f343d12a236',
160 'upload_date': '20190928',
162 'skip': 'restricted',
164 # Original formats are private
165 'url': 'https://archive.org/details/irelandthemakingofarepublic',
167 'id': 'irelandthemakingofarepublic',
168 'title': 'Ireland: The Making of a Republic',
169 'upload_date': '20160610',
170 'description': 'md5:f70956a156645a658a0dc9513d9e78b7',
171 'uploader': 'dimitrios@archive.org',
172 'creators': ['British Broadcasting Corporation', 'Time-Life Films'],
173 'timestamp': 1465594947,
177 'md5': '0b211261b26590d49df968f71b90690d',
179 'id': 'irelandthemakingofarepublic/irelandthemakingofarepublicreel1_01.mov',
181 'title': 'irelandthemakingofarepublicreel1_01.mov',
183 'thumbnail': 'https://archive.org/download/irelandthemakingofarepublic/irelandthemakingofarepublic.thumbs/irelandthemakingofarepublicreel1_01_000117.jpg',
184 'display_id': 'irelandthemakingofarepublicreel1_01.mov',
187 'md5': '67335ee3b23a0da930841981c1e79b02',
189 'id': 'irelandthemakingofarepublic/irelandthemakingofarepublicreel1_02.mov',
192 'title': 'irelandthemakingofarepublicreel1_02.mov',
193 'display_id': 'irelandthemakingofarepublicreel1_02.mov',
194 'thumbnail': 'https://archive.org/download/irelandthemakingofarepublic/irelandthemakingofarepublic.thumbs/irelandthemakingofarepublicreel1_02_001374.jpg',
197 'md5': 'e470e86787893603f4a341a16c281eb5',
199 'id': 'irelandthemakingofarepublic/irelandthemakingofarepublicreel2.mov',
202 'title': 'irelandthemakingofarepublicreel2.mov',
203 'thumbnail': 'https://archive.org/download/irelandthemakingofarepublic/irelandthemakingofarepublic.thumbs/irelandthemakingofarepublicreel2_001554.jpg',
204 'display_id': 'irelandthemakingofarepublicreel2.mov',
211 def _playlist_data(webpage
):
212 element
= re
.findall(r
'''(?xs)
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:._-]*|="[^"]*"|='[^']*'|))*?
220 return json
.loads(extract_attributes(element
)['value'])
222 def _real_extract(self
, url
):
223 video_id
= urllib
.parse
.unquote_plus(self
._match
_id
(url
))
224 identifier
, _
, entry_id
= video_id
.partition('/')
226 # Archive.org metadata API doesn't clearly demarcate playlist entries
227 # or subtitle tracks, so we get them from the embeddable player.
228 embed_page
= self
._download
_webpage
(f
'https://archive.org/embed/{identifier}', identifier
)
229 playlist
= self
._playlist
_data
(embed_page
)
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
:
238 entries
[p
['orig']] = {
241 'artist': p
.get('artist'),
242 'track': p
.get('title'),
246 for track
in p
.get('tracks', []):
247 if track
['kind'] != 'subtitles':
249 entries
[p
['orig']][track
['label']] = {
250 'url': 'https://archive.org/' + track
['file'].lstrip('/'),
253 metadata
= self
._download
_json
('http://archive.org/metadata/' + identifier
, identifier
)
254 m
= metadata
['metadata']
255 identifier
= m
['identifier']
260 'description': clean_html(m
.get('description')),
261 'uploader': dict_get(m
, ['uploader', 'adder']),
262 'creators': traverse_obj(m
, ('creator', {variadic}
, {lambda x: x[0] and list(x)}
)),
263 'license': m
.get('licenseurl'),
264 'release_date': unified_strdate(m
.get('date')),
265 'timestamp': unified_timestamp(dict_get(m
, ['publicdate', 'addeddate'])),
266 'webpage_url': f
'https://archive.org/details/{identifier}',
267 'location': m
.get('venue'),
268 'release_year': int_or_none(m
.get('year'))}
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')),
277 'creators': traverse_obj(f
, ('creator', {variadic}
, {lambda x: x[0] and list(x)}
)),
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']]
284 elif traverse_obj(f
, 'original', expected_type
=str) in entries
:
285 entry
= entries
[f
['original']]
289 if f
.get('format') == 'Thumbnail':
290 entry
['thumbnails'].append({
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'))})
297 _
, has_ext
, extension
= f
['name'].rpartition('.')
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
):
306 entry
['formats'].append({
307 'url': 'https://archive.org/download/' + identifier
+ '/' + urllib
.parse
.quote(f
['name']),
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')),
313 'source_preference': 0 if f
.get('source') == 'original' else -1,
314 'format_note': f
.get('source'),
317 for entry
in entries
.values():
318 entry
['_format_sort_fields'] = ('source', )
320 if len(entries
) == 1:
321 # If there's only one item, use it as the main info dict
322 only_video
= next(iter(entries
.values()))
324 info
= merge_dicts(only_video
, info
)
326 info
= merge_dicts(info
, only_video
)
328 # Otherwise, we have a playlist.
329 info
['_type'] = 'playlist'
330 info
['entries'] = list(entries
.values())
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')),
345 class YoutubeWebArchiveIE(InfoExtractor
):
346 IE_NAME
= 'web.archive:youtube'
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
355 )(?P<id>[0-9A-Za-z_-]{11})
357 (?::(?P<date2>[0-9]{14}))?$|
363 'url': 'https://web.archive.org/web/20150415002341/https://www.youtube.com/watch?v=aYAGB11YrSs',
367 'title': 'Team Fortress 2 - Sandviches!',
368 'description': 'md5:4984c0f9a07f349fc5d8e82ab7af4eaf',
369 'upload_date': '20110926',
370 'uploader': 'Zeurel',
371 'channel_id': 'UCukCyHaD-bK3in_pKpfH9Eg',
373 'uploader_id': 'Zeurel',
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',
380 'url': 'https://web.archive.org/web/2oe/http://wayback-fakeurl.archive.org/yt/97t7Xj_iBv0',
384 'title': 'Why Machines That Bend Are Better',
385 'description': 'md5:00404df2c632d16a674ff8df1ecfbb6c',
386 'upload_date': '20190312',
387 'uploader': 'Veritasium',
388 'channel_id': 'UCHnyfMqiRRG1u-2MsSQLbXA',
390 'uploader_id': '1veritasium',
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',
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
398 'url': 'https://web.archive.org/web/20120712231619/http://www.youtube.com/watch?v=AkhihxRKcrs&gl=US&hl=en',
402 'title': 'Limited Run: Mondo\'s Modern Classic 1 of 3 (SDCC 2012)',
403 'upload_date': '20120712',
405 'description': 'md5:ff4de6a7980cb65d951c2f6966a4f2f3',
406 'uploader_id': 'machinima',
407 'uploader_url': 'https://www.youtube.com/user/machinima',
408 'thumbnail': r
're:https?://.*\.(jpg|webp)',
409 'uploader': 'machinima',
412 # FLV video. Video file URL does not provide itag information
413 'url': 'https://web.archive.org/web/20081211103536/http://www.youtube.com/watch?v=jNQXAC9IVRw',
417 'title': 'Me at the zoo',
418 'upload_date': '20050423',
419 'channel_id': 'UC4QobU6STFB0P71PMvOGN5A',
421 'description': 'md5:10436b12e07ac43ff8df65287a56efb4',
422 'uploader_id': 'jawed',
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)',
429 'url': 'https://web.archive.org/web/20110712231407/http://www.youtube.com/watch?v=lTx3G6h2xyA',
433 'title': 'Madeon - Pop Culture (live mashup)',
434 'upload_date': '20110711',
435 'uploader': 'Madeon',
436 'channel_id': 'UCqMDNf3Pn5L7pcNkuSEeO3w',
438 'description': 'md5:f7535343b6eda34a314eff8b85444680',
439 'uploader_id': 'itsmadeon',
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)',
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',
450 'title': 'Fake Teen Doctor Strikes AGAIN! - Weekly Weird News',
451 'upload_date': '20160218',
452 'channel_id': 'UCdIaNUarhzLSXGoItz7BHVA',
454 'description': 'md5:21032bae736421e89c2edf36d1936947',
455 'uploader_id': 'MachinimaETC',
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',
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',
467 'title': 'WTF: Video Games Still Launch BROKEN?! - T.U.G.S.',
468 'upload_date': '20160219',
469 'channel_id': 'UCdIaNUarhzLSXGoItz7BHVA',
471 'description': 'md5:a1dbf12d9a3bd7cb4c5e33b27d77ffe7',
472 'uploader_id': 'MachinimaETC',
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',
478 'expected_warnings': [
479 r
'unable to download capture webpage \(it may not be archived\)',
481 }, { # Very old YouTube page, has - YouTube in title.
482 'url': 'http://web.archive.org/web/20070302011044/http://youtube.com/watch?v=-06-KB9XTzg',
486 'title': 'New Coin Hack!! 100% Safe!!',
489 'url': 'web.archive.org/https://www.youtube.com/watch?v=dWW7qP423y8',
493 'title': 'It\'s Bootleg AirPods Time.',
494 'upload_date': '20211021',
495 'channel_id': 'UC7Jwj9fkrf1adN4fMmTkpug',
496 'channel_url': 'https://www.youtube.com/channel/UC7Jwj9fkrf1adN4fMmTkpug',
498 'description': 'md5:7b567f898d8237b256f36c1a07d6d7bc',
499 'thumbnail': r
're:https?://.*\.(jpg|webp)',
500 'uploader': 'DankPods',
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',
508 'title': 'bitch lasagna',
509 'upload_date': '20181005',
510 'channel_id': 'UC-lHJZR3Gqxm24_Vd_AJ5Yw',
511 'channel_url': 'https://www.youtube.com/channel/UC-lHJZR3Gqxm24_Vd_AJ5Yw',
513 'description': 'md5:2dbe4051feeff2dab5f41f82bb6d11d0',
514 'uploader': 'PewDiePie',
515 'uploader_id': 'PewDiePie',
516 'uploader_url': 'https://www.youtube.com/user/PewDiePie',
517 'thumbnail': r
're:https?://.*\.(jpg|webp)',
520 # ~June 2010 Capture. swfconfig
521 'url': 'https://web.archive.org/web/0/https://www.youtube.com/watch?v=8XeW5ilk-9Y',
525 'title': 'Story of Stuff, The Critique Part 4 of 4',
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',
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',
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)',
547 'uploader_url': 'https://www.youtube.com/user/claybutlermusic',
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',
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)',
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',
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',
576 'thumbnail': r
're:https?://.*\.(jpg|webp)',
580 'url': 'https://web.archive.org/web/*/https://www.youtube.com/watch?v=9eO1aasHyTM',
584 'title': 'Polar-oid',
585 'description': 'Cameras and bears are dangerous!',
586 'uploader_url': 'https://www.youtube.com/user/punkybird',
587 'uploader_id': 'punkybird',
589 'channel_id': 'UC62R2cBezNBOqxSerfb1nMQ',
590 'channel_url': 'https://www.youtube.com/channel/UC62R2cBezNBOqxSerfb1nMQ',
591 'upload_date': '20060428',
592 'uploader': 'punkybird',
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',
600 'title': 'A Dramatic Pool Story (by Jamie Spicer-Lewis) - Game Grumps Animated',
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',
612 # watch7-user-header with yt-user-info
613 'url': 'ytarchive:kbh4T_b4Ixw:20160307085057',
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',
621 'description': 'md5:804b4a9ce37b050a5fefdbb23aeba54d',
622 'thumbnail': r
're:https?://.*\.(jpg|webp)',
623 'upload_date': '20150503',
624 'channel_id': 'UCnTaGvsHmMy792DWeT6HbGA',
628 'url': 'https://web.archive.org/web/0/https://www.youtube.com/watch?v=SOm7mPoPskU',
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',
638 'upload_date': '20120407',
639 'uploader_id': 'thecomputernerd01',
642 'url': 'https://web.archive.org/web/http://www.youtube.com/watch?v=kH-G_aIBlFw',
643 'only_matching': True,
645 'url': 'https://web.archive.org/web/20050214000000_if/http://www.youtube.com/watch?v=0altSZ96U4M',
646 'only_matching': True,
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',
650 'only_matching': True,
652 'url': 'https://web.archive.org/web/20120712231619/http%3A//www.youtube.com/watch%3Fgl%3DUS%26v%3DAkhihxRKcrs%26hl%3Den',
653 'only_matching': True,
655 'url': 'https://web.archive.org/web/20120712231619/http%3A//www.youtube.com/watch%3Fv%3DAkhihxRKcrs%26gl%3DUS%26hl%3Den',
656 'only_matching': True,
658 'url': 'https://web.archive.org/web/20060527081937/http://www.youtube.com:80/watch.php?v=ELTFsLT73fA&search=soccer',
659 'only_matching': True,
661 'url': 'https://web.archive.org/http://www.youtube.com:80/watch?v=-05VVye-ffg',
662 'only_matching': True,
664 'url': 'ytarchive:BaW_jenozKc:20050214000000',
665 'only_matching': True,
667 'url': 'ytarchive:BaW_jenozKc',
668 'only_matching': True,
671 _YT_INITIAL_DATA_RE
= YoutubeBaseInfoExtractor
._YT
_INITIAL
_DATA
_RE
672 _YT_INITIAL_PLAYER_RESPONSE_RE
= fr
'''(?x:
673 (?:window\s*\[\s*["\']ytInitialPlayerResponse
["\']\s*\]|ytInitialPlayerResponse)\s*=[(\s]*|
674 {YoutubeBaseInfoExtractor._YT_INITIAL_PLAYER_RESPONSE_RE}
677 _YT_DEFAULT_THUMB_SERVERS = ['i.ytimg.com'] # thumbnails most likely archived on these servers
678 _YT_ALL_THUMB_SERVERS = orderedSet(
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)]])
681 _WAYBACK_BASE_URL = 'https://web.archive.org/web/%sif_/'
682 _OLDEST_CAPTURE_DATE = 20050214000000
683 _NEWEST_CAPTURE_DATE = 20500101000000
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):
686 # CDX docs: https://github.com/internetarchive/wayback/blob/master/wayback-cdx-server/README.md
690 'fl': 'original,mimetype,length,timestamp',
692 'filter': ['statuscode:200'] + (filters or []),
693 'collapse': collapse or [],
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)
699 if isinstance(res, list) and len(res) >= 2:
700 # format response to make it easier to use
701 return [dict(zip(res[0], v)) for v in res[1:]]
702 elif not isinstance(res, list) or len(res) != 0:
703 self.report_warning('Error while parsing CDX API response' + bug_reports_message())
705 def _extract_webpage_title(self, webpage):
706 page_title = self._html_extract_title(webpage, default='')
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='')
712 def _extract_metadata(self, video_id, webpage):
713 search_meta = ((lambda x: self._html_search_meta(x, webpage, default=None)) if webpage else (lambda x: None))
714 player_response = self._search_json(
715 self._YT_INITIAL_PLAYER_RESPONSE_RE, webpage, 'initial player response',
716 video_id, default={})
717 initial_data = self._search_json(
718 self._YT_INITIAL_DATA_RE, webpage, 'initial data', video_id, default={})
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 {})
724 # XXX: this also may contain a 'ptchn' key
727 r'(?:yt\.playerConfig|ytplayer\.config|swfConfig)\s*=',
728 webpage, 'player config', video_id, default=None)
729 or ytcfg.get('PLAYER_CONFIG') or {})
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
736 if not player_response:
738 player_response = self._parse_json(
739 traverse_obj(player_config, ('args', 'player_response')) or '{}', video_id, fatal=False)
741 initial_data_video = traverse_obj(
742 initial_data, ('contents', 'twoColumnWatchNextResults', 'results', 'results', 'contents', ..., 'videoPrimaryInfoRenderer'),
743 expected_type=dict, get_all=False, default={})
745 video_details = traverse_obj(
746 player_response, 'videoDetails', expected_type=dict, get_all=False, default={})
748 microformats = traverse_obj(
749 player_response, ('microformat', 'playerMicroformatRenderer'), expected_type=dict, get_all=False, default={})
752 video_details.get('title')
753 or YoutubeBaseInfoExtractor._get_text(microformats, 'title')
754 or YoutubeBaseInfoExtractor._get_text(initial_data_video, 'title')
755 or traverse_obj(player_config, ('args', 'title'))
756 or self._extract_webpage_title(webpage)
757 or search_meta(['og:title', 'twitter:title', 'title']))
759 def id_from_url(url, type_):
760 return self._search_regex(
761 rf'(?:{type_})/([^/#&?]+)', url or '', f'{type_} id', default=None)
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)
770 owner_profile_url = url_or_none(microformats.get('ownerProfileUrl')) # @a6211d2
772 # Uploader refers to the /user/ id ONLY
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
779 # XXX: do we want to differentiate uploader and channel?
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'))
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
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
')))
808 channel_url = f'https
://www
.youtube
.com
/channel
/{channel_id}
' if channel_id else None
809 duration = int_or_none(
810 video_details.get('lengthSeconds
')
811 or microformats.get('lengthSeconds
')
812 or traverse_obj(player_config, ('args
', ('length_seconds
', 'l
')), get_all=False)
813 or parse_duration(search_meta('duration
')))
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
']))
820 upload_date = unified_strdate(
821 dict_get(microformats, ('uploadDate
', 'publishDate
'))
822 or search_meta(['uploadDate
', 'datePublished
'])
823 or self._search_regex(
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)
827 webpage, 'upload date', default=None))
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,
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',))]
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'})
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')),
858 'preference': int_or_none(thumbnail_dict.get('length')),
859 } for thumbnail_dict in response)
863 self._remove_duplicate_formats(thumbnails)
866 def _get_capture_dates(self, video_id, url_date):
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 []
872 all_captures = sorted(int_or_none(r['timestamp']) for r in response if int_or_none(r['timestamp']) is not None)
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
876 modern_captures = [x for x in all_captures if x >= 20200701000000]
878 capture_dates.append(modern_captures[0])
879 capture_dates.append(url_date)
881 capture_dates.append(all_captures[0])
883 if 'captures' in self._configuration_arg('check_all'):
884 capture_dates.extend(modern_captures + all_captures)
886 # Fallbacks if any of the above fail
887 capture_dates.extend([self._OLDEST_CAPTURE_DATE, self._NEWEST_CAPTURE_DATE])
888 return orderedSet(filter(None, capture_dates))
890 def _real_extract(self, url):
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
895 retry_manager = self.RetryManager(fatal=False)
896 for retry in retry_manager:
898 urlh = self._request_webpage(
899 HEADRequest(f'https://web.archive.org/web/2oe_/http://wayback-fakeurl.archive.org/yt/{video_id}'),
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.
903 if isinstance(e.cause, HTTPError) and e.cause.status == 404:
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)
909 if retry_manager.error:
910 self.raise_no_formats(retry_manager.error, expected=True, video_id=video_id)
912 capture_dates = self._get_capture_dates(video_id, int_or_none(url_date))
913 self.write_debug('Captures to try: ' + join_nonempty(*capture_dates, delim=', '))
914 info = {'id': video_id}
915 for capture in capture_dates:
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'):
927 info['thumbnails'] = self._extract_thumbnails(video_id)
930 url = urllib.parse.unquote(urlh.url)
931 video_file_url_qs = parse_qs(url)
932 # Attempt to recover any ext & format info from playback url & response headers
933 fmt = {'url': url, 'filesize': int_or_none(urlh.headers.get('x-archive-orig-content-length'))}
934 itag = try_get(video_file_url_qs, lambda x: x['itag'][0])
935 if itag and itag in YoutubeIE._formats:
936 fmt.update(YoutubeIE._formats[itag])
937 fmt.update({'format_id': itag})
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')))
943 fmt.update({'ext': ext})
944 info['formats'] = [fmt]
945 if not info.get('duration'):
946 info['duration'] = str_to_int(try_get(video_file_url_qs, lambda x: x['dur'][0]))
948 if not info.get('title'):
949 info['title'] = video_id