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