5 from .common
import InfoExtractor
6 from ..compat
import compat_etree_fromstring
7 from ..networking
import Request
8 from ..networking
.exceptions
import network_exceptions
34 class FacebookIE(InfoExtractor
):
38 (?:[\w-]+\.)?(?:facebook\.com|facebookwkhpilnemxj7asaniu7vnjjbiltxjqhye3mhbshg7kx5tfyd\.onion)/
49 )\?(?:.*?)(?:v|video_id|story_fbid)=|
50 [^/]+/videos/(?:[^/]+/)?|
53 groups/[^/]+/(?:permalink|posts)/(?:[\da-f]+/)?|
58 (?P<id>pfbid[A-Za-z0-9]+|\d+)
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
64 class=(?P<q1>[\'"])[^\'"]*\bfb-(?:video|post)\b[^\'"]*(?P=q1)[^>]+
65 data-href=(?P<q2>[\'"])(?P<url>(?:https?:)?//(?:www\.)?facebook.com/.+?)(?P=q2)''',
67 _LOGIN_URL = 'https
://www
.facebook
.com
/login
.php?next
=http
%3A
%2F
%2Ffacebook
.com
%2Fhome
.php
&login_attempt
=1'
68 _CHECKPOINT_URL = 'https
://www
.facebook
.com
/checkpoint
/?next
=http
%3A
%2F
%2Ffacebook
.com
%2Fhome
.php
&_fb_noscript
=1'
69 _NETRC_MACHINE = 'facebook
'
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
'
76 'url
': 'https
://www
.facebook
.com
/radiokicksfm
/videos
/3676516585958356/',
78 'id': '3676516585958356',
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',
89 'concurrent_view_count
': 0,
92 'url
': 'https
://www
.facebook
.com
/video
.php?v
=637842556329505&fref
=nf
',
93 'md5
': '6a40d33c0eccbb1af76cf0485a052659
',
95 'id': '637842556329505',
97 'title
': 're
:Did you know Kei Nishikori
is the first Asian man to ever reach a Grand Slam
',
98 'uploader
': 'Tennis on Facebook
',
99 'upload_date
': '20140908',
100 'timestamp
': 1410199200,
102 'skip
': 'Requires logging
in',
105 'url
': 'https
://www
.facebook
.com
/video
.php?v
=274175099429670',
107 'id': '274175099429670',
111 'uploader
': 'Asif Nawab Butt
',
112 'upload_date
': '20140506',
113 'timestamp
': 1399398998,
114 'thumbnail
': r're
:^https?
://.*',
115 'uploader_id
': 'pfbid05AzrFTXgY37tqwaSgbFTTEpCLBjjEJHkigogwGiRPtKEpAsJYJpzE94H1RxYXWEtl
',
117 'concurrent_view_count
': int,
121 'note
': 'Video with DASH manifest
',
122 'url
': 'https
://www
.facebook
.com
/video
.php?v
=957955867617029',
123 'md5
': 'b2c28d528273b323abe5c6ab59f0f030
',
125 'id': '957955867617029',
127 'title
': 'When you post epic content on instagram
.com
/433 8 million followers
, this
is ...',
128 'uploader
': 'Demy de Zeeuw
',
129 'upload_date
': '20160110',
130 'timestamp
': 1452431627,
132 'skip
': 'Requires logging
in',
134 'url
': 'https
://www
.facebook
.com
/maxlayn
/posts
/10153807558977570',
135 'md5
': '037b1fa7f3c2d02b7a0d7bc16031ecc6
',
137 'id': '544765982287235',
139 'title
': '"What are you doing running in the snow?"',
140 'uploader
': 'FailArmy
',
142 'skip
': 'Video gone
',
144 'url
': 'https
://m
.facebook
.com
/story
.php?story_fbid
=1035862816472149&id=116132035111903',
145 'md5
': '1deb90b6ac27f7efcf6d747c8a27f5e3
',
147 'id': '1035862816472149',
149 'title
': 'What the Flock Is Going On In New Zealand Credit
: ViralHog
',
150 'uploader
': 'S
. Saint
',
152 'skip
': 'Video gone
',
154 'note
': 'swf params escaped
',
155 'url
': 'https
://www
.facebook
.com
/barackobama
/posts
/10153664894881749',
156 'md5
': '97ba073838964d12c70566e0085c2b91
',
158 'id': '10153664894881749',
160 'title
': 'Average time to confirm recent Supreme Court nominees
: 67 days Longest it
\'s t
...',
161 'thumbnail
': r're
:^https?
://.*',
162 'timestamp
': 1456259628,
163 'upload_date
': '20160223',
164 'uploader
': 'Barack Obama
',
166 'skip
': 'Gif on giphy
.com gone
',
168 # have 1080P, but only up to 720p in swf params
169 # data.video.story.attachments[].media
170 'url
': 'https
://www
.facebook
.com
/cnn
/videos
/10155529876156509/',
171 'md5
': '1659aa21fb3dd1585874f668e81a72c8
',
173 'id': '10155529876156509',
175 'title
': 'Holocaust survivor becomes US citizen
',
176 'description
': 'She survived the holocaust —
and years later
, she’s getting her citizenship so she can vote
for Hillary Clinton http
://cnn
.it
/2eERh5f
',
177 'timestamp
': 1477818095,
178 'upload_date
': '20161030',
180 'thumbnail
': r're
:^https?
://.*',
182 'uploader_id
': '100059479812265',
183 'concurrent_view_count
': int,
187 # FIXME: unable to extract uploader, no formats found
188 # bigPipe.onPageletArrive ... onPageletArrive pagelet_group_mall
189 # data.node.comet_sections.content.story.attachments[].style_type_renderer.attachment.media
190 'url
': 'https
://www
.facebook
.com
/yaroslav
.korpan
/videos
/1417995061575415/',
192 'id': '1417995061575415',
194 'title
': 'Довгоочікуване відео | By Yaroslav
- Facebook
',
195 'description
': 'Довгоочікуване відео
',
196 'timestamp
': 1486648217,
197 'upload_date
': '20170209',
198 'uploader
': 'Yaroslav Korpan
',
199 'uploader_id
': 'pfbid06AScABAWcW91qpiuGrLt99Ef9tvwHoXP6t8KeFYEqkSfreMtfa9nTveh8b2ZEVSWl
',
200 'concurrent_view_count
': int,
201 'thumbnail
': r're
:^https?
://.*',
203 'duration
': 11736.446,
206 'skip_download
': True,
209 # FIXME: Cannot parse data error
210 'url
': 'https
://www
.facebook
.com
/LaGuiaDelVaron
/posts
/1072691702860471',
212 'id': '1072691702860471',
214 'title
': 'md5
:ae2d22a93fbb12dad20dc393a869739d
',
215 'timestamp
': 1477305000,
216 'upload_date
': '20161024',
217 'uploader
': 'La Guía Del Varón
',
218 'thumbnail
': r're
:^https?
://.*',
220 'skip
': 'Requires logging
in',
222 # data.node.comet_sections.content.story.attachments[].style_type_renderer.attachment.media
223 'url
': 'https
://www
.facebook
.com
/groups
/1024490957622648/permalink
/1396382447100162/',
225 'id': '202882990186699',
227 'title
': 'birb (O v O
") | Hello? Yes your uber ride is here',
228 'description': 'Hello? Yes your uber ride is here * Jukin Media Verified * Find this video and others like it by visiting...',
229 'timestamp': 1486035513,
230 'upload_date': '20170202',
231 'uploader': 'Elisabeth Ahtn',
232 'uploader_id': '100013949973717',
234 'skip': 'Requires logging in',
236 # data.node.comet_sections.content.story.attachments[].throwbackStyles.attachment_target_renderer.attachment.target.attachments[].styles.attachment.media
237 'url': 'https://www.facebook.com/groups/1645456212344334/posts/3737828833107051/',
239 'id': '1569199726448814',
241 'title': 'Pence MUST GO!',
242 'description': 'Vickie Gentry shared a memory.',
243 'timestamp': 1511548260,
244 'upload_date': '20171124',
245 'uploader': 'Vickie Gentry',
246 'uploader_id': 'pfbid0FkkycT95ySNNyfCw4Cho6u5G7WbbZEcxT496Hq8rtx1K3LcTCATpR3wnyYhmyGC5l',
247 'thumbnail': r're:^https?://.*',
251 # data.node.comet_sections.content.story.attachments[].styles.attachment.media
252 'url': 'https://www.facebook.com/attn/posts/pfbid0j1Czf2gGDVqeQ8KiMLFm3pWN8GxsQmeRrVhimWDzMuKQoR8r4b1knNsejELmUgyhl',
254 'id': '6968553779868435',
256 'description': 'md5:2f2fcf93e97ac00244fe64521bbdb0cb',
258 'upload_date': '20231207',
261 'uploader_id': '100064451419378',
263 'thumbnail': r're:^https?://.*',
264 'timestamp': 1701975646,
267 # data.node.comet_sections.content.story.attachments[].styles.attachment.media
268 'url': 'https://www.facebook.com/permalink.php?story_fbid=pfbid0fqQuVEQyXRa9Dp4RcaTR14KHU3uULHV1EK7eckNXSH63JMuoALsAvVCJ97zAGitil&id=100068861234290',
270 'id': '270103405756416',
272 'title': 'Lela Evans',
273 'description': 'Today Makkovik\'s own Pilot Mandy Smith made her inaugural landing on the airstrip in her hometown. What a proud moment as we all cheered and...',
274 'thumbnail': r're:^https?://.*',
275 'uploader': 'Lela Evans',
276 'uploader_id': 'pfbid0swT2y7t6TAsZVBvcyeYPdhTMefGaS26mzUwML3vd1ma6ndGZKxsyS4Ssu3jitZLXl',
277 'upload_date': '20231228',
278 'timestamp': 1703804085,
283 'url': 'https://www.facebook.com/story.php?story_fbid=pfbid0Fnzhm8UuzjBYpPMNFzaSpFE9UmLdU4fJN8qTANi1Dmtj5q7DNrL5NERXfsAzDEV7l&id=100073071055552',
284 'only_matching': True,
286 'url': 'https://www.facebook.com/video.php?v=10204634152394104',
287 'only_matching': True,
289 'url': 'https://www.facebook.com/amogood/videos/1618742068337349/?fref=nf',
290 'only_matching': True,
292 # data.mediaset.currMedia.edges
293 'url': 'https://www.facebook.com/ChristyClarkForBC/videos/vb.22819070941/10153870694020942/?type=2&theater',
294 'only_matching': True,
296 # data.video.story.attachments[].media
297 'url': 'facebook:544765982287235',
298 'only_matching': True,
300 # data.node.comet_sections.content.story.attachments[].style_type_renderer.attachment.media
301 'url': 'https://www.facebook.com/groups/164828000315060/permalink/764967300301124/',
302 'only_matching': True,
304 # data.video.creation_story.attachments[].media
305 'url': 'https://zh-hk.facebook.com/peoplespower/videos/1135894589806027/',
306 'only_matching': True,
309 'url': 'https://www.facebookwkhpilnemxj7asaniu7vnjjbiltxjqhye3mhbshg7kx5tfyd.onion/video.php?v=274175099429670',
310 'only_matching': True,
313 'url': 'https://www.facebook.com/onlycleverentertainment/videos/1947995502095005/',
314 'only_matching': True,
317 'url': 'https://www.facebook.com/WatchESLOne/videos/359649331226507/',
319 'id': '359649331226507',
321 'title': 'Fnatic vs. EG - Group A - Opening Match - ESL One Birmingham Day 1',
322 'description': '#ESLOne VoD - Birmingham Finals Day#1 Fnatic vs. @Evil Geniuses',
323 'timestamp': 1527084179,
324 'upload_date': '20180523',
325 'uploader': 'ESL One Dota 2',
326 'uploader_id': '100066514874195',
327 'duration': 4524.001,
329 'thumbnail': r're:^https?://.*',
330 'concurrent_view_count': int,
333 'skip_download': True,
336 # data.node.comet_sections.content.story.attachments[].style_type_renderer.attachment.all_subattachments.nodes[].media
337 'url': 'https://www.facebook.com/100033620354545/videos/106560053808006/',
339 'id': '106560053808006',
342 'thumbnail': r're:^https?://.*',
343 'concurrent_view_count': int,
344 'uploader_id': 'pfbid02gpfwRM2XvdEJfsERupwQiNmBiDArc38RMRYZnap372q6Vs7MtFTVy72mmFWpJBTKl',
345 'timestamp': 1549275572,
347 'uploader': 'Josef Novak',
349 'upload_date': '20190204',
352 # data.video.story.attachments[].media
353 'url': 'https://www.facebook.com/watch/?v=647537299265662',
354 'only_matching': True,
356 # FIXME: https://github.com/yt-dlp/yt-dlp/issues/542
357 # data.node.comet_sections.content.story.attachments[].style_type_renderer.attachment.all_subattachments.nodes[].media
358 'url': 'https://www.facebook.com/PankajShahLondon/posts/10157667649866271',
360 'id': '10157667649866271',
363 'skip': 'Requires logging in',
365 # data.nodes[].comet_sections.content.story.attachments[].style_type_renderer.attachment.media
366 'url': 'https://m.facebook.com/Alliance.Police.Department/posts/4048563708499330',
368 'id': '117576630041613',
370 # TODO: title can be extracted from video page
371 'title': 'Facebook video #117576630041613',
372 'uploader_id': '189393014416438',
373 'upload_date': '20201123',
374 'timestamp': 1606162592,
376 'skip': 'Requires logging in',
378 # node.comet_sections.content.story.attached_story.attachments.style_type_renderer.attachment.media
379 'url': 'https://www.facebook.com/groups/ateistiskselskab/permalink/10154930137678856/',
381 'id': '211567722618337',
383 'title': 'Facebook video #211567722618337',
384 'uploader_id': '127875227654254',
385 'upload_date': '20161122',
386 'timestamp': 1479793574,
390 # data.video.creation_story.attachments[].media
391 'url': 'https://www.facebook.com/watch/live/?v=1823658634322275',
392 'only_matching': True,
394 'url': 'https://www.facebook.com/watchparty/211641140192478',
396 'id': '211641140192478',
399 'skip': 'Requires logging in',
401 # FIXME: Cannot parse data error
402 # data.event.cover_media_renderer.cover_video
403 'url': 'https://m.facebook.com/events/1509582499515440',
405 'id': '637246984455045',
407 'title': 'ANALISI IN CAMPO OSCURO " Coaguli nel sangue dei vaccinati
"',
408 'description': 'Other event by Comitato Liberi Pensatori on Tuesday, October 18 2022',
409 'thumbnail': r're:^https?://.*',
410 'uploader': 'Comitato Liberi Pensatori',
411 'uploader_id': '100065709540881',
414 'url': 'https://www.facebook.com/groups/1513990329015294/posts/d41d8cd9/2013209885760000/?app=fbl',
415 'only_matching': True,
417 _SUPPORTED_PAGLETS_REGEX = r'(?:pagelet_group_mall|permalink_video_pagelet|hyperfeed_story_id_[0-9a-f]+)'
419 'graphURI': '/api/graphql/',
422 def _perform_login(self, username, password):
423 login_page_req = Request(self._LOGIN_URL)
424 self._set_cookie('facebook.com', 'locale', 'en_US')
425 login_page = self._download_webpage(login_page_req, None,
426 note='Downloading login page',
427 errnote='Unable to download login page')
428 lsd = self._search_regex(
429 r'<input type="hidden
" name="lsd
" value="([^
"]*)"',
431 lgnrnd = self._search_regex(r'name
="lgnrnd" value
="([^"]*?
)"', login_page, 'lgnrnd')
438 'next': 'http://facebook.com/home.php',
439 'default_persistent': '0',
440 'legacy_return': '1',
444 request = Request(self._LOGIN_URL, urlencode_postdata(login_form))
445 request.headers['Content-Type'] = 'application/x-www-form-urlencoded'
447 login_results = self._download_webpage(request, None,
448 note='Logging in', errnote='unable to fetch login page')
449 if re.search(r'<form(.*)name="login
"(.*)</form>', login_results) is not None:
450 error = self._html_search_regex(
451 r'(?s)<div[^>]+class=(["\']).*?login_error_box
.*?\
1[^
>]*><div
[^
>]*>.*?
</div
><div
[^
>]*>(?P
<error
>.+?
)</div
>',
452 login_results, 'login error
', default=None, group='error
')
454 raise ExtractorError(f'Unable to login
: {error}
', expected=True)
455 self.report_warning('unable to log
in: bad username
/password
, or exceeded login rate
limit (~
3/min). Check credentials
or wait
.')
458 fb_dtsg = self._search_regex(
459 r'name
="fb_dtsg" value
="(.+?)"', login_results, 'fb_dtsg
', default=None)
460 h = self._search_regex(
461 r'name
="h"\s
+(?
:\w
+="[^"]+"\s+)*?value="([^
"]+)"', login_results, 'h
', default=None)
463 if not fb_dtsg or not h:
469 'name_action_selected
': 'dont_save
',
471 check_req = Request(self._CHECKPOINT_URL, urlencode_postdata(check_form))
472 check_req.headers['Content
-Type
'] = 'application
/x
-www
-form
-urlencoded
'
473 check_response = self._download_webpage(check_req, None,
474 note='Confirming login
')
475 if re.search(r'id="checkpointSubmitButton"', check_response) is not None:
476 self.report_warning('Unable to confirm login
, you have to login
in your browser
and authorize the login
.')
477 except network_exceptions as err:
478 self.report_warning(f'unable to log
in: {err}
')
481 def _extract_from_url(self, url, video_id):
482 webpage = self._download_webpage(
483 url.replace('://m
.facebook
.com
/', '://www
.facebook
.com
/'), video_id)
485 def extract_metadata(webpage):
486 post_data = [self._parse_json(j, video_id, fatal=False) for j in re.findall(
487 r'data
-sjs
>({.*?ScheduledServerJS
.*?
})</script
>', webpage)]
488 post = traverse_obj(post_data, (
489 ..., 'require
', ..., ..., ..., '__bbox
', 'require
', ..., ..., ..., '__bbox
', 'result
', 'data
'), expected_type=dict) or []
490 media = traverse_obj(post, (..., 'attachments
', ..., lambda k, v: (
491 k == 'media
' and str(v['id']) == video_id and v['__typename
'] == 'Video
')), expected_type=dict)
492 title = get_first(media, ('title
', 'text
'))
493 description = get_first(media, ('creation_story
', 'comet_sections
', 'message
', 'story
', 'message
', 'text
'))
494 page_title = title or self._html_search_regex((
495 r'<h2\s
+[^
>]*class="uiHeaderTitle"[^
>]*>(?P
<content
>[^
<]*)</h2
>',
496 r'(?s
)<span
class="fbPhotosPhotoCaption".*?
id="fbPhotoPageCaption"><span
class="hasCaption">(?P
<content
>.*?
)</span
>',
497 self._meta_regex('og
:title
'), self._meta_regex('twitter
:title
'), r'<title
>(?P
<content
>.+?
)</title
>',
498 ), webpage, 'title
', default=None, group='content
')
499 description = description or self._html_search_meta(
500 ['description
', 'og
:description
', 'twitter
:description
'],
501 webpage, 'description
', default=None)
503 get_first(media, ('owner
', {dict}))
504 or get_first(post, ('video
', 'creation_story
', 'attachments
', ..., 'media
', lambda k, v: k == 'owner
' and v['name
']))
505 or get_first(post, (..., 'video
', lambda k, v: k == 'owner
' and v['name
']))
506 or get_first(post, ('node
', 'actors
', ..., {dict}))
507 or get_first(post, ('event
', 'event_creator
', {dict}))
508 or get_first(post, ('video
', 'creation_story
', 'short_form_video_context
', 'video_owner
', {dict})) or {})
509 uploader = uploader_data.get('name
') or (
510 clean_html(get_element_by_id('fbPhotoPageAuthorName
', webpage))
511 or self._search_regex(
512 (r'ownerName\s
*:\s
*"([^"]+)"', *self._og_regexes('title')), webpage, 'uploader', fatal=False))
513 timestamp = int_or_none(self._search_regex(
514 r'<abbr[^>]+data-utime=["\'](\d
+)', webpage,
515 'timestamp
', default=None))
516 thumbnail = self._html_search_meta(
517 ['og
:image
', 'twitter
:image
'], webpage, 'thumbnail
', default=None)
518 # some webpages contain unretrievable thumbnail urls
519 # like https://lookaside.fbsbx.com/lookaside/crawler/media/?media_id=10155168902769113&get_thumbnail=1
520 # in https://www.facebook.com/yaroslav.korpan/videos/1417995061575415/
521 if thumbnail and not re.search(r'\
.(?
:jpg|png
)', thumbnail):
524 'description
': description,
525 'uploader
': uploader,
526 'uploader_id
': uploader_data.get('id'),
527 'timestamp
': timestamp,
528 'thumbnail
': thumbnail,
529 'view_count
': parse_count(self._search_regex(
530 (r'\bviewCount\s
*:\s
*["\']([\d,.]+)', r'video_view_count["\']\s
*:\s
*(\d
+)'),
531 webpage, 'view count
', default=None)),
532 'concurrent_view_count
': get_first(post, (
533 ('video
', (..., ..., 'attachments
', ..., 'media
')), 'liveViewerCount
', {int_or_none})),
534 **traverse_obj(post, (lambda _, v: video_id in v['url
'], 'feedback
', {
535 'like_count
': ('likers
', 'count
', {int}),
536 'comment_count
': ('total_comment_count
', {int}),
537 'repost_count
': ('share_count_reduced
', {parse_count}),
541 info_json_ld = self._search_json_ld(webpage, video_id, default={})
542 info_json_ld['title
'] = (re.sub(r'\s
*\|\s
*Facebook$
', '', title or info_json_ld.get('title
') or page_title or '')
543 or (description or '').replace('\n', ' ') or f'Facebook video
#{video_id}')
544 return merge_dicts(info_json_ld
, info_dict
)
548 def extract_video_data(instances
):
550 for item
in instances
:
551 if try_get(item
, lambda x
: x
[1][0]) == 'VideoConfig':
552 video_item
= item
[2][0]
553 if video_item
.get('video_id'):
554 video_data
.append(video_item
['videoData'])
557 server_js_data
= self
._parse
_json
(self
._search
_regex
(
558 [r
'handleServerJS\(({.+})(?:\);|,")', r
'\bs\.handle\(({.+?})\);'],
559 webpage
, 'server js data', default
='{}'), video_id
, fatal
=False)
562 video_data
= extract_video_data(server_js_data
.get('instances', []))
564 def extract_from_jsmods_instances(js_data
):
566 return extract_video_data(try_get(
567 js_data
, lambda x
: x
['jsmods']['instances'], list) or [])
569 def extract_dash_manifest(vid_data
, formats
, mpd_url
=None):
570 dash_manifest
= traverse_obj(
571 vid_data
, 'dash_manifest', 'playlist', 'dash_manifest_xml_string', 'manifest_xml', expected_type
=str)
573 formats
.extend(self
._parse
_mpd
_formats
(
574 compat_etree_fromstring(urllib
.parse
.unquote_plus(dash_manifest
)),
575 mpd_url
=url_or_none(vid_data
.get('dash_manifest_url')) or mpd_url
))
577 def process_formats(info
):
578 # Downloads with browser's User-Agent are rate limited. Working around
579 # with non-browser User-Agent.
580 for f
in info
['formats']:
581 # Downloads with browser's User-Agent are rate limited. Working around
582 # with non-browser User-Agent.
583 f
.setdefault('http_headers', {})['User-Agent'] = 'facebookexternalhit/1.1'
584 # Formats larger than ~500MB will return error 403 unless chunk size is regulated
585 f
.setdefault('downloader_options', {})['http_chunk_size'] = 250 << 20
587 def yield_all_relay_data(_filter
):
588 for relay_data
in re
.findall(rf
'data-sjs>({{.*?{_filter}.*?}})</script>', webpage
):
589 yield self
._parse
_json
(relay_data
, video_id
, fatal
=False) or {}
591 def extract_relay_data(_filter
):
592 return next(filter(None, yield_all_relay_data(_filter
)), {})
594 def extract_relay_prefetched_data(_filter
, target_keys
=None):
596 if target_keys
is not None:
597 path
= lambda k
, v
: k
== 'data' and any(target
in v
for target
in variadic(target_keys
))
598 return traverse_obj(yield_all_relay_data(_filter
), (
599 ..., 'require', (None, (..., ..., ..., '__bbox', 'require')),
600 lambda _
, v
: any(key
.startswith('RelayPrefetchedStreamCache') for key
in v
),
601 ..., ..., '__bbox', 'result', path
, {dict}
), get_all
=False) or {}
604 server_js_data
= self
._parse
_json
(self
._search
_regex
([
605 r
'bigPipe\.onPageletArrive\(({.+?})\)\s*;\s*}\s*\)\s*,\s*["\']onPageletArrive\s
+' + self._SUPPORTED_PAGLETS_REGEX,
606 rf'bigPipe\
.onPageletArrive\
(({{.*?
id\s
*:\s
*"{self._SUPPORTED_PAGLETS_REGEX}".*?
}})\
);',
607 ], webpage, 'js data
', default='{}'), video_id, js_to_json, False)
608 video_data = extract_from_jsmods_instances(server_js_data)
611 data = extract_relay_prefetched_data(
612 r'"(?:dash_manifest|playable_url(?:_quality_hd)?)',
613 target_keys=('video', 'event', 'nodes', 'node', 'mediaset'))
617 def parse_graphql_video(video):
618 v_id = video.get('videoId') or video.get('id') or video_id
619 reel_info = traverse_obj(
620 video, ('creation_story', 'short_form_video_context', 'playback_video', {dict}))
622 video = video['creation_story']
623 video['owner'] = traverse_obj(video, ('short_form_video_context', 'video_owner'))
624 video.update(reel_info)
627 q = qualities(['sd', 'hd'])
629 # Legacy formats extraction
630 fmt_data = traverse_obj(video, ('videoDeliveryLegacyFields', {dict})) or video
631 for key, format_id in (('playable_url', 'sd'), ('playable_url_quality_hd', 'hd'),
632 ('playable_url_dash', ''), ('browser_native_hd_url', 'hd'),
633 ('browser_native_sd_url', 'sd')):
634 playable_url = fmt_data.get(key)
637 if determine_ext(playable_url) == 'mpd':
638 formats.extend(self._extract_mpd_formats(playable_url, video_id, fatal=False))
641 'format_id': format_id,
642 # sd, hd formats w/o resolution info should be deprioritized below DASH
643 'quality': q(format_id) - 3,
646 extract_dash_manifest(fmt_data, formats)
648 # New videoDeliveryResponse formats extraction
649 fmt_data = traverse_obj(video, ('videoDeliveryResponseFragment', 'videoDeliveryResponseResult'))
650 mpd_urls = traverse_obj(fmt_data, ('dash_manifest_urls', ..., 'manifest_url', {url_or_none}))
651 dash_manifests = traverse_obj(fmt_data, ('dash_manifests', lambda _, v: v['manifest_xml']))
652 for idx, dash_manifest in enumerate(dash_manifests):
653 extract_dash_manifest(dash_manifest, formats, mpd_url=traverse_obj(mpd_urls, idx))
654 if not dash_manifests:
655 # Only extract from MPD URLs if the manifests are not already provided
656 for mpd_url in mpd_urls:
657 formats.extend(self._extract_mpd_formats(mpd_url, video_id, fatal=False))
658 for prog_fmt in traverse_obj(fmt_data, ('progressive_urls', lambda _, v: v['progressive_url'])):
659 format_id = traverse_obj(prog_fmt, ('metadata', 'quality', {str.lower}))
661 'format_id': format_id,
662 # sd, hd formats w/o resolution info should be deprioritized below DASH
663 'quality': q(format_id) - 3,
664 'url': prog_fmt['progressive_url'],
666 for m3u8_url in traverse_obj(fmt_data, ('hls_playlist_urls', ..., 'hls_playlist_url', {url_or_none})):
667 formats.extend(self._extract_m3u8_formats(m3u8_url, video_id, 'mp4', fatal=False, m3u8_id='hls'))
670 # Do not append false positive entry w/o any formats
673 automatic_captions, subtitles = {}, {}
674 is_broadcast = traverse_obj(video, ('is_video_broadcast', {bool}))
675 for caption in traverse_obj(video, (
676 'video_available_captions_locales',
677 {lambda x: sorted(x, key=lambda c: c['locale'])},
678 lambda _, v: url_or_none(v['captions_url']),
680 lang = caption.get('localized_language') or 'und'
682 'url': caption['captions_url'],
683 'name': format_field(caption, 'localized_country', f'{lang} (%s)', default=lang),
685 if caption.get('localized_creation_method') or is_broadcast:
686 automatic_captions.setdefault(caption['locale'], []).append(subs)
688 subtitles.setdefault(caption['locale'], []).append(subs)
689 captions_url = traverse_obj(video, ('captions_url', {url_or_none}))
690 if captions_url and not automatic_captions and not subtitles:
691 locale = self._html_search_meta(
692 ['og:locale', 'twitter:locale'], webpage, 'locale', default='en_US')
693 (automatic_captions if is_broadcast else subtitles)[locale] = [{'url': captions_url}]
698 'thumbnail': traverse_obj(
699 video, ('thumbnailImage', 'uri'), ('preferred_thumbnail', 'image', 'uri')),
700 'uploader_id': traverse_obj(video, ('owner', 'id', {str_or_none})),
701 'timestamp': traverse_obj(video, 'publish_time', 'creation_time', expected_type=int_or_none),
702 'duration': (float_or_none(video.get('playable_duration_in_ms'), 1000)
703 or float_or_none(video.get('length_in_second'))),
704 'automatic_captions': automatic_captions,
705 'subtitles': subtitles,
707 process_formats(info)
708 description = try_get(video, lambda x: x['savable_description']['text'])
709 title = video.get('name')
713 'description': description,
716 info['title'] = description or f'Facebook video #{v_id}'
719 def parse_attachment(attachment, key='media'):
720 media = attachment.get(key) or {}
721 if media.get('__typename') == 'Video':
722 return parse_graphql_video(media)
724 nodes = variadic(traverse_obj(data, 'nodes', 'node') or [])
725 attachments = traverse_obj(nodes, (
726 ..., 'comet_sections', 'content', 'story', (None, 'attached_story'), 'attachments',
727 ..., ('styles', 'style_type_renderer', ('throwbackStyles', 'attachment_target_renderer')),
728 'attachment', {dict}))
729 for attachment in attachments:
730 ns = traverse_obj(attachment, ('all_subattachments', 'nodes', ..., {dict}),
731 ('target', 'attachments', ..., 'styles', 'attachment', {dict}))
734 parse_attachment(attachment)
736 edges = try_get(data, lambda x: x['mediaset']['currMedia']['edges'], list) or []
738 parse_attachment(edge, key='node')
740 video = traverse_obj(data, (
741 'event', 'cover_media_renderer', 'cover_video'), 'video', expected_type=dict) or {}
743 attachments = try_get(video, [
744 lambda x: x['story']['attachments'],
745 lambda x: x['creation_story']['attachments'],
747 for attachment in attachments:
748 parse_attachment(attachment)
750 parse_graphql_video(video)
753 return self.playlist_result(entries, video_id)
755 video_info = entries[0] if entries else {'id': video_id}
756 webpage_info = extract_metadata(webpage)
757 # honor precise duration in video info
758 if video_info.get('duration'):
759 webpage_info['duration'] = video_info['duration']
760 # preserve preferred_thumbnail in video info
761 if video_info.get('thumbnail'):
762 webpage_info['thumbnail'] = video_info['thumbnail']
763 return merge_dicts(webpage_info, video_info)
766 m_msg = re.search(r'class="[^
"]*uiInterstitialContent[^"]*"><div>(.*?)</div>', webpage)
767 if m_msg is not None:
768 raise ExtractorError(
769 f'The video is not available, Facebook said: "{m_msg
.group(1)}"',
771 elif any(p in webpage for p in (
772 '>You must log in to continue',
774 'id="loginbutton
"')):
775 self.raise_login_required()
777 if not video_data and '/watchparty/' in url:
779 'doc_id': 3731964053542869,
780 'variables': json.dumps({
781 'livingRoomID': video_id,
785 prefetched_data = extract_relay_prefetched_data(r'"login_data
"\s*:\s*{')
787 lsd = try_get(prefetched_data, lambda x: x['login_data']['lsd'], dict)
789 post_data[lsd['name']] = lsd['value']
791 relay_data = extract_relay_data(r'\[\s*"RelayAPIConfigDefaults
"\s*,')
792 for define in (relay_data.get('define') or []):
793 if define[0] == 'RelayAPIConfigDefaults':
794 self._api_config = define[2]
796 living_room = self._download_json(
797 urljoin(url, self._api_config['graphURI']), video_id,
798 data=urlencode_postdata(post_data))['data']['living_room']
801 for edge in (try_get(living_room, lambda x: x['recap']['watched_content']['edges']) or []):
802 video = try_get(edge, lambda x: x['node']['video']) or {}
803 v_id = video.get('id')
807 entries.append(self.url_result(
808 self._VIDEO_PAGE_TEMPLATE % v_id,
809 self.ie_key(), v_id, video.get('name')))
811 return self.playlist_result(entries, video_id)
814 # Video info not in first request, do a secondary request using
815 # tahoe player specific URL
816 tahoe_data = self._download_webpage(
817 self._VIDEO_PAGE_TAHOE_TEMPLATE % video_id, video_id,
818 data=urlencode_postdata({
820 '__pc': self._search_regex(
821 r'pkg_cohort["\']\s
*:\s
*["\'](.+?)["\']', webpage,
822 'pkg cohort
', default='PHASED
:DEFAULT
'),
823 '__rev
': self._search_regex(
824 r'client_revision
["\']\s*:\s*(\d+),', webpage,
825 'client revision', default='3944515'),
826 'fb_dtsg': self._search_regex(
827 r'"DTSGInitialData
"\s*,\s*\[\]\s*,\s*{\s*"token
"\s*:\s*"([^
"]+)"',
828 webpage, 'dtsg token
', default=''),
831 'Content
-Type
': 'application
/x
-www
-form
-urlencoded
',
833 tahoe_js_data = self._parse_json(
835 r'for\s
+\
(\s
*;\s
*;\s
*\
)\s
*;(.+)', tahoe_data,
836 'tahoe js data
', default='{}'),
837 video_id, fatal=False)
838 video_data = extract_from_jsmods_instances(tahoe_js_data)
841 raise ExtractorError('Cannot parse data
')
843 if len(video_data) > 1:
846 video_url = v[0].get('video_url
')
849 entries.append(self.url_result(urljoin(
850 url, video_url), self.ie_key(), v[0].get('video_id
')))
851 return self.playlist_result(entries, video_id)
852 video_data = video_data[0]
857 format_id = f['stream_type
']
858 if f and isinstance(f, dict):
860 if not f or not isinstance(f, list):
862 for quality in ('sd
', 'hd
'):
863 for src_type in ('src
', 'src_no_ratelimit
'):
864 src = f[0].get(f'{quality}_{src_type}
')
866 # sd, hd formats w/o resolution info should be deprioritized below DASH
867 # TODO: investigate if progressive or src formats still exist
868 preference = -10 if format_id == 'progressive
' else -3
872 'format_id
': f'{format_id}_{quality}_{src_type}
',
874 'quality
': preference,
875 'height
': 720 if quality == 'hd
' else None,
877 extract_dash_manifest(f[0], formats)
878 subtitles_src = f[0].get('subtitles_src
')
880 subtitles.setdefault('en
', []).append({'url
': subtitles_src})
885 'subtitles
': subtitles,
887 process_formats(info_dict)
888 info_dict.update(extract_metadata(webpage))
892 def _real_extract(self, url):
893 video_id = self._match_id(url)
895 real_url = self._VIDEO_PAGE_TEMPLATE % video_id if url.startswith('facebook
:') else url
896 return self._extract_from_url(real_url, video_id)
899 class FacebookPluginsVideoIE(InfoExtractor):
900 _VALID_URL = r'https?
://(?
:[\w
-]+\
.)?facebook\
.com
/plugins
/video\
.php
\?.*?
\bhref
=(?P
<id>https
.+)'
903 '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',
904 'md5
': '5954e92cdfe51fe5782ae9bda7058a07
',
906 'id': '10154383743583686',
908 # TODO: Fix title, uploader
909 'title
': 'What to do during the haze?
',
910 'uploader
': 'Gov
.sg
',
911 'upload_date
': '20160826',
912 'timestamp
': 1472184808,
914 'add_ie
': [FacebookIE.ie_key()],
916 'url
': 'https
://www
.facebook
.com
/plugins
/video
.php?href
=https
%3A
%2F
%2Fwww
.facebook
.com
%2Fvideo
.php
%3Fv
%3D10204634152394104
',
917 'only_matching
': True,
919 'url
': 'https
://www
.facebook
.com
/plugins
/video
.php?href
=https
://www
.facebook
.com
/gov
.sg
/videos
/10154383743583686/&show_text
=0&width
=560',
920 'only_matching
': True,
923 def _real_extract(self, url):
924 return self.url_result(
925 urllib.parse.unquote(self._match_id(url)),
929 class FacebookRedirectURLIE(InfoExtractor):
930 IE_DESC = False # Do not list
931 _VALID_URL = r'https?
://(?
:[\w
-]+\
.)?facebook\
.com
/flx
/warn
[/?
]'
933 'url
': 'https
://www
.facebook
.com
/flx
/warn
/?h
=TAQHsoToz
&u
=https
%3A
%2F
%2Fwww
.youtube
.com
%2Fwatch
%3Fv
%3DpO8h3EaFRdo
&s
=1',
937 'title
': 'Tripeo Boiler Room x Dekmantel Festival DJ Set
',
938 'description
': 'md5
:2d713ccbb45b686a1888397b2c77ca6b
',
939 'channel_id
': 'UCGBpxWJr9FNOcFYA5GkKrMg
',
940 'playable_in_embed
': True,
941 'categories
': ['Music
'],
942 'channel
': 'Boiler Room
',
943 'uploader_id
': 'brtvofficial
',
944 'uploader
': 'Boiler Room
',
947 'live_status
': 'not_live
',
948 'thumbnail
': 'https
://i
.ytimg
.com
/vi
/pO8h3EaFRdo
/maxresdefault
.jpg
',
949 'channel_url
': 'https
://www
.youtube
.com
/channel
/UCGBpxWJr9FNOcFYA5GkKrMg
',
950 'availability
': 'public
',
951 'uploader_url
': 'http
://www
.youtube
.com
/user
/brtvofficial
',
952 'upload_date
': '20150917',
957 'add_ie
': ['Youtube
'],
958 'params
': {'skip_download
': 'Youtube
'},
961 def _real_extract(self, url):
962 redirect_url = url_or_none(parse_qs(url).get('u
', [None])[-1])
964 raise ExtractorError('Invalid facebook redirect URL
', expected=True)
965 return self.url_result(redirect_url)
968 class FacebookReelIE(InfoExtractor):
969 _VALID_URL = r'https?
://(?
:[\w
-]+\
.)?facebook\
.com
/reel
/(?P
<id>\d
+)'
970 IE_NAME = 'facebook
:reel
'
973 'url
': 'https
://www
.facebook
.com
/reel
/1195289147628387',
974 'md5
': 'a53256d10fc2105441fe0c4212ed8cea
',
976 'id': '1195289147628387',
978 'title
': r're
:9\
.6K views ·
355 reactions
.+ Let the “Slapathon” commence
!! .+ LL COOL J · Mama Said Knock You Out$
',
979 'description
': r're
:When your trying to
help your partner
.+ LL COOL J · Mama Said Knock You Out$
',
980 'uploader
': 'Beast Camp Training
',
981 'uploader_id
': '100040874179269',
983 'timestamp
': 1637502609,
984 'upload_date
': '20211121',
985 'thumbnail
': r're
:^https?
://.*',
987 'comment_count
': int,
992 def _real_extract(self, url):
993 video_id = self._match_id(url)
994 return self.url_result(
995 f'https
://m
.facebook
.com
/watch
/?v
={video_id}
&_rdr
', FacebookIE, video_id)
998 class FacebookAdsIE(InfoExtractor):
999 _VALID_URL = r'https?
://(?
:[\w
-]+\
.)?facebook\
.com
/ads
/library
/?
\?(?
:[^
#]+&)?id=(?P<id>\d+)'
1000 IE_NAME
= 'facebook:ads'
1003 'url': 'https://www.facebook.com/ads/library/?id=899206155126718',
1005 'id': '899206155126718',
1007 'title': 'video by Kandao',
1008 'description': 'md5:0822724069e3aca97cbed5dabbab282e',
1009 'uploader': 'Kandao',
1010 'uploader_id': '774114102743284',
1011 'uploader_url': r
're:^https?://.*',
1012 'timestamp': 1702548330,
1013 'thumbnail': r
're:^https?://.*',
1014 'upload_date': '20231214',
1018 # key 'watermarked_video_sd_url' missing
1019 'url': 'https://www.facebook.com/ads/library/?id=501152689226254',
1021 'id': '501152689226254',
1023 'title': 'video by mat.nawrocki',
1024 'description': 'md5:02a446ace7ff8c3c37a2892922492490',
1025 'uploader': 'mat.nawrocki',
1026 'uploader_id': '148586968341456',
1027 'uploader_url': r
're:^https?://.*',
1028 'timestamp': 1723452305,
1029 'thumbnail': r
're:^https?://.*',
1030 'upload_date': '20240812',
1034 'url': 'https://www.facebook.com/ads/library/?id=893637265423481',
1036 'id': '893637265423481',
1037 'title': 'Jusqu\u2019\u00e0 -25% sur une s\u00e9lection de vins p\u00e9tillants italiens ',
1038 'uploader': 'Eataly Paris Marais',
1039 'uploader_id': '2086668958314152',
1040 'uploader_url': r
're:^https?://.*',
1041 'timestamp': 1703571529,
1042 'upload_date': '20231226',
1045 'playlist_count': 3,
1047 'url': 'https://es-la.facebook.com/ads/library/?id=901230958115569',
1048 'only_matching': True,
1050 'url': 'https://m.facebook.com/ads/library/?id=901230958115569',
1051 'only_matching': True,
1055 'watermarked_video_sd_url': ('sd-wmk', 'SD, watermarked'),
1056 'video_sd_url': ('sd', None),
1057 'watermarked_video_hd_url': ('hd-wmk', 'HD, watermarked'),
1058 'video_hd_url': ('hd', None),
1061 def _extract_formats(self
, video_dict
):
1063 for format_key
, format_url
in traverse_obj(video_dict
, (
1064 {dict.items
}, lambda _
, v
: v
[0] in self
._FORMATS
_MAP
and url_or_none(v
[1]),
1067 'format_id': self
._FORMATS
_MAP
[format_key
][0],
1068 'format_note': self
._FORMATS
_MAP
[format_key
][1],
1071 'quality': qualities(tuple(self
._FORMATS
_MAP
))(format_key
),
1075 def _real_extract(self
, url
):
1076 video_id
= self
._match
_id
(url
)
1077 webpage
= self
._download
_webpage
(url
, video_id
)
1079 post_data
= traverse_obj(
1080 re
.findall(r
'data-sjs>({.*?ScheduledServerJS.*?})</script>', webpage
), (..., {json
.loads
}))
1081 data
= get_first(post_data
, (
1082 'require', ..., ..., ..., '__bbox', 'require', ..., ..., ...,
1083 'entryPointRoot', 'otherProps', 'deeplinkAdCard', 'snapshot', {dict}
))
1085 raise ExtractorError('Unable to extract ad data')
1087 title
= data
.get('title')
1088 if not title
or title
== '{{product.name}}':
1089 title
= join_nonempty('display_format', 'page_name', delim
=' by ', from_dict
=data
)
1090 markup_id
= traverse_obj(data
, ('body', '__m', {str}
))
1091 markup
= traverse_obj(post_data
, (
1092 ..., 'require', ..., ..., ..., '__bbox', 'markup', lambda _
, v
: v
[0].startswith(markup_id
),
1093 ..., '__html', {clean_html}
, {lambda x
: not x
.startswith('{{product.') and x
}, any
))
1095 info_dict
= merge_dicts({
1097 'description': markup
or None,
1098 }, traverse_obj(data
, {
1099 'description': ('link_description', {lambda x
: x
if not x
.startswith('{{product.') else None}),
1100 'uploader': ('page_name', {str}
),
1101 'uploader_id': ('page_id', {str_or_none}
),
1102 'uploader_url': ('page_profile_uri', {url_or_none}
),
1103 'timestamp': ('creation_time', {int_or_none}
),
1104 'like_count': ('page_like_count', {int_or_none}
),
1108 for idx
, entry
in enumerate(traverse_obj(
1109 data
, (('videos', 'cards'), lambda _
, v
: any(url_or_none(v
.get(f
)) for f
in self
._FORMATS
_MAP
))), 1,
1112 'id': f
'{video_id}_{idx}',
1113 'title': entry
.get('title') or title
,
1114 'description': traverse_obj(entry
, 'body', 'link_description') or info_dict
.get('description'),
1115 'thumbnail': url_or_none(entry
.get('video_preview_image_url')),
1116 'formats': self
._extract
_formats
(entry
),
1119 if len(entries
) == 1:
1120 info_dict
.update(entries
[0])
1122 elif len(entries
) > 1:
1124 'title': entries
[0]['title'],
1126 '_type': 'playlist',
1129 info_dict
['id'] = video_id