]> jfr.im git - yt-dlp.git/blame_incremental - yt_dlp/extractor/facebook.py
[ie/facebook] Improve subtitles extraction (#8296)
[yt-dlp.git] / yt_dlp / extractor / facebook.py
... / ...
CommitLineData
1import json
2import re
3import urllib.parse
4
5from .common import InfoExtractor
6from ..compat import (
7 compat_etree_fromstring,
8 compat_str,
9 compat_urllib_parse_unquote,
10)
11from ..networking import Request
12from ..networking.exceptions import network_exceptions
13from ..utils import (
14 ExtractorError,
15 clean_html,
16 determine_ext,
17 error_to_compat_str,
18 float_or_none,
19 format_field,
20 get_element_by_id,
21 get_first,
22 int_or_none,
23 js_to_json,
24 merge_dicts,
25 parse_count,
26 parse_qs,
27 qualities,
28 str_or_none,
29 traverse_obj,
30 try_get,
31 url_or_none,
32 urlencode_postdata,
33 urljoin,
34 variadic,
35)
36
37
38class FacebookIE(InfoExtractor):
39 _VALID_URL = r'''(?x)
40 (?:
41 https?://
42 (?:[\w-]+\.)?(?:facebook\.com|facebookwkhpilnemxj7asaniu7vnjjbiltxjqhye3mhbshg7kx5tfyd\.onion)/
43 (?:[^#]*?\#!/)?
44 (?:
45 (?:
46 video/video\.php|
47 photo\.php|
48 video\.php|
49 video/embed|
50 story\.php|
51 watch(?:/live)?/?
52 )\?(?:.*?)(?:v|video_id|story_fbid)=|
53 [^/]+/videos/(?:[^/]+/)?|
54 [^/]+/posts/|
55 groups/[^/]+/permalink/|
56 watchparty/
57 )|
58 facebook:
59 )
60 (?P<id>[0-9]+)
61 '''
62 _EMBED_REGEX = [
63 r'<iframe[^>]+?src=(["\'])(?P<url>https?://www\.facebook\.com/(?:video/embed|plugins/video\.php).+?)\1',
64 # Facebook API embed https://developers.facebook.com/docs/plugins/embedded-video-player
65 r'''(?x)<div[^>]+
66 class=(?P<q1>[\'"])[^\'"]*\bfb-(?:video|post)\b[^\'"]*(?P=q1)[^>]+
67 data-href=(?P<q2>[\'"])(?P<url>(?:https?:)?//(?:www\.)?facebook.com/.+?)(?P=q2)''',
68 ]
69 _LOGIN_URL = 'https://www.facebook.com/login.php?next=http%3A%2F%2Ffacebook.com%2Fhome.php&login_attempt=1'
70 _CHECKPOINT_URL = 'https://www.facebook.com/checkpoint/?next=http%3A%2F%2Ffacebook.com%2Fhome.php&_fb_noscript=1'
71 _NETRC_MACHINE = 'facebook'
72 IE_NAME = 'facebook'
73
74 _VIDEO_PAGE_TEMPLATE = 'https://www.facebook.com/video/video.php?v=%s'
75 _VIDEO_PAGE_TAHOE_TEMPLATE = 'https://www.facebook.com/video/tahoe/async/%s/?chain=true&isvideo=true&payloadtype=primary'
76
77 _TESTS = [{
78 'url': 'https://www.facebook.com/radiokicksfm/videos/3676516585958356/',
79 'info_dict': {
80 'id': '3676516585958356',
81 'ext': 'mp4',
82 'title': 'dr Adam Przygoda',
83 'description': 'md5:34675bda53336b1d16400265c2bb9b3b',
84 'uploader': 'RADIO KICKS FM',
85 'upload_date': '20230818',
86 'timestamp': 1692346159,
87 'thumbnail': r're:^https?://.*',
88 'uploader_id': '100063551323670',
89 'duration': 3132.184,
90 'view_count': int,
91 'concurrent_view_count': 0,
92 },
93 }, {
94 'url': 'https://www.facebook.com/video.php?v=637842556329505&fref=nf',
95 'md5': '6a40d33c0eccbb1af76cf0485a052659',
96 'info_dict': {
97 'id': '637842556329505',
98 'ext': 'mp4',
99 'title': 're:Did you know Kei Nishikori is the first Asian man to ever reach a Grand Slam',
100 'uploader': 'Tennis on Facebook',
101 'upload_date': '20140908',
102 'timestamp': 1410199200,
103 },
104 'skip': 'Requires logging in',
105 }, {
106 # data.video
107 'url': 'https://www.facebook.com/video.php?v=274175099429670',
108 'info_dict': {
109 'id': '274175099429670',
110 'ext': 'mp4',
111 'title': 'Asif',
112 'description': '',
113 'uploader': 'Asif Nawab Butt',
114 'upload_date': '20140506',
115 'timestamp': 1399398998,
116 'thumbnail': r're:^https?://.*',
117 'uploader_id': 'pfbid028wxorhX2ErLFJ578N6P3crHD3PHmXTCqCvfBpsnbSLmbokwSY75p5hWBjHGkG4zxl',
118 'duration': 131.03,
119 'concurrent_view_count': int,
120 },
121 }, {
122 'note': 'Video with DASH manifest',
123 'url': 'https://www.facebook.com/video.php?v=957955867617029',
124 'md5': 'b2c28d528273b323abe5c6ab59f0f030',
125 'info_dict': {
126 'id': '957955867617029',
127 'ext': 'mp4',
128 'title': 'When you post epic content on instagram.com/433 8 million followers, this is ...',
129 'uploader': 'Demy de Zeeuw',
130 'upload_date': '20160110',
131 'timestamp': 1452431627,
132 },
133 'skip': 'Requires logging in',
134 }, {
135 'url': 'https://www.facebook.com/maxlayn/posts/10153807558977570',
136 'md5': '037b1fa7f3c2d02b7a0d7bc16031ecc6',
137 'info_dict': {
138 'id': '544765982287235',
139 'ext': 'mp4',
140 'title': '"What are you doing running in the snow?"',
141 'uploader': 'FailArmy',
142 },
143 'skip': 'Video gone',
144 }, {
145 'url': 'https://m.facebook.com/story.php?story_fbid=1035862816472149&id=116132035111903',
146 'md5': '1deb90b6ac27f7efcf6d747c8a27f5e3',
147 'info_dict': {
148 'id': '1035862816472149',
149 'ext': 'mp4',
150 'title': 'What the Flock Is Going On In New Zealand Credit: ViralHog',
151 'uploader': 'S. Saint',
152 },
153 'skip': 'Video gone',
154 }, {
155 'note': 'swf params escaped',
156 'url': 'https://www.facebook.com/barackobama/posts/10153664894881749',
157 'md5': '97ba073838964d12c70566e0085c2b91',
158 'info_dict': {
159 'id': '10153664894881749',
160 'ext': 'mp4',
161 'title': 'Average time to confirm recent Supreme Court nominees: 67 days Longest it\'s t...',
162 'thumbnail': r're:^https?://.*',
163 'timestamp': 1456259628,
164 'upload_date': '20160223',
165 'uploader': 'Barack Obama',
166 },
167 'skip': 'Gif on giphy.com gone',
168 }, {
169 # have 1080P, but only up to 720p in swf params
170 # data.video.story.attachments[].media
171 'url': 'https://www.facebook.com/cnn/videos/10155529876156509/',
172 'md5': 'ca63897a90c9452efee5f8c40d080e25',
173 'info_dict': {
174 'id': '10155529876156509',
175 'ext': 'mp4',
176 'title': 'Holocaust survivor becomes US citizen',
177 'description': 'She survived the holocaust — and years later, she’s getting her citizenship so she can vote for Hillary Clinton http://cnn.it/2eERh5f',
178 'timestamp': 1477818095,
179 'upload_date': '20161030',
180 'uploader': 'CNN',
181 'thumbnail': r're:^https?://.*',
182 'view_count': int,
183 'uploader_id': '100059479812265',
184 'concurrent_view_count': int,
185 'duration': 44.478,
186 },
187 }, {
188 # bigPipe.onPageletArrive ... onPageletArrive pagelet_group_mall
189 # data.node.comet_sections.content.story.attachments[].style_type_renderer.attachment.media
190 'url': 'https://www.facebook.com/yaroslav.korpan/videos/1417995061575415/',
191 'info_dict': {
192 'id': '1417995061575415',
193 'ext': 'mp4',
194 'title': 'Довгоочікуване відео | By Yaroslav - Facebook',
195 'description': 'Довгоочікуване відео',
196 'timestamp': 1486648217,
197 'upload_date': '20170209',
198 'uploader': 'Yaroslav Korpan',
199 'uploader_id': 'pfbid06AScABAWcW91qpiuGrLt99Ef9tvwHoXP6t8KeFYEqkSfreMtfa9nTveh8b2ZEVSWl',
200 'concurrent_view_count': int,
201 'thumbnail': r're:^https?://.*',
202 'view_count': int,
203 'duration': 11736.446,
204 },
205 'params': {
206 'skip_download': True,
207 },
208 }, {
209 # FIXME
210 'url': 'https://www.facebook.com/LaGuiaDelVaron/posts/1072691702860471',
211 'info_dict': {
212 'id': '1072691702860471',
213 'ext': 'mp4',
214 'title': 'md5:ae2d22a93fbb12dad20dc393a869739d',
215 'timestamp': 1477305000,
216 'upload_date': '20161024',
217 'uploader': 'La Guía Del Varón',
218 'thumbnail': r're:^https?://.*',
219 },
220 'skip': 'Requires logging in',
221 }, {
222 # data.node.comet_sections.content.story.attachments[].style_type_renderer.attachment.media
223 'url': 'https://www.facebook.com/groups/1024490957622648/permalink/1396382447100162/',
224 'info_dict': {
225 'id': '202882990186699',
226 'ext': 'mp4',
227 'title': 'birb (O v O") | Hello? Yes your uber ride is here',
228 'description': 'Hello? Yes your uber ride is here * Jukin Media Verified * Find this video and others like it by visiting...',
229 'timestamp': 1486035513,
230 'upload_date': '20170202',
231 'uploader': 'Elisabeth Ahtn',
232 'uploader_id': '100013949973717',
233 },
234 'skip': 'Requires logging in',
235 }, {
236 'url': 'https://www.facebook.com/video.php?v=10204634152394104',
237 'only_matching': True,
238 }, {
239 'url': 'https://www.facebook.com/amogood/videos/1618742068337349/?fref=nf',
240 'only_matching': True,
241 }, {
242 # data.mediaset.currMedia.edges
243 'url': 'https://www.facebook.com/ChristyClarkForBC/videos/vb.22819070941/10153870694020942/?type=2&theater',
244 'only_matching': True,
245 }, {
246 # data.video.story.attachments[].media
247 'url': 'facebook:544765982287235',
248 'only_matching': True,
249 }, {
250 # data.node.comet_sections.content.story.attachments[].style_type_renderer.attachment.media
251 'url': 'https://www.facebook.com/groups/164828000315060/permalink/764967300301124/',
252 'only_matching': True,
253 }, {
254 # data.video.creation_story.attachments[].media
255 'url': 'https://zh-hk.facebook.com/peoplespower/videos/1135894589806027/',
256 'only_matching': True,
257 }, {
258 # data.video
259 'url': 'https://www.facebookwkhpilnemxj7asaniu7vnjjbiltxjqhye3mhbshg7kx5tfyd.onion/video.php?v=274175099429670',
260 'only_matching': True,
261 }, {
262 # no title
263 'url': 'https://www.facebook.com/onlycleverentertainment/videos/1947995502095005/',
264 'only_matching': True,
265 }, {
266 # data.video
267 'url': 'https://www.facebook.com/WatchESLOne/videos/359649331226507/',
268 'info_dict': {
269 'id': '359649331226507',
270 'ext': 'mp4',
271 'title': 'Fnatic vs. EG - Group A - Opening Match - ESL One Birmingham Day 1',
272 'description': '#ESLOne VoD - Birmingham Finals Day#1 Fnatic vs. @Evil Geniuses',
273 'timestamp': 1527084179,
274 'upload_date': '20180523',
275 'uploader': 'ESL One Dota 2',
276 'uploader_id': '100066514874195',
277 'duration': 4524.212,
278 'view_count': int,
279 'thumbnail': r're:^https?://.*',
280 'concurrent_view_count': int,
281 },
282 'params': {
283 'skip_download': True,
284 },
285 }, {
286 # data.node.comet_sections.content.story.attachments[].style_type_renderer.attachment.all_subattachments.nodes[].media
287 'url': 'https://www.facebook.com/100033620354545/videos/106560053808006/',
288 'info_dict': {
289 'id': '106560053808006',
290 'ext': 'mp4',
291 'title': 'Josef',
292 'thumbnail': r're:^https?://.*',
293 'concurrent_view_count': int,
294 'uploader_id': 'pfbid0cibUN6tV7DYgdbJdsUFN46wc4jKpVSPAvJQhFofGqBGmVn3V3JtAs2tfUwziw2hUl',
295 'timestamp': 1549275572,
296 'duration': 3.413,
297 'uploader': 'Josef Novak',
298 'description': '',
299 'upload_date': '20190204',
300 },
301 }, {
302 # data.video.story.attachments[].media
303 'url': 'https://www.facebook.com/watch/?v=647537299265662',
304 'only_matching': True,
305 }, {
306 # FIXME: https://github.com/yt-dlp/yt-dlp/issues/542
307 # data.node.comet_sections.content.story.attachments[].style_type_renderer.attachment.all_subattachments.nodes[].media
308 'url': 'https://www.facebook.com/PankajShahLondon/posts/10157667649866271',
309 'info_dict': {
310 'id': '10157667649866271',
311 },
312 'playlist_count': 3,
313 'skip': 'Requires logging in',
314 }, {
315 # data.nodes[].comet_sections.content.story.attachments[].style_type_renderer.attachment.media
316 'url': 'https://m.facebook.com/Alliance.Police.Department/posts/4048563708499330',
317 'info_dict': {
318 'id': '117576630041613',
319 'ext': 'mp4',
320 # TODO: title can be extracted from video page
321 'title': 'Facebook video #117576630041613',
322 'uploader_id': '189393014416438',
323 'upload_date': '20201123',
324 'timestamp': 1606162592,
325 },
326 'skip': 'Requires logging in',
327 }, {
328 # node.comet_sections.content.story.attached_story.attachments.style_type_renderer.attachment.media
329 'url': 'https://www.facebook.com/groups/ateistiskselskab/permalink/10154930137678856/',
330 'info_dict': {
331 'id': '211567722618337',
332 'ext': 'mp4',
333 'title': 'Facebook video #211567722618337',
334 'uploader_id': '127875227654254',
335 'upload_date': '20161122',
336 'timestamp': 1479793574,
337 },
338 'skip': 'No video',
339 }, {
340 # data.video.creation_story.attachments[].media
341 'url': 'https://www.facebook.com/watch/live/?v=1823658634322275',
342 'only_matching': True,
343 }, {
344 'url': 'https://www.facebook.com/watchparty/211641140192478',
345 'info_dict': {
346 'id': '211641140192478',
347 },
348 'playlist_count': 1,
349 'skip': 'Requires logging in',
350 }]
351 _SUPPORTED_PAGLETS_REGEX = r'(?:pagelet_group_mall|permalink_video_pagelet|hyperfeed_story_id_[0-9a-f]+)'
352 _api_config = {
353 'graphURI': '/api/graphql/'
354 }
355
356 def _perform_login(self, username, password):
357 login_page_req = Request(self._LOGIN_URL)
358 self._set_cookie('facebook.com', 'locale', 'en_US')
359 login_page = self._download_webpage(login_page_req, None,
360 note='Downloading login page',
361 errnote='Unable to download login page')
362 lsd = self._search_regex(
363 r'<input type="hidden" name="lsd" value="([^"]*)"',
364 login_page, 'lsd')
365 lgnrnd = self._search_regex(r'name="lgnrnd" value="([^"]*?)"', login_page, 'lgnrnd')
366
367 login_form = {
368 'email': username,
369 'pass': password,
370 'lsd': lsd,
371 'lgnrnd': lgnrnd,
372 'next': 'http://facebook.com/home.php',
373 'default_persistent': '0',
374 'legacy_return': '1',
375 'timezone': '-60',
376 'trynum': '1',
377 }
378 request = Request(self._LOGIN_URL, urlencode_postdata(login_form))
379 request.headers['Content-Type'] = 'application/x-www-form-urlencoded'
380 try:
381 login_results = self._download_webpage(request, None,
382 note='Logging in', errnote='unable to fetch login page')
383 if re.search(r'<form(.*)name="login"(.*)</form>', login_results) is not None:
384 error = self._html_search_regex(
385 r'(?s)<div[^>]+class=(["\']).*?login_error_box.*?\1[^>]*><div[^>]*>.*?</div><div[^>]*>(?P<error>.+?)</div>',
386 login_results, 'login error', default=None, group='error')
387 if error:
388 raise ExtractorError('Unable to login: %s' % error, expected=True)
389 self.report_warning('unable to log in: bad username/password, or exceeded login rate limit (~3/min). Check credentials or wait.')
390 return
391
392 fb_dtsg = self._search_regex(
393 r'name="fb_dtsg" value="(.+?)"', login_results, 'fb_dtsg', default=None)
394 h = self._search_regex(
395 r'name="h"\s+(?:\w+="[^"]+"\s+)*?value="([^"]+)"', login_results, 'h', default=None)
396
397 if not fb_dtsg or not h:
398 return
399
400 check_form = {
401 'fb_dtsg': fb_dtsg,
402 'h': h,
403 'name_action_selected': 'dont_save',
404 }
405 check_req = Request(self._CHECKPOINT_URL, urlencode_postdata(check_form))
406 check_req.headers['Content-Type'] = 'application/x-www-form-urlencoded'
407 check_response = self._download_webpage(check_req, None,
408 note='Confirming login')
409 if re.search(r'id="checkpointSubmitButton"', check_response) is not None:
410 self.report_warning('Unable to confirm login, you have to login in your browser and authorize the login.')
411 except network_exceptions as err:
412 self.report_warning('unable to log in: %s' % error_to_compat_str(err))
413 return
414
415 def _extract_from_url(self, url, video_id):
416 webpage = self._download_webpage(
417 url.replace('://m.facebook.com/', '://www.facebook.com/'), video_id)
418
419 def extract_metadata(webpage):
420 post_data = [self._parse_json(j, video_id, fatal=False) for j in re.findall(
421 r'data-sjs>({.*?ScheduledServerJS.*?})</script>', webpage)]
422 post = traverse_obj(post_data, (
423 ..., 'require', ..., ..., ..., '__bbox', 'require', ..., ..., ..., '__bbox', 'result', 'data'), expected_type=dict) or []
424
425 automatic_captions, subtitles = {}, {}
426 subs_data = traverse_obj(post, (..., 'video', ..., 'attachments', ..., lambda k, v: (
427 k == 'media' and str(v['id']) == video_id and v['__typename'] == 'Video')))
428 is_video_broadcast = get_first(subs_data, 'is_video_broadcast', expected_type=bool)
429 captions = get_first(subs_data, 'video_available_captions_locales', 'captions_url')
430 if url_or_none(captions): # if subs_data only had a 'captions_url'
431 locale = self._html_search_meta(['og:locale', 'twitter:locale'], webpage, 'locale', default='en_US')
432 subtitles[locale] = [{'url': captions}]
433 # or else subs_data had 'video_available_captions_locales', a list of dicts
434 for caption in traverse_obj(captions, (
435 {lambda x: sorted(x, key=lambda c: c['locale'])}, lambda _, v: v['captions_url'])
436 ):
437 lang = caption.get('localized_language') or ''
438 subs = {
439 'url': caption['captions_url'],
440 'name': format_field(caption, 'localized_country', f'{lang} (%s)', default=lang),
441 }
442 if caption.get('localized_creation_method') or is_video_broadcast:
443 automatic_captions.setdefault(caption['locale'], []).append(subs)
444 else:
445 subtitles.setdefault(caption['locale'], []).append(subs)
446
447 media = traverse_obj(post, (..., 'attachments', ..., lambda k, v: (
448 k == 'media' and str(v['id']) == video_id and v['__typename'] == 'Video')), expected_type=dict)
449 title = get_first(media, ('title', 'text'))
450 description = get_first(media, ('creation_story', 'comet_sections', 'message', 'story', 'message', 'text'))
451 uploader_data = (
452 get_first(media, ('owner', {dict}))
453 or get_first(post, (..., 'video', lambda k, v: k == 'owner' and v['name']))
454 or get_first(post, ('node', 'actors', ..., {dict})) or {})
455
456 page_title = title or self._html_search_regex((
457 r'<h2\s+[^>]*class="uiHeaderTitle"[^>]*>(?P<content>[^<]*)</h2>',
458 r'(?s)<span class="fbPhotosPhotoCaption".*?id="fbPhotoPageCaption"><span class="hasCaption">(?P<content>.*?)</span>',
459 self._meta_regex('og:title'), self._meta_regex('twitter:title'), r'<title>(?P<content>.+?)</title>'
460 ), webpage, 'title', default=None, group='content')
461 description = description or self._html_search_meta(
462 ['description', 'og:description', 'twitter:description'],
463 webpage, 'description', default=None)
464 uploader = uploader_data.get('name') or (
465 clean_html(get_element_by_id('fbPhotoPageAuthorName', webpage))
466 or self._search_regex(
467 (r'ownerName\s*:\s*"([^"]+)"', *self._og_regexes('title')), webpage, 'uploader', fatal=False))
468
469 timestamp = int_or_none(self._search_regex(
470 r'<abbr[^>]+data-utime=["\'](\d+)', webpage,
471 'timestamp', default=None))
472 thumbnail = self._html_search_meta(
473 ['og:image', 'twitter:image'], webpage, 'thumbnail', default=None)
474 # some webpages contain unretrievable thumbnail urls
475 # like https://lookaside.fbsbx.com/lookaside/crawler/media/?media_id=10155168902769113&get_thumbnail=1
476 # in https://www.facebook.com/yaroslav.korpan/videos/1417995061575415/
477 if thumbnail and not re.search(r'\.(?:jpg|png)', thumbnail):
478 thumbnail = None
479 info_dict = {
480 'description': description,
481 'uploader': uploader,
482 'uploader_id': uploader_data.get('id'),
483 'timestamp': timestamp,
484 'thumbnail': thumbnail,
485 'view_count': parse_count(self._search_regex(
486 (r'\bviewCount\s*:\s*["\']([\d,.]+)', r'video_view_count["\']\s*:\s*(\d+)',),
487 webpage, 'view count', default=None)),
488 'concurrent_view_count': get_first(post, (
489 ('video', (..., ..., 'attachments', ..., 'media')), 'liveViewerCount', {int_or_none})),
490 'automatic_captions': automatic_captions,
491 'subtitles': subtitles,
492 }
493
494 info_json_ld = self._search_json_ld(webpage, video_id, default={})
495 info_json_ld['title'] = (re.sub(r'\s*\|\s*Facebook$', '', title or info_json_ld.get('title') or page_title or '')
496 or (description or '').replace('\n', ' ') or f'Facebook video #{video_id}')
497 return merge_dicts(info_json_ld, info_dict)
498
499 video_data = None
500
501 def extract_video_data(instances):
502 video_data = []
503 for item in instances:
504 if try_get(item, lambda x: x[1][0]) == 'VideoConfig':
505 video_item = item[2][0]
506 if video_item.get('video_id'):
507 video_data.append(video_item['videoData'])
508 return video_data
509
510 server_js_data = self._parse_json(self._search_regex(
511 [r'handleServerJS\(({.+})(?:\);|,")', r'\bs\.handle\(({.+?})\);'],
512 webpage, 'server js data', default='{}'), video_id, fatal=False)
513
514 if server_js_data:
515 video_data = extract_video_data(server_js_data.get('instances', []))
516
517 def extract_from_jsmods_instances(js_data):
518 if js_data:
519 return extract_video_data(try_get(
520 js_data, lambda x: x['jsmods']['instances'], list) or [])
521
522 def extract_dash_manifest(video, formats):
523 dash_manifest = video.get('dash_manifest')
524 if dash_manifest:
525 formats.extend(self._parse_mpd_formats(
526 compat_etree_fromstring(urllib.parse.unquote_plus(dash_manifest)),
527 mpd_url=video.get('dash_manifest_url')))
528
529 def process_formats(info):
530 # Downloads with browser's User-Agent are rate limited. Working around
531 # with non-browser User-Agent.
532 for f in info['formats']:
533 f.setdefault('http_headers', {})['User-Agent'] = 'facebookexternalhit/1.1'
534
535 def extract_relay_data(_filter):
536 return self._parse_json(self._search_regex(
537 r'data-sjs>({.*?%s.*?})</script>' % _filter,
538 webpage, 'replay data', default='{}'), video_id, fatal=False) or {}
539
540 def extract_relay_prefetched_data(_filter):
541 return traverse_obj(extract_relay_data(_filter), (
542 'require', (None, (..., ..., ..., '__bbox', 'require')),
543 lambda _, v: 'RelayPrefetchedStreamCache' in v, ..., ...,
544 '__bbox', 'result', 'data', {dict}), get_all=False) or {}
545
546 if not video_data:
547 server_js_data = self._parse_json(self._search_regex([
548 r'bigPipe\.onPageletArrive\(({.+?})\)\s*;\s*}\s*\)\s*,\s*["\']onPageletArrive\s+' + self._SUPPORTED_PAGLETS_REGEX,
549 r'bigPipe\.onPageletArrive\(({.*?id\s*:\s*"%s".*?})\);' % self._SUPPORTED_PAGLETS_REGEX
550 ], webpage, 'js data', default='{}'), video_id, js_to_json, False)
551 video_data = extract_from_jsmods_instances(server_js_data)
552
553 if not video_data:
554 data = extract_relay_prefetched_data(
555 r'"(?:dash_manifest|playable_url(?:_quality_hd)?)')
556 if data:
557 entries = []
558
559 def parse_graphql_video(video):
560 v_id = video.get('videoId') or video.get('id') or video_id
561 reel_info = traverse_obj(
562 video, ('creation_story', 'short_form_video_context', 'playback_video', {dict}))
563 if reel_info:
564 video = video['creation_story']
565 video['owner'] = traverse_obj(video, ('short_form_video_context', 'video_owner'))
566 video.update(reel_info)
567 formats = []
568 q = qualities(['sd', 'hd'])
569 for key, format_id in (('playable_url', 'sd'), ('playable_url_quality_hd', 'hd'),
570 ('playable_url_dash', ''), ('browser_native_hd_url', 'hd'),
571 ('browser_native_sd_url', 'sd')):
572 playable_url = video.get(key)
573 if not playable_url:
574 continue
575 if determine_ext(playable_url) == 'mpd':
576 formats.extend(self._extract_mpd_formats(playable_url, video_id))
577 else:
578 formats.append({
579 'format_id': format_id,
580 # sd, hd formats w/o resolution info should be deprioritized below DASH
581 'quality': q(format_id) - 3,
582 'url': playable_url,
583 })
584 extract_dash_manifest(video, formats)
585 info = {
586 'id': v_id,
587 'formats': formats,
588 'thumbnail': traverse_obj(
589 video, ('thumbnailImage', 'uri'), ('preferred_thumbnail', 'image', 'uri')),
590 'uploader_id': traverse_obj(video, ('owner', 'id', {str_or_none})),
591 'timestamp': traverse_obj(video, 'publish_time', 'creation_time', expected_type=int_or_none),
592 'duration': (float_or_none(video.get('playable_duration_in_ms'), 1000)
593 or float_or_none(video.get('length_in_second'))),
594 }
595 process_formats(info)
596 description = try_get(video, lambda x: x['savable_description']['text'])
597 title = video.get('name')
598 if title:
599 info.update({
600 'title': title,
601 'description': description,
602 })
603 else:
604 info['title'] = description or 'Facebook video #%s' % v_id
605 entries.append(info)
606
607 def parse_attachment(attachment, key='media'):
608 media = attachment.get(key) or {}
609 if media.get('__typename') == 'Video':
610 return parse_graphql_video(media)
611
612 nodes = variadic(traverse_obj(data, 'nodes', 'node') or [])
613 attachments = traverse_obj(nodes, (
614 ..., 'comet_sections', 'content', 'story', (None, 'attached_story'), 'attachments',
615 ..., ('styles', 'style_type_renderer'), 'attachment'), expected_type=dict) or []
616 for attachment in attachments:
617 ns = try_get(attachment, lambda x: x['all_subattachments']['nodes'], list) or []
618 for n in ns:
619 parse_attachment(n)
620 parse_attachment(attachment)
621
622 edges = try_get(data, lambda x: x['mediaset']['currMedia']['edges'], list) or []
623 for edge in edges:
624 parse_attachment(edge, key='node')
625
626 video = data.get('video') or {}
627 if video:
628 attachments = try_get(video, [
629 lambda x: x['story']['attachments'],
630 lambda x: x['creation_story']['attachments']
631 ], list) or []
632 for attachment in attachments:
633 parse_attachment(attachment)
634 if not entries:
635 parse_graphql_video(video)
636
637 if len(entries) > 1:
638 return self.playlist_result(entries, video_id)
639
640 video_info = entries[0]
641 webpage_info = extract_metadata(webpage)
642 # honor precise duration in video info
643 if video_info.get('duration'):
644 webpage_info['duration'] = video_info['duration']
645 return merge_dicts(webpage_info, video_info)
646
647 if not video_data:
648 m_msg = re.search(r'class="[^"]*uiInterstitialContent[^"]*"><div>(.*?)</div>', webpage)
649 if m_msg is not None:
650 raise ExtractorError(
651 'The video is not available, Facebook said: "%s"' % m_msg.group(1),
652 expected=True)
653 elif any(p in webpage for p in (
654 '>You must log in to continue',
655 'id="login_form"',
656 'id="loginbutton"')):
657 self.raise_login_required()
658
659 if not video_data and '/watchparty/' in url:
660 post_data = {
661 'doc_id': 3731964053542869,
662 'variables': json.dumps({
663 'livingRoomID': video_id,
664 }),
665 }
666
667 prefetched_data = extract_relay_prefetched_data(r'"login_data"\s*:\s*{')
668 if prefetched_data:
669 lsd = try_get(prefetched_data, lambda x: x['login_data']['lsd'], dict)
670 if lsd:
671 post_data[lsd['name']] = lsd['value']
672
673 relay_data = extract_relay_data(r'\[\s*"RelayAPIConfigDefaults"\s*,')
674 for define in (relay_data.get('define') or []):
675 if define[0] == 'RelayAPIConfigDefaults':
676 self._api_config = define[2]
677
678 living_room = self._download_json(
679 urljoin(url, self._api_config['graphURI']), video_id,
680 data=urlencode_postdata(post_data))['data']['living_room']
681
682 entries = []
683 for edge in (try_get(living_room, lambda x: x['recap']['watched_content']['edges']) or []):
684 video = try_get(edge, lambda x: x['node']['video']) or {}
685 v_id = video.get('id')
686 if not v_id:
687 continue
688 v_id = compat_str(v_id)
689 entries.append(self.url_result(
690 self._VIDEO_PAGE_TEMPLATE % v_id,
691 self.ie_key(), v_id, video.get('name')))
692
693 return self.playlist_result(entries, video_id)
694
695 if not video_data:
696 # Video info not in first request, do a secondary request using
697 # tahoe player specific URL
698 tahoe_data = self._download_webpage(
699 self._VIDEO_PAGE_TAHOE_TEMPLATE % video_id, video_id,
700 data=urlencode_postdata({
701 '__a': 1,
702 '__pc': self._search_regex(
703 r'pkg_cohort["\']\s*:\s*["\'](.+?)["\']', webpage,
704 'pkg cohort', default='PHASED:DEFAULT'),
705 '__rev': self._search_regex(
706 r'client_revision["\']\s*:\s*(\d+),', webpage,
707 'client revision', default='3944515'),
708 'fb_dtsg': self._search_regex(
709 r'"DTSGInitialData"\s*,\s*\[\]\s*,\s*{\s*"token"\s*:\s*"([^"]+)"',
710 webpage, 'dtsg token', default=''),
711 }),
712 headers={
713 'Content-Type': 'application/x-www-form-urlencoded',
714 })
715 tahoe_js_data = self._parse_json(
716 self._search_regex(
717 r'for\s+\(\s*;\s*;\s*\)\s*;(.+)', tahoe_data,
718 'tahoe js data', default='{}'),
719 video_id, fatal=False)
720 video_data = extract_from_jsmods_instances(tahoe_js_data)
721
722 if not video_data:
723 raise ExtractorError('Cannot parse data')
724
725 if len(video_data) > 1:
726 entries = []
727 for v in video_data:
728 video_url = v[0].get('video_url')
729 if not video_url:
730 continue
731 entries.append(self.url_result(urljoin(
732 url, video_url), self.ie_key(), v[0].get('video_id')))
733 return self.playlist_result(entries, video_id)
734 video_data = video_data[0]
735
736 formats = []
737 subtitles = {}
738 for f in video_data:
739 format_id = f['stream_type']
740 if f and isinstance(f, dict):
741 f = [f]
742 if not f or not isinstance(f, list):
743 continue
744 for quality in ('sd', 'hd'):
745 for src_type in ('src', 'src_no_ratelimit'):
746 src = f[0].get('%s_%s' % (quality, src_type))
747 if src:
748 # sd, hd formats w/o resolution info should be deprioritized below DASH
749 # TODO: investigate if progressive or src formats still exist
750 preference = -10 if format_id == 'progressive' else -3
751 if quality == 'hd':
752 preference += 1
753 formats.append({
754 'format_id': '%s_%s_%s' % (format_id, quality, src_type),
755 'url': src,
756 'quality': preference,
757 'height': 720 if quality == 'hd' else None
758 })
759 extract_dash_manifest(f[0], formats)
760 subtitles_src = f[0].get('subtitles_src')
761 if subtitles_src:
762 subtitles.setdefault('en', []).append({'url': subtitles_src})
763
764 info_dict = {
765 'id': video_id,
766 'formats': formats,
767 'subtitles': subtitles,
768 }
769 process_formats(info_dict)
770 info_dict.update(extract_metadata(webpage))
771
772 return info_dict
773
774 def _real_extract(self, url):
775 video_id = self._match_id(url)
776
777 real_url = self._VIDEO_PAGE_TEMPLATE % video_id if url.startswith('facebook:') else url
778 return self._extract_from_url(real_url, video_id)
779
780
781class FacebookPluginsVideoIE(InfoExtractor):
782 _VALID_URL = r'https?://(?:[\w-]+\.)?facebook\.com/plugins/video\.php\?.*?\bhref=(?P<id>https.+)'
783
784 _TESTS = [{
785 'url': 'https://www.facebook.com/plugins/video.php?href=https%3A%2F%2Fwww.facebook.com%2Fgov.sg%2Fvideos%2F10154383743583686%2F&show_text=0&width=560',
786 'md5': '5954e92cdfe51fe5782ae9bda7058a07',
787 'info_dict': {
788 'id': '10154383743583686',
789 'ext': 'mp4',
790 # TODO: Fix title, uploader
791 'title': 'What to do during the haze?',
792 'uploader': 'Gov.sg',
793 'upload_date': '20160826',
794 'timestamp': 1472184808,
795 },
796 'add_ie': [FacebookIE.ie_key()],
797 }, {
798 'url': 'https://www.facebook.com/plugins/video.php?href=https%3A%2F%2Fwww.facebook.com%2Fvideo.php%3Fv%3D10204634152394104',
799 'only_matching': True,
800 }, {
801 'url': 'https://www.facebook.com/plugins/video.php?href=https://www.facebook.com/gov.sg/videos/10154383743583686/&show_text=0&width=560',
802 'only_matching': True,
803 }]
804
805 def _real_extract(self, url):
806 return self.url_result(
807 compat_urllib_parse_unquote(self._match_id(url)),
808 FacebookIE.ie_key())
809
810
811class FacebookRedirectURLIE(InfoExtractor):
812 IE_DESC = False # Do not list
813 _VALID_URL = r'https?://(?:[\w-]+\.)?facebook\.com/flx/warn[/?]'
814 _TESTS = [{
815 'url': 'https://www.facebook.com/flx/warn/?h=TAQHsoToz&u=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DpO8h3EaFRdo&s=1',
816 'info_dict': {
817 'id': 'pO8h3EaFRdo',
818 'ext': 'mp4',
819 'title': 'Tripeo Boiler Room x Dekmantel Festival DJ Set',
820 'description': 'md5:2d713ccbb45b686a1888397b2c77ca6b',
821 'channel_id': 'UCGBpxWJr9FNOcFYA5GkKrMg',
822 'playable_in_embed': True,
823 'categories': ['Music'],
824 'channel': 'Boiler Room',
825 'uploader_id': 'brtvofficial',
826 'uploader': 'Boiler Room',
827 'tags': 'count:11',
828 'duration': 3332,
829 'live_status': 'not_live',
830 'thumbnail': 'https://i.ytimg.com/vi/pO8h3EaFRdo/maxresdefault.jpg',
831 'channel_url': 'https://www.youtube.com/channel/UCGBpxWJr9FNOcFYA5GkKrMg',
832 'availability': 'public',
833 'uploader_url': 'http://www.youtube.com/user/brtvofficial',
834 'upload_date': '20150917',
835 'age_limit': 0,
836 'view_count': int,
837 'like_count': int,
838 },
839 'add_ie': ['Youtube'],
840 'params': {'skip_download': 'Youtube'},
841 }]
842
843 def _real_extract(self, url):
844 redirect_url = url_or_none(parse_qs(url).get('u', [None])[-1])
845 if not redirect_url:
846 raise ExtractorError('Invalid facebook redirect URL', expected=True)
847 return self.url_result(redirect_url)
848
849
850class FacebookReelIE(InfoExtractor):
851 _VALID_URL = r'https?://(?:[\w-]+\.)?facebook\.com/reel/(?P<id>\d+)'
852 IE_NAME = 'facebook:reel'
853
854 _TESTS = [{
855 'url': 'https://www.facebook.com/reel/1195289147628387',
856 'md5': 'f13dd37f2633595982db5ed8765474d3',
857 'info_dict': {
858 'id': '1195289147628387',
859 'ext': 'mp4',
860 'title': 'md5:b05800b5b1ad56c0ca78bd3807b6a61e',
861 'description': 'md5:22f03309b216ac84720183961441d8db',
862 'uploader': 'md5:723e6cb3091241160f20b3c5dc282af1',
863 'uploader_id': '100040874179269',
864 'duration': 9.579,
865 'timestamp': 1637502609,
866 'upload_date': '20211121',
867 'thumbnail': r're:^https?://.*',
868 }
869 }]
870
871 def _real_extract(self, url):
872 video_id = self._match_id(url)
873 return self.url_result(
874 f'https://m.facebook.com/watch/?v={video_id}&_rdr', FacebookIE, video_id)