]> jfr.im git - yt-dlp.git/blob - yt_dlp/extractor/facebook.py
[ie/youtube] Suppress "Unavailable videos are hidden" warning (#10159)
[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 if not formats:
625 # Do not append false positive entry w/o any formats
626 return
627
628 automatic_captions, subtitles = {}, {}
629 is_broadcast = traverse_obj(video, ('is_video_broadcast', {bool}))
630 for caption in traverse_obj(video, (
631 'video_available_captions_locales',
632 {lambda x: sorted(x, key=lambda c: c['locale'])},
633 lambda _, v: url_or_none(v['captions_url']),
634 )):
635 lang = caption.get('localized_language') or 'und'
636 subs = {
637 'url': caption['captions_url'],
638 'name': format_field(caption, 'localized_country', f'{lang} (%s)', default=lang),
639 }
640 if caption.get('localized_creation_method') or is_broadcast:
641 automatic_captions.setdefault(caption['locale'], []).append(subs)
642 else:
643 subtitles.setdefault(caption['locale'], []).append(subs)
644 captions_url = traverse_obj(video, ('captions_url', {url_or_none}))
645 if captions_url and not automatic_captions and not subtitles:
646 locale = self._html_search_meta(
647 ['og:locale', 'twitter:locale'], webpage, 'locale', default='en_US')
648 (automatic_captions if is_broadcast else subtitles)[locale] = [{'url': captions_url}]
649
650 info = {
651 'id': v_id,
652 'formats': formats,
653 'thumbnail': traverse_obj(
654 video, ('thumbnailImage', 'uri'), ('preferred_thumbnail', 'image', 'uri')),
655 'uploader_id': traverse_obj(video, ('owner', 'id', {str_or_none})),
656 'timestamp': traverse_obj(video, 'publish_time', 'creation_time', expected_type=int_or_none),
657 'duration': (float_or_none(video.get('playable_duration_in_ms'), 1000)
658 or float_or_none(video.get('length_in_second'))),
659 'automatic_captions': automatic_captions,
660 'subtitles': subtitles,
661 }
662 process_formats(info)
663 description = try_get(video, lambda x: x['savable_description']['text'])
664 title = video.get('name')
665 if title:
666 info.update({
667 'title': title,
668 'description': description,
669 })
670 else:
671 info['title'] = description or f'Facebook video #{v_id}'
672 entries.append(info)
673
674 def parse_attachment(attachment, key='media'):
675 media = attachment.get(key) or {}
676 if media.get('__typename') == 'Video':
677 return parse_graphql_video(media)
678
679 nodes = variadic(traverse_obj(data, 'nodes', 'node') or [])
680 attachments = traverse_obj(nodes, (
681 ..., 'comet_sections', 'content', 'story', (None, 'attached_story'), 'attachments',
682 ..., ('styles', 'style_type_renderer', ('throwbackStyles', 'attachment_target_renderer')),
683 'attachment', {dict}))
684 for attachment in attachments:
685 ns = traverse_obj(attachment, ('all_subattachments', 'nodes', ..., {dict}),
686 ('target', 'attachments', ..., 'styles', 'attachment', {dict}))
687 for n in ns:
688 parse_attachment(n)
689 parse_attachment(attachment)
690
691 edges = try_get(data, lambda x: x['mediaset']['currMedia']['edges'], list) or []
692 for edge in edges:
693 parse_attachment(edge, key='node')
694
695 video = traverse_obj(data, (
696 'event', 'cover_media_renderer', 'cover_video'), 'video', expected_type=dict) or {}
697 if video:
698 attachments = try_get(video, [
699 lambda x: x['story']['attachments'],
700 lambda x: x['creation_story']['attachments'],
701 ], list) or []
702 for attachment in attachments:
703 parse_attachment(attachment)
704 if not entries:
705 parse_graphql_video(video)
706
707 if len(entries) > 1:
708 return self.playlist_result(entries, video_id)
709
710 video_info = entries[0] if entries else {'id': video_id}
711 webpage_info = extract_metadata(webpage)
712 # honor precise duration in video info
713 if video_info.get('duration'):
714 webpage_info['duration'] = video_info['duration']
715 # preserve preferred_thumbnail in video info
716 if video_info.get('thumbnail'):
717 webpage_info['thumbnail'] = video_info['thumbnail']
718 return merge_dicts(webpage_info, video_info)
719
720 if not video_data:
721 m_msg = re.search(r'class="[^"]*uiInterstitialContent[^"]*"><div>(.*?)</div>', webpage)
722 if m_msg is not None:
723 raise ExtractorError(
724 f'The video is not available, Facebook said: "{m_msg.group(1)}"',
725 expected=True)
726 elif any(p in webpage for p in (
727 '>You must log in to continue',
728 'id="login_form"',
729 'id="loginbutton"')):
730 self.raise_login_required()
731
732 if not video_data and '/watchparty/' in url:
733 post_data = {
734 'doc_id': 3731964053542869,
735 'variables': json.dumps({
736 'livingRoomID': video_id,
737 }),
738 }
739
740 prefetched_data = extract_relay_prefetched_data(r'"login_data"\s*:\s*{')
741 if prefetched_data:
742 lsd = try_get(prefetched_data, lambda x: x['login_data']['lsd'], dict)
743 if lsd:
744 post_data[lsd['name']] = lsd['value']
745
746 relay_data = extract_relay_data(r'\[\s*"RelayAPIConfigDefaults"\s*,')
747 for define in (relay_data.get('define') or []):
748 if define[0] == 'RelayAPIConfigDefaults':
749 self._api_config = define[2]
750
751 living_room = self._download_json(
752 urljoin(url, self._api_config['graphURI']), video_id,
753 data=urlencode_postdata(post_data))['data']['living_room']
754
755 entries = []
756 for edge in (try_get(living_room, lambda x: x['recap']['watched_content']['edges']) or []):
757 video = try_get(edge, lambda x: x['node']['video']) or {}
758 v_id = video.get('id')
759 if not v_id:
760 continue
761 v_id = str(v_id)
762 entries.append(self.url_result(
763 self._VIDEO_PAGE_TEMPLATE % v_id,
764 self.ie_key(), v_id, video.get('name')))
765
766 return self.playlist_result(entries, video_id)
767
768 if not video_data:
769 # Video info not in first request, do a secondary request using
770 # tahoe player specific URL
771 tahoe_data = self._download_webpage(
772 self._VIDEO_PAGE_TAHOE_TEMPLATE % video_id, video_id,
773 data=urlencode_postdata({
774 '__a': 1,
775 '__pc': self._search_regex(
776 r'pkg_cohort["\']\s*:\s*["\'](.+?)["\']', webpage,
777 'pkg cohort', default='PHASED:DEFAULT'),
778 '__rev': self._search_regex(
779 r'client_revision["\']\s*:\s*(\d+),', webpage,
780 'client revision', default='3944515'),
781 'fb_dtsg': self._search_regex(
782 r'"DTSGInitialData"\s*,\s*\[\]\s*,\s*{\s*"token"\s*:\s*"([^"]+)"',
783 webpage, 'dtsg token', default=''),
784 }),
785 headers={
786 'Content-Type': 'application/x-www-form-urlencoded',
787 })
788 tahoe_js_data = self._parse_json(
789 self._search_regex(
790 r'for\s+\(\s*;\s*;\s*\)\s*;(.+)', tahoe_data,
791 'tahoe js data', default='{}'),
792 video_id, fatal=False)
793 video_data = extract_from_jsmods_instances(tahoe_js_data)
794
795 if not video_data:
796 raise ExtractorError('Cannot parse data')
797
798 if len(video_data) > 1:
799 entries = []
800 for v in video_data:
801 video_url = v[0].get('video_url')
802 if not video_url:
803 continue
804 entries.append(self.url_result(urljoin(
805 url, video_url), self.ie_key(), v[0].get('video_id')))
806 return self.playlist_result(entries, video_id)
807 video_data = video_data[0]
808
809 formats = []
810 subtitles = {}
811 for f in video_data:
812 format_id = f['stream_type']
813 if f and isinstance(f, dict):
814 f = [f]
815 if not f or not isinstance(f, list):
816 continue
817 for quality in ('sd', 'hd'):
818 for src_type in ('src', 'src_no_ratelimit'):
819 src = f[0].get(f'{quality}_{src_type}')
820 if src:
821 # sd, hd formats w/o resolution info should be deprioritized below DASH
822 # TODO: investigate if progressive or src formats still exist
823 preference = -10 if format_id == 'progressive' else -3
824 if quality == 'hd':
825 preference += 1
826 formats.append({
827 'format_id': f'{format_id}_{quality}_{src_type}',
828 'url': src,
829 'quality': preference,
830 'height': 720 if quality == 'hd' else None,
831 })
832 extract_dash_manifest(f[0], formats)
833 subtitles_src = f[0].get('subtitles_src')
834 if subtitles_src:
835 subtitles.setdefault('en', []).append({'url': subtitles_src})
836
837 info_dict = {
838 'id': video_id,
839 'formats': formats,
840 'subtitles': subtitles,
841 }
842 process_formats(info_dict)
843 info_dict.update(extract_metadata(webpage))
844
845 return info_dict
846
847 def _real_extract(self, url):
848 video_id = self._match_id(url)
849
850 real_url = self._VIDEO_PAGE_TEMPLATE % video_id if url.startswith('facebook:') else url
851 return self._extract_from_url(real_url, video_id)
852
853
854 class FacebookPluginsVideoIE(InfoExtractor):
855 _VALID_URL = r'https?://(?:[\w-]+\.)?facebook\.com/plugins/video\.php\?.*?\bhref=(?P<id>https.+)'
856
857 _TESTS = [{
858 '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',
859 'md5': '5954e92cdfe51fe5782ae9bda7058a07',
860 'info_dict': {
861 'id': '10154383743583686',
862 'ext': 'mp4',
863 # TODO: Fix title, uploader
864 'title': 'What to do during the haze?',
865 'uploader': 'Gov.sg',
866 'upload_date': '20160826',
867 'timestamp': 1472184808,
868 },
869 'add_ie': [FacebookIE.ie_key()],
870 }, {
871 'url': 'https://www.facebook.com/plugins/video.php?href=https%3A%2F%2Fwww.facebook.com%2Fvideo.php%3Fv%3D10204634152394104',
872 'only_matching': True,
873 }, {
874 'url': 'https://www.facebook.com/plugins/video.php?href=https://www.facebook.com/gov.sg/videos/10154383743583686/&show_text=0&width=560',
875 'only_matching': True,
876 }]
877
878 def _real_extract(self, url):
879 return self.url_result(
880 urllib.parse.unquote(self._match_id(url)),
881 FacebookIE.ie_key())
882
883
884 class FacebookRedirectURLIE(InfoExtractor):
885 IE_DESC = False # Do not list
886 _VALID_URL = r'https?://(?:[\w-]+\.)?facebook\.com/flx/warn[/?]'
887 _TESTS = [{
888 'url': 'https://www.facebook.com/flx/warn/?h=TAQHsoToz&u=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DpO8h3EaFRdo&s=1',
889 'info_dict': {
890 'id': 'pO8h3EaFRdo',
891 'ext': 'mp4',
892 'title': 'Tripeo Boiler Room x Dekmantel Festival DJ Set',
893 'description': 'md5:2d713ccbb45b686a1888397b2c77ca6b',
894 'channel_id': 'UCGBpxWJr9FNOcFYA5GkKrMg',
895 'playable_in_embed': True,
896 'categories': ['Music'],
897 'channel': 'Boiler Room',
898 'uploader_id': 'brtvofficial',
899 'uploader': 'Boiler Room',
900 'tags': 'count:11',
901 'duration': 3332,
902 'live_status': 'not_live',
903 'thumbnail': 'https://i.ytimg.com/vi/pO8h3EaFRdo/maxresdefault.jpg',
904 'channel_url': 'https://www.youtube.com/channel/UCGBpxWJr9FNOcFYA5GkKrMg',
905 'availability': 'public',
906 'uploader_url': 'http://www.youtube.com/user/brtvofficial',
907 'upload_date': '20150917',
908 'age_limit': 0,
909 'view_count': int,
910 'like_count': int,
911 },
912 'add_ie': ['Youtube'],
913 'params': {'skip_download': 'Youtube'},
914 }]
915
916 def _real_extract(self, url):
917 redirect_url = url_or_none(parse_qs(url).get('u', [None])[-1])
918 if not redirect_url:
919 raise ExtractorError('Invalid facebook redirect URL', expected=True)
920 return self.url_result(redirect_url)
921
922
923 class FacebookReelIE(InfoExtractor):
924 _VALID_URL = r'https?://(?:[\w-]+\.)?facebook\.com/reel/(?P<id>\d+)'
925 IE_NAME = 'facebook:reel'
926
927 _TESTS = [{
928 'url': 'https://www.facebook.com/reel/1195289147628387',
929 'md5': 'f13dd37f2633595982db5ed8765474d3',
930 'info_dict': {
931 'id': '1195289147628387',
932 'ext': 'mp4',
933 'title': 'md5:b05800b5b1ad56c0ca78bd3807b6a61e',
934 'description': 'md5:22f03309b216ac84720183961441d8db',
935 'uploader': 'md5:723e6cb3091241160f20b3c5dc282af1',
936 'uploader_id': '100040874179269',
937 'duration': 9.579,
938 'timestamp': 1637502609,
939 'upload_date': '20211121',
940 'thumbnail': r're:^https?://.*',
941 },
942 }]
943
944 def _real_extract(self, url):
945 video_id = self._match_id(url)
946 return self.url_result(
947 f'https://m.facebook.com/watch/?v={video_id}&_rdr', FacebookIE, video_id)
948
949
950 class FacebookAdsIE(InfoExtractor):
951 _VALID_URL = r'https?://(?:[\w-]+\.)?facebook\.com/ads/library/?\?(?:[^#]+&)?id=(?P<id>\d+)'
952 IE_NAME = 'facebook:ads'
953
954 _TESTS = [{
955 'url': 'https://www.facebook.com/ads/library/?id=899206155126718',
956 'info_dict': {
957 'id': '899206155126718',
958 'ext': 'mp4',
959 'title': 'video by Kandao',
960 'uploader': 'Kandao',
961 'uploader_id': '774114102743284',
962 'uploader_url': r're:^https?://.*',
963 'timestamp': 1702548330,
964 'thumbnail': r're:^https?://.*',
965 'upload_date': '20231214',
966 'like_count': int,
967 },
968 }, {
969 'url': 'https://www.facebook.com/ads/library/?id=893637265423481',
970 'info_dict': {
971 'id': '893637265423481',
972 'title': 'Jusqu\u2019\u00e0 -25% sur une s\u00e9lection de vins p\u00e9tillants italiens ',
973 'uploader': 'Eataly Paris Marais',
974 'uploader_id': '2086668958314152',
975 'uploader_url': r're:^https?://.*',
976 'timestamp': 1703571529,
977 'upload_date': '20231226',
978 'like_count': int,
979 },
980 'playlist_count': 3,
981 }, {
982 'url': 'https://es-la.facebook.com/ads/library/?id=901230958115569',
983 'only_matching': True,
984 }, {
985 'url': 'https://m.facebook.com/ads/library/?id=901230958115569',
986 'only_matching': True,
987 }]
988
989 _FORMATS_MAP = {
990 'watermarked_video_sd_url': ('sd-wmk', 'SD, watermarked'),
991 'video_sd_url': ('sd', None),
992 'watermarked_video_hd_url': ('hd-wmk', 'HD, watermarked'),
993 'video_hd_url': ('hd', None),
994 }
995
996 def _extract_formats(self, video_dict):
997 formats = []
998 for format_key, format_url in traverse_obj(video_dict, (
999 {dict.items}, lambda _, v: v[0] in self._FORMATS_MAP and url_or_none(v[1]),
1000 )):
1001 formats.append({
1002 'format_id': self._FORMATS_MAP[format_key][0],
1003 'format_note': self._FORMATS_MAP[format_key][1],
1004 'url': format_url,
1005 'ext': 'mp4',
1006 'quality': qualities(tuple(self._FORMATS_MAP))(format_key),
1007 })
1008 return formats
1009
1010 def _real_extract(self, url):
1011 video_id = self._match_id(url)
1012 webpage = self._download_webpage(url, video_id)
1013
1014 post_data = [self._parse_json(j, video_id, fatal=False)
1015 for j in re.findall(r's\.handle\(({.*})\);requireLazy\(', webpage)]
1016 data = traverse_obj(post_data, (
1017 ..., 'require', ..., ..., ..., 'props', 'deeplinkAdCard', 'snapshot', {dict}), get_all=False)
1018 if not data:
1019 raise ExtractorError('Unable to extract ad data')
1020
1021 title = data.get('title')
1022 if not title or title == '{{product.name}}':
1023 title = join_nonempty('display_format', 'page_name', delim=' by ', from_dict=data)
1024
1025 info_dict = traverse_obj(data, {
1026 'description': ('link_description', {str}, {lambda x: x if x != '{{product.description}}' else None}),
1027 'uploader': ('page_name', {str}),
1028 'uploader_id': ('page_id', {str_or_none}),
1029 'uploader_url': ('page_profile_uri', {url_or_none}),
1030 'timestamp': ('creation_time', {int_or_none}),
1031 'like_count': ('page_like_count', {int_or_none}),
1032 })
1033
1034 entries = []
1035 for idx, entry in enumerate(traverse_obj(
1036 data, (('videos', 'cards'), lambda _, v: any(url_or_none(v[f]) for f in self._FORMATS_MAP))), 1,
1037 ):
1038 entries.append({
1039 'id': f'{video_id}_{idx}',
1040 'title': entry.get('title') or title,
1041 'description': entry.get('link_description') or info_dict.get('description'),
1042 'thumbnail': url_or_none(entry.get('video_preview_image_url')),
1043 'formats': self._extract_formats(entry),
1044 })
1045
1046 if len(entries) == 1:
1047 info_dict.update(entries[0])
1048
1049 elif len(entries) > 1:
1050 info_dict.update({
1051 'title': entries[0]['title'],
1052 'entries': entries,
1053 '_type': 'playlist',
1054 })
1055
1056 info_dict['id'] = video_id
1057
1058 return info_dict