]> jfr.im git - yt-dlp.git/blob - yt_dlp/extractor/archiveorg.py
[cleanup] Use `_html_extract_title`
[yt-dlp.git] / yt_dlp / extractor / archiveorg.py
1 # coding: utf-8
2 from __future__ import unicode_literals
3
4 import re
5 import json
6 from .common import InfoExtractor
7 from .youtube import YoutubeIE, YoutubeBaseInfoExtractor
8 from ..compat import (
9 compat_urllib_parse_unquote,
10 compat_urllib_parse_unquote_plus,
11 compat_HTTPError
12 )
13 from ..utils import (
14 bug_reports_message,
15 clean_html,
16 dict_get,
17 extract_attributes,
18 ExtractorError,
19 get_element_by_id,
20 HEADRequest,
21 int_or_none,
22 join_nonempty,
23 KNOWN_EXTENSIONS,
24 merge_dicts,
25 mimetype2ext,
26 orderedSet,
27 parse_duration,
28 parse_qs,
29 str_to_int,
30 str_or_none,
31 traverse_obj,
32 try_get,
33 unified_strdate,
34 unified_timestamp,
35 urlhandle_detect_ext,
36 url_or_none
37 )
38
39
40 class ArchiveOrgIE(InfoExtractor):
41 IE_NAME = 'archive.org'
42 IE_DESC = 'archive.org video and audio'
43 _VALID_URL = r'https?://(?:www\.)?archive\.org/(?:details|embed)/(?P<id>[^?#]+)(?:[?].*)?$'
44 _TESTS = [{
45 'url': 'http://archive.org/details/XD300-23_68HighlightsAResearchCntAugHumanIntellect',
46 'md5': '8af1d4cf447933ed3c7f4871162602db',
47 'info_dict': {
48 'id': 'XD300-23_68HighlightsAResearchCntAugHumanIntellect',
49 'ext': 'ogv',
50 'title': '1968 Demo - FJCC Conference Presentation Reel #1',
51 'description': 'md5:da45c349df039f1cc8075268eb1b5c25',
52 'release_date': '19681210',
53 'timestamp': 1268695290,
54 'upload_date': '20100315',
55 'creator': 'SRI International',
56 'uploader': 'laura@archive.org',
57 },
58 }, {
59 'url': 'https://archive.org/details/Cops1922',
60 'md5': '0869000b4ce265e8ca62738b336b268a',
61 'info_dict': {
62 'id': 'Cops1922',
63 'ext': 'mp4',
64 'title': 'Buster Keaton\'s "Cops" (1922)',
65 'description': 'md5:43a603fd6c5b4b90d12a96b921212b9c',
66 'uploader': 'yorkmba99@hotmail.com',
67 'timestamp': 1387699629,
68 'upload_date': '20131222',
69 },
70 }, {
71 'url': 'http://archive.org/embed/XD300-23_68HighlightsAResearchCntAugHumanIntellect',
72 'only_matching': True,
73 }, {
74 'url': 'https://archive.org/details/Election_Ads',
75 'md5': '284180e857160cf866358700bab668a3',
76 'info_dict': {
77 'id': 'Election_Ads/Commercial-JFK1960ElectionAdCampaignJingle.mpg',
78 'title': 'Commercial-JFK1960ElectionAdCampaignJingle.mpg',
79 'ext': 'mp4',
80 },
81 }, {
82 'url': 'https://archive.org/details/Election_Ads/Commercial-Nixon1960ElectionAdToughonDefense.mpg',
83 'md5': '7915213ef02559b5501fe630e1a53f59',
84 'info_dict': {
85 'id': 'Election_Ads/Commercial-Nixon1960ElectionAdToughonDefense.mpg',
86 'title': 'Commercial-Nixon1960ElectionAdToughonDefense.mpg',
87 'ext': 'mp4',
88 'timestamp': 1205588045,
89 'uploader': 'mikedavisstripmaster@yahoo.com',
90 'description': '1960 Presidential Campaign Election Commercials John F Kennedy, Richard M Nixon',
91 'upload_date': '20080315',
92 },
93 }, {
94 'url': 'https://archive.org/details/gd1977-05-08.shure57.stevenson.29303.flac16',
95 'md5': '7d07ffb42aba6537c28e053efa4b54c9',
96 'info_dict': {
97 'id': 'gd1977-05-08.shure57.stevenson.29303.flac16/gd1977-05-08d01t01.flac',
98 'title': 'Turning',
99 'ext': 'flac',
100 },
101 }, {
102 'url': 'https://archive.org/details/gd1977-05-08.shure57.stevenson.29303.flac16/gd1977-05-08d01t07.flac',
103 'md5': 'a07cd8c6ab4ee1560f8a0021717130f3',
104 'info_dict': {
105 'id': 'gd1977-05-08.shure57.stevenson.29303.flac16/gd1977-05-08d01t07.flac',
106 'title': 'Deal',
107 'ext': 'flac',
108 'timestamp': 1205895624,
109 'uploader': 'mvernon54@yahoo.com',
110 'description': 'md5:6a31f1996db0aa0fc9da6d6e708a1bb0',
111 'upload_date': '20080319',
112 'location': 'Barton Hall - Cornell University',
113 },
114 }, {
115 'url': 'https://archive.org/details/lp_the-music-of-russia_various-artists-a-askaryan-alexander-melik',
116 'md5': '7cb019baa9b332e82ea7c10403acd180',
117 'info_dict': {
118 'id': 'lp_the-music-of-russia_various-artists-a-askaryan-alexander-melik/disc1/01.01. Bells Of Rostov.mp3',
119 'title': 'Bells Of Rostov',
120 'ext': 'mp3',
121 },
122 }, {
123 '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',
124 'md5': '1d0aabe03edca83ca58d9ed3b493a3c3',
125 'info_dict': {
126 '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',
127 'title': 'Song And Chorus In The Polovetsian Camp From "Prince Igor" (Act 2, Scene 1)',
128 'ext': 'mp3',
129 'timestamp': 1569662587,
130 'uploader': 'associate-joygen-odiongan@archive.org',
131 'description': 'md5:012b2d668ae753be36896f343d12a236',
132 'upload_date': '20190928',
133 },
134 }]
135
136 @staticmethod
137 def _playlist_data(webpage):
138 element = re.findall(r'''(?xs)
139 <input
140 (?:\s+[a-zA-Z0-9:._-]+(?:=[a-zA-Z0-9:._-]*|="[^"]*"|='[^']*'|))*?
141 \s+class=['"]?js-play8-playlist['"]?
142 (?:\s+[a-zA-Z0-9:._-]+(?:=[a-zA-Z0-9:._-]*|="[^"]*"|='[^']*'|))*?
143 \s*/>
144 ''', webpage)[0]
145
146 return json.loads(extract_attributes(element)['value'])
147
148 def _real_extract(self, url):
149 video_id = compat_urllib_parse_unquote_plus(self._match_id(url))
150 identifier, entry_id = (video_id.split('/', 1) + [None])[:2]
151
152 # Archive.org metadata API doesn't clearly demarcate playlist entries
153 # or subtitle tracks, so we get them from the embeddable player.
154 embed_page = self._download_webpage(f'https://archive.org/embed/{identifier}', identifier)
155 playlist = self._playlist_data(embed_page)
156
157 entries = {}
158 for p in playlist:
159 # If the user specified a playlist entry in the URL, ignore the
160 # rest of the playlist.
161 if entry_id and p['orig'] != entry_id:
162 continue
163
164 entries[p['orig']] = {
165 'formats': [],
166 'thumbnails': [],
167 'artist': p.get('artist'),
168 'track': p.get('title'),
169 'subtitles': {},
170 }
171
172 for track in p.get('tracks', []):
173 if track['kind'] != 'subtitles':
174 continue
175 entries[p['orig']][track['label']] = {
176 'url': 'https://archive.org/' + track['file'].lstrip('/')
177 }
178
179 metadata = self._download_json('http://archive.org/metadata/' + identifier, identifier)
180 m = metadata['metadata']
181 identifier = m['identifier']
182
183 info = {
184 'id': identifier,
185 'title': m['title'],
186 'description': clean_html(m.get('description')),
187 'uploader': dict_get(m, ['uploader', 'adder']),
188 'creator': m.get('creator'),
189 'license': m.get('licenseurl'),
190 'release_date': unified_strdate(m.get('date')),
191 'timestamp': unified_timestamp(dict_get(m, ['publicdate', 'addeddate'])),
192 'webpage_url': f'https://archive.org/details/{identifier}',
193 'location': m.get('venue'),
194 'release_year': int_or_none(m.get('year'))}
195
196 for f in metadata['files']:
197 if f['name'] in entries:
198 entries[f['name']] = merge_dicts(entries[f['name']], {
199 'id': identifier + '/' + f['name'],
200 'title': f.get('title') or f['name'],
201 'display_id': f['name'],
202 'description': clean_html(f.get('description')),
203 'creator': f.get('creator'),
204 'duration': parse_duration(f.get('length')),
205 'track_number': int_or_none(f.get('track')),
206 'album': f.get('album'),
207 'discnumber': int_or_none(f.get('disc')),
208 'release_year': int_or_none(f.get('year'))})
209 entry = entries[f['name']]
210 elif traverse_obj(f, 'original', expected_type=str) in entries:
211 entry = entries[f['original']]
212 else:
213 continue
214
215 if f.get('format') == 'Thumbnail':
216 entry['thumbnails'].append({
217 'id': f['name'],
218 'url': 'https://archive.org/download/' + identifier + '/' + f['name'],
219 'width': int_or_none(f.get('width')),
220 'height': int_or_none(f.get('width')),
221 'filesize': int_or_none(f.get('size'))})
222
223 extension = (f['name'].rsplit('.', 1) + [None])[1]
224 if extension in KNOWN_EXTENSIONS:
225 entry['formats'].append({
226 'url': 'https://archive.org/download/' + identifier + '/' + f['name'],
227 'format': f.get('format'),
228 'width': int_or_none(f.get('width')),
229 'height': int_or_none(f.get('height')),
230 'filesize': int_or_none(f.get('size')),
231 'protocol': 'https'})
232
233 for entry in entries.values():
234 self._sort_formats(entry['formats'])
235
236 if len(entries) == 1:
237 # If there's only one item, use it as the main info dict
238 only_video = next(iter(entries.values()))
239 if entry_id:
240 info = merge_dicts(only_video, info)
241 else:
242 info = merge_dicts(info, only_video)
243 else:
244 # Otherwise, we have a playlist.
245 info['_type'] = 'playlist'
246 info['entries'] = list(entries.values())
247
248 if metadata.get('reviews'):
249 info['comments'] = []
250 for review in metadata['reviews']:
251 info['comments'].append({
252 'id': review.get('review_id'),
253 'author': review.get('reviewer'),
254 'text': str_or_none(review.get('reviewtitle'), '') + '\n\n' + review.get('reviewbody'),
255 'timestamp': unified_timestamp(review.get('createdate')),
256 'parent': 'root'})
257
258 return info
259
260
261 class YoutubeWebArchiveIE(InfoExtractor):
262 IE_NAME = 'web.archive:youtube'
263 IE_DESC = 'web.archive.org saved youtube videos, "ytarchive:" prefix'
264 _VALID_URL = r'''(?x)(?:(?P<prefix>ytarchive:)|
265 (?:https?://)?web\.archive\.org/
266 (?:web/)?(?:(?P<date>[0-9]{14})?[0-9A-Za-z_*]*/)? # /web and the version index is optional
267 (?:https?(?::|%3[Aa])//)?(?:
268 (?:\w+\.)?youtube\.com(?::(?:80|443))?/watch(?:\.php)?(?:\?|%3[fF])(?:[^\#]+(?:&|%26))?v(?:=|%3[dD]) # Youtube URL
269 |(?:wayback-fakeurl\.archive\.org/yt/) # Or the internal fake url
270 )
271 )(?P<id>[0-9A-Za-z_-]{11})
272 (?(prefix)
273 (?::(?P<date2>[0-9]{14}))?$|
274 (?:%26|[#&]|$)
275 )'''
276
277 _TESTS = [
278 {
279 'url': 'https://web.archive.org/web/20150415002341/https://www.youtube.com/watch?v=aYAGB11YrSs',
280 'info_dict': {
281 'id': 'aYAGB11YrSs',
282 'ext': 'webm',
283 'title': 'Team Fortress 2 - Sandviches!',
284 'description': 'md5:4984c0f9a07f349fc5d8e82ab7af4eaf',
285 'upload_date': '20110926',
286 'uploader': 'Zeurel',
287 'channel_id': 'UCukCyHaD-bK3in_pKpfH9Eg',
288 'duration': 32,
289 'uploader_id': 'Zeurel',
290 'uploader_url': 'http://www.youtube.com/user/Zeurel'
291 }
292 }, {
293 # Internal link
294 'url': 'https://web.archive.org/web/2oe/http://wayback-fakeurl.archive.org/yt/97t7Xj_iBv0',
295 'info_dict': {
296 'id': '97t7Xj_iBv0',
297 'ext': 'mp4',
298 'title': 'Why Machines That Bend Are Better',
299 'description': 'md5:00404df2c632d16a674ff8df1ecfbb6c',
300 'upload_date': '20190312',
301 'uploader': 'Veritasium',
302 'channel_id': 'UCHnyfMqiRRG1u-2MsSQLbXA',
303 'duration': 771,
304 'uploader_id': '1veritasium',
305 'uploader_url': 'http://www.youtube.com/user/1veritasium'
306 }
307 }, {
308 # Video from 2012, webm format itag 45. Newest capture is deleted video, with an invalid description.
309 # Should use the date in the link. Title ends with '- Youtube'. Capture has description in eow-description
310 'url': 'https://web.archive.org/web/20120712231619/http://www.youtube.com/watch?v=AkhihxRKcrs&gl=US&hl=en',
311 'info_dict': {
312 'id': 'AkhihxRKcrs',
313 'ext': 'webm',
314 'title': 'Limited Run: Mondo\'s Modern Classic 1 of 3 (SDCC 2012)',
315 'upload_date': '20120712',
316 'duration': 398,
317 'description': 'md5:ff4de6a7980cb65d951c2f6966a4f2f3',
318 'uploader_id': 'machinima',
319 'uploader_url': 'http://www.youtube.com/user/machinima'
320 }
321 }, {
322 # FLV video. Video file URL does not provide itag information
323 'url': 'https://web.archive.org/web/20081211103536/http://www.youtube.com/watch?v=jNQXAC9IVRw',
324 'info_dict': {
325 'id': 'jNQXAC9IVRw',
326 'ext': 'flv',
327 'title': 'Me at the zoo',
328 'upload_date': '20050423',
329 'channel_id': 'UC4QobU6STFB0P71PMvOGN5A',
330 'duration': 19,
331 'description': 'md5:10436b12e07ac43ff8df65287a56efb4',
332 'uploader_id': 'jawed',
333 'uploader_url': 'http://www.youtube.com/user/jawed'
334 }
335 }, {
336 'url': 'https://web.archive.org/web/20110712231407/http://www.youtube.com/watch?v=lTx3G6h2xyA',
337 'info_dict': {
338 'id': 'lTx3G6h2xyA',
339 'ext': 'flv',
340 'title': 'Madeon - Pop Culture (live mashup)',
341 'upload_date': '20110711',
342 'uploader': 'Madeon',
343 'channel_id': 'UCqMDNf3Pn5L7pcNkuSEeO3w',
344 'duration': 204,
345 'description': 'md5:f7535343b6eda34a314eff8b85444680',
346 'uploader_id': 'itsmadeon',
347 'uploader_url': 'http://www.youtube.com/user/itsmadeon'
348 }
349 }, {
350 # First capture is of dead video, second is the oldest from CDX response.
351 'url': 'https://web.archive.org/https://www.youtube.com/watch?v=1JYutPM8O6E',
352 'info_dict': {
353 'id': '1JYutPM8O6E',
354 'ext': 'mp4',
355 'title': 'Fake Teen Doctor Strikes AGAIN! - Weekly Weird News',
356 'upload_date': '20160218',
357 'channel_id': 'UCdIaNUarhzLSXGoItz7BHVA',
358 'duration': 1236,
359 'description': 'md5:21032bae736421e89c2edf36d1936947',
360 'uploader_id': 'MachinimaETC',
361 'uploader_url': 'http://www.youtube.com/user/MachinimaETC'
362 }
363 }, {
364 # First capture of dead video, capture date in link links to dead capture.
365 'url': 'https://web.archive.org/web/20180803221945/https://www.youtube.com/watch?v=6FPhZJGvf4E',
366 'info_dict': {
367 'id': '6FPhZJGvf4E',
368 'ext': 'mp4',
369 'title': 'WTF: Video Games Still Launch BROKEN?! - T.U.G.S.',
370 'upload_date': '20160219',
371 'channel_id': 'UCdIaNUarhzLSXGoItz7BHVA',
372 'duration': 798,
373 'description': 'md5:a1dbf12d9a3bd7cb4c5e33b27d77ffe7',
374 'uploader_id': 'MachinimaETC',
375 'uploader_url': 'http://www.youtube.com/user/MachinimaETC'
376 },
377 'expected_warnings': [
378 r'unable to download capture webpage \(it may not be archived\)'
379 ]
380 }, { # Very old YouTube page, has - YouTube in title.
381 'url': 'http://web.archive.org/web/20070302011044/http://youtube.com/watch?v=-06-KB9XTzg',
382 'info_dict': {
383 'id': '-06-KB9XTzg',
384 'ext': 'flv',
385 'title': 'New Coin Hack!! 100% Safe!!'
386 }
387 }, {
388 'url': 'web.archive.org/https://www.youtube.com/watch?v=dWW7qP423y8',
389 'info_dict': {
390 'id': 'dWW7qP423y8',
391 'ext': 'mp4',
392 'title': 'It\'s Bootleg AirPods Time.',
393 'upload_date': '20211021',
394 'channel_id': 'UC7Jwj9fkrf1adN4fMmTkpug',
395 'channel_url': 'http://www.youtube.com/channel/UC7Jwj9fkrf1adN4fMmTkpug',
396 'duration': 810,
397 'description': 'md5:7b567f898d8237b256f36c1a07d6d7bc',
398 'uploader': 'DankPods',
399 'uploader_id': 'UC7Jwj9fkrf1adN4fMmTkpug',
400 'uploader_url': 'http://www.youtube.com/channel/UC7Jwj9fkrf1adN4fMmTkpug'
401 }
402 }, {
403 # player response contains '};' See: https://github.com/ytdl-org/youtube-dl/issues/27093
404 'url': 'https://web.archive.org/web/20200827003909if_/http://www.youtube.com/watch?v=6Dh-RL__uN4',
405 'info_dict': {
406 'id': '6Dh-RL__uN4',
407 'ext': 'mp4',
408 'title': 'bitch lasagna',
409 'upload_date': '20181005',
410 'channel_id': 'UC-lHJZR3Gqxm24_Vd_AJ5Yw',
411 'channel_url': 'http://www.youtube.com/channel/UC-lHJZR3Gqxm24_Vd_AJ5Yw',
412 'duration': 135,
413 'description': 'md5:2dbe4051feeff2dab5f41f82bb6d11d0',
414 'uploader': 'PewDiePie',
415 'uploader_id': 'PewDiePie',
416 'uploader_url': 'http://www.youtube.com/user/PewDiePie'
417 }
418 }, {
419 'url': 'https://web.archive.org/web/http://www.youtube.com/watch?v=kH-G_aIBlFw',
420 'only_matching': True
421 }, {
422 'url': 'https://web.archive.org/web/20050214000000_if/http://www.youtube.com/watch?v=0altSZ96U4M',
423 'only_matching': True
424 }, {
425 # Video not archived, only capture is unavailable video page
426 'url': 'https://web.archive.org/web/20210530071008/https://www.youtube.com/watch?v=lHJTf93HL1s&spfreload=10',
427 'only_matching': True
428 }, { # Encoded url
429 'url': 'https://web.archive.org/web/20120712231619/http%3A//www.youtube.com/watch%3Fgl%3DUS%26v%3DAkhihxRKcrs%26hl%3Den',
430 'only_matching': True
431 }, {
432 'url': 'https://web.archive.org/web/20120712231619/http%3A//www.youtube.com/watch%3Fv%3DAkhihxRKcrs%26gl%3DUS%26hl%3Den',
433 'only_matching': True
434 }, {
435 'url': 'https://web.archive.org/web/20060527081937/http://www.youtube.com:80/watch.php?v=ELTFsLT73fA&amp;search=soccer',
436 'only_matching': True
437 }, {
438 'url': 'https://web.archive.org/http://www.youtube.com:80/watch?v=-05VVye-ffg',
439 'only_matching': True
440 }, {
441 'url': 'ytarchive:BaW_jenozKc:20050214000000',
442 'only_matching': True
443 }, {
444 'url': 'ytarchive:BaW_jenozKc',
445 'only_matching': True
446 },
447 ]
448 _YT_INITIAL_DATA_RE = r'(?:(?:(?:window\s*\[\s*["\']ytInitialData["\']\s*\]|ytInitialData)\s*=\s*({.+?})\s*;)|%s)' % YoutubeBaseInfoExtractor._YT_INITIAL_DATA_RE
449 _YT_INITIAL_PLAYER_RESPONSE_RE = r'(?:(?:(?:window\s*\[\s*["\']ytInitialPlayerResponse["\']\s*\]|ytInitialPlayerResponse)\s*=[(\s]*({.+?})[)\s]*;)|%s)' % YoutubeBaseInfoExtractor._YT_INITIAL_PLAYER_RESPONSE_RE
450 _YT_INITIAL_BOUNDARY_RE = r'(?:(?:var\s+meta|</script|\n)|%s)' % YoutubeBaseInfoExtractor._YT_INITIAL_BOUNDARY_RE
451
452 _YT_DEFAULT_THUMB_SERVERS = ['i.ytimg.com'] # thumbnails most likely archived on these servers
453 _YT_ALL_THUMB_SERVERS = orderedSet(
454 _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)]])
455
456 _WAYBACK_BASE_URL = 'https://web.archive.org/web/%sif_/'
457 _OLDEST_CAPTURE_DATE = 20050214000000
458 _NEWEST_CAPTURE_DATE = 20500101000000
459
460 def _call_cdx_api(self, item_id, url, filters: list = None, collapse: list = None, query: dict = None, note=None, fatal=False):
461 # CDX docs: https://github.com/internetarchive/wayback/blob/master/wayback-cdx-server/README.md
462 query = {
463 'url': url,
464 'output': 'json',
465 'fl': 'original,mimetype,length,timestamp',
466 'limit': 500,
467 'filter': ['statuscode:200'] + (filters or []),
468 'collapse': collapse or [],
469 **(query or {})
470 }
471 res = self._download_json(
472 'https://web.archive.org/cdx/search/cdx', item_id,
473 note or 'Downloading CDX API JSON', query=query, fatal=fatal)
474 if isinstance(res, list) and len(res) >= 2:
475 # format response to make it easier to use
476 return list(dict(zip(res[0], v)) for v in res[1:])
477 elif not isinstance(res, list) or len(res) != 0:
478 self.report_warning('Error while parsing CDX API response' + bug_reports_message())
479
480 def _extract_yt_initial_variable(self, webpage, regex, video_id, name):
481 return self._parse_json(self._search_regex(
482 (r'%s\s*%s' % (regex, self._YT_INITIAL_BOUNDARY_RE),
483 regex), webpage, name, default='{}'), video_id, fatal=False)
484
485 def _extract_webpage_title(self, webpage):
486 page_title = self._html_extract_title(webpage, default='')
487 # YouTube video pages appear to always have either 'YouTube -' as prefix or '- YouTube' as suffix.
488 return self._html_search_regex(
489 r'(?:YouTube\s*-\s*(.*)$)|(?:(.*)\s*-\s*YouTube$)',
490 page_title, 'title', default='')
491
492 def _extract_metadata(self, video_id, webpage):
493 search_meta = ((lambda x: self._html_search_meta(x, webpage, default=None)) if webpage else (lambda x: None))
494 player_response = self._extract_yt_initial_variable(
495 webpage, self._YT_INITIAL_PLAYER_RESPONSE_RE, video_id, 'initial player response') or {}
496 initial_data = self._extract_yt_initial_variable(
497 webpage, self._YT_INITIAL_DATA_RE, video_id, 'initial player response') or {}
498
499 initial_data_video = traverse_obj(
500 initial_data, ('contents', 'twoColumnWatchNextResults', 'results', 'results', 'contents', ..., 'videoPrimaryInfoRenderer'),
501 expected_type=dict, get_all=False, default={})
502
503 video_details = traverse_obj(
504 player_response, 'videoDetails', expected_type=dict, get_all=False, default={})
505
506 microformats = traverse_obj(
507 player_response, ('microformat', 'playerMicroformatRenderer'), expected_type=dict, get_all=False, default={})
508
509 video_title = (
510 video_details.get('title')
511 or YoutubeBaseInfoExtractor._get_text(microformats, 'title')
512 or YoutubeBaseInfoExtractor._get_text(initial_data_video, 'title')
513 or self._extract_webpage_title(webpage)
514 or search_meta(['og:title', 'twitter:title', 'title']))
515
516 channel_id = str_or_none(
517 video_details.get('channelId')
518 or microformats.get('externalChannelId')
519 or search_meta('channelId')
520 or self._search_regex(
521 r'data-channel-external-id=(["\'])(?P<id>(?:(?!\1).)+)\1', # @b45a9e6
522 webpage, 'channel id', default=None, group='id'))
523 channel_url = f'http://www.youtube.com/channel/{channel_id}' if channel_id else None
524
525 duration = int_or_none(
526 video_details.get('lengthSeconds')
527 or microformats.get('lengthSeconds')
528 or parse_duration(search_meta('duration')))
529 description = (
530 video_details.get('shortDescription')
531 or YoutubeBaseInfoExtractor._get_text(microformats, 'description')
532 or clean_html(get_element_by_id('eow-description', webpage)) # @9e6dd23
533 or search_meta(['description', 'og:description', 'twitter:description']))
534
535 uploader = video_details.get('author')
536
537 # Uploader ID and URL
538 uploader_mobj = re.search(
539 r'<link itemprop="url" href="(?P<uploader_url>https?://www\.youtube\.com/(?:user|channel)/(?P<uploader_id>[^"]+))">', # @fd05024
540 webpage)
541 if uploader_mobj is not None:
542 uploader_id, uploader_url = uploader_mobj.group('uploader_id'), uploader_mobj.group('uploader_url')
543 else:
544 # @a6211d2
545 uploader_url = url_or_none(microformats.get('ownerProfileUrl'))
546 uploader_id = self._search_regex(
547 r'(?:user|channel)/([^/]+)', uploader_url or '', 'uploader id', default=None)
548
549 upload_date = unified_strdate(
550 dict_get(microformats, ('uploadDate', 'publishDate'))
551 or search_meta(['uploadDate', 'datePublished'])
552 or self._search_regex(
553 [r'(?s)id="eow-date.*?>(.*?)</span>',
554 r'(?:id="watch-uploader-info".*?>.*?|["\']simpleText["\']\s*:\s*["\'])(?:Published|Uploaded|Streamed live|Started) on (.+?)[<"\']'], # @7998520
555 webpage, 'upload date', default=None))
556
557 return {
558 'title': video_title,
559 'description': description,
560 'upload_date': upload_date,
561 'uploader': uploader,
562 'channel_id': channel_id,
563 'channel_url': channel_url,
564 'duration': duration,
565 'uploader_url': uploader_url,
566 'uploader_id': uploader_id,
567 }
568
569 def _extract_thumbnails(self, video_id):
570 try_all = 'thumbnails' in self._configuration_arg('check_all')
571 thumbnail_base_urls = ['http://{server}/vi{webp}/{video_id}'.format(
572 webp='_webp' if ext == 'webp' else '', video_id=video_id, server=server)
573 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',))]
574
575 thumbnails = []
576 for url in thumbnail_base_urls:
577 response = self._call_cdx_api(
578 video_id, url, filters=['mimetype:image/(?:webp|jpeg)'],
579 collapse=['urlkey'], query={'matchType': 'prefix'})
580 if not response:
581 continue
582 thumbnails.extend(
583 {
584 'url': (self._WAYBACK_BASE_URL % (int_or_none(thumbnail_dict.get('timestamp')) or self._OLDEST_CAPTURE_DATE)) + thumbnail_dict.get('original'),
585 'filesize': int_or_none(thumbnail_dict.get('length')),
586 'preference': int_or_none(thumbnail_dict.get('length'))
587 } for thumbnail_dict in response)
588 if not try_all:
589 break
590
591 self._remove_duplicate_formats(thumbnails)
592 return thumbnails
593
594 def _get_capture_dates(self, video_id, url_date):
595 capture_dates = []
596 # Note: CDX API will not find watch pages with extra params in the url.
597 response = self._call_cdx_api(
598 video_id, f'https://www.youtube.com/watch?v={video_id}',
599 filters=['mimetype:text/html'], collapse=['timestamp:6', 'digest'], query={'matchType': 'prefix'}) or []
600 all_captures = sorted([int_or_none(r['timestamp']) for r in response if int_or_none(r['timestamp']) is not None])
601
602 # Prefer the new polymer UI captures as we support extracting more metadata from them
603 # WBM captures seem to all switch to this layout ~July 2020
604 modern_captures = [x for x in all_captures if x >= 20200701000000]
605 if modern_captures:
606 capture_dates.append(modern_captures[0])
607 capture_dates.append(url_date)
608 if all_captures:
609 capture_dates.append(all_captures[0])
610
611 if 'captures' in self._configuration_arg('check_all'):
612 capture_dates.extend(modern_captures + all_captures)
613
614 # Fallbacks if any of the above fail
615 capture_dates.extend([self._OLDEST_CAPTURE_DATE, self._NEWEST_CAPTURE_DATE])
616 return orderedSet(filter(None, capture_dates))
617
618 def _real_extract(self, url):
619 video_id, url_date, url_date_2 = self._match_valid_url(url).group('id', 'date', 'date2')
620 url_date = url_date or url_date_2
621
622 urlh = None
623 try:
624 urlh = self._request_webpage(
625 HEADRequest('https://web.archive.org/web/2oe_/http://wayback-fakeurl.archive.org/yt/%s' % video_id),
626 video_id, note='Fetching archived video file url', expected_status=True)
627 except ExtractorError as e:
628 # HTTP Error 404 is expected if the video is not saved.
629 if isinstance(e.cause, compat_HTTPError) and e.cause.code == 404:
630 self.raise_no_formats(
631 'The requested video is not archived, indexed, or there is an issue with web.archive.org',
632 expected=True)
633 else:
634 raise
635
636 capture_dates = self._get_capture_dates(video_id, int_or_none(url_date))
637 self.write_debug('Captures to try: ' + join_nonempty(*capture_dates, delim=', '))
638 info = {'id': video_id}
639 for capture in capture_dates:
640 webpage = self._download_webpage(
641 (self._WAYBACK_BASE_URL + 'http://www.youtube.com/watch?v=%s') % (capture, video_id),
642 video_id=video_id, fatal=False, errnote='unable to download capture webpage (it may not be archived)',
643 note='Downloading capture webpage')
644 current_info = self._extract_metadata(video_id, webpage or '')
645 # Try avoid getting deleted video metadata
646 if current_info.get('title'):
647 info = merge_dicts(info, current_info)
648 if 'captures' not in self._configuration_arg('check_all'):
649 break
650
651 info['thumbnails'] = self._extract_thumbnails(video_id)
652
653 if urlh:
654 url = compat_urllib_parse_unquote(urlh.geturl())
655 video_file_url_qs = parse_qs(url)
656 # Attempt to recover any ext & format info from playback url & response headers
657 format = {'url': url, 'filesize': int_or_none(urlh.headers.get('x-archive-orig-content-length'))}
658 itag = try_get(video_file_url_qs, lambda x: x['itag'][0])
659 if itag and itag in YoutubeIE._formats:
660 format.update(YoutubeIE._formats[itag])
661 format.update({'format_id': itag})
662 else:
663 mime = try_get(video_file_url_qs, lambda x: x['mime'][0])
664 ext = (mimetype2ext(mime)
665 or urlhandle_detect_ext(urlh)
666 or mimetype2ext(urlh.headers.get('x-archive-guessed-content-type')))
667 format.update({'ext': ext})
668 info['formats'] = [format]
669 if not info.get('duration'):
670 info['duration'] = str_to_int(try_get(video_file_url_qs, lambda x: x['dur'][0]))
671
672 if not info.get('title'):
673 info['title'] = video_id
674 return info