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