]> jfr.im git - yt-dlp.git/blame - yt_dlp/extractor/archiveorg.py
[extractors/rtvc] Add extractors (#6578)
[yt-dlp.git] / yt_dlp / extractor / archiveorg.py
CommitLineData
a3e26449 1import json
ac668111 2import re
b3eaab7c 3import urllib.error
ac668111 4import urllib.parse
5
a4a554a7 6from .common import InfoExtractor
b3eaab7c 7from .naver import NaverBaseIE
ac668111 8from .youtube import YoutubeBaseInfoExtractor, YoutubeIE
9from ..compat import compat_HTTPError, compat_urllib_parse_unquote
d50aca41 10from ..utils import (
ac668111 11 KNOWN_EXTENSIONS,
12 ExtractorError,
13 HEADRequest,
aa4b0545 14 bug_reports_message,
d50aca41 15 clean_html,
a3e26449 16 dict_get,
879e7199 17 extract_attributes,
aa4b0545 18 get_element_by_id,
a3e26449 19 int_or_none,
1f13021e 20 join_nonempty,
217753f4 21 js_to_json,
a3e26449 22 merge_dicts,
879e7199 23 mimetype2ext,
aa4b0545 24 orderedSet,
879e7199 25 parse_duration,
4dfbf869 26 parse_qs,
879e7199 27 str_or_none,
ac668111 28 str_to_int,
aa4b0545 29 traverse_obj,
879e7199 30 try_get,
31 unified_strdate,
32 unified_timestamp,
ac668111 33 url_or_none,
aa4b0545 34 urlhandle_detect_ext,
d50aca41 35)
5fe3a3c3
PH
36
37
a4a554a7 38class ArchiveOrgIE(InfoExtractor):
5fe3a3c3 39 IE_NAME = 'archive.org'
a3e26449 40 IE_DESC = 'archive.org video and audio'
41 _VALID_URL = r'https?://(?:www\.)?archive\.org/(?:details|embed)/(?P<id>[^?#]+)(?:[?].*)?$'
e8e28989
S
42 _TESTS = [{
43 'url': 'http://archive.org/details/XD300-23_68HighlightsAResearchCntAugHumanIntellect',
3798eadc
PH
44 'md5': '8af1d4cf447933ed3c7f4871162602db',
45 'info_dict': {
e8e28989 46 'id': 'XD300-23_68HighlightsAResearchCntAugHumanIntellect',
a3e26449 47 'ext': 'ogv',
e8e28989 48 'title': '1968 Demo - FJCC Conference Presentation Reel #1',
d50aca41 49 'description': 'md5:da45c349df039f1cc8075268eb1b5c25',
a3e26449 50 'release_date': '19681210',
51 'timestamp': 1268695290,
52 'upload_date': '20100315',
53 'creator': 'SRI International',
54 'uploader': 'laura@archive.org',
871a8929 55 'thumbnail': r're:https://archive\.org/download/.*\.jpg',
56 'release_year': 1968,
57 'display_id': 'XD300-23_68HighlightsAResearchCntAugHumanIntellect.cdr',
58 'track': 'XD300-23 68HighlightsAResearchCntAugHumanIntellect',
59
a3e26449 60 },
e8e28989
S
61 }, {
62 'url': 'https://archive.org/details/Cops1922',
c12b4b80 63 'md5': '0869000b4ce265e8ca62738b336b268a',
e8e28989
S
64 'info_dict': {
65 'id': 'Cops1922',
d50aca41 66 'ext': 'mp4',
e8e28989 67 'title': 'Buster Keaton\'s "Cops" (1922)',
871a8929 68 'description': 'md5:cd6f9910c35aedd5fc237dbc3957e2ca',
a3e26449 69 'uploader': 'yorkmba99@hotmail.com',
70 'timestamp': 1387699629,
1f13021e 71 'upload_date': '20131222',
871a8929 72 'display_id': 'Cops-v2.mp4',
73 'thumbnail': r're:https://archive\.org/download/.*\.jpg',
74 'duration': 1091.96,
a3e26449 75 },
d50aca41
RA
76 }, {
77 'url': 'http://archive.org/embed/XD300-23_68HighlightsAResearchCntAugHumanIntellect',
78 'only_matching': True,
a3e26449 79 }, {
80 'url': 'https://archive.org/details/Election_Ads',
871a8929 81 'md5': 'eec5cddebd4793c6a653b69c3b11f2e6',
a3e26449 82 'info_dict': {
83 'id': 'Election_Ads/Commercial-JFK1960ElectionAdCampaignJingle.mpg',
84 'title': 'Commercial-JFK1960ElectionAdCampaignJingle.mpg',
871a8929 85 'ext': 'mpg',
86 'thumbnail': r're:https://archive\.org/download/.*\.jpg',
87 'duration': 59.77,
88 'display_id': 'Commercial-JFK1960ElectionAdCampaignJingle.mpg',
a3e26449 89 },
90 }, {
91 'url': 'https://archive.org/details/Election_Ads/Commercial-Nixon1960ElectionAdToughonDefense.mpg',
871a8929 92 'md5': 'ea1eed8234e7d4165f38c8c769edef38',
a3e26449 93 'info_dict': {
94 'id': 'Election_Ads/Commercial-Nixon1960ElectionAdToughonDefense.mpg',
95 'title': 'Commercial-Nixon1960ElectionAdToughonDefense.mpg',
871a8929 96 'ext': 'mpg',
a3e26449 97 'timestamp': 1205588045,
98 'uploader': 'mikedavisstripmaster@yahoo.com',
99 'description': '1960 Presidential Campaign Election Commercials John F Kennedy, Richard M Nixon',
100 'upload_date': '20080315',
871a8929 101 'display_id': 'Commercial-Nixon1960ElectionAdToughonDefense.mpg',
102 'duration': 59.51,
103 'license': 'http://creativecommons.org/licenses/publicdomain/',
104 'thumbnail': r're:https://archive\.org/download/.*\.jpg',
a3e26449 105 },
106 }, {
107 'url': 'https://archive.org/details/gd1977-05-08.shure57.stevenson.29303.flac16',
108 'md5': '7d07ffb42aba6537c28e053efa4b54c9',
109 'info_dict': {
110 'id': 'gd1977-05-08.shure57.stevenson.29303.flac16/gd1977-05-08d01t01.flac',
111 'title': 'Turning',
112 'ext': 'flac',
871a8929 113 'track': 'Turning',
114 'creator': 'Grateful Dead',
115 'display_id': 'gd1977-05-08d01t01.flac',
116 'track_number': 1,
117 'album': '1977-05-08 - Barton Hall - Cornell University',
118 'duration': 39.8,
a3e26449 119 },
120 }, {
121 'url': 'https://archive.org/details/gd1977-05-08.shure57.stevenson.29303.flac16/gd1977-05-08d01t07.flac',
122 'md5': 'a07cd8c6ab4ee1560f8a0021717130f3',
123 'info_dict': {
124 'id': 'gd1977-05-08.shure57.stevenson.29303.flac16/gd1977-05-08d01t07.flac',
125 'title': 'Deal',
126 'ext': 'flac',
127 'timestamp': 1205895624,
128 'uploader': 'mvernon54@yahoo.com',
871a8929 129 'description': 'md5:6c921464414814720c6593810a5c7e3d',
a3e26449 130 'upload_date': '20080319',
131 'location': 'Barton Hall - Cornell University',
871a8929 132 'duration': 438.68,
133 'track': 'Deal',
134 'creator': 'Grateful Dead',
135 'album': '1977-05-08 - Barton Hall - Cornell University',
136 'release_date': '19770508',
137 'display_id': 'gd1977-05-08d01t07.flac',
138 'release_year': 1977,
139 'track_number': 7,
a3e26449 140 },
141 }, {
871a8929 142 # FIXME: give a better error message than just IndexError when all available formats are restricted
a3e26449 143 'url': 'https://archive.org/details/lp_the-music-of-russia_various-artists-a-askaryan-alexander-melik',
144 'md5': '7cb019baa9b332e82ea7c10403acd180',
145 'info_dict': {
146 'id': 'lp_the-music-of-russia_various-artists-a-askaryan-alexander-melik/disc1/01.01. Bells Of Rostov.mp3',
147 'title': 'Bells Of Rostov',
148 'ext': 'mp3',
149 },
871a8929 150 'skip': 'restricted'
a3e26449 151 }, {
152 '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',
153 'md5': '1d0aabe03edca83ca58d9ed3b493a3c3',
154 'info_dict': {
155 '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',
156 'title': 'Song And Chorus In The Polovetsian Camp From "Prince Igor" (Act 2, Scene 1)',
157 'ext': 'mp3',
158 'timestamp': 1569662587,
159 'uploader': 'associate-joygen-odiongan@archive.org',
160 'description': 'md5:012b2d668ae753be36896f343d12a236',
161 'upload_date': '20190928',
162 },
871a8929 163 'skip': 'restricted'
164 }, {
165 # Original formats are private
166 'url': 'https://archive.org/details/irelandthemakingofarepublic',
167 'info_dict': {
168 'id': 'irelandthemakingofarepublic',
169 'title': 'Ireland: The Making of a Republic',
170 'upload_date': '20160610',
171 'description': 'md5:f70956a156645a658a0dc9513d9e78b7',
172 'uploader': 'dimitrios@archive.org',
173 'creator': ['British Broadcasting Corporation', 'Time-Life Films'],
174 'timestamp': 1465594947,
175 },
176 'playlist': [
177 {
178 'md5': '0b211261b26590d49df968f71b90690d',
179 'info_dict': {
180 'id': 'irelandthemakingofarepublic/irelandthemakingofarepublicreel1_01.mov',
181 'ext': 'mp4',
182 'title': 'irelandthemakingofarepublicreel1_01.mov',
183 'duration': 130.46,
184 'thumbnail': 'https://archive.org/download/irelandthemakingofarepublic/irelandthemakingofarepublic.thumbs/irelandthemakingofarepublicreel1_01_000117.jpg',
185 'display_id': 'irelandthemakingofarepublicreel1_01.mov',
186 },
187 }, {
188 'md5': '67335ee3b23a0da930841981c1e79b02',
189 'info_dict': {
190 'id': 'irelandthemakingofarepublic/irelandthemakingofarepublicreel1_02.mov',
191 'ext': 'mp4',
192 'duration': 1395.13,
193 'title': 'irelandthemakingofarepublicreel1_02.mov',
194 'display_id': 'irelandthemakingofarepublicreel1_02.mov',
195 'thumbnail': 'https://archive.org/download/irelandthemakingofarepublic/irelandthemakingofarepublic.thumbs/irelandthemakingofarepublicreel1_02_001374.jpg',
196 },
197 }, {
198 'md5': 'e470e86787893603f4a341a16c281eb5',
199 'info_dict': {
200 'id': 'irelandthemakingofarepublic/irelandthemakingofarepublicreel2.mov',
201 'ext': 'mp4',
202 'duration': 1602.67,
203 'title': 'irelandthemakingofarepublicreel2.mov',
204 'thumbnail': 'https://archive.org/download/irelandthemakingofarepublic/irelandthemakingofarepublic.thumbs/irelandthemakingofarepublicreel2_001554.jpg',
205 'display_id': 'irelandthemakingofarepublicreel2.mov',
206 },
207 }
208 ]
e8e28989 209 }]
ff7a07d5 210
a3e26449 211 @staticmethod
212 def _playlist_data(webpage):
213 element = re.findall(r'''(?xs)
214 <input
215 (?:\s+[a-zA-Z0-9:._-]+(?:=[a-zA-Z0-9:._-]*|="[^"]*"|='[^']*'|))*?
216 \s+class=['"]?js-play8-playlist['"]?
217 (?:\s+[a-zA-Z0-9:._-]+(?:=[a-zA-Z0-9:._-]*|="[^"]*"|='[^']*'|))*?
218 \s*/>
219 ''', webpage)[0]
220
221 return json.loads(extract_attributes(element)['value'])
222
5fe3a3c3 223 def _real_extract(self, url):
ac668111 224 video_id = urllib.parse.unquote_plus(self._match_id(url))
a3e26449 225 identifier, entry_id = (video_id.split('/', 1) + [None])[:2]
226
227 # Archive.org metadata API doesn't clearly demarcate playlist entries
228 # or subtitle tracks, so we get them from the embeddable player.
1f13021e 229 embed_page = self._download_webpage(f'https://archive.org/embed/{identifier}', identifier)
a3e26449 230 playlist = self._playlist_data(embed_page)
231
232 entries = {}
233 for p in playlist:
234 # If the user specified a playlist entry in the URL, ignore the
235 # rest of the playlist.
236 if entry_id and p['orig'] != entry_id:
237 continue
238
239 entries[p['orig']] = {
240 'formats': [],
241 'thumbnails': [],
242 'artist': p.get('artist'),
243 'track': p.get('title'),
1f13021e 244 'subtitles': {},
245 }
a3e26449 246
247 for track in p.get('tracks', []):
248 if track['kind'] != 'subtitles':
249 continue
a3e26449 250 entries[p['orig']][track['label']] = {
1f13021e 251 'url': 'https://archive.org/' + track['file'].lstrip('/')
252 }
5fe3a3c3 253
1f13021e 254 metadata = self._download_json('http://archive.org/metadata/' + identifier, identifier)
a3e26449 255 m = metadata['metadata']
256 identifier = m['identifier']
257
258 info = {
259 'id': identifier,
260 'title': m['title'],
261 'description': clean_html(m.get('description')),
262 'uploader': dict_get(m, ['uploader', 'adder']),
263 'creator': m.get('creator'),
264 'license': m.get('licenseurl'),
265 'release_date': unified_strdate(m.get('date')),
266 'timestamp': unified_timestamp(dict_get(m, ['publicdate', 'addeddate'])),
1f13021e 267 'webpage_url': f'https://archive.org/details/{identifier}',
a3e26449 268 'location': m.get('venue'),
269 'release_year': int_or_none(m.get('year'))}
270
271 for f in metadata['files']:
272 if f['name'] in entries:
273 entries[f['name']] = merge_dicts(entries[f['name']], {
274 'id': identifier + '/' + f['name'],
275 'title': f.get('title') or f['name'],
276 'display_id': f['name'],
277 'description': clean_html(f.get('description')),
278 'creator': f.get('creator'),
279 'duration': parse_duration(f.get('length')),
280 'track_number': int_or_none(f.get('track')),
281 'album': f.get('album'),
282 'discnumber': int_or_none(f.get('disc')),
283 'release_year': int_or_none(f.get('year'))})
284 entry = entries[f['name']]
e612f66c 285 elif traverse_obj(f, 'original', expected_type=str) in entries:
a3e26449 286 entry = entries[f['original']]
287 else:
288 continue
289
290 if f.get('format') == 'Thumbnail':
291 entry['thumbnails'].append({
292 'id': f['name'],
293 'url': 'https://archive.org/download/' + identifier + '/' + f['name'],
294 'width': int_or_none(f.get('width')),
295 'height': int_or_none(f.get('width')),
296 'filesize': int_or_none(f.get('size'))})
297
298 extension = (f['name'].rsplit('.', 1) + [None])[1]
871a8929 299
300 # We don't want to skip private formats if the user has access to them,
301 # however without access to an account with such privileges we can't implement/test this.
302 # For now to be safe, we will only skip them if there is no user logged in.
303 is_logged_in = bool(self._get_cookies('https://archive.org').get('logged-in-sig'))
304 if extension in KNOWN_EXTENSIONS and (not f.get('private') or is_logged_in):
a3e26449 305 entry['formats'].append({
306 'url': 'https://archive.org/download/' + identifier + '/' + f['name'],
307 'format': f.get('format'),
308 'width': int_or_none(f.get('width')),
309 'height': int_or_none(f.get('height')),
310 'filesize': int_or_none(f.get('size')),
871a8929 311 'protocol': 'https',
312 'source_preference': 0 if f.get('source') == 'original' else -1,
313 'format_note': f.get('source')
314 })
a3e26449 315
a3e26449 316 for entry in entries.values():
9f14daf2 317 entry['_format_sort_fields'] = ('source', )
a3e26449 318
319 if len(entries) == 1:
320 # If there's only one item, use it as the main info dict
1f13021e 321 only_video = next(iter(entries.values()))
a3e26449 322 if entry_id:
323 info = merge_dicts(only_video, info)
324 else:
325 info = merge_dicts(info, only_video)
326 else:
327 # Otherwise, we have a playlist.
328 info['_type'] = 'playlist'
329 info['entries'] = list(entries.values())
330
331 if metadata.get('reviews'):
332 info['comments'] = []
333 for review in metadata['reviews']:
334 info['comments'].append({
335 'id': review.get('review_id'),
336 'author': review.get('reviewer'),
337 'text': str_or_none(review.get('reviewtitle'), '') + '\n\n' + review.get('reviewbody'),
338 'timestamp': unified_timestamp(review.get('createdate')),
339 'parent': 'root'})
340
84bc23b4 341 return info
879e7199 342
343
344class YoutubeWebArchiveIE(InfoExtractor):
345 IE_NAME = 'web.archive:youtube'
1f13021e 346 IE_DESC = 'web.archive.org saved youtube videos, "ytarchive:" prefix'
347 _VALID_URL = r'''(?x)(?:(?P<prefix>ytarchive:)|
348 (?:https?://)?web\.archive\.org/
349 (?:web/)?(?:(?P<date>[0-9]{14})?[0-9A-Za-z_*]*/)? # /web and the version index is optional
350 (?:https?(?::|%3[Aa])//)?(?:
351 (?:\w+\.)?youtube\.com(?::(?:80|443))?/watch(?:\.php)?(?:\?|%3[fF])(?:[^\#]+(?:&|%26))?v(?:=|%3[dD]) # Youtube URL
352 |(?:wayback-fakeurl\.archive\.org/yt/) # Or the internal fake url
353 )
354 )(?P<id>[0-9A-Za-z_-]{11})
355 (?(prefix)
356 (?::(?P<date2>[0-9]{14}))?$|
357 (?:%26|[#&]|$)
358 )'''
879e7199 359
360 _TESTS = [
361 {
362 'url': 'https://web.archive.org/web/20150415002341/https://www.youtube.com/watch?v=aYAGB11YrSs',
363 'info_dict': {
364 'id': 'aYAGB11YrSs',
365 'ext': 'webm',
aa4b0545 366 'title': 'Team Fortress 2 - Sandviches!',
367 'description': 'md5:4984c0f9a07f349fc5d8e82ab7af4eaf',
368 'upload_date': '20110926',
369 'uploader': 'Zeurel',
370 'channel_id': 'UCukCyHaD-bK3in_pKpfH9Eg',
371 'duration': 32,
372 'uploader_id': 'Zeurel',
217753f4
M
373 'uploader_url': 'https://www.youtube.com/user/Zeurel',
374 'thumbnail': r're:https?://.*\.(jpg|webp)',
375 'channel_url': 'https://www.youtube.com/channel/UCukCyHaD-bK3in_pKpfH9Eg',
879e7199 376 }
aa4b0545 377 }, {
879e7199 378 # Internal link
379 'url': 'https://web.archive.org/web/2oe/http://wayback-fakeurl.archive.org/yt/97t7Xj_iBv0',
380 'info_dict': {
381 'id': '97t7Xj_iBv0',
382 'ext': 'mp4',
aa4b0545 383 'title': 'Why Machines That Bend Are Better',
384 'description': 'md5:00404df2c632d16a674ff8df1ecfbb6c',
385 'upload_date': '20190312',
386 'uploader': 'Veritasium',
387 'channel_id': 'UCHnyfMqiRRG1u-2MsSQLbXA',
388 'duration': 771,
389 'uploader_id': '1veritasium',
217753f4
M
390 'uploader_url': 'https://www.youtube.com/user/1veritasium',
391 'thumbnail': r're:https?://.*\.(jpg|webp)',
392 'channel_url': 'https://www.youtube.com/channel/UCHnyfMqiRRG1u-2MsSQLbXA',
879e7199 393 }
aa4b0545 394 }, {
395 # Video from 2012, webm format itag 45. Newest capture is deleted video, with an invalid description.
396 # Should use the date in the link. Title ends with '- Youtube'. Capture has description in eow-description
879e7199 397 'url': 'https://web.archive.org/web/20120712231619/http://www.youtube.com/watch?v=AkhihxRKcrs&gl=US&hl=en',
398 'info_dict': {
399 'id': 'AkhihxRKcrs',
400 'ext': 'webm',
aa4b0545 401 'title': 'Limited Run: Mondo\'s Modern Classic 1 of 3 (SDCC 2012)',
402 'upload_date': '20120712',
403 'duration': 398,
404 'description': 'md5:ff4de6a7980cb65d951c2f6966a4f2f3',
405 'uploader_id': 'machinima',
217753f4
M
406 'uploader_url': 'https://www.youtube.com/user/machinima',
407 'thumbnail': r're:https?://.*\.(jpg|webp)',
408 'uploader': 'machinima'
879e7199 409 }
aa4b0545 410 }, {
411 # FLV video. Video file URL does not provide itag information
879e7199 412 'url': 'https://web.archive.org/web/20081211103536/http://www.youtube.com/watch?v=jNQXAC9IVRw',
413 'info_dict': {
414 'id': 'jNQXAC9IVRw',
aa4b0545 415 'ext': 'flv',
416 'title': 'Me at the zoo',
417 'upload_date': '20050423',
418 'channel_id': 'UC4QobU6STFB0P71PMvOGN5A',
419 'duration': 19,
420 'description': 'md5:10436b12e07ac43ff8df65287a56efb4',
421 'uploader_id': 'jawed',
217753f4
M
422 'uploader_url': 'https://www.youtube.com/user/jawed',
423 'channel_url': 'https://www.youtube.com/channel/UC4QobU6STFB0P71PMvOGN5A',
424 'thumbnail': r're:https?://.*\.(jpg|webp)',
425 'uploader': 'jawed',
879e7199 426 }
aa4b0545 427 }, {
879e7199 428 'url': 'https://web.archive.org/web/20110712231407/http://www.youtube.com/watch?v=lTx3G6h2xyA',
429 'info_dict': {
430 'id': 'lTx3G6h2xyA',
431 'ext': 'flv',
aa4b0545 432 'title': 'Madeon - Pop Culture (live mashup)',
433 'upload_date': '20110711',
434 'uploader': 'Madeon',
435 'channel_id': 'UCqMDNf3Pn5L7pcNkuSEeO3w',
436 'duration': 204,
437 'description': 'md5:f7535343b6eda34a314eff8b85444680',
438 'uploader_id': 'itsmadeon',
217753f4
M
439 'uploader_url': 'https://www.youtube.com/user/itsmadeon',
440 'channel_url': 'https://www.youtube.com/channel/UCqMDNf3Pn5L7pcNkuSEeO3w',
441 'thumbnail': r're:https?://.*\.(jpg|webp)',
879e7199 442 }
aa4b0545 443 }, {
444 # First capture is of dead video, second is the oldest from CDX response.
445 'url': 'https://web.archive.org/https://www.youtube.com/watch?v=1JYutPM8O6E',
879e7199 446 'info_dict': {
aa4b0545 447 'id': '1JYutPM8O6E',
879e7199 448 'ext': 'mp4',
aa4b0545 449 'title': 'Fake Teen Doctor Strikes AGAIN! - Weekly Weird News',
450 'upload_date': '20160218',
451 'channel_id': 'UCdIaNUarhzLSXGoItz7BHVA',
217753f4 452 'duration': 1235,
aa4b0545 453 'description': 'md5:21032bae736421e89c2edf36d1936947',
454 'uploader_id': 'MachinimaETC',
217753f4
M
455 'uploader_url': 'https://www.youtube.com/user/MachinimaETC',
456 'channel_url': 'https://www.youtube.com/channel/UCdIaNUarhzLSXGoItz7BHVA',
457 'thumbnail': r're:https?://.*\.(jpg|webp)',
458 'uploader': 'ETC News',
aa4b0545 459 }
460 }, {
461 # First capture of dead video, capture date in link links to dead capture.
462 'url': 'https://web.archive.org/web/20180803221945/https://www.youtube.com/watch?v=6FPhZJGvf4E',
879e7199 463 'info_dict': {
aa4b0545 464 'id': '6FPhZJGvf4E',
879e7199 465 'ext': 'mp4',
aa4b0545 466 'title': 'WTF: Video Games Still Launch BROKEN?! - T.U.G.S.',
467 'upload_date': '20160219',
468 'channel_id': 'UCdIaNUarhzLSXGoItz7BHVA',
217753f4 469 'duration': 797,
aa4b0545 470 'description': 'md5:a1dbf12d9a3bd7cb4c5e33b27d77ffe7',
471 'uploader_id': 'MachinimaETC',
217753f4
M
472 'uploader_url': 'https://www.youtube.com/user/MachinimaETC',
473 'channel_url': 'https://www.youtube.com/channel/UCdIaNUarhzLSXGoItz7BHVA',
474 'thumbnail': r're:https?://.*\.(jpg|webp)',
475 'uploader': 'ETC News',
879e7199 476 },
477 'expected_warnings': [
aa4b0545 478 r'unable to download capture webpage \(it may not be archived\)'
879e7199 479 ]
aa4b0545 480 }, { # Very old YouTube page, has - YouTube in title.
481 'url': 'http://web.archive.org/web/20070302011044/http://youtube.com/watch?v=-06-KB9XTzg',
482 'info_dict': {
483 'id': '-06-KB9XTzg',
484 'ext': 'flv',
485 'title': 'New Coin Hack!! 100% Safe!!'
486 }
487 }, {
488 'url': 'web.archive.org/https://www.youtube.com/watch?v=dWW7qP423y8',
489 'info_dict': {
490 'id': 'dWW7qP423y8',
491 'ext': 'mp4',
492 'title': 'It\'s Bootleg AirPods Time.',
493 'upload_date': '20211021',
494 'channel_id': 'UC7Jwj9fkrf1adN4fMmTkpug',
217753f4 495 'channel_url': 'https://www.youtube.com/channel/UC7Jwj9fkrf1adN4fMmTkpug',
aa4b0545 496 'duration': 810,
497 'description': 'md5:7b567f898d8237b256f36c1a07d6d7bc',
217753f4 498 'thumbnail': r're:https?://.*\.(jpg|webp)',
aa4b0545 499 'uploader': 'DankPods',
aa4b0545 500 }
501 }, {
502 # player response contains '};' See: https://github.com/ytdl-org/youtube-dl/issues/27093
503 'url': 'https://web.archive.org/web/20200827003909if_/http://www.youtube.com/watch?v=6Dh-RL__uN4',
504 'info_dict': {
505 'id': '6Dh-RL__uN4',
506 'ext': 'mp4',
507 'title': 'bitch lasagna',
508 'upload_date': '20181005',
509 'channel_id': 'UC-lHJZR3Gqxm24_Vd_AJ5Yw',
217753f4 510 'channel_url': 'https://www.youtube.com/channel/UC-lHJZR3Gqxm24_Vd_AJ5Yw',
aa4b0545 511 'duration': 135,
512 'description': 'md5:2dbe4051feeff2dab5f41f82bb6d11d0',
513 'uploader': 'PewDiePie',
514 'uploader_id': 'PewDiePie',
217753f4
M
515 'uploader_url': 'https://www.youtube.com/user/PewDiePie',
516 'thumbnail': r're:https?://.*\.(jpg|webp)',
517 }
518 }, {
519 # ~June 2010 Capture. swfconfig
520 'url': 'https://web.archive.org/web/0/https://www.youtube.com/watch?v=8XeW5ilk-9Y',
521 'info_dict': {
522 'id': '8XeW5ilk-9Y',
523 'ext': 'flv',
524 'title': 'Story of Stuff, The Critique Part 4 of 4',
525 'duration': 541,
526 'description': 'md5:28157da06f2c5e94c97f7f3072509972',
527 'uploader': 'HowTheWorldWorks',
528 'uploader_id': 'HowTheWorldWorks',
529 'thumbnail': r're:https?://.*\.(jpg|webp)',
530 'uploader_url': 'https://www.youtube.com/user/HowTheWorldWorks',
531 'upload_date': '20090520',
532 }
533 }, {
534 # Jan 2011: watch-video-date/eow-date surrounded by whitespace
535 'url': 'https://web.archive.org/web/20110126141719/http://www.youtube.com/watch?v=Q_yjX80U7Yc',
536 'info_dict': {
537 'id': 'Q_yjX80U7Yc',
538 'ext': 'flv',
539 'title': 'Spray Paint Art by Clay Butler: Purple Fantasy Forest',
540 'uploader_id': 'claybutlermusic',
541 'description': 'md5:4595264559e3d0a0ceb3f011f6334543',
542 'upload_date': '20090803',
543 'uploader': 'claybutlermusic',
544 'thumbnail': r're:https?://.*\.(jpg|webp)',
545 'duration': 132,
546 'uploader_url': 'https://www.youtube.com/user/claybutlermusic',
547 }
548 }, {
549 # ~May 2009 swfArgs. ytcfg is spread out over various vars
550 'url': 'https://web.archive.org/web/0/https://www.youtube.com/watch?v=c5uJgG05xUY',
551 'info_dict': {
552 'id': 'c5uJgG05xUY',
553 'ext': 'webm',
554 'title': 'Story of Stuff, The Critique Part 1 of 4',
555 'uploader_id': 'HowTheWorldWorks',
556 'uploader': 'HowTheWorldWorks',
557 'uploader_url': 'https://www.youtube.com/user/HowTheWorldWorks',
558 'upload_date': '20090513',
559 'description': 'md5:4ca77d79538064e41e4cc464e93f44f0',
560 'thumbnail': r're:https?://.*\.(jpg|webp)',
561 'duration': 754,
562 }
563 }, {
564 # ~June 2012. Upload date is in another lang so cannot extract.
565 'url': 'https://web.archive.org/web/20120607174520/http://www.youtube.com/watch?v=xWTLLl-dQaA',
566 'info_dict': {
567 'id': 'xWTLLl-dQaA',
568 'ext': 'mp4',
569 'title': 'Black Nerd eHarmony Video Bio Parody (SPOOF)',
570 'uploader_url': 'https://www.youtube.com/user/BlackNerdComedy',
571 'description': 'md5:e25f0133aaf9e6793fb81c18021d193e',
572 'uploader_id': 'BlackNerdComedy',
573 'uploader': 'BlackNerdComedy',
574 'duration': 182,
575 'thumbnail': r're:https?://.*\.(jpg|webp)',
576 }
577 }, {
578 # ~July 2013
579 'url': 'https://web.archive.org/web/*/https://www.youtube.com/watch?v=9eO1aasHyTM',
580 'info_dict': {
581 'id': '9eO1aasHyTM',
582 'ext': 'mp4',
583 'title': 'Polar-oid',
584 'description': 'Cameras and bears are dangerous!',
585 'uploader_url': 'https://www.youtube.com/user/punkybird',
586 'uploader_id': 'punkybird',
587 'duration': 202,
588 'channel_id': 'UC62R2cBezNBOqxSerfb1nMQ',
589 'channel_url': 'https://www.youtube.com/channel/UC62R2cBezNBOqxSerfb1nMQ',
590 'upload_date': '20060428',
591 'uploader': 'punkybird',
592 }
593 }, {
594 # April 2020: Player response in player config
595 'url': 'https://web.archive.org/web/20200416034815/https://www.youtube.com/watch?v=Cf7vS8jc7dY&gl=US&hl=en',
596 'info_dict': {
597 'id': 'Cf7vS8jc7dY',
598 'ext': 'mp4',
599 'title': 'A Dramatic Pool Story (by Jamie Spicer-Lewis) - Game Grumps Animated',
600 'duration': 64,
601 'upload_date': '20200408',
602 'uploader_id': 'GameGrumps',
603 'uploader': 'GameGrumps',
604 'channel_url': 'https://www.youtube.com/channel/UC9CuvdOVfMPvKCiwdGKL3cQ',
605 'channel_id': 'UC9CuvdOVfMPvKCiwdGKL3cQ',
606 'thumbnail': r're:https?://.*\.(jpg|webp)',
607 'description': 'md5:c625bb3c02c4f5fb4205971e468fa341',
608 'uploader_url': 'https://www.youtube.com/user/GameGrumps',
609 }
610 }, {
611 # watch7-user-header with yt-user-info
612 'url': 'ytarchive:kbh4T_b4Ixw:20160307085057',
613 'info_dict': {
614 'id': 'kbh4T_b4Ixw',
615 'ext': 'mp4',
616 'title': 'Shovel Knight OST - Strike the Earth! Plains of Passage 16 bit SNES style remake / remix',
617 'channel_url': 'https://www.youtube.com/channel/UCnTaGvsHmMy792DWeT6HbGA',
618 'uploader': 'Nelward music',
619 'duration': 213,
620 'description': 'md5:804b4a9ce37b050a5fefdbb23aeba54d',
621 'thumbnail': r're:https?://.*\.(jpg|webp)',
622 'upload_date': '20150503',
623 'channel_id': 'UCnTaGvsHmMy792DWeT6HbGA',
624 }
625 }, {
626 # April 2012
627 'url': 'https://web.archive.org/web/0/https://www.youtube.com/watch?v=SOm7mPoPskU',
628 'info_dict': {
629 'id': 'SOm7mPoPskU',
630 'ext': 'mp4',
631 'title': 'Boyfriend - Justin Bieber Parody',
632 'uploader_url': 'https://www.youtube.com/user/thecomputernerd01',
633 'uploader': 'thecomputernerd01',
634 'thumbnail': r're:https?://.*\.(jpg|webp)',
635 'description': 'md5:dd7fa635519c2a5b4d566beaecad7491',
636 'duration': 200,
637 'upload_date': '20120407',
638 'uploader_id': 'thecomputernerd01',
aa4b0545 639 }
640 }, {
641 'url': 'https://web.archive.org/web/http://www.youtube.com/watch?v=kH-G_aIBlFw',
642 'only_matching': True
643 }, {
644 'url': 'https://web.archive.org/web/20050214000000_if/http://www.youtube.com/watch?v=0altSZ96U4M',
645 'only_matching': True
646 }, {
879e7199 647 # Video not archived, only capture is unavailable video page
648 'url': 'https://web.archive.org/web/20210530071008/https://www.youtube.com/watch?v=lHJTf93HL1s&spfreload=10',
aa4b0545 649 'only_matching': True
650 }, { # Encoded url
879e7199 651 'url': 'https://web.archive.org/web/20120712231619/http%3A//www.youtube.com/watch%3Fgl%3DUS%26v%3DAkhihxRKcrs%26hl%3Den',
aa4b0545 652 'only_matching': True
653 }, {
879e7199 654 'url': 'https://web.archive.org/web/20120712231619/http%3A//www.youtube.com/watch%3Fv%3DAkhihxRKcrs%26gl%3DUS%26hl%3Den',
aa4b0545 655 'only_matching': True
656 }, {
657 'url': 'https://web.archive.org/web/20060527081937/http://www.youtube.com:80/watch.php?v=ELTFsLT73fA&amp;search=soccer',
658 'only_matching': True
659 }, {
660 'url': 'https://web.archive.org/http://www.youtube.com:80/watch?v=-05VVye-ffg',
661 'only_matching': True
1f13021e 662 }, {
663 'url': 'ytarchive:BaW_jenozKc:20050214000000',
664 'only_matching': True
88f23a18 665 }, {
1f13021e 666 'url': 'ytarchive:BaW_jenozKc',
667 'only_matching': True
668 },
879e7199 669 ]
b7c47b74 670 _YT_INITIAL_DATA_RE = YoutubeBaseInfoExtractor._YT_INITIAL_DATA_RE
19b4e59a 671 _YT_INITIAL_PLAYER_RESPONSE_RE = fr'''(?x:
b7c47b74 672 (?:window\s*\[\s*["\']ytInitialPlayerResponse["\']\s*\]|ytInitialPlayerResponse)\s*=[(\s]*|
19b4e59a 673 {YoutubeBaseInfoExtractor._YT_INITIAL_PLAYER_RESPONSE_RE}
674 )'''
aa4b0545 675
676 _YT_DEFAULT_THUMB_SERVERS = ['i.ytimg.com'] # thumbnails most likely archived on these servers
677 _YT_ALL_THUMB_SERVERS = orderedSet(
678 _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)]])
679
680 _WAYBACK_BASE_URL = 'https://web.archive.org/web/%sif_/'
681 _OLDEST_CAPTURE_DATE = 20050214000000
682 _NEWEST_CAPTURE_DATE = 20500101000000
683
c8e856a5 684 def _call_cdx_api(self, item_id, url, filters: list = None, collapse: list = None, query: dict = None, note=None, fatal=False):
aa4b0545 685 # CDX docs: https://github.com/internetarchive/wayback/blob/master/wayback-cdx-server/README.md
686 query = {
687 'url': url,
688 'output': 'json',
689 'fl': 'original,mimetype,length,timestamp',
690 'limit': 500,
691 'filter': ['statuscode:200'] + (filters or []),
692 'collapse': collapse or [],
693 **(query or {})
694 }
c8e856a5 695 res = self._download_json(
696 'https://web.archive.org/cdx/search/cdx', item_id,
697 note or 'Downloading CDX API JSON', query=query, fatal=fatal)
aa4b0545 698 if isinstance(res, list) and len(res) >= 2:
699 # format response to make it easier to use
700 return list(dict(zip(res[0], v)) for v in res[1:])
701 elif not isinstance(res, list) or len(res) != 0:
702 self.report_warning('Error while parsing CDX API response' + bug_reports_message())
703
aa4b0545 704 def _extract_webpage_title(self, webpage):
04f3fd2c 705 page_title = self._html_extract_title(webpage, default='')
aa4b0545 706 # YouTube video pages appear to always have either 'YouTube -' as prefix or '- YouTube' as suffix.
707 return self._html_search_regex(
708 r'(?:YouTube\s*-\s*(.*)$)|(?:(.*)\s*-\s*YouTube$)',
709 page_title, 'title', default='')
710
711 def _extract_metadata(self, video_id, webpage):
aa4b0545 712 search_meta = ((lambda x: self._html_search_meta(x, webpage, default=None)) if webpage else (lambda x: None))
b7c47b74 713 player_response = self._search_json(
714 self._YT_INITIAL_PLAYER_RESPONSE_RE, webpage, 'initial player response',
f0bc6e20 715 video_id, default={})
b7c47b74 716 initial_data = self._search_json(
f0bc6e20 717 self._YT_INITIAL_DATA_RE, webpage, 'initial data', video_id, default={})
aa4b0545 718
217753f4
M
719 ytcfg = {}
720 for j in re.findall(r'yt\.setConfig\(\s*(?P<json>{\s*(?s:.+?)\s*})\s*\);', webpage): # ~June 2010
721 ytcfg.update(self._parse_json(j, video_id, fatal=False, ignore_extra=True, transform_source=js_to_json, errnote='') or {})
722
723 # XXX: this also may contain a 'ptchn' key
724 player_config = (
725 self._search_json(
726 r'(?:yt\.playerConfig|ytplayer\.config|swfConfig)\s*=',
727 webpage, 'player config', video_id, default=None)
728 or ytcfg.get('PLAYER_CONFIG') or {})
729
730 # XXX: this may also contain a 'creator' key.
731 swf_args = self._search_json(r'swfArgs\s*=', webpage, 'swf config', video_id, default={})
732 if swf_args and not traverse_obj(player_config, ('args',)):
733 player_config['args'] = swf_args
734
735 if not player_response:
736 # April 2020
737 player_response = self._parse_json(
738 traverse_obj(player_config, ('args', 'player_response')) or '{}', video_id, fatal=False)
739
aa4b0545 740 initial_data_video = traverse_obj(
741 initial_data, ('contents', 'twoColumnWatchNextResults', 'results', 'results', 'contents', ..., 'videoPrimaryInfoRenderer'),
742 expected_type=dict, get_all=False, default={})
743
744 video_details = traverse_obj(
745 player_response, 'videoDetails', expected_type=dict, get_all=False, default={})
746
747 microformats = traverse_obj(
748 player_response, ('microformat', 'playerMicroformatRenderer'), expected_type=dict, get_all=False, default={})
749
750 video_title = (
751 video_details.get('title')
752 or YoutubeBaseInfoExtractor._get_text(microformats, 'title')
753 or YoutubeBaseInfoExtractor._get_text(initial_data_video, 'title')
217753f4 754 or traverse_obj(player_config, ('args', 'title'))
aa4b0545 755 or self._extract_webpage_title(webpage)
756 or search_meta(['og:title', 'twitter:title', 'title']))
757
217753f4
M
758 def id_from_url(url, type_):
759 return self._search_regex(
760 rf'(?:{type_})/([^/#&?]+)', url or '', f'{type_} id', default=None)
761
762 # XXX: would the get_elements_by_... functions be better suited here?
763 _CHANNEL_URL_HREF_RE = r'href="[^"]*(?P<url>https?://www\.youtube\.com/(?:user|channel)/[^"]+)"'
764 uploader_or_channel_url = self._search_regex(
765 [fr'<(?:link\s*itemprop=\"url\"|a\s*id=\"watch-username\").*?\b{_CHANNEL_URL_HREF_RE}>', # @fd05024
766 fr'<div\s*id=\"(?:watch-channel-stats|watch-headline-user-info)\"[^>]*>\s*<a[^>]*\b{_CHANNEL_URL_HREF_RE}'], # ~ May 2009, ~June 2012
767 webpage, 'uploader or channel url', default=None)
768
769 owner_profile_url = url_or_none(microformats.get('ownerProfileUrl')) # @a6211d2
770
771 # Uploader refers to the /user/ id ONLY
772 uploader_id = (
773 id_from_url(owner_profile_url, 'user')
774 or id_from_url(uploader_or_channel_url, 'user')
775 or ytcfg.get('VIDEO_USERNAME'))
776 uploader_url = f'https://www.youtube.com/user/{uploader_id}' if uploader_id else None
777
778 # XXX: do we want to differentiate uploader and channel?
779 uploader = (
780 self._search_regex(
781 [r'<a\s*id="watch-username"[^>]*>\s*<strong>([^<]+)</strong>', # June 2010
782 r'var\s*watchUsername\s*=\s*\'(.+?)\';', # ~May 2009
783 r'<div\s*\bid=\"watch-channel-stats"[^>]*>\s*<a[^>]*>\s*(.+?)\s*</a', # ~May 2009
784 r'<a\s*id="watch-userbanner"[^>]*title="\s*(.+?)\s*"'], # ~June 2012
785 webpage, 'uploader', default=None)
786 or self._html_search_regex(
787 [r'(?s)<div\s*class="yt-user-info".*?<a[^>]*[^>]*>\s*(.*?)\s*</a', # March 2016
788 r'(?s)<a[^>]*yt-user-name[^>]*>\s*(.*?)\s*</a'], # july 2013
789 get_element_by_id('watch7-user-header', webpage), 'uploader', default=None)
790 or self._html_search_regex(
791 r'<button\s*href="/user/[^>]*>\s*<span[^>]*>\s*(.+?)\s*<', # April 2012
792 get_element_by_id('watch-headline-user-info', webpage), 'uploader', default=None)
793 or traverse_obj(player_config, ('args', 'creator'))
794 or video_details.get('author'))
795
aa4b0545 796 channel_id = str_or_none(
797 video_details.get('channelId')
798 or microformats.get('externalChannelId')
799 or search_meta('channelId')
800 or self._search_regex(
801 r'data-channel-external-id=(["\'])(?P<id>(?:(?!\1).)+)\1', # @b45a9e6
217753f4
M
802 webpage, 'channel id', default=None, group='id')
803 or id_from_url(owner_profile_url, 'channel')
804 or id_from_url(uploader_or_channel_url, 'channel')
805 or traverse_obj(player_config, ('args', 'ucid')))
aa4b0545 806
217753f4 807 channel_url = f'https://www.youtube.com/channel/{channel_id}' if channel_id else None
aa4b0545 808 duration = int_or_none(
809 video_details.get('lengthSeconds')
810 or microformats.get('lengthSeconds')
217753f4 811 or traverse_obj(player_config, ('args', ('length_seconds', 'l')), get_all=False)
aa4b0545 812 or parse_duration(search_meta('duration')))
813 description = (
814 video_details.get('shortDescription')
815 or YoutubeBaseInfoExtractor._get_text(microformats, 'description')
816 or clean_html(get_element_by_id('eow-description', webpage)) # @9e6dd23
817 or search_meta(['description', 'og:description', 'twitter:description']))
818
aa4b0545 819 upload_date = unified_strdate(
820 dict_get(microformats, ('uploadDate', 'publishDate'))
821 or search_meta(['uploadDate', 'datePublished'])
822 or self._search_regex(
217753f4
M
823 [r'(?s)id="eow-date.*?>\s*(.*?)\s*</span>',
824 r'(?:id="watch-uploader-info".*?>.*?|["\']simpleText["\']\s*:\s*["\'])(?:Published|Uploaded|Streamed live|Started) on (.+?)[<"\']', # @7998520
825 r'class\s*=\s*"(?:watch-video-date|watch-video-added post-date)"[^>]*>\s*([^<]+?)\s*<'], # ~June 2010, ~Jan 2009 (respectively)
aa4b0545 826 webpage, 'upload date', default=None))
827
828 return {
829 'title': video_title,
830 'description': description,
831 'upload_date': upload_date,
832 'uploader': uploader,
833 'channel_id': channel_id,
834 'channel_url': channel_url,
835 'duration': duration,
836 'uploader_url': uploader_url,
837 'uploader_id': uploader_id,
838 }
839
840 def _extract_thumbnails(self, video_id):
841 try_all = 'thumbnails' in self._configuration_arg('check_all')
842 thumbnail_base_urls = ['http://{server}/vi{webp}/{video_id}'.format(
843 webp='_webp' if ext == 'webp' else '', video_id=video_id, server=server)
844 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',))]
845
846 thumbnails = []
847 for url in thumbnail_base_urls:
848 response = self._call_cdx_api(
849 video_id, url, filters=['mimetype:image/(?:webp|jpeg)'],
850 collapse=['urlkey'], query={'matchType': 'prefix'})
851 if not response:
852 continue
853 thumbnails.extend(
854 {
855 'url': (self._WAYBACK_BASE_URL % (int_or_none(thumbnail_dict.get('timestamp')) or self._OLDEST_CAPTURE_DATE)) + thumbnail_dict.get('original'),
856 'filesize': int_or_none(thumbnail_dict.get('length')),
857 'preference': int_or_none(thumbnail_dict.get('length'))
858 } for thumbnail_dict in response)
859 if not try_all:
860 break
861
862 self._remove_duplicate_formats(thumbnails)
863 return thumbnails
864
865 def _get_capture_dates(self, video_id, url_date):
866 capture_dates = []
867 # Note: CDX API will not find watch pages with extra params in the url.
868 response = self._call_cdx_api(
869 video_id, f'https://www.youtube.com/watch?v={video_id}',
870 filters=['mimetype:text/html'], collapse=['timestamp:6', 'digest'], query={'matchType': 'prefix'}) or []
86e5f3ed 871 all_captures = sorted(int_or_none(r['timestamp']) for r in response if int_or_none(r['timestamp']) is not None)
aa4b0545 872
873 # Prefer the new polymer UI captures as we support extracting more metadata from them
874 # WBM captures seem to all switch to this layout ~July 2020
1f13021e 875 modern_captures = [x for x in all_captures if x >= 20200701000000]
aa4b0545 876 if modern_captures:
877 capture_dates.append(modern_captures[0])
878 capture_dates.append(url_date)
879 if all_captures:
880 capture_dates.append(all_captures[0])
881
882 if 'captures' in self._configuration_arg('check_all'):
883 capture_dates.extend(modern_captures + all_captures)
884
885 # Fallbacks if any of the above fail
886 capture_dates.extend([self._OLDEST_CAPTURE_DATE, self._NEWEST_CAPTURE_DATE])
1f13021e 887 return orderedSet(filter(None, capture_dates))
879e7199 888
889 def _real_extract(self, url):
1f13021e 890 video_id, url_date, url_date_2 = self._match_valid_url(url).group('id', 'date', 'date2')
891 url_date = url_date or url_date_2
aa4b0545 892
893 urlh = None
217753f4
M
894 retry_manager = self.RetryManager(fatal=False)
895 for retry in retry_manager:
896 try:
897 urlh = self._request_webpage(
898 HEADRequest('https://web.archive.org/web/2oe_/http://wayback-fakeurl.archive.org/yt/%s' % video_id),
899 video_id, note='Fetching archived video file url', expected_status=True)
900 except ExtractorError as e:
901 # HTTP Error 404 is expected if the video is not saved.
902 if isinstance(e.cause, compat_HTTPError) and e.cause.code == 404:
903 self.raise_no_formats(
904 'The requested video is not archived, indexed, or there is an issue with web.archive.org (try again later)', expected=True)
905 else:
906 retry.error = e
907
908 if retry_manager.error:
909 self.raise_no_formats(retry_manager.error, expected=True, video_id=video_id)
aa4b0545 910
911 capture_dates = self._get_capture_dates(video_id, int_or_none(url_date))
1f13021e 912 self.write_debug('Captures to try: ' + join_nonempty(*capture_dates, delim=', '))
aa4b0545 913 info = {'id': video_id}
914 for capture in capture_dates:
aa4b0545 915 webpage = self._download_webpage(
916 (self._WAYBACK_BASE_URL + 'http://www.youtube.com/watch?v=%s') % (capture, video_id),
917 video_id=video_id, fatal=False, errnote='unable to download capture webpage (it may not be archived)',
918 note='Downloading capture webpage')
919 current_info = self._extract_metadata(video_id, webpage or '')
920 # Try avoid getting deleted video metadata
921 if current_info.get('title'):
922 info = merge_dicts(info, current_info)
923 if 'captures' not in self._configuration_arg('check_all'):
924 break
925
926 info['thumbnails'] = self._extract_thumbnails(video_id)
927
928 if urlh:
1f13021e 929 url = compat_urllib_parse_unquote(urlh.geturl())
aa4b0545 930 video_file_url_qs = parse_qs(url)
931 # Attempt to recover any ext & format info from playback url & response headers
932 format = {'url': url, 'filesize': int_or_none(urlh.headers.get('x-archive-orig-content-length'))}
933 itag = try_get(video_file_url_qs, lambda x: x['itag'][0])
934 if itag and itag in YoutubeIE._formats:
935 format.update(YoutubeIE._formats[itag])
936 format.update({'format_id': itag})
937 else:
938 mime = try_get(video_file_url_qs, lambda x: x['mime'][0])
939 ext = (mimetype2ext(mime)
940 or urlhandle_detect_ext(urlh)
941 or mimetype2ext(urlh.headers.get('x-archive-guessed-content-type')))
942 format.update({'ext': ext})
943 info['formats'] = [format]
944 if not info.get('duration'):
945 info['duration'] = str_to_int(try_get(video_file_url_qs, lambda x: x['dur'][0]))
946
947 if not info.get('title'):
948 info['title'] = video_id
949 return info
b3eaab7c 950
951
952class VLiveWebArchiveIE(InfoExtractor):
953 IE_NAME = 'web.archive:vlive'
954 IE_DESC = 'web.archive.org saved vlive videos'
955 _VALID_URL = r'''(?x)
956 (?:https?://)?web\.archive\.org/
957 (?:web/)?(?:(?P<date>[0-9]{14})?[0-9A-Za-z_*]*/)? # /web and the version index is optional
958 (?:https?(?::|%3[Aa])//)?(?:
959 (?:(?:www|m)\.)?vlive\.tv(?::(?:80|443))?/(?:video|embed)/(?P<id>[0-9]+) # VLive URL
960 )
961 '''
962 _TESTS = [{
963 'url': 'https://web.archive.org/web/20221221144331/http://www.vlive.tv/video/1326',
964 'md5': 'cc7314812855ce56de70a06a27314983',
965 'info_dict': {
966 'id': '1326',
967 'ext': 'mp4',
968 'title': "Girl's Day's Broadcast",
969 'creator': "Girl's Day",
970 'view_count': int,
971 'uploader_id': 'muploader_a',
972 'uploader_url': None,
973 'uploader': None,
974 'upload_date': '20150817',
975 'thumbnail': r're:^https?://.*\.(?:jpg|png)$',
976 'timestamp': 1439816449,
977 'like_count': int,
978 'channel': 'Girl\'s Day',
979 'channel_id': 'FDF27',
980 'comment_count': int,
981 'release_timestamp': 1439818140,
982 'release_date': '20150817',
983 'duration': 1014,
984 },
985 'params': {
986 'skip_download': True,
987 },
988 }, {
989 'url': 'https://web.archive.org/web/20221221182103/http://www.vlive.tv/video/16937',
990 'info_dict': {
991 'id': '16937',
992 'ext': 'mp4',
993 'title': '첸백시 걍방',
994 'creator': 'EXO',
995 'view_count': int,
996 'subtitles': 'mincount:12',
997 'uploader_id': 'muploader_j',
998 'uploader_url': 'http://vlive.tv',
999 'uploader': None,
1000 'upload_date': '20161112',
1001 'thumbnail': r're:^https?://.*\.(?:jpg|png)$',
1002 'timestamp': 1478923074,
1003 'like_count': int,
1004 'channel': 'EXO',
1005 'channel_id': 'F94BD',
1006 'comment_count': int,
1007 'release_timestamp': 1478924280,
1008 'release_date': '20161112',
1009 'duration': 906,
1010 },
1011 'params': {
1012 'skip_download': True,
1013 },
1014 }, {
1015 'url': 'https://web.archive.org/web/20221127190050/http://www.vlive.tv/video/101870',
1016 'info_dict': {
1017 'id': '101870',
1018 'ext': 'mp4',
1019 'title': '[ⓓ xV] “레벨이들 매력에 반해? 안 반해?” 움직이는 HD 포토 (레드벨벳:Red Velvet)',
1020 'creator': 'Dispatch',
1021 'view_count': int,
1022 'subtitles': 'mincount:6',
1023 'uploader_id': 'V__FRA08071',
1024 'uploader_url': 'http://vlive.tv',
1025 'uploader': None,
1026 'upload_date': '20181130',
1027 'thumbnail': r're:^https?://.*\.(?:jpg|png)$',
1028 'timestamp': 1543601327,
1029 'like_count': int,
1030 'channel': 'Dispatch',
1031 'channel_id': 'C796F3',
1032 'comment_count': int,
1033 'release_timestamp': 1543601040,
1034 'release_date': '20181130',
1035 'duration': 279,
1036 },
1037 'params': {
1038 'skip_download': True,
1039 },
1040 }]
1041
1042 # The wayback machine has special timestamp and "mode" values:
1043 # timestamp:
1044 # 1 = the first capture
1045 # 2 = the last capture
1046 # mode:
1047 # id_ = Identity - perform no alterations of the original resource, return it as it was archived.
1048 _WAYBACK_BASE_URL = 'https://web.archive.org/web/2id_/'
1049
1050 def _download_archived_page(self, url, video_id, *, timestamp='2', **kwargs):
1051 for retry in self.RetryManager():
1052 try:
1053 return self._download_webpage(f'https://web.archive.org/web/{timestamp}id_/{url}', video_id, **kwargs)
1054 except ExtractorError as e:
1055 if isinstance(e.cause, urllib.error.HTTPError) and e.cause.code == 404:
1056 raise ExtractorError('Page was not archived', expected=True)
1057 retry.error = e
1058 continue
1059
1060 def _download_archived_json(self, url, video_id, **kwargs):
1061 page = self._download_archived_page(url, video_id, **kwargs)
1062 if not page:
1063 raise ExtractorError('Page was not archived', expected=True)
1064 else:
1065 return self._parse_json(page, video_id)
1066
1067 def _extract_formats_from_m3u8(self, m3u8_url, params, video_id):
1068 m3u8_doc = self._download_archived_page(m3u8_url, video_id, note='Downloading m3u8', query=params, fatal=False)
1069 if not m3u8_doc:
1070 return
1071
1072 # M3U8 document should be changed to archive domain
1073 m3u8_doc = m3u8_doc.splitlines()
1074 url_base = m3u8_url.rsplit('/', 1)[0]
1075 first_segment = None
1076 for i, line in enumerate(m3u8_doc):
1077 if not line.startswith('#'):
1078 m3u8_doc[i] = f'{self._WAYBACK_BASE_URL}{url_base}/{line}?{urllib.parse.urlencode(params)}'
1079 first_segment = first_segment or m3u8_doc[i]
1080
1081 # Segments may not have been archived. See https://web.archive.org/web/20221127190050/http://www.vlive.tv/video/101870
1082 urlh = self._request_webpage(HEADRequest(first_segment), video_id, errnote=False,
1083 fatal=False, note='Check first segment availablity')
1084 if urlh:
1085 formats, subtitles = self._parse_m3u8_formats_and_subtitles('\n'.join(m3u8_doc), ext='mp4', video_id=video_id)
1086 if subtitles:
1087 self._report_ignoring_subs('m3u8')
1088 return formats
1089
1090 # Closely follows the logic of the ArchiveTeam grab script
1091 # See: https://github.com/ArchiveTeam/vlive-grab/blob/master/vlive.lua
1092 def _real_extract(self, url):
1093 video_id, url_date = self._match_valid_url(url).group('id', 'date')
1094
1095 webpage = self._download_archived_page(f'https://www.vlive.tv/video/{video_id}', video_id, timestamp=url_date)
1096
1097 player_info = self._search_json(r'__PRELOADED_STATE__\s*=', webpage, 'player info', video_id)
1098 user_country = traverse_obj(player_info, ('common', 'userCountry'))
1099
1100 main_script_url = self._search_regex(r'<script\s+src="([^"]+/js/main\.[^"]+\.js)"', webpage, 'main script url')
1101 main_script = self._download_archived_page(main_script_url, video_id, note='Downloading main script')
1102 app_id = self._search_regex(r'appId\s*=\s*"([^"]+)"', main_script, 'app id')
1103
1104 inkey = self._download_archived_json(
1105 f'https://www.vlive.tv/globalv-web/vam-web/video/v1.0/vod/{video_id}/inkey', video_id, note='Fetching inkey', query={
1106 'appId': app_id,
1107 'platformType': 'PC',
1108 'gcc': user_country,
1109 'locale': 'en_US',
1110 }, fatal=False)
1111
1112 vod_id = traverse_obj(player_info, ('postDetail', 'post', 'officialVideo', 'vodId'))
1113
1114 vod_data = self._download_archived_json(
1115 f'https://apis.naver.com/rmcnmv/rmcnmv/vod/play/v2.0/{vod_id}', video_id, note='Fetching vod data', query={
1116 'key': inkey.get('inkey'),
1117 'pid': 'rmcPlayer_16692457559726800', # partially unix time and partially random. Fixed value used by archiveteam project
1118 'sid': '2024',
1119 'ver': '2.0',
1120 'devt': 'html5_pc',
1121 'doct': 'json',
1122 'ptc': 'https',
1123 'sptc': 'https',
1124 'cpt': 'vtt',
1125 'ctls': '%7B%22visible%22%3A%7B%22fullscreen%22%3Atrue%2C%22logo%22%3Afalse%2C%22playbackRate%22%3Afalse%2C%22scrap%22%3Afalse%2C%22playCount%22%3Atrue%2C%22commentCount%22%3Atrue%2C%22title%22%3Atrue%2C%22writer%22%3Atrue%2C%22expand%22%3Afalse%2C%22subtitles%22%3Atrue%2C%22thumbnails%22%3Atrue%2C%22quality%22%3Atrue%2C%22setting%22%3Atrue%2C%22script%22%3Afalse%2C%22logoDimmed%22%3Atrue%2C%22badge%22%3Atrue%2C%22seekingTime%22%3Atrue%2C%22muted%22%3Atrue%2C%22muteButton%22%3Afalse%2C%22viewerNotice%22%3Afalse%2C%22linkCount%22%3Afalse%2C%22createTime%22%3Afalse%2C%22thumbnail%22%3Atrue%7D%2C%22clicked%22%3A%7B%22expand%22%3Afalse%2C%22subtitles%22%3Afalse%7D%7D',
1126 'pv': '4.26.9',
1127 'dr': '1920x1080',
1128 'cpl': 'en_US',
1129 'lc': 'en_US',
1130 'adi': '%5B%7B%22type%22%3A%22pre%22%2C%22exposure%22%3Afalse%2C%22replayExposure%22%3Afalse%7D%5D',
1131 'adu': '%2F',
1132 'videoId': vod_id,
1133 'cc': user_country,
1134 })
1135
1136 formats = []
1137
1138 streams = traverse_obj(vod_data, ('streams', ...))
1139 if len(streams) > 1:
1140 self.report_warning('Multiple streams found. Only the first stream will be downloaded.')
1141 stream = streams[0]
1142
1143 max_stream = max(
1144 stream.get('videos') or [],
1145 key=lambda v: traverse_obj(v, ('bitrate', 'video'), default=0), default=None)
1146 if max_stream is not None:
1147 params = {arg.get('name'): arg.get('value') for arg in stream.get('keys', []) if arg.get('type') == 'param'}
1148 formats = self._extract_formats_from_m3u8(max_stream.get('source'), params, video_id) or []
1149
1150 # For parts of the project MP4 files were archived
1151 max_video = max(
1152 traverse_obj(vod_data, ('videos', 'list', ...)),
1153 key=lambda v: traverse_obj(v, ('bitrate', 'video'), default=0), default=None)
1154 if max_video is not None:
1155 video_url = self._WAYBACK_BASE_URL + max_video.get('source')
1156 urlh = self._request_webpage(HEADRequest(video_url), video_id, errnote=False,
1157 fatal=False, note='Check video availablity')
1158 if urlh:
1159 formats.append({'url': video_url})
1160
1161 return {
1162 'id': video_id,
1163 'formats': formats,
1164 **traverse_obj(player_info, ('postDetail', 'post', {
1165 'title': ('officialVideo', 'title', {str}),
1166 'creator': ('author', 'nickname', {str}),
1167 'channel': ('channel', 'channelName', {str}),
1168 'channel_id': ('channel', 'channelCode', {str}),
1169 'duration': ('officialVideo', 'playTime', {int_or_none}),
1170 'view_count': ('officialVideo', 'playCount', {int_or_none}),
1171 'like_count': ('officialVideo', 'likeCount', {int_or_none}),
1172 'comment_count': ('officialVideo', 'commentCount', {int_or_none}),
1173 'timestamp': ('officialVideo', 'createdAt', {lambda x: int_or_none(x, scale=1000)}),
1174 'release_timestamp': ('officialVideo', 'willStartAt', {lambda x: int_or_none(x, scale=1000)}),
1175 })),
1176 **traverse_obj(vod_data, ('meta', {
1177 'uploader_id': ('user', 'id', {str}),
1178 'uploader': ('user', 'name', {str}),
1179 'uploader_url': ('user', 'url', {url_or_none}),
1180 'thumbnail': ('cover', 'source', {url_or_none}),
1181 }), expected_type=lambda x: x or None),
1182 **NaverBaseIE.process_subtitles(vod_data, lambda x: [self._WAYBACK_BASE_URL + x]),
1183 }