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