]> jfr.im git - yt-dlp.git/blob - yt_dlp/extractor/facebook.py
[cleanup] Add more ruff rules (#10149)
[yt-dlp.git] / yt_dlp / extractor / facebook.py
1 import json
2 import re
3 import urllib.parse
4
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,
31 )
32
33
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/
55 )|
56 facebook:
57 )
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)''',
66 ]
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'
71
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'
74
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': 3132.184,
88 'view_count': int,
89 'concurrent_view_count': 0,
90 },
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,
101 },
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': 'pfbid028wxorhX2ErLFJ578N6P3crHD3PHmXTCqCvfBpsnbSLmbokwSY75p5hWBjHGkG4zxl',
116 'duration': 131.03,
117 'concurrent_view_count': int,
118 },
119 }, {
120 'note': 'Video with DASH manifest',
121 'url': 'https://www.facebook.com/video.php?v=957955867617029',
122 'md5': 'b2c28d528273b323abe5c6ab59f0f030',
123 'info_dict': {
124 'id': '957955867617029',
125 'ext': 'mp4',
126 'title': 'When you post epic content on instagram.com/433 8 million followers, this is ...',
127 'uploader': 'Demy de Zeeuw',
128 'upload_date': '20160110',
129 'timestamp': 1452431627,
130 },
131 'skip': 'Requires logging in',
132 }, {
133 'url': 'https://www.facebook.com/maxlayn/posts/10153807558977570',
134 'md5': '037b1fa7f3c2d02b7a0d7bc16031ecc6',
135 'info_dict': {
136 'id': '544765982287235',
137 'ext': 'mp4',
138 'title': '"What are you doing running in the snow?"',
139 'uploader': 'FailArmy',
140 },
141 'skip': 'Video gone',
142 }, {
143 'url': 'https://m.facebook.com/story.php?story_fbid=1035862816472149&id=116132035111903',
144 'md5': '1deb90b6ac27f7efcf6d747c8a27f5e3',
145 'info_dict': {
146 'id': '1035862816472149',
147 'ext': 'mp4',
148 'title': 'What the Flock Is Going On In New Zealand Credit: ViralHog',
149 'uploader': 'S. Saint',
150 },
151 'skip': 'Video gone',
152 }, {
153 'note': 'swf params escaped',
154 'url': 'https://www.facebook.com/barackobama/posts/10153664894881749',
155 'md5': '97ba073838964d12c70566e0085c2b91',
156 'info_dict': {
157 'id': '10153664894881749',
158 'ext': 'mp4',
159 'title': 'Average time to confirm recent Supreme Court nominees: 67 days Longest it\'s t...',
160 'thumbnail': r're:^https?://.*',
161 'timestamp': 1456259628,
162 'upload_date': '20160223',
163 'uploader': 'Barack Obama',
164 },
165 'skip': 'Gif on giphy.com gone',
166 }, {
167 # have 1080P, but only up to 720p in swf params
168 # data.video.story.attachments[].media
169 'url': 'https://www.facebook.com/cnn/videos/10155529876156509/',
170 'md5': 'ca63897a90c9452efee5f8c40d080e25',
171 'info_dict': {
172 'id': '10155529876156509',
173 'ext': 'mp4',
174 'title': 'Holocaust survivor becomes US citizen',
175 'description': 'She survived the holocaust — and years later, she’s getting her citizenship so she can vote for Hillary Clinton http://cnn.it/2eERh5f',
176 'timestamp': 1477818095,
177 'upload_date': '20161030',
178 'uploader': 'CNN',
179 'thumbnail': r're:^https?://.*',
180 'view_count': int,
181 'uploader_id': '100059479812265',
182 'concurrent_view_count': int,
183 'duration': 44.478,
184 },
185 }, {
186 # bigPipe.onPageletArrive ... onPageletArrive pagelet_group_mall
187 # data.node.comet_sections.content.story.attachments[].style_type_renderer.attachment.media
188 'url': 'https://www.facebook.com/yaroslav.korpan/videos/1417995061575415/',
189 'info_dict': {
190 'id': '1417995061575415',
191 'ext': 'mp4',
192 'title': 'Довгоочікуване відео | By Yaroslav - Facebook',
193 'description': 'Довгоочікуване відео',
194 'timestamp': 1486648217,
195 'upload_date': '20170209',
196 'uploader': 'Yaroslav Korpan',
197 'uploader_id': 'pfbid06AScABAWcW91qpiuGrLt99Ef9tvwHoXP6t8KeFYEqkSfreMtfa9nTveh8b2ZEVSWl',
198 'concurrent_view_count': int,
199 'thumbnail': r're:^https?://.*',
200 'view_count': int,
201 'duration': 11736.446,
202 },
203 'params': {
204 'skip_download': True,
205 },
206 }, {
207 # FIXME: Cannot parse data error
208 'url': 'https://www.facebook.com/LaGuiaDelVaron/posts/1072691702860471',
209 'info_dict': {
210 'id': '1072691702860471',
211 'ext': 'mp4',
212 'title': 'md5:ae2d22a93fbb12dad20dc393a869739d',
213 'timestamp': 1477305000,
214 'upload_date': '20161024',
215 'uploader': 'La Guía Del Varón',
216 'thumbnail': r're:^https?://.*',
217 },
218 'skip': 'Requires logging in',
219 }, {
220 # data.node.comet_sections.content.story.attachments[].style_type_renderer.attachment.media
221 'url': 'https://www.facebook.com/groups/1024490957622648/permalink/1396382447100162/',
222 'info_dict': {
223 'id': '202882990186699',
224 'ext': 'mp4',
225 'title': 'birb (O v O") | Hello? Yes your uber ride is here',
226 'description': 'Hello? Yes your uber ride is here * Jukin Media Verified * Find this video and others like it by visiting...',
227 'timestamp': 1486035513,
228 'upload_date': '20170202',
229 'uploader': 'Elisabeth Ahtn',
230 'uploader_id': '100013949973717',
231 },
232 'skip': 'Requires logging in',
233 }, {
234 # data.node.comet_sections.content.story.attachments[].throwbackStyles.attachment_target_renderer.attachment.target.attachments[].styles.attachment.media
235 'url': 'https://www.facebook.com/groups/1645456212344334/posts/3737828833107051/',
236 'info_dict': {
237 'id': '1569199726448814',
238 'ext': 'mp4',
239 'title': 'Pence MUST GO!',
240 'description': 'Vickie Gentry shared a memory.',
241 'timestamp': 1511548260,
242 'upload_date': '20171124',
243 'uploader': 'Vickie Gentry',
244 'uploader_id': 'pfbid0FuZhHCeWDAxWxEbr3yKPFaRstXvRxgsp9uCPG6GjD4J2AitB35NUAuJ4Q75KcjiDl',
245 'thumbnail': r're:^https?://.*',
246 'duration': 148.435,
247 },
248 }, {
249 # data.node.comet_sections.content.story.attachments[].styles.attachment.media
250 'url': 'https://www.facebook.com/attn/posts/pfbid0j1Czf2gGDVqeQ8KiMLFm3pWN8GxsQmeRrVhimWDzMuKQoR8r4b1knNsejELmUgyhl',
251 'info_dict': {
252 'id': '6968553779868435',
253 'ext': 'mp4',
254 'description': 'md5:2f2fcf93e97ac00244fe64521bbdb0cb',
255 'uploader': 'ATTN:',
256 'upload_date': '20231207',
257 'title': 'ATTN:',
258 'duration': 132.675,
259 'uploader_id': '100064451419378',
260 'view_count': int,
261 'thumbnail': r're:^https?://.*',
262 'timestamp': 1701975646,
263 },
264 }, {
265 # data.node.comet_sections.content.story.attachments[].styles.attachment.media
266 'url': 'https://www.facebook.com/permalink.php?story_fbid=pfbid0fqQuVEQyXRa9Dp4RcaTR14KHU3uULHV1EK7eckNXSH63JMuoALsAvVCJ97zAGitil&id=100068861234290',
267 'info_dict': {
268 'id': '270103405756416',
269 'ext': 'mp4',
270 'title': 'Lela Evans',
271 '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...',
272 'thumbnail': r're:^https?://.*',
273 'uploader': 'Lela Evans',
274 'uploader_id': 'pfbid0shZJipuigyy5mqrUJn9ub5LJFWNHvan5prtyi3LrDuuuJ4NwrURgnQHYR9fywBepl',
275 'upload_date': '20231228',
276 'timestamp': 1703804085,
277 'duration': 394.347,
278 'view_count': int,
279 },
280 }, {
281 'url': 'https://www.facebook.com/story.php?story_fbid=pfbid0Fnzhm8UuzjBYpPMNFzaSpFE9UmLdU4fJN8qTANi1Dmtj5q7DNrL5NERXfsAzDEV7l&id=100073071055552',
282 'only_matching': True,
283 }, {
284 'url': 'https://www.facebook.com/video.php?v=10204634152394104',
285 'only_matching': True,
286 }, {
287 'url': 'https://www.facebook.com/amogood/videos/1618742068337349/?fref=nf',
288 'only_matching': True,
289 }, {
290 # data.mediaset.currMedia.edges
291 'url': 'https://www.facebook.com/ChristyClarkForBC/videos/vb.22819070941/10153870694020942/?type=2&theater',
292 'only_matching': True,
293 }, {
294 # data.video.story.attachments[].media
295 'url': 'facebook:544765982287235',
296 'only_matching': True,
297 }, {
298 # data.node.comet_sections.content.story.attachments[].style_type_renderer.attachment.media
299 'url': 'https://www.facebook.com/groups/164828000315060/permalink/764967300301124/',
300 'only_matching': True,
301 }, {
302 # data.video.creation_story.attachments[].media
303 'url': 'https://zh-hk.facebook.com/peoplespower/videos/1135894589806027/',
304 'only_matching': True,
305 }, {
306 # data.video
307 'url': 'https://www.facebookwkhpilnemxj7asaniu7vnjjbiltxjqhye3mhbshg7kx5tfyd.onion/video.php?v=274175099429670',
308 'only_matching': True,
309 }, {
310 # no title
311 'url': 'https://www.facebook.com/onlycleverentertainment/videos/1947995502095005/',
312 'only_matching': True,
313 }, {
314 # data.video
315 'url': 'https://www.facebook.com/WatchESLOne/videos/359649331226507/',
316 'info_dict': {
317 'id': '359649331226507',
318 'ext': 'mp4',
319 'title': 'Fnatic vs. EG - Group A - Opening Match - ESL One Birmingham Day 1',
320 'description': '#ESLOne VoD - Birmingham Finals Day#1 Fnatic vs. @Evil Geniuses',
321 'timestamp': 1527084179,
322 'upload_date': '20180523',
323 'uploader': 'ESL One Dota 2',
324 'uploader_id': '100066514874195',
325 'duration': 4524.212,
326 'view_count': int,
327 'thumbnail': r're:^https?://.*',
328 'concurrent_view_count': int,
329 },
330 'params': {
331 'skip_download': True,
332 },
333 }, {
334 # data.node.comet_sections.content.story.attachments[].style_type_renderer.attachment.all_subattachments.nodes[].media
335 'url': 'https://www.facebook.com/100033620354545/videos/106560053808006/',
336 'info_dict': {
337 'id': '106560053808006',
338 'ext': 'mp4',
339 'title': 'Josef',
340 'thumbnail': r're:^https?://.*',
341 'concurrent_view_count': int,
342 'uploader_id': 'pfbid0cibUN6tV7DYgdbJdsUFN46wc4jKpVSPAvJQhFofGqBGmVn3V3JtAs2tfUwziw2hUl',
343 'timestamp': 1549275572,
344 'duration': 3.413,
345 'uploader': 'Josef Novak',
346 'description': '',
347 'upload_date': '20190204',
348 },
349 }, {
350 # data.video.story.attachments[].media
351 'url': 'https://www.facebook.com/watch/?v=647537299265662',
352 'only_matching': True,
353 }, {
354 # FIXME: https://github.com/yt-dlp/yt-dlp/issues/542
355 # data.node.comet_sections.content.story.attachments[].style_type_renderer.attachment.all_subattachments.nodes[].media
356 'url': 'https://www.facebook.com/PankajShahLondon/posts/10157667649866271',
357 'info_dict': {
358 'id': '10157667649866271',
359 },
360 'playlist_count': 3,
361 'skip': 'Requires logging in',
362 }, {
363 # data.nodes[].comet_sections.content.story.attachments[].style_type_renderer.attachment.media
364 'url': 'https://m.facebook.com/Alliance.Police.Department/posts/4048563708499330',
365 'info_dict': {
366 'id': '117576630041613',
367 'ext': 'mp4',
368 # TODO: title can be extracted from video page
369 'title': 'Facebook video #117576630041613',
370 'uploader_id': '189393014416438',
371 'upload_date': '20201123',
372 'timestamp': 1606162592,
373 },
374 'skip': 'Requires logging in',
375 }, {
376 # node.comet_sections.content.story.attached_story.attachments.style_type_renderer.attachment.media
377 'url': 'https://www.facebook.com/groups/ateistiskselskab/permalink/10154930137678856/',
378 'info_dict': {
379 'id': '211567722618337',
380 'ext': 'mp4',
381 'title': 'Facebook video #211567722618337',
382 'uploader_id': '127875227654254',
383 'upload_date': '20161122',
384 'timestamp': 1479793574,
385 },
386 'skip': 'No video',
387 }, {
388 # data.video.creation_story.attachments[].media
389 'url': 'https://www.facebook.com/watch/live/?v=1823658634322275',
390 'only_matching': True,
391 }, {
392 'url': 'https://www.facebook.com/watchparty/211641140192478',
393 'info_dict': {
394 'id': '211641140192478',
395 },
396 'playlist_count': 1,
397 'skip': 'Requires logging in',
398 }, {
399 # data.event.cover_media_renderer.cover_video
400 'url': 'https://m.facebook.com/events/1509582499515440',
401 'info_dict': {
402 'id': '637246984455045',
403 'ext': 'mp4',
404 'title': 'ANALISI IN CAMPO OSCURO " Coaguli nel sangue dei vaccinati"',
405 'description': 'Other event by Comitato Liberi Pensatori on Tuesday, October 18 2022',
406 'thumbnail': r're:^https?://.*',
407 'uploader': 'Comitato Liberi Pensatori',
408 'uploader_id': '100065709540881',
409 },
410 }]
411 _SUPPORTED_PAGLETS_REGEX = r'(?:pagelet_group_mall|permalink_video_pagelet|hyperfeed_story_id_[0-9a-f]+)'
412 _api_config = {
413 'graphURI': '/api/graphql/',
414 }
415
416 def _perform_login(self, username, password):
417 login_page_req = Request(self._LOGIN_URL)
418 self._set_cookie('facebook.com', 'locale', 'en_US')
419 login_page = self._download_webpage(login_page_req, None,
420 note='Downloading login page',
421 errnote='Unable to download login page')
422 lsd = self._search_regex(
423 r'<input type="hidden" name="lsd" value="([^"]*)"',
424 login_page, 'lsd')
425 lgnrnd = self._search_regex(r'name="lgnrnd" value="([^"]*?)"', login_page, 'lgnrnd')
426
427 login_form = {
428 'email': username,
429 'pass': password,
430 'lsd': lsd,
431 'lgnrnd': lgnrnd,
432 'next': 'http://facebook.com/home.php',
433 'default_persistent': '0',
434 'legacy_return': '1',
435 'timezone': '-60',
436 'trynum': '1',
437 }
438 request = Request(self._LOGIN_URL, urlencode_postdata(login_form))
439 request.headers['Content-Type'] = 'application/x-www-form-urlencoded'
440 try:
441 login_results = self._download_webpage(request, None,
442 note='Logging in', errnote='unable to fetch login page')
443 if re.search(r'<form(.*)name="login"(.*)</form>', login_results) is not None:
444 error = self._html_search_regex(
445 r'(?s)<div[^>]+class=(["\']).*?login_error_box.*?\1[^>]*><div[^>]*>.*?</div><div[^>]*>(?P<error>.+?)</div>',
446 login_results, 'login error', default=None, group='error')
447 if error:
448 raise ExtractorError(f'Unable to login: {error}', expected=True)
449 self.report_warning('unable to log in: bad username/password, or exceeded login rate limit (~3/min). Check credentials or wait.')
450 return
451
452 fb_dtsg = self._search_regex(
453 r'name="fb_dtsg" value="(.+?)"', login_results, 'fb_dtsg', default=None)
454 h = self._search_regex(
455 r'name="h"\s+(?:\w+="[^"]+"\s+)*?value="([^"]+)"', login_results, 'h', default=None)
456
457 if not fb_dtsg or not h:
458 return
459
460 check_form = {
461 'fb_dtsg': fb_dtsg,
462 'h': h,
463 'name_action_selected': 'dont_save',
464 }
465 check_req = Request(self._CHECKPOINT_URL, urlencode_postdata(check_form))
466 check_req.headers['Content-Type'] = 'application/x-www-form-urlencoded'
467 check_response = self._download_webpage(check_req, None,
468 note='Confirming login')
469 if re.search(r'id="checkpointSubmitButton"', check_response) is not None:
470 self.report_warning('Unable to confirm login, you have to login in your browser and authorize the login.')
471 except network_exceptions as err:
472 self.report_warning(f'unable to log in: {err}')
473 return
474
475 def _extract_from_url(self, url, video_id):
476 webpage = self._download_webpage(
477 url.replace('://m.facebook.com/', '://www.facebook.com/'), video_id)
478
479 def extract_metadata(webpage):
480 post_data = [self._parse_json(j, video_id, fatal=False) for j in re.findall(
481 r'data-sjs>({.*?ScheduledServerJS.*?})</script>', webpage)]
482 post = traverse_obj(post_data, (
483 ..., 'require', ..., ..., ..., '__bbox', 'require', ..., ..., ..., '__bbox', 'result', 'data'), expected_type=dict) or []
484 media = traverse_obj(post, (..., 'attachments', ..., lambda k, v: (
485 k == 'media' and str(v['id']) == video_id and v['__typename'] == 'Video')), expected_type=dict)
486 title = get_first(media, ('title', 'text'))
487 description = get_first(media, ('creation_story', 'comet_sections', 'message', 'story', 'message', 'text'))
488 page_title = title or self._html_search_regex((
489 r'<h2\s+[^>]*class="uiHeaderTitle"[^>]*>(?P<content>[^<]*)</h2>',
490 r'(?s)<span class="fbPhotosPhotoCaption".*?id="fbPhotoPageCaption"><span class="hasCaption">(?P<content>.*?)</span>',
491 self._meta_regex('og:title'), self._meta_regex('twitter:title'), r'<title>(?P<content>.+?)</title>',
492 ), webpage, 'title', default=None, group='content')
493 description = description or self._html_search_meta(
494 ['description', 'og:description', 'twitter:description'],
495 webpage, 'description', default=None)
496 uploader_data = (
497 get_first(media, ('owner', {dict}))
498 or get_first(post, ('video', 'creation_story', 'attachments', ..., 'media', lambda k, v: k == 'owner' and v['name']))
499 or get_first(post, (..., 'video', lambda k, v: k == 'owner' and v['name']))
500 or get_first(post, ('node', 'actors', ..., {dict}))
501 or get_first(post, ('event', 'event_creator', {dict})) or {})
502 uploader = uploader_data.get('name') or (
503 clean_html(get_element_by_id('fbPhotoPageAuthorName', webpage))
504 or self._search_regex(
505 (r'ownerName\s*:\s*"([^"]+)"', *self._og_regexes('title')), webpage, 'uploader', fatal=False))
506 timestamp = int_or_none(self._search_regex(
507 r'<abbr[^>]+data-utime=["\'](\d+)', webpage,
508 'timestamp', default=None))
509 thumbnail = self._html_search_meta(
510 ['og:image', 'twitter:image'], webpage, 'thumbnail', default=None)
511 # some webpages contain unretrievable thumbnail urls
512 # like https://lookaside.fbsbx.com/lookaside/crawler/media/?media_id=10155168902769113&get_thumbnail=1
513 # in https://www.facebook.com/yaroslav.korpan/videos/1417995061575415/
514 if thumbnail and not re.search(r'\.(?:jpg|png)', thumbnail):
515 thumbnail = None
516 info_dict = {
517 'description': description,
518 'uploader': uploader,
519 'uploader_id': uploader_data.get('id'),
520 'timestamp': timestamp,
521 'thumbnail': thumbnail,
522 'view_count': parse_count(self._search_regex(
523 (r'\bviewCount\s*:\s*["\']([\d,.]+)', r'video_view_count["\']\s*:\s*(\d+)'),
524 webpage, 'view count', default=None)),
525 'concurrent_view_count': get_first(post, (
526 ('video', (..., ..., 'attachments', ..., 'media')), 'liveViewerCount', {int_or_none})),
527 }
528
529 info_json_ld = self._search_json_ld(webpage, video_id, default={})
530 info_json_ld['title'] = (re.sub(r'\s*\|\s*Facebook$', '', title or info_json_ld.get('title') or page_title or '')
531 or (description or '').replace('\n', ' ') or f'Facebook video #{video_id}')
532 return merge_dicts(info_json_ld, info_dict)
533
534 video_data = None
535
536 def extract_video_data(instances):
537 video_data = []
538 for item in instances:
539 if try_get(item, lambda x: x[1][0]) == 'VideoConfig':
540 video_item = item[2][0]
541 if video_item.get('video_id'):
542 video_data.append(video_item['videoData'])
543 return video_data
544
545 server_js_data = self._parse_json(self._search_regex(
546 [r'handleServerJS\(({.+})(?:\);|,")', r'\bs\.handle\(({.+?})\);'],
547 webpage, 'server js data', default='{}'), video_id, fatal=False)
548
549 if server_js_data:
550 video_data = extract_video_data(server_js_data.get('instances', []))
551
552 def extract_from_jsmods_instances(js_data):
553 if js_data:
554 return extract_video_data(try_get(
555 js_data, lambda x: x['jsmods']['instances'], list) or [])
556
557 def extract_dash_manifest(video, formats):
558 dash_manifest = traverse_obj(video, 'dash_manifest', 'playlist', expected_type=str)
559 if dash_manifest:
560 formats.extend(self._parse_mpd_formats(
561 compat_etree_fromstring(urllib.parse.unquote_plus(dash_manifest)),
562 mpd_url=video.get('dash_manifest_url')))
563
564 def process_formats(info):
565 # Downloads with browser's User-Agent are rate limited. Working around
566 # with non-browser User-Agent.
567 for f in info['formats']:
568 # Downloads with browser's User-Agent are rate limited. Working around
569 # with non-browser User-Agent.
570 f.setdefault('http_headers', {})['User-Agent'] = 'facebookexternalhit/1.1'
571 # Formats larger than ~500MB will return error 403 unless chunk size is regulated
572 f.setdefault('downloader_options', {})['http_chunk_size'] = 250 << 20
573
574 def extract_relay_data(_filter):
575 return self._parse_json(self._search_regex(
576 rf'data-sjs>({{.*?{_filter}.*?}})</script>',
577 webpage, 'replay data', default='{}'), video_id, fatal=False) or {}
578
579 def extract_relay_prefetched_data(_filter):
580 return traverse_obj(extract_relay_data(_filter), (
581 'require', (None, (..., ..., ..., '__bbox', 'require')),
582 lambda _, v: any(key.startswith('RelayPrefetchedStreamCache') for key in v),
583 ..., ..., '__bbox', 'result', 'data', {dict}), get_all=False) or {}
584
585 if not video_data:
586 server_js_data = self._parse_json(self._search_regex([
587 r'bigPipe\.onPageletArrive\(({.+?})\)\s*;\s*}\s*\)\s*,\s*["\']onPageletArrive\s+' + self._SUPPORTED_PAGLETS_REGEX,
588 rf'bigPipe\.onPageletArrive\(({{.*?id\s*:\s*"{self._SUPPORTED_PAGLETS_REGEX}".*?}})\);',
589 ], webpage, 'js data', default='{}'), video_id, js_to_json, False)
590 video_data = extract_from_jsmods_instances(server_js_data)
591
592 if not video_data:
593 data = extract_relay_prefetched_data(
594 r'"(?:dash_manifest|playable_url(?:_quality_hd)?)')
595 if data:
596 entries = []
597
598 def parse_graphql_video(video):
599 v_id = video.get('videoId') or video.get('id') or video_id
600 reel_info = traverse_obj(
601 video, ('creation_story', 'short_form_video_context', 'playback_video', {dict}))
602 if reel_info:
603 video = video['creation_story']
604 video['owner'] = traverse_obj(video, ('short_form_video_context', 'video_owner'))
605 video.update(reel_info)
606 formats = []
607 q = qualities(['sd', 'hd'])
608 for key, format_id in (('playable_url', 'sd'), ('playable_url_quality_hd', 'hd'),
609 ('playable_url_dash', ''), ('browser_native_hd_url', 'hd'),
610 ('browser_native_sd_url', 'sd')):
611 playable_url = video.get(key)
612 if not playable_url:
613 continue
614 if determine_ext(playable_url) == 'mpd':
615 formats.extend(self._extract_mpd_formats(playable_url, video_id))
616 else:
617 formats.append({
618 'format_id': format_id,
619 # sd, hd formats w/o resolution info should be deprioritized below DASH
620 'quality': q(format_id) - 3,
621 'url': playable_url,
622 })
623 extract_dash_manifest(video, formats)
624
625 automatic_captions, subtitles = {}, {}
626 is_broadcast = traverse_obj(video, ('is_video_broadcast', {bool}))
627 for caption in traverse_obj(video, (
628 'video_available_captions_locales',
629 {lambda x: sorted(x, key=lambda c: c['locale'])},
630 lambda _, v: url_or_none(v['captions_url']),
631 )):
632 lang = caption.get('localized_language') or 'und'
633 subs = {
634 'url': caption['captions_url'],
635 'name': format_field(caption, 'localized_country', f'{lang} (%s)', default=lang),
636 }
637 if caption.get('localized_creation_method') or is_broadcast:
638 automatic_captions.setdefault(caption['locale'], []).append(subs)
639 else:
640 subtitles.setdefault(caption['locale'], []).append(subs)
641 captions_url = traverse_obj(video, ('captions_url', {url_or_none}))
642 if captions_url and not automatic_captions and not subtitles:
643 locale = self._html_search_meta(
644 ['og:locale', 'twitter:locale'], webpage, 'locale', default='en_US')
645 (automatic_captions if is_broadcast else subtitles)[locale] = [{'url': captions_url}]
646
647 info = {
648 'id': v_id,
649 'formats': formats,
650 'thumbnail': traverse_obj(
651 video, ('thumbnailImage', 'uri'), ('preferred_thumbnail', 'image', 'uri')),
652 'uploader_id': traverse_obj(video, ('owner', 'id', {str_or_none})),
653 'timestamp': traverse_obj(video, 'publish_time', 'creation_time', expected_type=int_or_none),
654 'duration': (float_or_none(video.get('playable_duration_in_ms'), 1000)
655 or float_or_none(video.get('length_in_second'))),
656 'automatic_captions': automatic_captions,
657 'subtitles': subtitles,
658 }
659 process_formats(info)
660 description = try_get(video, lambda x: x['savable_description']['text'])
661 title = video.get('name')
662 if title:
663 info.update({
664 'title': title,
665 'description': description,
666 })
667 else:
668 info['title'] = description or f'Facebook video #{v_id}'
669 entries.append(info)
670
671 def parse_attachment(attachment, key='media'):
672 media = attachment.get(key) or {}
673 if media.get('__typename') == 'Video':
674 return parse_graphql_video(media)
675
676 nodes = variadic(traverse_obj(data, 'nodes', 'node') or [])
677 attachments = traverse_obj(nodes, (
678 ..., 'comet_sections', 'content', 'story', (None, 'attached_story'), 'attachments',
679 ..., ('styles', 'style_type_renderer', ('throwbackStyles', 'attachment_target_renderer')),
680 'attachment', {dict}))
681 for attachment in attachments:
682 ns = traverse_obj(attachment, ('all_subattachments', 'nodes', ..., {dict}),
683 ('target', 'attachments', ..., 'styles', 'attachment', {dict}))
684 for n in ns:
685 parse_attachment(n)
686 parse_attachment(attachment)
687
688 edges = try_get(data, lambda x: x['mediaset']['currMedia']['edges'], list) or []
689 for edge in edges:
690 parse_attachment(edge, key='node')
691
692 video = traverse_obj(data, (
693 'event', 'cover_media_renderer', 'cover_video'), 'video', expected_type=dict) or {}
694 if video:
695 attachments = try_get(video, [
696 lambda x: x['story']['attachments'],
697 lambda x: x['creation_story']['attachments'],
698 ], list) or []
699 for attachment in attachments:
700 parse_attachment(attachment)
701 if not entries:
702 parse_graphql_video(video)
703
704 if len(entries) > 1:
705 return self.playlist_result(entries, video_id)
706
707 video_info = entries[0] if entries else {'id': video_id}
708 webpage_info = extract_metadata(webpage)
709 # honor precise duration in video info
710 if video_info.get('duration'):
711 webpage_info['duration'] = video_info['duration']
712 # preserve preferred_thumbnail in video info
713 if video_info.get('thumbnail'):
714 webpage_info['thumbnail'] = video_info['thumbnail']
715 return merge_dicts(webpage_info, video_info)
716
717 if not video_data:
718 m_msg = re.search(r'class="[^"]*uiInterstitialContent[^"]*"><div>(.*?)</div>', webpage)
719 if m_msg is not None:
720 raise ExtractorError(
721 f'The video is not available, Facebook said: "{m_msg.group(1)}"',
722 expected=True)
723 elif any(p in webpage for p in (
724 '>You must log in to continue',
725 'id="login_form"',
726 'id="loginbutton"')):
727 self.raise_login_required()
728
729 if not video_data and '/watchparty/' in url:
730 post_data = {
731 'doc_id': 3731964053542869,
732 'variables': json.dumps({
733 'livingRoomID': video_id,
734 }),
735 }
736
737 prefetched_data = extract_relay_prefetched_data(r'"login_data"\s*:\s*{')
738 if prefetched_data:
739 lsd = try_get(prefetched_data, lambda x: x['login_data']['lsd'], dict)
740 if lsd:
741 post_data[lsd['name']] = lsd['value']
742
743 relay_data = extract_relay_data(r'\[\s*"RelayAPIConfigDefaults"\s*,')
744 for define in (relay_data.get('define') or []):
745 if define[0] == 'RelayAPIConfigDefaults':
746 self._api_config = define[2]
747
748 living_room = self._download_json(
749 urljoin(url, self._api_config['graphURI']), video_id,
750 data=urlencode_postdata(post_data))['data']['living_room']
751
752 entries = []
753 for edge in (try_get(living_room, lambda x: x['recap']['watched_content']['edges']) or []):
754 video = try_get(edge, lambda x: x['node']['video']) or {}
755 v_id = video.get('id')
756 if not v_id:
757 continue
758 v_id = str(v_id)
759 entries.append(self.url_result(
760 self._VIDEO_PAGE_TEMPLATE % v_id,
761 self.ie_key(), v_id, video.get('name')))
762
763 return self.playlist_result(entries, video_id)
764
765 if not video_data:
766 # Video info not in first request, do a secondary request using
767 # tahoe player specific URL
768 tahoe_data = self._download_webpage(
769 self._VIDEO_PAGE_TAHOE_TEMPLATE % video_id, video_id,
770 data=urlencode_postdata({
771 '__a': 1,
772 '__pc': self._search_regex(
773 r'pkg_cohort["\']\s*:\s*["\'](.+?)["\']', webpage,
774 'pkg cohort', default='PHASED:DEFAULT'),
775 '__rev': self._search_regex(
776 r'client_revision["\']\s*:\s*(\d+),', webpage,
777 'client revision', default='3944515'),
778 'fb_dtsg': self._search_regex(
779 r'"DTSGInitialData"\s*,\s*\[\]\s*,\s*{\s*"token"\s*:\s*"([^"]+)"',
780 webpage, 'dtsg token', default=''),
781 }),
782 headers={
783 'Content-Type': 'application/x-www-form-urlencoded',
784 })
785 tahoe_js_data = self._parse_json(
786 self._search_regex(
787 r'for\s+\(\s*;\s*;\s*\)\s*;(.+)', tahoe_data,
788 'tahoe js data', default='{}'),
789 video_id, fatal=False)
790 video_data = extract_from_jsmods_instances(tahoe_js_data)
791
792 if not video_data:
793 raise ExtractorError('Cannot parse data')
794
795 if len(video_data) > 1:
796 entries = []
797 for v in video_data:
798 video_url = v[0].get('video_url')
799 if not video_url:
800 continue
801 entries.append(self.url_result(urljoin(
802 url, video_url), self.ie_key(), v[0].get('video_id')))
803 return self.playlist_result(entries, video_id)
804 video_data = video_data[0]
805
806 formats = []
807 subtitles = {}
808 for f in video_data:
809 format_id = f['stream_type']
810 if f and isinstance(f, dict):
811 f = [f]
812 if not f or not isinstance(f, list):
813 continue
814 for quality in ('sd', 'hd'):
815 for src_type in ('src', 'src_no_ratelimit'):
816 src = f[0].get(f'{quality}_{src_type}')
817 if src:
818 # sd, hd formats w/o resolution info should be deprioritized below DASH
819 # TODO: investigate if progressive or src formats still exist
820 preference = -10 if format_id == 'progressive' else -3
821 if quality == 'hd':
822 preference += 1
823 formats.append({
824 'format_id': f'{format_id}_{quality}_{src_type}',
825 'url': src,
826 'quality': preference,
827 'height': 720 if quality == 'hd' else None,
828 })
829 extract_dash_manifest(f[0], formats)
830 subtitles_src = f[0].get('subtitles_src')
831 if subtitles_src:
832 subtitles.setdefault('en', []).append({'url': subtitles_src})
833
834 info_dict = {
835 'id': video_id,
836 'formats': formats,
837 'subtitles': subtitles,
838 }
839 process_formats(info_dict)
840 info_dict.update(extract_metadata(webpage))
841
842 return info_dict
843
844 def _real_extract(self, url):
845 video_id = self._match_id(url)
846
847 real_url = self._VIDEO_PAGE_TEMPLATE % video_id if url.startswith('facebook:') else url
848 return self._extract_from_url(real_url, video_id)
849
850
851 class FacebookPluginsVideoIE(InfoExtractor):
852 _VALID_URL = r'https?://(?:[\w-]+\.)?facebook\.com/plugins/video\.php\?.*?\bhref=(?P<id>https.+)'
853
854 _TESTS = [{
855 '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',
856 'md5': '5954e92cdfe51fe5782ae9bda7058a07',
857 'info_dict': {
858 'id': '10154383743583686',
859 'ext': 'mp4',
860 # TODO: Fix title, uploader
861 'title': 'What to do during the haze?',
862 'uploader': 'Gov.sg',
863 'upload_date': '20160826',
864 'timestamp': 1472184808,
865 },
866 'add_ie': [FacebookIE.ie_key()],
867 }, {
868 'url': 'https://www.facebook.com/plugins/video.php?href=https%3A%2F%2Fwww.facebook.com%2Fvideo.php%3Fv%3D10204634152394104',
869 'only_matching': True,
870 }, {
871 'url': 'https://www.facebook.com/plugins/video.php?href=https://www.facebook.com/gov.sg/videos/10154383743583686/&show_text=0&width=560',
872 'only_matching': True,
873 }]
874
875 def _real_extract(self, url):
876 return self.url_result(
877 urllib.parse.unquote(self._match_id(url)),
878 FacebookIE.ie_key())
879
880
881 class FacebookRedirectURLIE(InfoExtractor):
882 IE_DESC = False # Do not list
883 _VALID_URL = r'https?://(?:[\w-]+\.)?facebook\.com/flx/warn[/?]'
884 _TESTS = [{
885 'url': 'https://www.facebook.com/flx/warn/?h=TAQHsoToz&u=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DpO8h3EaFRdo&s=1',
886 'info_dict': {
887 'id': 'pO8h3EaFRdo',
888 'ext': 'mp4',
889 'title': 'Tripeo Boiler Room x Dekmantel Festival DJ Set',
890 'description': 'md5:2d713ccbb45b686a1888397b2c77ca6b',
891 'channel_id': 'UCGBpxWJr9FNOcFYA5GkKrMg',
892 'playable_in_embed': True,
893 'categories': ['Music'],
894 'channel': 'Boiler Room',
895 'uploader_id': 'brtvofficial',
896 'uploader': 'Boiler Room',
897 'tags': 'count:11',
898 'duration': 3332,
899 'live_status': 'not_live',
900 'thumbnail': 'https://i.ytimg.com/vi/pO8h3EaFRdo/maxresdefault.jpg',
901 'channel_url': 'https://www.youtube.com/channel/UCGBpxWJr9FNOcFYA5GkKrMg',
902 'availability': 'public',
903 'uploader_url': 'http://www.youtube.com/user/brtvofficial',
904 'upload_date': '20150917',
905 'age_limit': 0,
906 'view_count': int,
907 'like_count': int,
908 },
909 'add_ie': ['Youtube'],
910 'params': {'skip_download': 'Youtube'},
911 }]
912
913 def _real_extract(self, url):
914 redirect_url = url_or_none(parse_qs(url).get('u', [None])[-1])
915 if not redirect_url:
916 raise ExtractorError('Invalid facebook redirect URL', expected=True)
917 return self.url_result(redirect_url)
918
919
920 class FacebookReelIE(InfoExtractor):
921 _VALID_URL = r'https?://(?:[\w-]+\.)?facebook\.com/reel/(?P<id>\d+)'
922 IE_NAME = 'facebook:reel'
923
924 _TESTS = [{
925 'url': 'https://www.facebook.com/reel/1195289147628387',
926 'md5': 'f13dd37f2633595982db5ed8765474d3',
927 'info_dict': {
928 'id': '1195289147628387',
929 'ext': 'mp4',
930 'title': 'md5:b05800b5b1ad56c0ca78bd3807b6a61e',
931 'description': 'md5:22f03309b216ac84720183961441d8db',
932 'uploader': 'md5:723e6cb3091241160f20b3c5dc282af1',
933 'uploader_id': '100040874179269',
934 'duration': 9.579,
935 'timestamp': 1637502609,
936 'upload_date': '20211121',
937 'thumbnail': r're:^https?://.*',
938 },
939 }]
940
941 def _real_extract(self, url):
942 video_id = self._match_id(url)
943 return self.url_result(
944 f'https://m.facebook.com/watch/?v={video_id}&_rdr', FacebookIE, video_id)
945
946
947 class FacebookAdsIE(InfoExtractor):
948 _VALID_URL = r'https?://(?:[\w-]+\.)?facebook\.com/ads/library/?\?(?:[^#]+&)?id=(?P<id>\d+)'
949 IE_NAME = 'facebook:ads'
950
951 _TESTS = [{
952 'url': 'https://www.facebook.com/ads/library/?id=899206155126718',
953 'info_dict': {
954 'id': '899206155126718',
955 'ext': 'mp4',
956 'title': 'video by Kandao',
957 'uploader': 'Kandao',
958 'uploader_id': '774114102743284',
959 'uploader_url': r're:^https?://.*',
960 'timestamp': 1702548330,
961 'thumbnail': r're:^https?://.*',
962 'upload_date': '20231214',
963 'like_count': int,
964 },
965 }, {
966 'url': 'https://www.facebook.com/ads/library/?id=893637265423481',
967 'info_dict': {
968 'id': '893637265423481',
969 'title': 'Jusqu\u2019\u00e0 -25% sur une s\u00e9lection de vins p\u00e9tillants italiens ',
970 'uploader': 'Eataly Paris Marais',
971 'uploader_id': '2086668958314152',
972 'uploader_url': r're:^https?://.*',
973 'timestamp': 1703571529,
974 'upload_date': '20231226',
975 'like_count': int,
976 },
977 'playlist_count': 3,
978 }, {
979 'url': 'https://es-la.facebook.com/ads/library/?id=901230958115569',
980 'only_matching': True,
981 }, {
982 'url': 'https://m.facebook.com/ads/library/?id=901230958115569',
983 'only_matching': True,
984 }]
985
986 _FORMATS_MAP = {
987 'watermarked_video_sd_url': ('sd-wmk', 'SD, watermarked'),
988 'video_sd_url': ('sd', None),
989 'watermarked_video_hd_url': ('hd-wmk', 'HD, watermarked'),
990 'video_hd_url': ('hd', None),
991 }
992
993 def _extract_formats(self, video_dict):
994 formats = []
995 for format_key, format_url in traverse_obj(video_dict, (
996 {dict.items}, lambda _, v: v[0] in self._FORMATS_MAP and url_or_none(v[1]),
997 )):
998 formats.append({
999 'format_id': self._FORMATS_MAP[format_key][0],
1000 'format_note': self._FORMATS_MAP[format_key][1],
1001 'url': format_url,
1002 'ext': 'mp4',
1003 'quality': qualities(tuple(self._FORMATS_MAP))(format_key),
1004 })
1005 return formats
1006
1007 def _real_extract(self, url):
1008 video_id = self._match_id(url)
1009 webpage = self._download_webpage(url, video_id)
1010
1011 post_data = [self._parse_json(j, video_id, fatal=False)
1012 for j in re.findall(r's\.handle\(({.*})\);requireLazy\(', webpage)]
1013 data = traverse_obj(post_data, (
1014 ..., 'require', ..., ..., ..., 'props', 'deeplinkAdCard', 'snapshot', {dict}), get_all=False)
1015 if not data:
1016 raise ExtractorError('Unable to extract ad data')
1017
1018 title = data.get('title')
1019 if not title or title == '{{product.name}}':
1020 title = join_nonempty('display_format', 'page_name', delim=' by ', from_dict=data)
1021
1022 info_dict = traverse_obj(data, {
1023 'description': ('link_description', {str}, {lambda x: x if x != '{{product.description}}' else None}),
1024 'uploader': ('page_name', {str}),
1025 'uploader_id': ('page_id', {str_or_none}),
1026 'uploader_url': ('page_profile_uri', {url_or_none}),
1027 'timestamp': ('creation_time', {int_or_none}),
1028 'like_count': ('page_like_count', {int_or_none}),
1029 })
1030
1031 entries = []
1032 for idx, entry in enumerate(traverse_obj(
1033 data, (('videos', 'cards'), lambda _, v: any(url_or_none(v[f]) for f in self._FORMATS_MAP))), 1,
1034 ):
1035 entries.append({
1036 'id': f'{video_id}_{idx}',
1037 'title': entry.get('title') or title,
1038 'description': entry.get('link_description') or info_dict.get('description'),
1039 'thumbnail': url_or_none(entry.get('video_preview_image_url')),
1040 'formats': self._extract_formats(entry),
1041 })
1042
1043 if len(entries) == 1:
1044 info_dict.update(entries[0])
1045
1046 elif len(entries) > 1:
1047 info_dict.update({
1048 'title': entries[0]['title'],
1049 'entries': entries,
1050 '_type': 'playlist',
1051 })
1052
1053 info_dict['id'] = video_id
1054
1055 return info_dict