[ie/wistia] Support password-protected videos (#11100)
[yt-dlp3.git] / yt_dlp / extractor / facebook.py
blob1adb35b5f0198f735103aff31dc371f54cc68bd4
1 import json
2 import re
3 import urllib.parse
5 from .common import InfoExtractor
6 from ..compat import compat_etree_fromstring
7 from ..networking import Request
8 from ..networking.exceptions import network_exceptions
9 from ..utils import (
10 ExtractorError,
11 clean_html,
12 determine_ext,
13 float_or_none,
14 format_field,
15 get_element_by_id,
16 get_first,
17 int_or_none,
18 join_nonempty,
19 js_to_json,
20 merge_dicts,
21 parse_count,
22 parse_qs,
23 qualities,
24 str_or_none,
25 traverse_obj,
26 try_get,
27 url_or_none,
28 urlencode_postdata,
29 urljoin,
30 variadic,
34 class FacebookIE(InfoExtractor):
35 _VALID_URL = r'''(?x)
36 (?:
37 https?://
38 (?:[\w-]+\.)?(?:facebook\.com|facebookwkhpilnemxj7asaniu7vnjjbiltxjqhye3mhbshg7kx5tfyd\.onion)/
39 (?:[^#]*?\#!/)?
40 (?:
41 (?:
42 permalink\.php|
43 video/video\.php|
44 photo\.php|
45 video\.php|
46 video/embed|
47 story\.php|
48 watch(?:/live)?/?
49 )\?(?:.*?)(?:v|video_id|story_fbid)=|
50 [^/]+/videos/(?:[^/]+/)?|
51 [^/]+/posts/|
52 events/(?:[^/]+/)?|
53 groups/[^/]+/(?:permalink|posts)/|
54 watchparty/
56 facebook:
58 (?P<id>pfbid[A-Za-z0-9]+|\d+)
59 '''
60 _EMBED_REGEX = [
61 r'<iframe[^>]+?src=(["\'])(?P<url>https?://www\.facebook\.com/(?:video/embed|plugins/video\.php).+?)\1',
62 # Facebook API embed https://developers.facebook.com/docs/plugins/embedded-video-player
63 r'''(?x)<div[^>]+
64 class=(?P<q1>[\'"])[^\'"]*\bfb-(?:video|post)\b[^\'"]*(?P=q1)[^>]+
65 data-href=(?P<q2>[\'"])(?P<url>(?:https?:)?//(?:www\.)?facebook.com/.+?)(?P=q2)''',
67 _LOGIN_URL = 'https://www.facebook.com/login.php?next=http%3A%2F%2Ffacebook.com%2Fhome.php&login_attempt=1'
68 _CHECKPOINT_URL = 'https://www.facebook.com/checkpoint/?next=http%3A%2F%2Ffacebook.com%2Fhome.php&_fb_noscript=1'
69 _NETRC_MACHINE = 'facebook'
70 IE_NAME = 'facebook'
72 _VIDEO_PAGE_TEMPLATE = 'https://www.facebook.com/video/video.php?v=%s'
73 _VIDEO_PAGE_TAHOE_TEMPLATE = 'https://www.facebook.com/video/tahoe/async/%s/?chain=true&isvideo=true&payloadtype=primary'
75 _TESTS = [{
76 'url': 'https://www.facebook.com/radiokicksfm/videos/3676516585958356/',
77 'info_dict': {
78 'id': '3676516585958356',
79 'ext': 'mp4',
80 'title': 'dr Adam Przygoda',
81 'description': 'md5:34675bda53336b1d16400265c2bb9b3b',
82 'uploader': 'RADIO KICKS FM',
83 'upload_date': '20230818',
84 'timestamp': 1692346159,
85 'thumbnail': r're:^https?://.*',
86 'uploader_id': '100063551323670',
87 'duration': 3133.583,
88 'view_count': int,
89 'concurrent_view_count': 0,
91 }, {
92 'url': 'https://www.facebook.com/video.php?v=637842556329505&fref=nf',
93 'md5': '6a40d33c0eccbb1af76cf0485a052659',
94 'info_dict': {
95 'id': '637842556329505',
96 'ext': 'mp4',
97 'title': 're:Did you know Kei Nishikori is the first Asian man to ever reach a Grand Slam',
98 'uploader': 'Tennis on Facebook',
99 'upload_date': '20140908',
100 'timestamp': 1410199200,
102 'skip': 'Requires logging in',
103 }, {
104 # data.video
105 'url': 'https://www.facebook.com/video.php?v=274175099429670',
106 'info_dict': {
107 'id': '274175099429670',
108 'ext': 'mp4',
109 'title': 'Asif',
110 'description': '',
111 'uploader': 'Asif Nawab Butt',
112 'upload_date': '20140506',
113 'timestamp': 1399398998,
114 'thumbnail': r're:^https?://.*',
115 'uploader_id': 'pfbid05AzrFTXgY37tqwaSgbFTTEpCLBjjEJHkigogwGiRPtKEpAsJYJpzE94H1RxYXWEtl',
116 'duration': 131.03,
117 'concurrent_view_count': int,
118 'view_count': int,
120 }, {
121 'note': 'Video with DASH manifest',
122 'url': 'https://www.facebook.com/video.php?v=957955867617029',
123 'md5': 'b2c28d528273b323abe5c6ab59f0f030',
124 'info_dict': {
125 'id': '957955867617029',
126 'ext': 'mp4',
127 'title': 'When you post epic content on instagram.com/433 8 million followers, this is ...',
128 'uploader': 'Demy de Zeeuw',
129 'upload_date': '20160110',
130 'timestamp': 1452431627,
132 'skip': 'Requires logging in',
133 }, {
134 'url': 'https://www.facebook.com/maxlayn/posts/10153807558977570',
135 'md5': '037b1fa7f3c2d02b7a0d7bc16031ecc6',
136 'info_dict': {
137 'id': '544765982287235',
138 'ext': 'mp4',
139 'title': '"What are you doing running in the snow?"',
140 'uploader': 'FailArmy',
142 'skip': 'Video gone',
143 }, {
144 'url': 'https://m.facebook.com/story.php?story_fbid=1035862816472149&id=116132035111903',
145 'md5': '1deb90b6ac27f7efcf6d747c8a27f5e3',
146 'info_dict': {
147 'id': '1035862816472149',
148 'ext': 'mp4',
149 'title': 'What the Flock Is Going On In New Zealand Credit: ViralHog',
150 'uploader': 'S. Saint',
152 'skip': 'Video gone',
153 }, {
154 'note': 'swf params escaped',
155 'url': 'https://www.facebook.com/barackobama/posts/10153664894881749',
156 'md5': '97ba073838964d12c70566e0085c2b91',
157 'info_dict': {
158 'id': '10153664894881749',
159 'ext': 'mp4',
160 'title': 'Average time to confirm recent Supreme Court nominees: 67 days Longest it\'s t...',
161 'thumbnail': r're:^https?://.*',
162 'timestamp': 1456259628,
163 'upload_date': '20160223',
164 'uploader': 'Barack Obama',
166 'skip': 'Gif on giphy.com gone',
167 }, {
168 # have 1080P, but only up to 720p in swf params
169 # data.video.story.attachments[].media
170 'url': 'https://www.facebook.com/cnn/videos/10155529876156509/',
171 'md5': '1659aa21fb3dd1585874f668e81a72c8',
172 'info_dict': {
173 'id': '10155529876156509',
174 'ext': 'mp4',
175 'title': 'Holocaust survivor becomes US citizen',
176 'description': 'She survived the holocaust — and years later, she’s getting her citizenship so she can vote for Hillary Clinton http://cnn.it/2eERh5f',
177 'timestamp': 1477818095,
178 'upload_date': '20161030',
179 'uploader': 'CNN',
180 'thumbnail': r're:^https?://.*',
181 'view_count': int,
182 'uploader_id': '100059479812265',
183 'concurrent_view_count': int,
184 'duration': 44.181,
186 }, {
187 # FIXME: unable to extract uploader, no formats found
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,
205 'params': {
206 'skip_download': True,
208 }, {
209 # FIXME: Cannot parse data error
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?://.*',
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',
234 'skip': 'Requires logging in',
235 }, {
236 # data.node.comet_sections.content.story.attachments[].throwbackStyles.attachment_target_renderer.attachment.target.attachments[].styles.attachment.media
237 'url': 'https://www.facebook.com/groups/1645456212344334/posts/3737828833107051/',
238 'info_dict': {
239 'id': '1569199726448814',
240 'ext': 'mp4',
241 'title': 'Pence MUST GO!',
242 'description': 'Vickie Gentry shared a memory.',
243 'timestamp': 1511548260,
244 'upload_date': '20171124',
245 'uploader': 'Vickie Gentry',
246 'uploader_id': 'pfbid0FkkycT95ySNNyfCw4Cho6u5G7WbbZEcxT496Hq8rtx1K3LcTCATpR3wnyYhmyGC5l',
247 'thumbnail': r're:^https?://.*',
248 'duration': 148.224,
250 }, {
251 # data.node.comet_sections.content.story.attachments[].styles.attachment.media
252 'url': 'https://www.facebook.com/attn/posts/pfbid0j1Czf2gGDVqeQ8KiMLFm3pWN8GxsQmeRrVhimWDzMuKQoR8r4b1knNsejELmUgyhl',
253 'info_dict': {
254 'id': '6968553779868435',
255 'ext': 'mp4',
256 'description': 'md5:2f2fcf93e97ac00244fe64521bbdb0cb',
257 'uploader': 'ATTN:',
258 'upload_date': '20231207',
259 'title': 'ATTN:',
260 'duration': 132.675,
261 'uploader_id': '100064451419378',
262 'view_count': int,
263 'thumbnail': r're:^https?://.*',
264 'timestamp': 1701975646,
266 }, {
267 # data.node.comet_sections.content.story.attachments[].styles.attachment.media
268 'url': 'https://www.facebook.com/permalink.php?story_fbid=pfbid0fqQuVEQyXRa9Dp4RcaTR14KHU3uULHV1EK7eckNXSH63JMuoALsAvVCJ97zAGitil&id=100068861234290',
269 'info_dict': {
270 'id': '270103405756416',
271 'ext': 'mp4',
272 'title': 'Lela Evans',
273 'description': 'Today Makkovik\'s own Pilot Mandy Smith made her inaugural landing on the airstrip in her hometown. What a proud moment as we all cheered and...',
274 'thumbnail': r're:^https?://.*',
275 'uploader': 'Lela Evans',
276 'uploader_id': 'pfbid0swT2y7t6TAsZVBvcyeYPdhTMefGaS26mzUwML3vd1ma6ndGZKxsyS4Ssu3jitZLXl',
277 'upload_date': '20231228',
278 'timestamp': 1703804085,
279 'duration': 394.347,
280 'view_count': int,
282 }, {
283 'url': 'https://www.facebook.com/story.php?story_fbid=pfbid0Fnzhm8UuzjBYpPMNFzaSpFE9UmLdU4fJN8qTANi1Dmtj5q7DNrL5NERXfsAzDEV7l&id=100073071055552',
284 'only_matching': True,
285 }, {
286 'url': 'https://www.facebook.com/video.php?v=10204634152394104',
287 'only_matching': True,
288 }, {
289 'url': 'https://www.facebook.com/amogood/videos/1618742068337349/?fref=nf',
290 'only_matching': True,
291 }, {
292 # data.mediaset.currMedia.edges
293 'url': 'https://www.facebook.com/ChristyClarkForBC/videos/vb.22819070941/10153870694020942/?type=2&theater',
294 'only_matching': True,
295 }, {
296 # data.video.story.attachments[].media
297 'url': 'facebook:544765982287235',
298 'only_matching': True,
299 }, {
300 # data.node.comet_sections.content.story.attachments[].style_type_renderer.attachment.media
301 'url': 'https://www.facebook.com/groups/164828000315060/permalink/764967300301124/',
302 'only_matching': True,
303 }, {
304 # data.video.creation_story.attachments[].media
305 'url': 'https://zh-hk.facebook.com/peoplespower/videos/1135894589806027/',
306 'only_matching': True,
307 }, {
308 # data.video
309 'url': 'https://www.facebookwkhpilnemxj7asaniu7vnjjbiltxjqhye3mhbshg7kx5tfyd.onion/video.php?v=274175099429670',
310 'only_matching': True,
311 }, {
312 # no title
313 'url': 'https://www.facebook.com/onlycleverentertainment/videos/1947995502095005/',
314 'only_matching': True,
315 }, {
316 # data.video
317 'url': 'https://www.facebook.com/WatchESLOne/videos/359649331226507/',
318 'info_dict': {
319 'id': '359649331226507',
320 'ext': 'mp4',
321 'title': 'Fnatic vs. EG - Group A - Opening Match - ESL One Birmingham Day 1',
322 'description': '#ESLOne VoD - Birmingham Finals Day#1 Fnatic vs. @Evil Geniuses',
323 'timestamp': 1527084179,
324 'upload_date': '20180523',
325 'uploader': 'ESL One Dota 2',
326 'uploader_id': '100066514874195',
327 'duration': 4524.001,
328 'view_count': int,
329 'thumbnail': r're:^https?://.*',
330 'concurrent_view_count': int,
332 'params': {
333 'skip_download': True,
335 }, {
336 # data.node.comet_sections.content.story.attachments[].style_type_renderer.attachment.all_subattachments.nodes[].media
337 'url': 'https://www.facebook.com/100033620354545/videos/106560053808006/',
338 'info_dict': {
339 'id': '106560053808006',
340 'ext': 'mp4',
341 'title': 'Josef',
342 'thumbnail': r're:^https?://.*',
343 'concurrent_view_count': int,
344 'uploader_id': 'pfbid02gpfwRM2XvdEJfsERupwQiNmBiDArc38RMRYZnap372q6Vs7MtFTVy72mmFWpJBTKl',
345 'timestamp': 1549275572,
346 'duration': 3.283,
347 'uploader': 'Josef Novak',
348 'description': '',
349 'upload_date': '20190204',
351 }, {
352 # data.video.story.attachments[].media
353 'url': 'https://www.facebook.com/watch/?v=647537299265662',
354 'only_matching': True,
355 }, {
356 # FIXME: https://github.com/yt-dlp/yt-dlp/issues/542
357 # data.node.comet_sections.content.story.attachments[].style_type_renderer.attachment.all_subattachments.nodes[].media
358 'url': 'https://www.facebook.com/PankajShahLondon/posts/10157667649866271',
359 'info_dict': {
360 'id': '10157667649866271',
362 'playlist_count': 3,
363 'skip': 'Requires logging in',
364 }, {
365 # data.nodes[].comet_sections.content.story.attachments[].style_type_renderer.attachment.media
366 'url': 'https://m.facebook.com/Alliance.Police.Department/posts/4048563708499330',
367 'info_dict': {
368 'id': '117576630041613',
369 'ext': 'mp4',
370 # TODO: title can be extracted from video page
371 'title': 'Facebook video #117576630041613',
372 'uploader_id': '189393014416438',
373 'upload_date': '20201123',
374 'timestamp': 1606162592,
376 'skip': 'Requires logging in',
377 }, {
378 # node.comet_sections.content.story.attached_story.attachments.style_type_renderer.attachment.media
379 'url': 'https://www.facebook.com/groups/ateistiskselskab/permalink/10154930137678856/',
380 'info_dict': {
381 'id': '211567722618337',
382 'ext': 'mp4',
383 'title': 'Facebook video #211567722618337',
384 'uploader_id': '127875227654254',
385 'upload_date': '20161122',
386 'timestamp': 1479793574,
388 'skip': 'No video',
389 }, {
390 # data.video.creation_story.attachments[].media
391 'url': 'https://www.facebook.com/watch/live/?v=1823658634322275',
392 'only_matching': True,
393 }, {
394 'url': 'https://www.facebook.com/watchparty/211641140192478',
395 'info_dict': {
396 'id': '211641140192478',
398 'playlist_count': 1,
399 'skip': 'Requires logging in',
400 }, {
401 # FIXME: Cannot parse data error
402 # data.event.cover_media_renderer.cover_video
403 'url': 'https://m.facebook.com/events/1509582499515440',
404 'info_dict': {
405 'id': '637246984455045',
406 'ext': 'mp4',
407 'title': 'ANALISI IN CAMPO OSCURO " Coaguli nel sangue dei vaccinati"',
408 'description': 'Other event by Comitato Liberi Pensatori on Tuesday, October 18 2022',
409 'thumbnail': r're:^https?://.*',
410 'uploader': 'Comitato Liberi Pensatori',
411 'uploader_id': '100065709540881',
414 _SUPPORTED_PAGLETS_REGEX = r'(?:pagelet_group_mall|permalink_video_pagelet|hyperfeed_story_id_[0-9a-f]+)'
415 _api_config = {
416 'graphURI': '/api/graphql/',
419 def _perform_login(self, username, password):
420 login_page_req = Request(self._LOGIN_URL)
421 self._set_cookie('facebook.com', 'locale', 'en_US')
422 login_page = self._download_webpage(login_page_req, None,
423 note='Downloading login page',
424 errnote='Unable to download login page')
425 lsd = self._search_regex(
426 r'<input type="hidden" name="lsd" value="([^"]*)"',
427 login_page, 'lsd')
428 lgnrnd = self._search_regex(r'name="lgnrnd" value="([^"]*?)"', login_page, 'lgnrnd')
430 login_form = {
431 'email': username,
432 'pass': password,
433 'lsd': lsd,
434 'lgnrnd': lgnrnd,
435 'next': 'http://facebook.com/home.php',
436 'default_persistent': '0',
437 'legacy_return': '1',
438 'timezone': '-60',
439 'trynum': '1',
441 request = Request(self._LOGIN_URL, urlencode_postdata(login_form))
442 request.headers['Content-Type'] = 'application/x-www-form-urlencoded'
443 try:
444 login_results = self._download_webpage(request, None,
445 note='Logging in', errnote='unable to fetch login page')
446 if re.search(r'<form(.*)name="login"(.*)</form>', login_results) is not None:
447 error = self._html_search_regex(
448 r'(?s)<div[^>]+class=(["\']).*?login_error_box.*?\1[^>]*><div[^>]*>.*?</div><div[^>]*>(?P<error>.+?)</div>',
449 login_results, 'login error', default=None, group='error')
450 if error:
451 raise ExtractorError(f'Unable to login: {error}', expected=True)
452 self.report_warning('unable to log in: bad username/password, or exceeded login rate limit (~3/min). Check credentials or wait.')
453 return
455 fb_dtsg = self._search_regex(
456 r'name="fb_dtsg" value="(.+?)"', login_results, 'fb_dtsg', default=None)
457 h = self._search_regex(
458 r'name="h"\s+(?:\w+="[^"]+"\s+)*?value="([^"]+)"', login_results, 'h', default=None)
460 if not fb_dtsg or not h:
461 return
463 check_form = {
464 'fb_dtsg': fb_dtsg,
465 'h': h,
466 'name_action_selected': 'dont_save',
468 check_req = Request(self._CHECKPOINT_URL, urlencode_postdata(check_form))
469 check_req.headers['Content-Type'] = 'application/x-www-form-urlencoded'
470 check_response = self._download_webpage(check_req, None,
471 note='Confirming login')
472 if re.search(r'id="checkpointSubmitButton"', check_response) is not None:
473 self.report_warning('Unable to confirm login, you have to login in your browser and authorize the login.')
474 except network_exceptions as err:
475 self.report_warning(f'unable to log in: {err}')
476 return
478 def _extract_from_url(self, url, video_id):
479 webpage = self._download_webpage(
480 url.replace('://m.facebook.com/', '://www.facebook.com/'), video_id)
482 def extract_metadata(webpage):
483 post_data = [self._parse_json(j, video_id, fatal=False) for j in re.findall(
484 r'data-sjs>({.*?ScheduledServerJS.*?})</script>', webpage)]
485 post = traverse_obj(post_data, (
486 ..., 'require', ..., ..., ..., '__bbox', 'require', ..., ..., ..., '__bbox', 'result', 'data'), expected_type=dict) or []
487 media = traverse_obj(post, (..., 'attachments', ..., lambda k, v: (
488 k == 'media' and str(v['id']) == video_id and v['__typename'] == 'Video')), expected_type=dict)
489 title = get_first(media, ('title', 'text'))
490 description = get_first(media, ('creation_story', 'comet_sections', 'message', 'story', 'message', 'text'))
491 page_title = title or self._html_search_regex((
492 r'<h2\s+[^>]*class="uiHeaderTitle"[^>]*>(?P<content>[^<]*)</h2>',
493 r'(?s)<span class="fbPhotosPhotoCaption".*?id="fbPhotoPageCaption"><span class="hasCaption">(?P<content>.*?)</span>',
494 self._meta_regex('og:title'), self._meta_regex('twitter:title'), r'<title>(?P<content>.+?)</title>',
495 ), webpage, 'title', default=None, group='content')
496 description = description or self._html_search_meta(
497 ['description', 'og:description', 'twitter:description'],
498 webpage, 'description', default=None)
499 uploader_data = (
500 get_first(media, ('owner', {dict}))
501 or get_first(post, ('video', 'creation_story', 'attachments', ..., 'media', lambda k, v: k == 'owner' and v['name']))
502 or get_first(post, (..., 'video', lambda k, v: k == 'owner' and v['name']))
503 or get_first(post, ('node', 'actors', ..., {dict}))
504 or get_first(post, ('event', 'event_creator', {dict}))
505 or get_first(post, ('video', 'creation_story', 'short_form_video_context', 'video_owner', {dict})) or {})
506 uploader = uploader_data.get('name') or (
507 clean_html(get_element_by_id('fbPhotoPageAuthorName', webpage))
508 or self._search_regex(
509 (r'ownerName\s*:\s*"([^"]+)"', *self._og_regexes('title')), webpage, 'uploader', fatal=False))
510 timestamp = int_or_none(self._search_regex(
511 r'<abbr[^>]+data-utime=["\'](\d+)', webpage,
512 'timestamp', default=None))
513 thumbnail = self._html_search_meta(
514 ['og:image', 'twitter:image'], webpage, 'thumbnail', default=None)
515 # some webpages contain unretrievable thumbnail urls
516 # like https://lookaside.fbsbx.com/lookaside/crawler/media/?media_id=10155168902769113&get_thumbnail=1
517 # in https://www.facebook.com/yaroslav.korpan/videos/1417995061575415/
518 if thumbnail and not re.search(r'\.(?:jpg|png)', thumbnail):
519 thumbnail = None
520 info_dict = {
521 'description': description,
522 'uploader': uploader,
523 'uploader_id': uploader_data.get('id'),
524 'timestamp': timestamp,
525 'thumbnail': thumbnail,
526 'view_count': parse_count(self._search_regex(
527 (r'\bviewCount\s*:\s*["\']([\d,.]+)', r'video_view_count["\']\s*:\s*(\d+)'),
528 webpage, 'view count', default=None)),
529 'concurrent_view_count': get_first(post, (
530 ('video', (..., ..., 'attachments', ..., 'media')), 'liveViewerCount', {int_or_none})),
531 **traverse_obj(post, (lambda _, v: video_id in v['url'], 'feedback', {
532 'like_count': ('likers', 'count', {int}),
533 'comment_count': ('total_comment_count', {int}),
534 'repost_count': ('share_count_reduced', {parse_count}),
535 }), get_all=False),
538 info_json_ld = self._search_json_ld(webpage, video_id, default={})
539 info_json_ld['title'] = (re.sub(r'\s*\|\s*Facebook$', '', title or info_json_ld.get('title') or page_title or '')
540 or (description or '').replace('\n', ' ') or f'Facebook video #{video_id}')
541 return merge_dicts(info_json_ld, info_dict)
543 video_data = None
545 def extract_video_data(instances):
546 video_data = []
547 for item in instances:
548 if try_get(item, lambda x: x[1][0]) == 'VideoConfig':
549 video_item = item[2][0]
550 if video_item.get('video_id'):
551 video_data.append(video_item['videoData'])
552 return video_data
554 server_js_data = self._parse_json(self._search_regex(
555 [r'handleServerJS\(({.+})(?:\);|,")', r'\bs\.handle\(({.+?})\);'],
556 webpage, 'server js data', default='{}'), video_id, fatal=False)
558 if server_js_data:
559 video_data = extract_video_data(server_js_data.get('instances', []))
561 def extract_from_jsmods_instances(js_data):
562 if js_data:
563 return extract_video_data(try_get(
564 js_data, lambda x: x['jsmods']['instances'], list) or [])
566 def extract_dash_manifest(video, formats):
567 dash_manifest = traverse_obj(video, 'dash_manifest', 'playlist', expected_type=str)
568 if dash_manifest:
569 formats.extend(self._parse_mpd_formats(
570 compat_etree_fromstring(urllib.parse.unquote_plus(dash_manifest)),
571 mpd_url=video.get('dash_manifest_url')))
573 def process_formats(info):
574 # Downloads with browser's User-Agent are rate limited. Working around
575 # with non-browser User-Agent.
576 for f in info['formats']:
577 # Downloads with browser's User-Agent are rate limited. Working around
578 # with non-browser User-Agent.
579 f.setdefault('http_headers', {})['User-Agent'] = 'facebookexternalhit/1.1'
580 # Formats larger than ~500MB will return error 403 unless chunk size is regulated
581 f.setdefault('downloader_options', {})['http_chunk_size'] = 250 << 20
583 def yield_all_relay_data(_filter):
584 for relay_data in re.findall(rf'data-sjs>({{.*?{_filter}.*?}})</script>', webpage):
585 yield self._parse_json(relay_data, video_id, fatal=False) or {}
587 def extract_relay_data(_filter):
588 return next(filter(None, yield_all_relay_data(_filter)), {})
590 def extract_relay_prefetched_data(_filter, target_keys=None):
591 path = 'data'
592 if target_keys is not None:
593 path = lambda k, v: k == 'data' and any(target in v for target in variadic(target_keys))
594 return traverse_obj(yield_all_relay_data(_filter), (
595 ..., 'require', (None, (..., ..., ..., '__bbox', 'require')),
596 lambda _, v: any(key.startswith('RelayPrefetchedStreamCache') for key in v),
597 ..., ..., '__bbox', 'result', path, {dict}), get_all=False) or {}
599 if not video_data:
600 server_js_data = self._parse_json(self._search_regex([
601 r'bigPipe\.onPageletArrive\(({.+?})\)\s*;\s*}\s*\)\s*,\s*["\']onPageletArrive\s+' + self._SUPPORTED_PAGLETS_REGEX,
602 rf'bigPipe\.onPageletArrive\(({{.*?id\s*:\s*"{self._SUPPORTED_PAGLETS_REGEX}".*?}})\);',
603 ], webpage, 'js data', default='{}'), video_id, js_to_json, False)
604 video_data = extract_from_jsmods_instances(server_js_data)
606 if not video_data:
607 data = extract_relay_prefetched_data(
608 r'"(?:dash_manifest|playable_url(?:_quality_hd)?)',
609 target_keys=('video', 'event', 'nodes', 'node', 'mediaset'))
610 if data:
611 entries = []
613 def parse_graphql_video(video):
614 v_id = video.get('videoId') or video.get('id') or video_id
615 reel_info = traverse_obj(
616 video, ('creation_story', 'short_form_video_context', 'playback_video', {dict}))
617 if reel_info:
618 video = video['creation_story']
619 video['owner'] = traverse_obj(video, ('short_form_video_context', 'video_owner'))
620 video.update(reel_info)
621 formats = []
622 q = qualities(['sd', 'hd'])
623 for key, format_id in (('playable_url', 'sd'), ('playable_url_quality_hd', 'hd'),
624 ('playable_url_dash', ''), ('browser_native_hd_url', 'hd'),
625 ('browser_native_sd_url', 'sd')):
626 playable_url = video.get(key)
627 if not playable_url:
628 continue
629 if determine_ext(playable_url) == 'mpd':
630 formats.extend(self._extract_mpd_formats(playable_url, video_id))
631 else:
632 formats.append({
633 'format_id': format_id,
634 # sd, hd formats w/o resolution info should be deprioritized below DASH
635 'quality': q(format_id) - 3,
636 'url': playable_url,
638 extract_dash_manifest(video, formats)
639 if not formats:
640 # Do not append false positive entry w/o any formats
641 return
643 automatic_captions, subtitles = {}, {}
644 is_broadcast = traverse_obj(video, ('is_video_broadcast', {bool}))
645 for caption in traverse_obj(video, (
646 'video_available_captions_locales',
647 {lambda x: sorted(x, key=lambda c: c['locale'])},
648 lambda _, v: url_or_none(v['captions_url']),
650 lang = caption.get('localized_language') or 'und'
651 subs = {
652 'url': caption['captions_url'],
653 'name': format_field(caption, 'localized_country', f'{lang} (%s)', default=lang),
655 if caption.get('localized_creation_method') or is_broadcast:
656 automatic_captions.setdefault(caption['locale'], []).append(subs)
657 else:
658 subtitles.setdefault(caption['locale'], []).append(subs)
659 captions_url = traverse_obj(video, ('captions_url', {url_or_none}))
660 if captions_url and not automatic_captions and not subtitles:
661 locale = self._html_search_meta(
662 ['og:locale', 'twitter:locale'], webpage, 'locale', default='en_US')
663 (automatic_captions if is_broadcast else subtitles)[locale] = [{'url': captions_url}]
665 info = {
666 'id': v_id,
667 'formats': formats,
668 'thumbnail': traverse_obj(
669 video, ('thumbnailImage', 'uri'), ('preferred_thumbnail', 'image', 'uri')),
670 'uploader_id': traverse_obj(video, ('owner', 'id', {str_or_none})),
671 'timestamp': traverse_obj(video, 'publish_time', 'creation_time', expected_type=int_or_none),
672 'duration': (float_or_none(video.get('playable_duration_in_ms'), 1000)
673 or float_or_none(video.get('length_in_second'))),
674 'automatic_captions': automatic_captions,
675 'subtitles': subtitles,
677 process_formats(info)
678 description = try_get(video, lambda x: x['savable_description']['text'])
679 title = video.get('name')
680 if title:
681 info.update({
682 'title': title,
683 'description': description,
685 else:
686 info['title'] = description or f'Facebook video #{v_id}'
687 entries.append(info)
689 def parse_attachment(attachment, key='media'):
690 media = attachment.get(key) or {}
691 if media.get('__typename') == 'Video':
692 return parse_graphql_video(media)
694 nodes = variadic(traverse_obj(data, 'nodes', 'node') or [])
695 attachments = traverse_obj(nodes, (
696 ..., 'comet_sections', 'content', 'story', (None, 'attached_story'), 'attachments',
697 ..., ('styles', 'style_type_renderer', ('throwbackStyles', 'attachment_target_renderer')),
698 'attachment', {dict}))
699 for attachment in attachments:
700 ns = traverse_obj(attachment, ('all_subattachments', 'nodes', ..., {dict}),
701 ('target', 'attachments', ..., 'styles', 'attachment', {dict}))
702 for n in ns:
703 parse_attachment(n)
704 parse_attachment(attachment)
706 edges = try_get(data, lambda x: x['mediaset']['currMedia']['edges'], list) or []
707 for edge in edges:
708 parse_attachment(edge, key='node')
710 video = traverse_obj(data, (
711 'event', 'cover_media_renderer', 'cover_video'), 'video', expected_type=dict) or {}
712 if video:
713 attachments = try_get(video, [
714 lambda x: x['story']['attachments'],
715 lambda x: x['creation_story']['attachments'],
716 ], list) or []
717 for attachment in attachments:
718 parse_attachment(attachment)
719 if not entries:
720 parse_graphql_video(video)
722 if len(entries) > 1:
723 return self.playlist_result(entries, video_id)
725 video_info = entries[0] if entries else {'id': video_id}
726 webpage_info = extract_metadata(webpage)
727 # honor precise duration in video info
728 if video_info.get('duration'):
729 webpage_info['duration'] = video_info['duration']
730 # preserve preferred_thumbnail in video info
731 if video_info.get('thumbnail'):
732 webpage_info['thumbnail'] = video_info['thumbnail']
733 return merge_dicts(webpage_info, video_info)
735 if not video_data:
736 m_msg = re.search(r'class="[^"]*uiInterstitialContent[^"]*"><div>(.*?)</div>', webpage)
737 if m_msg is not None:
738 raise ExtractorError(
739 f'The video is not available, Facebook said: "{m_msg.group(1)}"',
740 expected=True)
741 elif any(p in webpage for p in (
742 '>You must log in to continue',
743 'id="login_form"',
744 'id="loginbutton"')):
745 self.raise_login_required()
747 if not video_data and '/watchparty/' in url:
748 post_data = {
749 'doc_id': 3731964053542869,
750 'variables': json.dumps({
751 'livingRoomID': video_id,
755 prefetched_data = extract_relay_prefetched_data(r'"login_data"\s*:\s*{')
756 if prefetched_data:
757 lsd = try_get(prefetched_data, lambda x: x['login_data']['lsd'], dict)
758 if lsd:
759 post_data[lsd['name']] = lsd['value']
761 relay_data = extract_relay_data(r'\[\s*"RelayAPIConfigDefaults"\s*,')
762 for define in (relay_data.get('define') or []):
763 if define[0] == 'RelayAPIConfigDefaults':
764 self._api_config = define[2]
766 living_room = self._download_json(
767 urljoin(url, self._api_config['graphURI']), video_id,
768 data=urlencode_postdata(post_data))['data']['living_room']
770 entries = []
771 for edge in (try_get(living_room, lambda x: x['recap']['watched_content']['edges']) or []):
772 video = try_get(edge, lambda x: x['node']['video']) or {}
773 v_id = video.get('id')
774 if not v_id:
775 continue
776 v_id = str(v_id)
777 entries.append(self.url_result(
778 self._VIDEO_PAGE_TEMPLATE % v_id,
779 self.ie_key(), v_id, video.get('name')))
781 return self.playlist_result(entries, video_id)
783 if not video_data:
784 # Video info not in first request, do a secondary request using
785 # tahoe player specific URL
786 tahoe_data = self._download_webpage(
787 self._VIDEO_PAGE_TAHOE_TEMPLATE % video_id, video_id,
788 data=urlencode_postdata({
789 '__a': 1,
790 '__pc': self._search_regex(
791 r'pkg_cohort["\']\s*:\s*["\'](.+?)["\']', webpage,
792 'pkg cohort', default='PHASED:DEFAULT'),
793 '__rev': self._search_regex(
794 r'client_revision["\']\s*:\s*(\d+),', webpage,
795 'client revision', default='3944515'),
796 'fb_dtsg': self._search_regex(
797 r'"DTSGInitialData"\s*,\s*\[\]\s*,\s*{\s*"token"\s*:\s*"([^"]+)"',
798 webpage, 'dtsg token', default=''),
800 headers={
801 'Content-Type': 'application/x-www-form-urlencoded',
803 tahoe_js_data = self._parse_json(
804 self._search_regex(
805 r'for\s+\(\s*;\s*;\s*\)\s*;(.+)', tahoe_data,
806 'tahoe js data', default='{}'),
807 video_id, fatal=False)
808 video_data = extract_from_jsmods_instances(tahoe_js_data)
810 if not video_data:
811 raise ExtractorError('Cannot parse data')
813 if len(video_data) > 1:
814 entries = []
815 for v in video_data:
816 video_url = v[0].get('video_url')
817 if not video_url:
818 continue
819 entries.append(self.url_result(urljoin(
820 url, video_url), self.ie_key(), v[0].get('video_id')))
821 return self.playlist_result(entries, video_id)
822 video_data = video_data[0]
824 formats = []
825 subtitles = {}
826 for f in video_data:
827 format_id = f['stream_type']
828 if f and isinstance(f, dict):
829 f = [f]
830 if not f or not isinstance(f, list):
831 continue
832 for quality in ('sd', 'hd'):
833 for src_type in ('src', 'src_no_ratelimit'):
834 src = f[0].get(f'{quality}_{src_type}')
835 if src:
836 # sd, hd formats w/o resolution info should be deprioritized below DASH
837 # TODO: investigate if progressive or src formats still exist
838 preference = -10 if format_id == 'progressive' else -3
839 if quality == 'hd':
840 preference += 1
841 formats.append({
842 'format_id': f'{format_id}_{quality}_{src_type}',
843 'url': src,
844 'quality': preference,
845 'height': 720 if quality == 'hd' else None,
847 extract_dash_manifest(f[0], formats)
848 subtitles_src = f[0].get('subtitles_src')
849 if subtitles_src:
850 subtitles.setdefault('en', []).append({'url': subtitles_src})
852 info_dict = {
853 'id': video_id,
854 'formats': formats,
855 'subtitles': subtitles,
857 process_formats(info_dict)
858 info_dict.update(extract_metadata(webpage))
860 return info_dict
862 def _real_extract(self, url):
863 video_id = self._match_id(url)
865 real_url = self._VIDEO_PAGE_TEMPLATE % video_id if url.startswith('facebook:') else url
866 return self._extract_from_url(real_url, video_id)
869 class FacebookPluginsVideoIE(InfoExtractor):
870 _VALID_URL = r'https?://(?:[\w-]+\.)?facebook\.com/plugins/video\.php\?.*?\bhref=(?P<id>https.+)'
872 _TESTS = [{
873 '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',
874 'md5': '5954e92cdfe51fe5782ae9bda7058a07',
875 'info_dict': {
876 'id': '10154383743583686',
877 'ext': 'mp4',
878 # TODO: Fix title, uploader
879 'title': 'What to do during the haze?',
880 'uploader': 'Gov.sg',
881 'upload_date': '20160826',
882 'timestamp': 1472184808,
884 'add_ie': [FacebookIE.ie_key()],
885 }, {
886 'url': 'https://www.facebook.com/plugins/video.php?href=https%3A%2F%2Fwww.facebook.com%2Fvideo.php%3Fv%3D10204634152394104',
887 'only_matching': True,
888 }, {
889 'url': 'https://www.facebook.com/plugins/video.php?href=https://www.facebook.com/gov.sg/videos/10154383743583686/&show_text=0&width=560',
890 'only_matching': True,
893 def _real_extract(self, url):
894 return self.url_result(
895 urllib.parse.unquote(self._match_id(url)),
896 FacebookIE.ie_key())
899 class FacebookRedirectURLIE(InfoExtractor):
900 IE_DESC = False # Do not list
901 _VALID_URL = r'https?://(?:[\w-]+\.)?facebook\.com/flx/warn[/?]'
902 _TESTS = [{
903 'url': 'https://www.facebook.com/flx/warn/?h=TAQHsoToz&u=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DpO8h3EaFRdo&s=1',
904 'info_dict': {
905 'id': 'pO8h3EaFRdo',
906 'ext': 'mp4',
907 'title': 'Tripeo Boiler Room x Dekmantel Festival DJ Set',
908 'description': 'md5:2d713ccbb45b686a1888397b2c77ca6b',
909 'channel_id': 'UCGBpxWJr9FNOcFYA5GkKrMg',
910 'playable_in_embed': True,
911 'categories': ['Music'],
912 'channel': 'Boiler Room',
913 'uploader_id': 'brtvofficial',
914 'uploader': 'Boiler Room',
915 'tags': 'count:11',
916 'duration': 3332,
917 'live_status': 'not_live',
918 'thumbnail': 'https://i.ytimg.com/vi/pO8h3EaFRdo/maxresdefault.jpg',
919 'channel_url': 'https://www.youtube.com/channel/UCGBpxWJr9FNOcFYA5GkKrMg',
920 'availability': 'public',
921 'uploader_url': 'http://www.youtube.com/user/brtvofficial',
922 'upload_date': '20150917',
923 'age_limit': 0,
924 'view_count': int,
925 'like_count': int,
927 'add_ie': ['Youtube'],
928 'params': {'skip_download': 'Youtube'},
931 def _real_extract(self, url):
932 redirect_url = url_or_none(parse_qs(url).get('u', [None])[-1])
933 if not redirect_url:
934 raise ExtractorError('Invalid facebook redirect URL', expected=True)
935 return self.url_result(redirect_url)
938 class FacebookReelIE(InfoExtractor):
939 _VALID_URL = r'https?://(?:[\w-]+\.)?facebook\.com/reel/(?P<id>\d+)'
940 IE_NAME = 'facebook:reel'
942 _TESTS = [{
943 'url': 'https://www.facebook.com/reel/1195289147628387',
944 'md5': 'a53256d10fc2105441fe0c4212ed8cea',
945 'info_dict': {
946 'id': '1195289147628387',
947 'ext': 'mp4',
948 'title': r're:9\.6K views · 355 reactions .+ Let the “Slapathon” commence!! .+ LL COOL J · Mama Said Knock You Out$',
949 'description': r're:When your trying to help your partner .+ LL COOL J · Mama Said Knock You Out$',
950 'uploader': 'Beast Camp Training',
951 'uploader_id': '100040874179269',
952 'duration': 9.579,
953 'timestamp': 1637502609,
954 'upload_date': '20211121',
955 'thumbnail': r're:^https?://.*',
956 'like_count': int,
957 'comment_count': int,
958 'repost_count': int,
962 def _real_extract(self, url):
963 video_id = self._match_id(url)
964 return self.url_result(
965 f'https://m.facebook.com/watch/?v={video_id}&_rdr', FacebookIE, video_id)
968 class FacebookAdsIE(InfoExtractor):
969 _VALID_URL = r'https?://(?:[\w-]+\.)?facebook\.com/ads/library/?\?(?:[^#]+&)?id=(?P<id>\d+)'
970 IE_NAME = 'facebook:ads'
972 _TESTS = [{
973 'url': 'https://www.facebook.com/ads/library/?id=899206155126718',
974 'info_dict': {
975 'id': '899206155126718',
976 'ext': 'mp4',
977 'title': 'video by Kandao',
978 'description': 'md5:0822724069e3aca97cbed5dabbab282e',
979 'uploader': 'Kandao',
980 'uploader_id': '774114102743284',
981 'uploader_url': r're:^https?://.*',
982 'timestamp': 1702548330,
983 'thumbnail': r're:^https?://.*',
984 'upload_date': '20231214',
985 'like_count': int,
987 }, {
988 # key 'watermarked_video_sd_url' missing
989 'url': 'https://www.facebook.com/ads/library/?id=501152689226254',
990 'info_dict': {
991 'id': '501152689226254',
992 'ext': 'mp4',
993 'title': 'video by mat.nawrocki',
994 'description': 'md5:02a446ace7ff8c3c37a2892922492490',
995 'uploader': 'mat.nawrocki',
996 'uploader_id': '148586968341456',
997 'uploader_url': r're:^https?://.*',
998 'timestamp': 1723452305,
999 'thumbnail': r're:^https?://.*',
1000 'upload_date': '20240812',
1001 'like_count': int,
1003 }, {
1004 'url': 'https://www.facebook.com/ads/library/?id=893637265423481',
1005 'info_dict': {
1006 'id': '893637265423481',
1007 'title': 'Jusqu\u2019\u00e0 -25% sur une s\u00e9lection de vins p\u00e9tillants italiens ',
1008 'uploader': 'Eataly Paris Marais',
1009 'uploader_id': '2086668958314152',
1010 'uploader_url': r're:^https?://.*',
1011 'timestamp': 1703571529,
1012 'upload_date': '20231226',
1013 'like_count': int,
1015 'playlist_count': 3,
1016 }, {
1017 'url': 'https://es-la.facebook.com/ads/library/?id=901230958115569',
1018 'only_matching': True,
1019 }, {
1020 'url': 'https://m.facebook.com/ads/library/?id=901230958115569',
1021 'only_matching': True,
1024 _FORMATS_MAP = {
1025 'watermarked_video_sd_url': ('sd-wmk', 'SD, watermarked'),
1026 'video_sd_url': ('sd', None),
1027 'watermarked_video_hd_url': ('hd-wmk', 'HD, watermarked'),
1028 'video_hd_url': ('hd', None),
1031 def _extract_formats(self, video_dict):
1032 formats = []
1033 for format_key, format_url in traverse_obj(video_dict, (
1034 {dict.items}, lambda _, v: v[0] in self._FORMATS_MAP and url_or_none(v[1]),
1036 formats.append({
1037 'format_id': self._FORMATS_MAP[format_key][0],
1038 'format_note': self._FORMATS_MAP[format_key][1],
1039 'url': format_url,
1040 'ext': 'mp4',
1041 'quality': qualities(tuple(self._FORMATS_MAP))(format_key),
1043 return formats
1045 def _real_extract(self, url):
1046 video_id = self._match_id(url)
1047 webpage = self._download_webpage(url, video_id)
1049 post_data = traverse_obj(
1050 re.findall(r'data-sjs>({.*?ScheduledServerJS.*?})</script>', webpage), (..., {json.loads}))
1051 data = get_first(post_data, (
1052 'require', ..., ..., ..., '__bbox', 'require', ..., ..., ...,
1053 'entryPointRoot', 'otherProps', 'deeplinkAdCard', 'snapshot', {dict}))
1054 if not data:
1055 raise ExtractorError('Unable to extract ad data')
1057 title = data.get('title')
1058 if not title or title == '{{product.name}}':
1059 title = join_nonempty('display_format', 'page_name', delim=' by ', from_dict=data)
1060 markup_id = traverse_obj(data, ('body', '__m', {str}))
1061 markup = traverse_obj(post_data, (
1062 ..., 'require', ..., ..., ..., '__bbox', 'markup', lambda _, v: v[0].startswith(markup_id),
1063 ..., '__html', {clean_html}, {lambda x: not x.startswith('{{product.') and x}, any))
1065 info_dict = merge_dicts({
1066 'title': title,
1067 'description': markup or None,
1068 }, traverse_obj(data, {
1069 'description': ('link_description', {lambda x: x if not x.startswith('{{product.') else None}),
1070 'uploader': ('page_name', {str}),
1071 'uploader_id': ('page_id', {str_or_none}),
1072 'uploader_url': ('page_profile_uri', {url_or_none}),
1073 'timestamp': ('creation_time', {int_or_none}),
1074 'like_count': ('page_like_count', {int_or_none}),
1077 entries = []
1078 for idx, entry in enumerate(traverse_obj(
1079 data, (('videos', 'cards'), lambda _, v: any(url_or_none(v.get(f)) for f in self._FORMATS_MAP))), 1,
1081 entries.append({
1082 'id': f'{video_id}_{idx}',
1083 'title': entry.get('title') or title,
1084 'description': traverse_obj(entry, 'body', 'link_description') or info_dict.get('description'),
1085 'thumbnail': url_or_none(entry.get('video_preview_image_url')),
1086 'formats': self._extract_formats(entry),
1089 if len(entries) == 1:
1090 info_dict.update(entries[0])
1092 elif len(entries) > 1:
1093 info_dict.update({
1094 'title': entries[0]['title'],
1095 'entries': entries,
1096 '_type': 'playlist',
1099 info_dict['id'] = video_id
1101 return info_dict