5 from .common
import InfoExtractor
7 compat_etree_fromstring
,
9 compat_urllib_parse_unquote
,
11 from ..networking
import Request
12 from ..networking
.exceptions
import network_exceptions
39 class FacebookIE(InfoExtractor
):
43 (?:[\w-]+\.)?(?:facebook\.com|facebookwkhpilnemxj7asaniu7vnjjbiltxjqhye3mhbshg7kx5tfyd\.onion)/
54 )\?(?:.*?)(?:v|video_id|story_fbid)=|
55 [^/]+/videos/(?:[^/]+/)?|
58 groups/[^/]+/(?:permalink|posts)/|
63 (?P<id>pfbid[A-Za-z0-9]+|\d+)
66 r
'<iframe[^>]+?src=(["\'])(?P
<url
>https?
://www\
.facebook\
.com
/(?
:video
/embed|plugins
/video\
.php
).+?
)\
1',
67 # Facebook API embed https://developers.facebook.com/docs/plugins/embedded-video-player
69 class=(?P<q1>[\'"])[^\'"]*\bfb-(?:video|post)\b[^\'"]*(?P=q1)[^>]+
70 data-href=(?P<q2>[\'"])(?P<url>(?:https?:)?//(?:www\.)?facebook.com/.+?)(?P=q2)''',
72 _LOGIN_URL = 'https
://www
.facebook
.com
/login
.php?next
=http
%3A
%2F
%2Ffacebook
.com
%2Fhome
.php
&login_attempt
=1'
73 _CHECKPOINT_URL = 'https
://www
.facebook
.com
/checkpoint
/?next
=http
%3A
%2F
%2Ffacebook
.com
%2Fhome
.php
&_fb_noscript
=1'
74 _NETRC_MACHINE = 'facebook
'
77 _VIDEO_PAGE_TEMPLATE = 'https
://www
.facebook
.com
/video
/video
.php?v
=%s'
78 _VIDEO_PAGE_TAHOE_TEMPLATE = 'https
://www
.facebook
.com
/video
/tahoe
/async/%s/?chain
=true
&isvideo
=true
&payloadtype
=primary
'
81 'url
': 'https
://www
.facebook
.com
/radiokicksfm
/videos
/3676516585958356/',
83 'id': '3676516585958356',
85 'title
': 'dr Adam Przygoda
',
86 'description
': 'md5
:34675bda53336b1d16400265c2bb9b3b
',
87 'uploader
': 'RADIO KICKS FM
',
88 'upload_date
': '20230818',
89 'timestamp
': 1692346159,
90 'thumbnail
': r're
:^https?
://.*',
91 'uploader_id
': '100063551323670',
94 'concurrent_view_count
': 0,
97 'url
': 'https
://www
.facebook
.com
/video
.php?v
=637842556329505&fref
=nf
',
98 'md5
': '6a40d33c0eccbb1af76cf0485a052659
',
100 'id': '637842556329505',
102 'title
': 're
:Did you know Kei Nishikori
is the first Asian man to ever reach a Grand Slam
',
103 'uploader
': 'Tennis on Facebook
',
104 'upload_date
': '20140908',
105 'timestamp
': 1410199200,
107 'skip
': 'Requires logging
in',
110 'url
': 'https
://www
.facebook
.com
/video
.php?v
=274175099429670',
112 'id': '274175099429670',
116 'uploader
': 'Asif Nawab Butt
',
117 'upload_date
': '20140506',
118 'timestamp
': 1399398998,
119 'thumbnail
': r're
:^https?
://.*',
120 'uploader_id
': 'pfbid028wxorhX2ErLFJ578N6P3crHD3PHmXTCqCvfBpsnbSLmbokwSY75p5hWBjHGkG4zxl
',
122 'concurrent_view_count
': int,
125 'note
': 'Video
with DASH manifest
',
126 'url
': 'https
://www
.facebook
.com
/video
.php?v
=957955867617029',
127 'md5
': 'b2c28d528273b323abe5c6ab59f0f030
',
129 'id': '957955867617029',
131 'title
': 'When you post epic content on instagram
.com
/433 8 million followers
, this
is ...',
132 'uploader
': 'Demy de Zeeuw
',
133 'upload_date
': '20160110',
134 'timestamp
': 1452431627,
136 'skip
': 'Requires logging
in',
138 'url
': 'https
://www
.facebook
.com
/maxlayn
/posts
/10153807558977570',
139 'md5
': '037b1fa7f3c2d02b7a0d7bc16031ecc6
',
141 'id': '544765982287235',
143 'title
': '"What are you doing running in the snow?"',
144 'uploader
': 'FailArmy
',
146 'skip
': 'Video gone
',
148 'url
': 'https
://m
.facebook
.com
/story
.php?story_fbid
=1035862816472149&id=116132035111903',
149 'md5
': '1deb90b6ac27f7efcf6d747c8a27f5e3
',
151 'id': '1035862816472149',
153 'title
': 'What the Flock Is Going On In New Zealand Credit
: ViralHog
',
154 'uploader
': 'S
. Saint
',
156 'skip
': 'Video gone
',
158 'note
': 'swf params escaped
',
159 'url
': 'https
://www
.facebook
.com
/barackobama
/posts
/10153664894881749',
160 'md5
': '97ba073838964d12c70566e0085c2b91
',
162 'id': '10153664894881749',
164 'title
': 'Average time to confirm recent Supreme Court nominees
: 67 days Longest it
\'s t
...',
165 'thumbnail
': r're
:^https?
://.*',
166 'timestamp
': 1456259628,
167 'upload_date
': '20160223',
168 'uploader
': 'Barack Obama
',
170 'skip
': 'Gif on giphy
.com gone
',
172 # have 1080P, but only up to 720p in swf params
173 # data.video.story.attachments[].media
174 'url
': 'https
://www
.facebook
.com
/cnn
/videos
/10155529876156509/',
175 'md5
': 'ca63897a90c9452efee5f8c40d080e25
',
177 'id': '10155529876156509',
179 'title
': 'Holocaust survivor becomes US citizen
',
180 'description
': 'She survived the holocaust —
and years later
, she’s getting her citizenship so she can vote
for Hillary Clinton http
://cnn
.it
/2eERh5f
',
181 'timestamp
': 1477818095,
182 'upload_date
': '20161030',
184 'thumbnail
': r're
:^https?
://.*',
186 'uploader_id
': '100059479812265',
187 'concurrent_view_count
': int,
191 # bigPipe.onPageletArrive ... onPageletArrive pagelet_group_mall
192 # data.node.comet_sections.content.story.attachments[].style_type_renderer.attachment.media
193 'url
': 'https
://www
.facebook
.com
/yaroslav
.korpan
/videos
/1417995061575415/',
195 'id': '1417995061575415',
197 'title
': 'Довгоочікуване відео | By Yaroslav
- Facebook
',
198 'description
': 'Довгоочікуване відео
',
199 'timestamp
': 1486648217,
200 'upload_date
': '20170209',
201 'uploader
': 'Yaroslav Korpan
',
202 'uploader_id
': 'pfbid06AScABAWcW91qpiuGrLt99Ef9tvwHoXP6t8KeFYEqkSfreMtfa9nTveh8b2ZEVSWl
',
203 'concurrent_view_count
': int,
204 'thumbnail
': r're
:^https?
://.*',
206 'duration
': 11736.446,
209 'skip_download
': True,
213 'url
': 'https
://www
.facebook
.com
/LaGuiaDelVaron
/posts
/1072691702860471',
215 'id': '1072691702860471',
217 'title
': 'md5
:ae2d22a93fbb12dad20dc393a869739d
',
218 'timestamp
': 1477305000,
219 'upload_date
': '20161024',
220 'uploader
': 'La Guía Del Varón
',
221 'thumbnail
': r're
:^https?
://.*',
223 'skip
': 'Requires logging
in',
225 # data.node.comet_sections.content.story.attachments[].style_type_renderer.attachment.media
226 'url
': 'https
://www
.facebook
.com
/groups
/1024490957622648/permalink
/1396382447100162/',
228 'id': '202882990186699',
230 'title
': 'birb (O v O
") | Hello? Yes your uber ride is here',
231 'description': 'Hello? Yes your uber ride is here * Jukin Media Verified * Find this video and others like it by visiting...',
232 'timestamp': 1486035513,
233 'upload_date': '20170202',
234 'uploader': 'Elisabeth Ahtn',
235 'uploader_id': '100013949973717',
237 'skip': 'Requires logging in',
239 # data.node.comet_sections.content.story.attachments[].throwbackStyles.attachment_target_renderer.attachment.target.attachments[].styles.attachment.media
240 'url': 'https://www.facebook.com/groups/1645456212344334/posts/3737828833107051/',
242 'id': '1569199726448814',
244 'title': 'Pence MUST GO!',
245 'description': 'Vickie Gentry shared a memory.',
246 'timestamp': 1511548260,
247 'upload_date': '20171124',
248 'uploader': 'Vickie Gentry',
249 'uploader_id': 'pfbid0FuZhHCeWDAxWxEbr3yKPFaRstXvRxgsp9uCPG6GjD4J2AitB35NUAuJ4Q75KcjiDl',
250 'thumbnail': r're:^https?://.*',
254 # data.node.comet_sections.content.story.attachments[].styles.attachment.media
255 'url': 'https://www.facebook.com/attn/posts/pfbid0j1Czf2gGDVqeQ8KiMLFm3pWN8GxsQmeRrVhimWDzMuKQoR8r4b1knNsejELmUgyhl',
257 'id': '6968553779868435',
259 'description': 'md5:2f2fcf93e97ac00244fe64521bbdb0cb',
261 'upload_date': '20231207',
264 'uploader_id': '100064451419378',
266 'thumbnail': r're:^https?://.*',
267 'timestamp': 1701975646,
270 # data.node.comet_sections.content.story.attachments[].styles.attachment.media
271 'url': 'https://www.facebook.com/permalink.php?story_fbid=pfbid0fqQuVEQyXRa9Dp4RcaTR14KHU3uULHV1EK7eckNXSH63JMuoALsAvVCJ97zAGitil&id=100068861234290',
273 'id': '270103405756416',
275 'title': 'Lela Evans',
276 'description': 'Today Makkovik\'s own Pilot Mandy Smith made her inaugural landing on the airstrip in her hometown. What a proud moment as we all cheered and...',
277 'thumbnail': r're:^https?://.*',
278 'uploader': 'Lela Evans',
279 'uploader_id': 'pfbid0shZJipuigyy5mqrUJn9ub5LJFWNHvan5prtyi3LrDuuuJ4NwrURgnQHYR9fywBepl',
280 'upload_date': '20231228',
281 'timestamp': 1703804085,
286 'url': 'https://www.facebook.com/story.php?story_fbid=pfbid0Fnzhm8UuzjBYpPMNFzaSpFE9UmLdU4fJN8qTANi1Dmtj5q7DNrL5NERXfsAzDEV7l&id=100073071055552',
287 'only_matching': True,
289 'url': 'https://www.facebook.com/video.php?v=10204634152394104',
290 'only_matching': True,
292 'url': 'https://www.facebook.com/amogood/videos/1618742068337349/?fref=nf',
293 'only_matching': True,
295 # data.mediaset.currMedia.edges
296 'url': 'https://www.facebook.com/ChristyClarkForBC/videos/vb.22819070941/10153870694020942/?type=2&theater',
297 'only_matching': True,
299 # data.video.story.attachments[].media
300 'url': 'facebook:544765982287235',
301 'only_matching': True,
303 # data.node.comet_sections.content.story.attachments[].style_type_renderer.attachment.media
304 'url': 'https://www.facebook.com/groups/164828000315060/permalink/764967300301124/',
305 'only_matching': True,
307 # data.video.creation_story.attachments[].media
308 'url': 'https://zh-hk.facebook.com/peoplespower/videos/1135894589806027/',
309 'only_matching': True,
312 'url': 'https://www.facebookwkhpilnemxj7asaniu7vnjjbiltxjqhye3mhbshg7kx5tfyd.onion/video.php?v=274175099429670',
313 'only_matching': True,
316 'url': 'https://www.facebook.com/onlycleverentertainment/videos/1947995502095005/',
317 'only_matching': True,
320 'url': 'https://www.facebook.com/WatchESLOne/videos/359649331226507/',
322 'id': '359649331226507',
324 'title': 'Fnatic vs. EG - Group A - Opening Match - ESL One Birmingham Day 1',
325 'description': '#ESLOne VoD - Birmingham Finals Day#1 Fnatic vs. @Evil Geniuses',
326 'timestamp': 1527084179,
327 'upload_date': '20180523',
328 'uploader': 'ESL One Dota 2',
329 'uploader_id': '100066514874195',
330 'duration': 4524.212,
332 'thumbnail': r're:^https?://.*',
333 'concurrent_view_count': int,
336 'skip_download': True,
339 # data.node.comet_sections.content.story.attachments[].style_type_renderer.attachment.all_subattachments.nodes[].media
340 'url': 'https://www.facebook.com/100033620354545/videos/106560053808006/',
342 'id': '106560053808006',
345 'thumbnail': r're:^https?://.*',
346 'concurrent_view_count': int,
347 'uploader_id': 'pfbid0cibUN6tV7DYgdbJdsUFN46wc4jKpVSPAvJQhFofGqBGmVn3V3JtAs2tfUwziw2hUl',
348 'timestamp': 1549275572,
350 'uploader': 'Josef Novak',
352 'upload_date': '20190204',
355 # data.video.story.attachments[].media
356 'url': 'https://www.facebook.com/watch/?v=647537299265662',
357 'only_matching': True,
359 # FIXME: https://github.com/yt-dlp/yt-dlp/issues/542
360 # data.node.comet_sections.content.story.attachments[].style_type_renderer.attachment.all_subattachments.nodes[].media
361 'url': 'https://www.facebook.com/PankajShahLondon/posts/10157667649866271',
363 'id': '10157667649866271',
366 'skip': 'Requires logging in',
368 # data.nodes[].comet_sections.content.story.attachments[].style_type_renderer.attachment.media
369 'url': 'https://m.facebook.com/Alliance.Police.Department/posts/4048563708499330',
371 'id': '117576630041613',
373 # TODO: title can be extracted from video page
374 'title': 'Facebook video #117576630041613',
375 'uploader_id': '189393014416438',
376 'upload_date': '20201123',
377 'timestamp': 1606162592,
379 'skip': 'Requires logging in',
381 # node.comet_sections.content.story.attached_story.attachments.style_type_renderer.attachment.media
382 'url': 'https://www.facebook.com/groups/ateistiskselskab/permalink/10154930137678856/',
384 'id': '211567722618337',
386 'title': 'Facebook video #211567722618337',
387 'uploader_id': '127875227654254',
388 'upload_date': '20161122',
389 'timestamp': 1479793574,
393 # data.video.creation_story.attachments[].media
394 'url': 'https://www.facebook.com/watch/live/?v=1823658634322275',
395 'only_matching': True,
397 'url': 'https://www.facebook.com/watchparty/211641140192478',
399 'id': '211641140192478',
402 'skip': 'Requires logging in',
404 # data.event.cover_media_renderer.cover_video
405 'url': 'https://m.facebook.com/events/1509582499515440',
407 'id': '637246984455045',
409 'title': 'ANALISI IN CAMPO OSCURO " Coaguli nel sangue dei vaccinati
"',
410 'description': 'Other event by Comitato Liberi Pensatori on Tuesday, October 18 2022',
411 'thumbnail': r're:^https?://.*',
412 'uploader': 'Comitato Liberi Pensatori',
413 'uploader_id': '100065709540881',
416 _SUPPORTED_PAGLETS_REGEX = r'(?:pagelet_group_mall|permalink_video_pagelet|hyperfeed_story_id_[0-9a-f]+)'
418 'graphURI': '/api/graphql/'
421 def _perform_login(self, username, password):
422 login_page_req = Request(self._LOGIN_URL)
423 self._set_cookie('facebook.com', 'locale', 'en_US')
424 login_page = self._download_webpage(login_page_req, None,
425 note='Downloading login page',
426 errnote='Unable to download login page')
427 lsd = self._search_regex(
428 r'<input type="hidden
" name="lsd
" value="([^
"]*)"',
430 lgnrnd = self._search_regex(r'name
="lgnrnd" value
="([^"]*?
)"', login_page, 'lgnrnd')
437 'next': 'http://facebook.com/home.php',
438 'default_persistent': '0',
439 'legacy_return': '1',
443 request = Request(self._LOGIN_URL, urlencode_postdata(login_form))
444 request.headers['Content-Type'] = 'application/x-www-form-urlencoded'
446 login_results = self._download_webpage(request, None,
447 note='Logging in', errnote='unable to fetch login page')
448 if re.search(r'<form(.*)name="login
"(.*)</form>', login_results) is not None:
449 error = self._html_search_regex(
450 r'(?s)<div[^>]+class=(["\']).*?login_error_box
.*?\
1[^
>]*><div
[^
>]*>.*?
</div
><div
[^
>]*>(?P
<error
>.+?
)</div
>',
451 login_results, 'login error
', default=None, group='error
')
453 raise ExtractorError('Unable to login
: %s' % error, expected=True)
454 self.report_warning('unable to log
in: bad username
/password
, or exceeded login rate
limit (~
3/min). Check credentials
or wait
.')
457 fb_dtsg = self._search_regex(
458 r'name
="fb_dtsg" value
="(.+?)"', login_results, 'fb_dtsg
', default=None)
459 h = self._search_regex(
460 r'name
="h"\s
+(?
:\w
+="[^"]+"\s+)*?value="([^
"]+)"', login_results, 'h
', default=None)
462 if not fb_dtsg or not h:
468 'name_action_selected
': 'dont_save
',
470 check_req = Request(self._CHECKPOINT_URL, urlencode_postdata(check_form))
471 check_req.headers['Content
-Type
'] = 'application
/x
-www
-form
-urlencoded
'
472 check_response = self._download_webpage(check_req, None,
473 note='Confirming login
')
474 if re.search(r'id="checkpointSubmitButton"', check_response) is not None:
475 self.report_warning('Unable to confirm login
, you have to login
in your browser
and authorize the login
.')
476 except network_exceptions as err:
477 self.report_warning('unable to log
in: %s' % error_to_compat_str(err))
480 def _extract_from_url(self, url, video_id):
481 webpage = self._download_webpage(
482 url.replace('://m
.facebook
.com
/', '://www
.facebook
.com
/'), video_id)
484 def extract_metadata(webpage):
485 post_data = [self._parse_json(j, video_id, fatal=False) for j in re.findall(
486 r'data
-sjs
>({.*?ScheduledServerJS.*?}
)</script
>', webpage)]
487 post = traverse_obj(post_data, (
488 ..., 'require
', ..., ..., ..., '__bbox
', 'require
', ..., ..., ..., '__bbox
', 'result
', 'data
'), expected_type=dict) or []
489 media = traverse_obj(post, (..., 'attachments
', ..., lambda k, v: (
490 k == 'media
' and str(v['id']) == video_id and v['__typename
'] == 'Video
')), expected_type=dict)
491 title = get_first(media, ('title
', 'text
'))
492 description = get_first(media, ('creation_story
', 'comet_sections
', 'message
', 'story
', 'message
', 'text
'))
493 page_title = title or self._html_search_regex((
494 r'<h2\s
+[^
>]*class="uiHeaderTitle"[^
>]*>(?P
<content
>[^
<]*)</h2
>',
495 r'(?s
)<span
class="fbPhotosPhotoCaption".*?
id="fbPhotoPageCaption"><span
class="hasCaption">(?P
<content
>.*?
)</span
>',
496 self._meta_regex('og
:title
'), self._meta_regex('twitter
:title
'), r'<title
>(?P
<content
>.+?
)</title
>'
497 ), webpage, 'title
', default=None, group='content
')
498 description = description or self._html_search_meta(
499 ['description
', 'og
:description
', 'twitter
:description
'],
500 webpage, 'description
', default=None)
502 get_first(media, ('owner
', {dict}))
503 or get_first(post, ('video
', 'creation_story
', 'attachments
', ..., 'media
', lambda k, v: k == 'owner
' and v['name
']))
504 or get_first(post, (..., 'video
', lambda k, v: k == 'owner
' and v['name
']))
505 or get_first(post, ('node
', 'actors
', ..., {dict}))
506 or get_first(post, ('event
', 'event_creator
', {dict})) or {})
507 uploader = uploader_data.get('name
') or (
508 clean_html(get_element_by_id('fbPhotoPageAuthorName
', webpage))
509 or self._search_regex(
510 (r'ownerName\s
*:\s
*"([^"]+)"', *self._og_regexes('title')), webpage, 'uploader', fatal=False))
511 timestamp = int_or_none(self._search_regex(
512 r'<abbr[^>]+data-utime=["\'](\d
+)', webpage,
513 'timestamp
', default=None))
514 thumbnail = self._html_search_meta(
515 ['og
:image
', 'twitter
:image
'], webpage, 'thumbnail
', default=None)
516 # some webpages contain unretrievable thumbnail urls
517 # like https://lookaside.fbsbx.com/lookaside/crawler/media/?media_id=10155168902769113&get_thumbnail=1
518 # in https://www.facebook.com/yaroslav.korpan/videos/1417995061575415/
519 if thumbnail and not re.search(r'\
.(?
:jpg|png
)', thumbnail):
522 'description
': description,
523 'uploader
': uploader,
524 'uploader_id
': uploader_data.get('id'),
525 'timestamp
': timestamp,
526 'thumbnail
': thumbnail,
527 'view_count
': parse_count(self._search_regex(
528 (r'\bviewCount\s
*:\s
*["\']([\d,.]+)', r'video_view_count["\']\s
*:\s
*(\d
+)',),
529 webpage, 'view count
', default=None)),
530 'concurrent_view_count
': get_first(post, (
531 ('video
', (..., ..., 'attachments
', ..., 'media
')), 'liveViewerCount
', {int_or_none})),
534 info_json_ld = self._search_json_ld(webpage, video_id, default={})
535 info_json_ld['title
'] = (re.sub(r'\s
*\|\s
*Facebook$
', '', title or info_json_ld.get('title
') or page_title or '')
536 or (description or '').replace('\n', ' ') or f'Facebook video
#{video_id}')
537 return merge_dicts(info_json_ld
, info_dict
)
541 def extract_video_data(instances
):
543 for item
in instances
:
544 if try_get(item
, lambda x
: x
[1][0]) == 'VideoConfig':
545 video_item
= item
[2][0]
546 if video_item
.get('video_id'):
547 video_data
.append(video_item
['videoData'])
550 server_js_data
= self
._parse
_json
(self
._search
_regex
(
551 [r
'handleServerJS\(({.+})(?:\);|,")', r
'\bs\.handle\(({.+?})\);'],
552 webpage
, 'server js data', default
='{}'), video_id
, fatal
=False)
555 video_data
= extract_video_data(server_js_data
.get('instances', []))
557 def extract_from_jsmods_instances(js_data
):
559 return extract_video_data(try_get(
560 js_data
, lambda x
: x
['jsmods']['instances'], list) or [])
562 def extract_dash_manifest(video
, formats
):
563 dash_manifest
= traverse_obj(video
, 'dash_manifest', 'playlist', expected_type
=str)
565 formats
.extend(self
._parse
_mpd
_formats
(
566 compat_etree_fromstring(urllib
.parse
.unquote_plus(dash_manifest
)),
567 mpd_url
=video
.get('dash_manifest_url')))
569 def process_formats(info
):
570 # Downloads with browser's User-Agent are rate limited. Working around
571 # with non-browser User-Agent.
572 for f
in info
['formats']:
573 # Downloads with browser's User-Agent are rate limited. Working around
574 # with non-browser User-Agent.
575 f
.setdefault('http_headers', {})['User-Agent'] = 'facebookexternalhit/1.1'
576 # Formats larger than ~500MB will return error 403 unless chunk size is regulated
577 f
.setdefault('downloader_options', {})['http_chunk_size'] = 250 << 20
579 def extract_relay_data(_filter
):
580 return self
._parse
_json
(self
._search
_regex
(
581 r
'data-sjs>({.*?%s.*?})</script>' % _filter
,
582 webpage
, 'replay data', default
='{}'), video_id, fatal=False) or {}
584 def extract_relay_prefetched_data(_filter):
585 return traverse_obj(extract_relay_data(_filter), (
586 'require
', (None, (..., ..., ..., '__bbox
', 'require
')),
587 lambda _, v: any(key.startswith('RelayPrefetchedStreamCache
') for key in v),
588 ..., ..., '__bbox
', 'result
', 'data
', {dict}), get_all=False) or {}
591 server_js_data = self._parse_json(self._search_regex([
592 r'bigPipe\
.onPageletArrive\
(({.+?}
)\
)\s
*;\s
*}\s
*\
)\s
*,\s
*["\']onPageletArrive\s+' + self._SUPPORTED_PAGLETS_REGEX,
593 r'bigPipe\.onPageletArrive\(({.*?id\s*:\s*"%s".*?})\);' % self._SUPPORTED_PAGLETS_REGEX
594 ], webpage, 'js data', default='{}'), video_id, js_to_json, False)
595 video_data = extract_from_jsmods_instances(server_js_data)
598 data = extract_relay_prefetched_data(
599 r'"(?
:dash_manifest|
playable_url(?
:_quality_hd
)?
)')
603 def parse_graphql_video(video):
604 v_id = video.get('videoId
') or video.get('id') or video_id
605 reel_info = traverse_obj(
606 video, ('creation_story
', 'short_form_video_context
', 'playback_video
', {dict}))
608 video = video['creation_story
']
609 video['owner
'] = traverse_obj(video, ('short_form_video_context
', 'video_owner
'))
610 video.update(reel_info)
612 q = qualities(['sd
', 'hd
'])
613 for key, format_id in (('playable_url
', 'sd
'), ('playable_url_quality_hd
', 'hd
'),
614 ('playable_url_dash
', ''), ('browser_native_hd_url
', 'hd
'),
615 ('browser_native_sd_url
', 'sd
')):
616 playable_url = video.get(key)
619 if determine_ext(playable_url) == 'mpd
':
620 formats.extend(self._extract_mpd_formats(playable_url, video_id))
623 'format_id
': format_id,
624 # sd, hd formats w/o resolution info should be deprioritized below DASH
625 'quality
': q(format_id) - 3,
628 extract_dash_manifest(video, formats)
630 automatic_captions, subtitles = {}, {}
631 is_broadcast = traverse_obj(video, ('is_video_broadcast
', {bool}))
632 for caption in traverse_obj(video, (
633 'video_available_captions_locales
',
634 {lambda x: sorted(x, key=lambda c: c['locale'])},
635 lambda _, v: url_or_none(v['captions_url
'])
637 lang = caption.get('localized_language
') or 'und
'
639 'url
': caption['captions_url
'],
640 'name
': format_field(caption, 'localized_country
', f'{lang}
(%s)', default=lang),
642 if caption.get('localized_creation_method
') or is_broadcast:
643 automatic_captions.setdefault(caption['locale
'], []).append(subs)
645 subtitles.setdefault(caption['locale
'], []).append(subs)
646 captions_url = traverse_obj(video, ('captions_url
', {url_or_none}))
647 if captions_url and not automatic_captions and not subtitles:
648 locale = self._html_search_meta(
649 ['og
:locale
', 'twitter
:locale
'], webpage, 'locale
', default='en_US
')
650 (automatic_captions if is_broadcast else subtitles)[locale] = [{'url': captions_url}]
655 'thumbnail
': traverse_obj(
656 video, ('thumbnailImage
', 'uri
'), ('preferred_thumbnail
', 'image
', 'uri
')),
657 'uploader_id
': traverse_obj(video, ('owner
', 'id', {str_or_none})),
658 'timestamp
': traverse_obj(video, 'publish_time
', 'creation_time
', expected_type=int_or_none),
659 'duration
': (float_or_none(video.get('playable_duration_in_ms
'), 1000)
660 or float_or_none(video.get('length_in_second
'))),
661 'automatic_captions
': automatic_captions,
662 'subtitles
': subtitles,
664 process_formats(info)
665 description = try_get(video, lambda x: x['savable_description
']['text
'])
666 title = video.get('name
')
670 'description
': description,
673 info['title
'] = description or 'Facebook video
#%s' % v_id
676 def parse_attachment(attachment
, key
='media'):
677 media
= attachment
.get(key
) or {}
678 if media
.get('__typename') == 'Video':
679 return parse_graphql_video(media
)
681 nodes
= variadic(traverse_obj(data
, 'nodes', 'node') or [])
682 attachments
= traverse_obj(nodes
, (
683 ..., 'comet_sections', 'content', 'story', (None, 'attached_story'), 'attachments',
684 ..., ('styles', 'style_type_renderer', ('throwbackStyles', 'attachment_target_renderer')),
685 'attachment', {dict}
))
686 for attachment
in attachments
:
687 ns
= traverse_obj(attachment
, ('all_subattachments', 'nodes', ..., {dict}
),
688 ('target', 'attachments', ..., 'styles', 'attachment', {dict}
))
691 parse_attachment(attachment
)
693 edges
= try_get(data
, lambda x
: x
['mediaset']['currMedia']['edges'], list) or []
695 parse_attachment(edge
, key
='node')
697 video
= traverse_obj(data
, (
698 'event', 'cover_media_renderer', 'cover_video'), 'video', expected_type
=dict) or {}
700 attachments
= try_get(video
, [
701 lambda x
: x
['story']['attachments'],
702 lambda x
: x
['creation_story']['attachments']
704 for attachment
in attachments
:
705 parse_attachment(attachment
)
707 parse_graphql_video(video
)
710 return self
.playlist_result(entries
, video_id
)
712 video_info
= entries
[0] if entries
else {'id': video_id}
713 webpage_info
= extract_metadata(webpage
)
714 # honor precise duration in video info
715 if video_info
.get('duration'):
716 webpage_info
['duration'] = video_info
['duration']
717 # preserve preferred_thumbnail in video info
718 if video_info
.get('thumbnail'):
719 webpage_info
['thumbnail'] = video_info
['thumbnail']
720 return merge_dicts(webpage_info
, video_info
)
723 m_msg
= re
.search(r
'class="[^"]*uiInterstitialContent[^"]*"><div>(.*?)</div>', webpage
)
724 if m_msg
is not None:
725 raise ExtractorError(
726 'The video is not available, Facebook said: "%s"' % m_msg
.group(1),
728 elif any(p
in webpage
for p
in (
729 '>You must log in to continue',
731 'id="loginbutton"')):
732 self
.raise_login_required()
734 if not video_data
and '/watchparty/' in url
:
736 'doc_id': 3731964053542869,
737 'variables': json
.dumps({
738 'livingRoomID': video_id
,
742 prefetched_data
= extract_relay_prefetched_data(r
'"login_data"\s*:\s*{')
744 lsd
= try_get(prefetched_data
, lambda x
: x
['login_data']['lsd'], dict)
746 post_data
[lsd
['name']] = lsd
['value']
748 relay_data
= extract_relay_data(r
'\[\s*"RelayAPIConfigDefaults"\s*,')
749 for define
in (relay_data
.get('define') or []):
750 if define
[0] == 'RelayAPIConfigDefaults':
751 self
._api
_config
= define
[2]
753 living_room
= self
._download
_json
(
754 urljoin(url
, self
._api
_config
['graphURI']), video_id
,
755 data
=urlencode_postdata(post_data
))['data']['living_room']
758 for edge
in (try_get(living_room
, lambda x
: x
['recap']['watched_content']['edges']) or []):
759 video
= try_get(edge
, lambda x
: x
['node']['video']) or {}
760 v_id
= video
.get('id')
763 v_id
= compat_str(v_id
)
764 entries
.append(self
.url_result(
765 self
._VIDEO
_PAGE
_TEMPLATE
% v_id
,
766 self
.ie_key(), v_id
, video
.get('name')))
768 return self
.playlist_result(entries
, video_id
)
771 # Video info not in first request, do a secondary request using
772 # tahoe player specific URL
773 tahoe_data
= self
._download
_webpage
(
774 self
._VIDEO
_PAGE
_TAHOE
_TEMPLATE
% video_id
, video_id
,
775 data
=urlencode_postdata({
777 '__pc': self
._search
_regex
(
778 r
'pkg_cohort["\']\s
*:\s
*["\'](.+?)["\']', webpage,
779 'pkg cohort
', default='PHASED
:DEFAULT
'),
780 '__rev
': self._search_regex(
781 r'client_revision
["\']\s*:\s*(\d+),', webpage,
782 'client revision', default='3944515'),
783 'fb_dtsg': self._search_regex(
784 r'"DTSGInitialData
"\s*,\s*\[\]\s*,\s*{\s*"token
"\s*:\s*"([^
"]+)"',
785 webpage, 'dtsg token
', default=''),
788 'Content
-Type
': 'application
/x
-www
-form
-urlencoded
',
790 tahoe_js_data = self._parse_json(
792 r'for\s
+\
(\s
*;\s
*;\s
*\
)\s
*;(.+)', tahoe_data,
793 'tahoe js data
', default='{}'),
794 video_id, fatal=False)
795 video_data = extract_from_jsmods_instances(tahoe_js_data)
798 raise ExtractorError('Cannot parse data
')
800 if len(video_data) > 1:
803 video_url = v[0].get('video_url
')
806 entries.append(self.url_result(urljoin(
807 url, video_url), self.ie_key(), v[0].get('video_id
')))
808 return self.playlist_result(entries, video_id)
809 video_data = video_data[0]
814 format_id = f['stream_type
']
815 if f and isinstance(f, dict):
817 if not f or not isinstance(f, list):
819 for quality in ('sd
', 'hd
'):
820 for src_type in ('src
', 'src_no_ratelimit
'):
821 src = f[0].get('%s_%s' % (quality, src_type))
823 # sd, hd formats w/o resolution info should be deprioritized below DASH
824 # TODO: investigate if progressive or src formats still exist
825 preference = -10 if format_id == 'progressive
' else -3
829 'format_id
': '%s_%s_%s' % (format_id, quality, src_type),
831 'quality
': preference,
832 'height
': 720 if quality == 'hd
' else None
834 extract_dash_manifest(f[0], formats)
835 subtitles_src = f[0].get('subtitles_src
')
837 subtitles.setdefault('en
', []).append({'url': subtitles_src})
842 'subtitles
': subtitles,
844 process_formats(info_dict)
845 info_dict.update(extract_metadata(webpage))
849 def _real_extract(self, url):
850 video_id = self._match_id(url)
852 real_url = self._VIDEO_PAGE_TEMPLATE % video_id if url.startswith('facebook
:') else url
853 return self._extract_from_url(real_url, video_id)
856 class FacebookPluginsVideoIE(InfoExtractor):
857 _VALID_URL = r'https?
://(?
:[\w
-]+\
.)?facebook\
.com
/plugins
/video\
.php
\?.*?
\bhref
=(?P
<id>https
.+)'
860 'url
': 'https
://www
.facebook
.com
/plugins
/video
.php?href
=https
%3A
%2F
%2Fwww
.facebook
.com
%2Fgov
.sg
%2Fvideos
%2F10154383743583686
%2F
&show_text
=0&width
=560',
861 'md5
': '5954e92cdfe51fe5782ae9bda7058a07
',
863 'id': '10154383743583686',
865 # TODO: Fix title, uploader
866 'title
': 'What to do during the haze?
',
867 'uploader
': 'Gov
.sg
',
868 'upload_date
': '20160826',
869 'timestamp
': 1472184808,
871 'add_ie
': [FacebookIE.ie_key()],
873 'url
': 'https
://www
.facebook
.com
/plugins
/video
.php?href
=https
%3A
%2F
%2Fwww
.facebook
.com
%2Fvideo
.php
%3Fv
%3D10204634152394104
',
874 'only_matching
': True,
876 'url
': 'https
://www
.facebook
.com
/plugins
/video
.php?href
=https
://www
.facebook
.com
/gov
.sg
/videos
/10154383743583686/&show_text
=0&width
=560',
877 'only_matching
': True,
880 def _real_extract(self, url):
881 return self.url_result(
882 compat_urllib_parse_unquote(self._match_id(url)),
886 class FacebookRedirectURLIE(InfoExtractor):
887 IE_DESC = False # Do not list
888 _VALID_URL = r'https?
://(?
:[\w
-]+\
.)?facebook\
.com
/flx
/warn
[/?
]'
890 'url
': 'https
://www
.facebook
.com
/flx
/warn
/?h
=TAQHsoToz
&u
=https
%3A
%2F
%2Fwww
.youtube
.com
%2Fwatch
%3Fv
%3DpO8h3EaFRdo
&s
=1',
894 'title
': 'Tripeo Boiler Room x Dekmantel Festival DJ Set
',
895 'description
': 'md5
:2d713ccbb45b686a1888397b2c77ca6b
',
896 'channel_id
': 'UCGBpxWJr9FNOcFYA5GkKrMg
',
897 'playable_in_embed
': True,
898 'categories
': ['Music
'],
899 'channel
': 'Boiler Room
',
900 'uploader_id
': 'brtvofficial
',
901 'uploader
': 'Boiler Room
',
904 'live_status
': 'not_live
',
905 'thumbnail
': 'https
://i
.ytimg
.com
/vi
/pO8h3EaFRdo
/maxresdefault
.jpg
',
906 'channel_url
': 'https
://www
.youtube
.com
/channel
/UCGBpxWJr9FNOcFYA5GkKrMg
',
907 'availability
': 'public
',
908 'uploader_url
': 'http
://www
.youtube
.com
/user
/brtvofficial
',
909 'upload_date
': '20150917',
914 'add_ie
': ['Youtube
'],
915 'params
': {'skip_download': 'Youtube'},
918 def _real_extract(self, url):
919 redirect_url = url_or_none(parse_qs(url).get('u
', [None])[-1])
921 raise ExtractorError('Invalid facebook redirect URL
', expected=True)
922 return self.url_result(redirect_url)
925 class FacebookReelIE(InfoExtractor):
926 _VALID_URL = r'https?
://(?
:[\w
-]+\
.)?facebook\
.com
/reel
/(?P
<id>\d
+)'
927 IE_NAME = 'facebook
:reel
'
930 'url
': 'https
://www
.facebook
.com
/reel
/1195289147628387',
931 'md5
': 'f13dd37f2633595982db5ed8765474d3
',
933 'id': '1195289147628387',
935 'title
': 'md5
:b05800b5b1ad56c0ca78bd3807b6a61e
',
936 'description
': 'md5
:22f03309b216ac84720183961441d8db
',
937 'uploader
': 'md5
:723e6cb3091241160f20b3c5dc282af1
',
938 'uploader_id
': '100040874179269',
940 'timestamp
': 1637502609,
941 'upload_date
': '20211121',
942 'thumbnail
': r're
:^https?
://.*',
946 def _real_extract(self, url):
947 video_id = self._match_id(url)
948 return self.url_result(
949 f'https
://m
.facebook
.com
/watch
/?v
={video_id}
&_rdr
', FacebookIE, video_id)
952 class FacebookAdsIE(InfoExtractor):
953 _VALID_URL = r'https?
://(?
:[\w
-]+\
.)?facebook\
.com
/ads
/library
/?
\?(?
:[^
#]+&)?id=(?P<id>\d+)'
954 IE_NAME
= 'facebook:ads'
957 'url': 'https://www.facebook.com/ads/library/?id=899206155126718',
959 'id': '899206155126718',
961 'title': 'video by Kandao',
962 'uploader': 'Kandao',
963 'uploader_id': '774114102743284',
964 'uploader_url': r
're:^https?://.*',
965 'timestamp': 1702548330,
966 'thumbnail': r
're:^https?://.*',
967 'upload_date': '20231214',
971 'url': 'https://www.facebook.com/ads/library/?id=893637265423481',
973 'id': '893637265423481',
974 'title': 'Jusqu\u2019\u00e0 -25% sur une s\u00e9lection de vins p\u00e9tillants italiens ',
975 'uploader': 'Eataly Paris Marais',
976 'uploader_id': '2086668958314152',
977 'uploader_url': r
're:^https?://.*',
978 'timestamp': 1703571529,
979 'upload_date': '20231226',
984 'url': 'https://es-la.facebook.com/ads/library/?id=901230958115569',
985 'only_matching': True,
987 'url': 'https://m.facebook.com/ads/library/?id=901230958115569',
988 'only_matching': True,
992 'watermarked_video_sd_url': ('sd-wmk', 'SD, watermarked'),
993 'video_sd_url': ('sd', None),
994 'watermarked_video_hd_url': ('hd-wmk', 'HD, watermarked'),
995 'video_hd_url': ('hd', None),
998 def _extract_formats(self
, video_dict
):
1000 for format_key
, format_url
in traverse_obj(video_dict
, (
1001 {dict.items}
, lambda _
, v
: v
[0] in self
._FORMATS
_MAP
and url_or_none(v
[1])
1004 'format_id': self
._FORMATS
_MAP
[format_key
][0],
1005 'format_note': self
._FORMATS
_MAP
[format_key
][1],
1008 'quality': qualities(tuple(self
._FORMATS
_MAP
))(format_key
),
1012 def _real_extract(self
, url
):
1013 video_id
= self
._match
_id
(url
)
1014 webpage
= self
._download
_webpage
(url
, video_id
)
1016 post_data
= [self
._parse
_json
(j
, video_id
, fatal
=False)
1017 for j
in re
.findall(r
's\.handle\(({.*})\);requireLazy\(', webpage
)]
1018 data
= traverse_obj(post_data
, (
1019 ..., 'require', ..., ..., ..., 'props', 'deeplinkAdCard', 'snapshot', {dict}
), get_all
=False)
1021 raise ExtractorError('Unable to extract ad data')
1023 title
= data
.get('title')
1024 if not title
or title
== '{{product.name}}':
1025 title
= join_nonempty('display_format', 'page_name', delim
=' by ', from_dict
=data
)
1027 info_dict
= traverse_obj(data
, {
1028 'description': ('link_description', {str}
, {lambda x: x if x != '{{product.description}
}' else None}),
1029 'uploader
': ('page_name
', {str}),
1030 'uploader_id
': ('page_id
', {str_or_none}),
1031 'uploader_url
': ('page_profile_uri
', {url_or_none}),
1032 'timestamp
': ('creation_time
', {int_or_none}),
1033 'like_count
': ('page_like_count
', {int_or_none}),
1037 for idx, entry in enumerate(traverse_obj(
1038 data, (('videos
', 'cards
'), lambda _, v: any([url_or_none(v[f]) for f in self._FORMATS_MAP]))), 1
1041 'id': f'{video_id}_{idx}
',
1042 'title
': entry.get('title
') or title,
1043 'description
': entry.get('link_description
') or info_dict.get('description
'),
1044 'thumbnail
': url_or_none(entry.get('video_preview_image_url
')),
1045 'formats
': self._extract_formats(entry),
1048 if len(entries) == 1:
1049 info_dict.update(entries[0])
1051 elif len(entries) > 1:
1053 'title
': entries[0]['title
'],
1055 '_type
': 'playlist
',
1058 info_dict['id'] = video_id