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)/|
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
': 'pfbid028wxorhX2ErLFJ578N6P3crHD3PHmXTCqCvfBpsnbSLmbokwSY75p5hWBjHGkG4zxl
',
117 'concurrent_view_count
': int,
120 'note
': 'Video
with DASH manifest
',
121 'url
': 'https
://www
.facebook
.com
/video
.php?v
=957955867617029',
122 'md5
': 'b2c28d528273b323abe5c6ab59f0f030
',
124 'id': '957955867617029',
126 'title
': 'When you post epic content on instagram
.com
/433 8 million followers
, this
is ...',
127 'uploader
': 'Demy de Zeeuw
',
128 'upload_date
': '20160110',
129 'timestamp
': 1452431627,
131 'skip
': 'Requires logging
in',
133 'url
': 'https
://www
.facebook
.com
/maxlayn
/posts
/10153807558977570',
134 'md5
': '037b1fa7f3c2d02b7a0d7bc16031ecc6
',
136 'id': '544765982287235',
138 'title
': '"What are you doing running in the snow?"',
139 'uploader
': 'FailArmy
',
141 'skip
': 'Video gone
',
143 'url
': 'https
://m
.facebook
.com
/story
.php?story_fbid
=1035862816472149&id=116132035111903',
144 'md5
': '1deb90b6ac27f7efcf6d747c8a27f5e3
',
146 'id': '1035862816472149',
148 'title
': 'What the Flock Is Going On In New Zealand Credit
: ViralHog
',
149 'uploader
': 'S
. Saint
',
151 'skip
': 'Video gone
',
153 'note
': 'swf params escaped
',
154 'url
': 'https
://www
.facebook
.com
/barackobama
/posts
/10153664894881749',
155 'md5
': '97ba073838964d12c70566e0085c2b91
',
157 'id': '10153664894881749',
159 'title
': 'Average time to confirm recent Supreme Court nominees
: 67 days Longest it
\'s t
...',
160 'thumbnail
': r're
:^https?
://.*',
161 'timestamp
': 1456259628,
162 'upload_date
': '20160223',
163 'uploader
': 'Barack Obama
',
165 'skip
': 'Gif on giphy
.com gone
',
167 # have 1080P, but only up to 720p in swf params
168 # data.video.story.attachments[].media
169 'url
': 'https
://www
.facebook
.com
/cnn
/videos
/10155529876156509/',
170 'md5
': 'ca63897a90c9452efee5f8c40d080e25
',
172 'id': '10155529876156509',
174 'title
': 'Holocaust survivor becomes US citizen
',
175 'description
': 'She survived the holocaust —
and years later
, she’s getting her citizenship so she can vote
for Hillary Clinton http
://cnn
.it
/2eERh5f
',
176 'timestamp
': 1477818095,
177 'upload_date
': '20161030',
179 'thumbnail
': r're
:^https?
://.*',
181 'uploader_id
': '100059479812265',
182 'concurrent_view_count
': int,
186 # bigPipe.onPageletArrive ... onPageletArrive pagelet_group_mall
187 # data.node.comet_sections.content.story.attachments[].style_type_renderer.attachment.media
188 'url
': 'https
://www
.facebook
.com
/yaroslav
.korpan
/videos
/1417995061575415/',
190 'id': '1417995061575415',
192 'title
': 'Довгоочікуване відео | By Yaroslav
- Facebook
',
193 'description
': 'Довгоочікуване відео
',
194 'timestamp
': 1486648217,
195 'upload_date
': '20170209',
196 'uploader
': 'Yaroslav Korpan
',
197 'uploader_id
': 'pfbid06AScABAWcW91qpiuGrLt99Ef9tvwHoXP6t8KeFYEqkSfreMtfa9nTveh8b2ZEVSWl
',
198 'concurrent_view_count
': int,
199 'thumbnail
': r're
:^https?
://.*',
201 'duration
': 11736.446,
204 'skip_download
': True,
207 # FIXME: Cannot parse data error
208 'url
': 'https
://www
.facebook
.com
/LaGuiaDelVaron
/posts
/1072691702860471',
210 'id': '1072691702860471',
212 'title
': 'md5
:ae2d22a93fbb12dad20dc393a869739d
',
213 'timestamp
': 1477305000,
214 'upload_date
': '20161024',
215 'uploader
': 'La Guía Del Varón
',
216 'thumbnail
': r're
:^https?
://.*',
218 'skip
': 'Requires logging
in',
220 # data.node.comet_sections.content.story.attachments[].style_type_renderer.attachment.media
221 'url
': 'https
://www
.facebook
.com
/groups
/1024490957622648/permalink
/1396382447100162/',
223 'id': '202882990186699',
225 'title
': 'birb (O v O
") | Hello? Yes your uber ride is here',
226 'description': 'Hello? Yes your uber ride is here * Jukin Media Verified * Find this video and others like it by visiting...',
227 'timestamp': 1486035513,
228 'upload_date': '20170202',
229 'uploader': 'Elisabeth Ahtn',
230 'uploader_id': '100013949973717',
232 'skip': 'Requires logging in',
234 # data.node.comet_sections.content.story.attachments[].throwbackStyles.attachment_target_renderer.attachment.target.attachments[].styles.attachment.media
235 'url': 'https://www.facebook.com/groups/1645456212344334/posts/3737828833107051/',
237 'id': '1569199726448814',
239 'title': 'Pence MUST GO!',
240 'description': 'Vickie Gentry shared a memory.',
241 'timestamp': 1511548260,
242 'upload_date': '20171124',
243 'uploader': 'Vickie Gentry',
244 'uploader_id': 'pfbid0FuZhHCeWDAxWxEbr3yKPFaRstXvRxgsp9uCPG6GjD4J2AitB35NUAuJ4Q75KcjiDl',
245 'thumbnail': r're:^https?://.*',
249 # data.node.comet_sections.content.story.attachments[].styles.attachment.media
250 'url': 'https://www.facebook.com/attn/posts/pfbid0j1Czf2gGDVqeQ8KiMLFm3pWN8GxsQmeRrVhimWDzMuKQoR8r4b1knNsejELmUgyhl',
252 'id': '6968553779868435',
254 'description': 'md5:2f2fcf93e97ac00244fe64521bbdb0cb',
256 'upload_date': '20231207',
259 'uploader_id': '100064451419378',
261 'thumbnail': r're:^https?://.*',
262 'timestamp': 1701975646,
265 # data.node.comet_sections.content.story.attachments[].styles.attachment.media
266 'url': 'https://www.facebook.com/permalink.php?story_fbid=pfbid0fqQuVEQyXRa9Dp4RcaTR14KHU3uULHV1EK7eckNXSH63JMuoALsAvVCJ97zAGitil&id=100068861234290',
268 'id': '270103405756416',
270 'title': 'Lela Evans',
271 'description': 'Today Makkovik\'s own Pilot Mandy Smith made her inaugural landing on the airstrip in her hometown. What a proud moment as we all cheered and...',
272 'thumbnail': r're:^https?://.*',
273 'uploader': 'Lela Evans',
274 'uploader_id': 'pfbid0shZJipuigyy5mqrUJn9ub5LJFWNHvan5prtyi3LrDuuuJ4NwrURgnQHYR9fywBepl',
275 'upload_date': '20231228',
276 'timestamp': 1703804085,
281 'url': 'https://www.facebook.com/story.php?story_fbid=pfbid0Fnzhm8UuzjBYpPMNFzaSpFE9UmLdU4fJN8qTANi1Dmtj5q7DNrL5NERXfsAzDEV7l&id=100073071055552',
282 'only_matching': True,
284 'url': 'https://www.facebook.com/video.php?v=10204634152394104',
285 'only_matching': True,
287 'url': 'https://www.facebook.com/amogood/videos/1618742068337349/?fref=nf',
288 'only_matching': True,
290 # data.mediaset.currMedia.edges
291 'url': 'https://www.facebook.com/ChristyClarkForBC/videos/vb.22819070941/10153870694020942/?type=2&theater',
292 'only_matching': True,
294 # data.video.story.attachments[].media
295 'url': 'facebook:544765982287235',
296 'only_matching': True,
298 # data.node.comet_sections.content.story.attachments[].style_type_renderer.attachment.media
299 'url': 'https://www.facebook.com/groups/164828000315060/permalink/764967300301124/',
300 'only_matching': True,
302 # data.video.creation_story.attachments[].media
303 'url': 'https://zh-hk.facebook.com/peoplespower/videos/1135894589806027/',
304 'only_matching': True,
307 'url': 'https://www.facebookwkhpilnemxj7asaniu7vnjjbiltxjqhye3mhbshg7kx5tfyd.onion/video.php?v=274175099429670',
308 'only_matching': True,
311 'url': 'https://www.facebook.com/onlycleverentertainment/videos/1947995502095005/',
312 'only_matching': True,
315 'url': 'https://www.facebook.com/WatchESLOne/videos/359649331226507/',
317 'id': '359649331226507',
319 'title': 'Fnatic vs. EG - Group A - Opening Match - ESL One Birmingham Day 1',
320 'description': '#ESLOne VoD - Birmingham Finals Day#1 Fnatic vs. @Evil Geniuses',
321 'timestamp': 1527084179,
322 'upload_date': '20180523',
323 'uploader': 'ESL One Dota 2',
324 'uploader_id': '100066514874195',
325 'duration': 4524.212,
327 'thumbnail': r're:^https?://.*',
328 'concurrent_view_count': int,
331 'skip_download': True,
334 # data.node.comet_sections.content.story.attachments[].style_type_renderer.attachment.all_subattachments.nodes[].media
335 'url': 'https://www.facebook.com/100033620354545/videos/106560053808006/',
337 'id': '106560053808006',
340 'thumbnail': r're:^https?://.*',
341 'concurrent_view_count': int,
342 'uploader_id': 'pfbid0cibUN6tV7DYgdbJdsUFN46wc4jKpVSPAvJQhFofGqBGmVn3V3JtAs2tfUwziw2hUl',
343 'timestamp': 1549275572,
345 'uploader': 'Josef Novak',
347 'upload_date': '20190204',
350 # data.video.story.attachments[].media
351 'url': 'https://www.facebook.com/watch/?v=647537299265662',
352 'only_matching': True,
354 # FIXME: https://github.com/yt-dlp/yt-dlp/issues/542
355 # data.node.comet_sections.content.story.attachments[].style_type_renderer.attachment.all_subattachments.nodes[].media
356 'url': 'https://www.facebook.com/PankajShahLondon/posts/10157667649866271',
358 'id': '10157667649866271',
361 'skip': 'Requires logging in',
363 # data.nodes[].comet_sections.content.story.attachments[].style_type_renderer.attachment.media
364 'url': 'https://m.facebook.com/Alliance.Police.Department/posts/4048563708499330',
366 'id': '117576630041613',
368 # TODO: title can be extracted from video page
369 'title': 'Facebook video #117576630041613',
370 'uploader_id': '189393014416438',
371 'upload_date': '20201123',
372 'timestamp': 1606162592,
374 'skip': 'Requires logging in',
376 # node.comet_sections.content.story.attached_story.attachments.style_type_renderer.attachment.media
377 'url': 'https://www.facebook.com/groups/ateistiskselskab/permalink/10154930137678856/',
379 'id': '211567722618337',
381 'title': 'Facebook video #211567722618337',
382 'uploader_id': '127875227654254',
383 'upload_date': '20161122',
384 'timestamp': 1479793574,
388 # data.video.creation_story.attachments[].media
389 'url': 'https://www.facebook.com/watch/live/?v=1823658634322275',
390 'only_matching': True,
392 'url': 'https://www.facebook.com/watchparty/211641140192478',
394 'id': '211641140192478',
397 'skip': 'Requires logging in',
399 # data.event.cover_media_renderer.cover_video
400 'url': 'https://m.facebook.com/events/1509582499515440',
402 'id': '637246984455045',
404 'title': 'ANALISI IN CAMPO OSCURO " Coaguli nel sangue dei vaccinati
"',
405 'description': 'Other event by Comitato Liberi Pensatori on Tuesday, October 18 2022',
406 'thumbnail': r're:^https?://.*',
407 'uploader': 'Comitato Liberi Pensatori',
408 'uploader_id': '100065709540881',
411 _SUPPORTED_PAGLETS_REGEX = r'(?:pagelet_group_mall|permalink_video_pagelet|hyperfeed_story_id_[0-9a-f]+)'
413 'graphURI': '/api/graphql/',
416 def _perform_login(self, username, password):
417 login_page_req = Request(self._LOGIN_URL)
418 self._set_cookie('facebook.com', 'locale', 'en_US')
419 login_page = self._download_webpage(login_page_req, None,
420 note='Downloading login page',
421 errnote='Unable to download login page')
422 lsd = self._search_regex(
423 r'<input type="hidden
" name="lsd
" value="([^
"]*)"',
425 lgnrnd = self._search_regex(r'name
="lgnrnd" value
="([^"]*?
)"', login_page, 'lgnrnd')
432 'next': 'http://facebook.com/home.php',
433 'default_persistent': '0',
434 'legacy_return': '1',
438 request = Request(self._LOGIN_URL, urlencode_postdata(login_form))
439 request.headers['Content-Type'] = 'application/x-www-form-urlencoded'
441 login_results = self._download_webpage(request, None,
442 note='Logging in', errnote='unable to fetch login page')
443 if re.search(r'<form(.*)name="login
"(.*)</form>', login_results) is not None:
444 error = self._html_search_regex(
445 r'(?s)<div[^>]+class=(["\']).*?login_error_box
.*?\
1[^
>]*><div
[^
>]*>.*?
</div
><div
[^
>]*>(?P
<error
>.+?
)</div
>',
446 login_results, 'login error
', default=None, group='error
')
448 raise ExtractorError(f'Unable to login
: {error}
', expected=True)
449 self.report_warning('unable to log
in: bad username
/password
, or exceeded login rate
limit (~
3/min). Check credentials
or wait
.')
452 fb_dtsg = self._search_regex(
453 r'name
="fb_dtsg" value
="(.+?)"', login_results, 'fb_dtsg
', default=None)
454 h = self._search_regex(
455 r'name
="h"\s
+(?
:\w
+="[^"]+"\s+)*?value="([^
"]+)"', login_results, 'h
', default=None)
457 if not fb_dtsg or not h:
463 'name_action_selected
': 'dont_save
',
465 check_req = Request(self._CHECKPOINT_URL, urlencode_postdata(check_form))
466 check_req.headers['Content
-Type
'] = 'application
/x
-www
-form
-urlencoded
'
467 check_response = self._download_webpage(check_req, None,
468 note='Confirming login
')
469 if re.search(r'id="checkpointSubmitButton"', check_response) is not None:
470 self.report_warning('Unable to confirm login
, you have to login
in your browser
and authorize the login
.')
471 except network_exceptions as err:
472 self.report_warning(f'unable to log
in: {err}
')
475 def _extract_from_url(self, url, video_id):
476 webpage = self._download_webpage(
477 url.replace('://m
.facebook
.com
/', '://www
.facebook
.com
/'), video_id)
479 def extract_metadata(webpage):
480 post_data = [self._parse_json(j, video_id, fatal=False) for j in re.findall(
481 r'data
-sjs
>({.*?ScheduledServerJS.*?}
)</script
>', webpage)]
482 post = traverse_obj(post_data, (
483 ..., 'require
', ..., ..., ..., '__bbox
', 'require
', ..., ..., ..., '__bbox
', 'result
', 'data
'), expected_type=dict) or []
484 media = traverse_obj(post, (..., 'attachments
', ..., lambda k, v: (
485 k == 'media
' and str(v['id']) == video_id and v['__typename
'] == 'Video
')), expected_type=dict)
486 title = get_first(media, ('title
', 'text
'))
487 description = get_first(media, ('creation_story
', 'comet_sections
', 'message
', 'story
', 'message
', 'text
'))
488 page_title = title or self._html_search_regex((
489 r'<h2\s
+[^
>]*class="uiHeaderTitle"[^
>]*>(?P
<content
>[^
<]*)</h2
>',
490 r'(?s
)<span
class="fbPhotosPhotoCaption".*?
id="fbPhotoPageCaption"><span
class="hasCaption">(?P
<content
>.*?
)</span
>',
491 self._meta_regex('og
:title
'), self._meta_regex('twitter
:title
'), r'<title
>(?P
<content
>.+?
)</title
>',
492 ), webpage, 'title
', default=None, group='content
')
493 description = description or self._html_search_meta(
494 ['description
', 'og
:description
', 'twitter
:description
'],
495 webpage, 'description
', default=None)
497 get_first(media, ('owner
', {dict}))
498 or get_first(post, ('video
', 'creation_story
', 'attachments
', ..., 'media
', lambda k, v: k == 'owner
' and v['name
']))
499 or get_first(post, (..., 'video
', lambda k, v: k == 'owner
' and v['name
']))
500 or get_first(post, ('node
', 'actors
', ..., {dict}))
501 or get_first(post, ('event
', 'event_creator
', {dict})) or {})
502 uploader = uploader_data.get('name
') or (
503 clean_html(get_element_by_id('fbPhotoPageAuthorName
', webpage))
504 or self._search_regex(
505 (r'ownerName\s
*:\s
*"([^"]+)"', *self._og_regexes('title')), webpage, 'uploader', fatal=False))
506 timestamp = int_or_none(self._search_regex(
507 r'<abbr[^>]+data-utime=["\'](\d
+)', webpage,
508 'timestamp
', default=None))
509 thumbnail = self._html_search_meta(
510 ['og
:image
', 'twitter
:image
'], webpage, 'thumbnail
', default=None)
511 # some webpages contain unretrievable thumbnail urls
512 # like https://lookaside.fbsbx.com/lookaside/crawler/media/?media_id=10155168902769113&get_thumbnail=1
513 # in https://www.facebook.com/yaroslav.korpan/videos/1417995061575415/
514 if thumbnail and not re.search(r'\
.(?
:jpg|png
)', thumbnail):
517 'description
': description,
518 'uploader
': uploader,
519 'uploader_id
': uploader_data.get('id'),
520 'timestamp
': timestamp,
521 'thumbnail
': thumbnail,
522 'view_count
': parse_count(self._search_regex(
523 (r'\bviewCount\s
*:\s
*["\']([\d,.]+)', r'video_view_count["\']\s
*:\s
*(\d
+)'),
524 webpage, 'view count
', default=None)),
525 'concurrent_view_count
': get_first(post, (
526 ('video
', (..., ..., 'attachments
', ..., 'media
')), 'liveViewerCount
', {int_or_none})),
529 info_json_ld = self._search_json_ld(webpage, video_id, default={})
530 info_json_ld['title
'] = (re.sub(r'\s
*\|\s
*Facebook$
', '', title or info_json_ld.get('title
') or page_title or '')
531 or (description or '').replace('\n', ' ') or f'Facebook video
#{video_id}')
532 return merge_dicts(info_json_ld
, info_dict
)
536 def extract_video_data(instances
):
538 for item
in instances
:
539 if try_get(item
, lambda x
: x
[1][0]) == 'VideoConfig':
540 video_item
= item
[2][0]
541 if video_item
.get('video_id'):
542 video_data
.append(video_item
['videoData'])
545 server_js_data
= self
._parse
_json
(self
._search
_regex
(
546 [r
'handleServerJS\(({.+})(?:\);|,")', r
'\bs\.handle\(({.+?})\);'],
547 webpage
, 'server js data', default
='{}'), video_id
, fatal
=False)
550 video_data
= extract_video_data(server_js_data
.get('instances', []))
552 def extract_from_jsmods_instances(js_data
):
554 return extract_video_data(try_get(
555 js_data
, lambda x
: x
['jsmods']['instances'], list) or [])
557 def extract_dash_manifest(video
, formats
):
558 dash_manifest
= traverse_obj(video
, 'dash_manifest', 'playlist', expected_type
=str)
560 formats
.extend(self
._parse
_mpd
_formats
(
561 compat_etree_fromstring(urllib
.parse
.unquote_plus(dash_manifest
)),
562 mpd_url
=video
.get('dash_manifest_url')))
564 def process_formats(info
):
565 # Downloads with browser's User-Agent are rate limited. Working around
566 # with non-browser User-Agent.
567 for f
in info
['formats']:
568 # Downloads with browser's User-Agent are rate limited. Working around
569 # with non-browser User-Agent.
570 f
.setdefault('http_headers', {})['User-Agent'] = 'facebookexternalhit/1.1'
571 # Formats larger than ~500MB will return error 403 unless chunk size is regulated
572 f
.setdefault('downloader_options', {})['http_chunk_size'] = 250 << 20
574 def extract_relay_data(_filter
):
575 return self
._parse
_json
(self
._search
_regex
(
576 rf
'data-sjs>({{.*?{_filter}.*?}})</script>',
577 webpage
, 'replay data', default
='{}'), video_id, fatal=False) or {}
579 def extract_relay_prefetched_data(_filter):
580 return traverse_obj(extract_relay_data(_filter), (
581 'require
', (None, (..., ..., ..., '__bbox
', 'require
')),
582 lambda _, v: any(key.startswith('RelayPrefetchedStreamCache
') for key in v),
583 ..., ..., '__bbox
', 'result
', 'data
', {dict}), get_all=False) or {}
586 server_js_data = self._parse_json(self._search_regex([
587 r'bigPipe\
.onPageletArrive\
(({.+?}
)\
)\s
*;\s
*}\s
*\
)\s
*,\s
*["\']onPageletArrive\s+' + self._SUPPORTED_PAGLETS_REGEX,
588 rf'bigPipe\.onPageletArrive\(({{.*?id\s*:\s*"{self._SUPPORTED_PAGLETS_REGEX}".*?
}})\
);',
589 ], webpage, 'js data
', default='{}'), video_id, js_to_json, False)
590 video_data = extract_from_jsmods_instances(server_js_data)
593 data = extract_relay_prefetched_data(
594 r'"(?:dash_manifest|playable_url(?:_quality_hd)?)')
598 def parse_graphql_video(video):
599 v_id = video.get('videoId') or video.get('id') or video_id
600 reel_info = traverse_obj(
601 video, ('creation_story', 'short_form_video_context', 'playback_video', {dict}))
603 video = video['creation_story']
604 video['owner'] = traverse_obj(video, ('short_form_video_context', 'video_owner'))
605 video.update(reel_info)
607 q = qualities(['sd', 'hd'])
608 for key, format_id in (('playable_url', 'sd'), ('playable_url_quality_hd', 'hd'),
609 ('playable_url_dash', ''), ('browser_native_hd_url', 'hd'),
610 ('browser_native_sd_url', 'sd')):
611 playable_url = video.get(key)
614 if determine_ext(playable_url) == 'mpd':
615 formats.extend(self._extract_mpd_formats(playable_url, video_id))
618 'format_id': format_id,
619 # sd, hd formats w/o resolution info should be deprioritized below DASH
620 'quality': q(format_id) - 3,
623 extract_dash_manifest(video, formats)
625 # Do not append false positive entry w/o any formats
628 automatic_captions, subtitles = {}, {}
629 is_broadcast = traverse_obj(video, ('is_video_broadcast', {bool}))
630 for caption in traverse_obj(video, (
631 'video_available_captions_locales',
632 {lambda x: sorted(x, key=lambda c: c['locale'])},
633 lambda _, v: url_or_none(v['captions_url']),
635 lang = caption.get('localized_language') or 'und'
637 'url': caption['captions_url'],
638 'name': format_field(caption, 'localized_country', f'{lang} (%s)', default=lang),
640 if caption.get('localized_creation_method') or is_broadcast:
641 automatic_captions.setdefault(caption['locale'], []).append(subs)
643 subtitles.setdefault(caption['locale'], []).append(subs)
644 captions_url = traverse_obj(video, ('captions_url', {url_or_none}))
645 if captions_url and not automatic_captions and not subtitles:
646 locale = self._html_search_meta(
647 ['og:locale', 'twitter:locale'], webpage, 'locale', default='en_US')
648 (automatic_captions if is_broadcast else subtitles)[locale] = [{'url': captions_url}]
653 'thumbnail': traverse_obj(
654 video, ('thumbnailImage', 'uri'), ('preferred_thumbnail', 'image', 'uri')),
655 'uploader_id': traverse_obj(video, ('owner', 'id', {str_or_none})),
656 'timestamp': traverse_obj(video, 'publish_time', 'creation_time', expected_type=int_or_none),
657 'duration': (float_or_none(video.get('playable_duration_in_ms'), 1000)
658 or float_or_none(video.get('length_in_second'))),
659 'automatic_captions': automatic_captions,
660 'subtitles': subtitles,
662 process_formats(info)
663 description = try_get(video, lambda x: x['savable_description']['text'])
664 title = video.get('name')
668 'description': description,
671 info['title'] = description or f'Facebook video #{v_id}'
674 def parse_attachment(attachment, key='media'):
675 media = attachment.get(key) or {}
676 if media.get('__typename') == 'Video':
677 return parse_graphql_video(media)
679 nodes = variadic(traverse_obj(data, 'nodes', 'node') or [])
680 attachments = traverse_obj(nodes, (
681 ..., 'comet_sections', 'content', 'story', (None, 'attached_story'), 'attachments',
682 ..., ('styles', 'style_type_renderer', ('throwbackStyles', 'attachment_target_renderer')),
683 'attachment', {dict}))
684 for attachment in attachments:
685 ns = traverse_obj(attachment, ('all_subattachments', 'nodes', ..., {dict}),
686 ('target', 'attachments', ..., 'styles', 'attachment', {dict}))
689 parse_attachment(attachment)
691 edges = try_get(data, lambda x: x['mediaset']['currMedia']['edges'], list) or []
693 parse_attachment(edge, key='node')
695 video = traverse_obj(data, (
696 'event', 'cover_media_renderer', 'cover_video'), 'video', expected_type=dict) or {}
698 attachments = try_get(video, [
699 lambda x: x['story']['attachments'],
700 lambda x: x['creation_story']['attachments'],
702 for attachment in attachments:
703 parse_attachment(attachment)
705 parse_graphql_video(video)
708 return self.playlist_result(entries, video_id)
710 video_info = entries[0] if entries else {'id': video_id}
711 webpage_info = extract_metadata(webpage)
712 # honor precise duration in video info
713 if video_info.get('duration'):
714 webpage_info['duration'] = video_info['duration']
715 # preserve preferred_thumbnail in video info
716 if video_info.get('thumbnail'):
717 webpage_info['thumbnail'] = video_info['thumbnail']
718 return merge_dicts(webpage_info, video_info)
721 m_msg = re.search(r'class="[^
"]*uiInterstitialContent[^"]*"><div>(.*?)</div>', webpage)
722 if m_msg is not None:
723 raise ExtractorError(
724 f'The video is not available, Facebook said: "{m_msg.group(1)}
"',
726 elif any(p in webpage for p in (
727 '>You must log in to continue',
729 'id="loginbutton
"')):
730 self.raise_login_required()
732 if not video_data and '/watchparty/' in url:
734 'doc_id': 3731964053542869,
735 'variables': json.dumps({
736 'livingRoomID': video_id,
740 prefetched_data = extract_relay_prefetched_data(r'"login_data
"\s*:\s*{')
742 lsd = try_get(prefetched_data, lambda x: x['login_data']['lsd'], dict)
744 post_data[lsd['name']] = lsd['value']
746 relay_data = extract_relay_data(r'\[\s*"RelayAPIConfigDefaults
"\s*,')
747 for define in (relay_data.get('define') or []):
748 if define[0] == 'RelayAPIConfigDefaults':
749 self._api_config = define[2]
751 living_room = self._download_json(
752 urljoin(url, self._api_config['graphURI']), video_id,
753 data=urlencode_postdata(post_data))['data']['living_room']
756 for edge in (try_get(living_room, lambda x: x['recap']['watched_content']['edges']) or []):
757 video = try_get(edge, lambda x: x['node']['video']) or {}
758 v_id = video.get('id')
762 entries.append(self.url_result(
763 self._VIDEO_PAGE_TEMPLATE % v_id,
764 self.ie_key(), v_id, video.get('name')))
766 return self.playlist_result(entries, video_id)
769 # Video info not in first request, do a secondary request using
770 # tahoe player specific URL
771 tahoe_data = self._download_webpage(
772 self._VIDEO_PAGE_TAHOE_TEMPLATE % video_id, video_id,
773 data=urlencode_postdata({
775 '__pc': self._search_regex(
776 r'pkg_cohort["\']\s
*:\s
*["\'](.+?)["\']', webpage,
777 'pkg cohort
', default='PHASED
:DEFAULT
'),
778 '__rev
': self._search_regex(
779 r'client_revision
["\']\s*:\s*(\d+),', webpage,
780 'client revision', default='3944515'),
781 'fb_dtsg': self._search_regex(
782 r'"DTSGInitialData
"\s*,\s*\[\]\s*,\s*{\s*"token
"\s*:\s*"([^
"]+)"',
783 webpage, 'dtsg token
', default=''),
786 'Content
-Type
': 'application
/x
-www
-form
-urlencoded
',
788 tahoe_js_data = self._parse_json(
790 r'for\s
+\
(\s
*;\s
*;\s
*\
)\s
*;(.+)', tahoe_data,
791 'tahoe js data
', default='{}'),
792 video_id, fatal=False)
793 video_data = extract_from_jsmods_instances(tahoe_js_data)
796 raise ExtractorError('Cannot parse data
')
798 if len(video_data) > 1:
801 video_url = v[0].get('video_url
')
804 entries.append(self.url_result(urljoin(
805 url, video_url), self.ie_key(), v[0].get('video_id
')))
806 return self.playlist_result(entries, video_id)
807 video_data = video_data[0]
812 format_id = f['stream_type
']
813 if f and isinstance(f, dict):
815 if not f or not isinstance(f, list):
817 for quality in ('sd
', 'hd
'):
818 for src_type in ('src
', 'src_no_ratelimit
'):
819 src = f[0].get(f'{quality}_{src_type}
')
821 # sd, hd formats w/o resolution info should be deprioritized below DASH
822 # TODO: investigate if progressive or src formats still exist
823 preference = -10 if format_id == 'progressive
' else -3
827 'format_id
': f'{format_id}_{quality}_{src_type}
',
829 'quality
': preference,
830 'height
': 720 if quality == 'hd
' else None,
832 extract_dash_manifest(f[0], formats)
833 subtitles_src = f[0].get('subtitles_src
')
835 subtitles.setdefault('en
', []).append({'url': subtitles_src})
840 'subtitles
': subtitles,
842 process_formats(info_dict)
843 info_dict.update(extract_metadata(webpage))
847 def _real_extract(self, url):
848 video_id = self._match_id(url)
850 real_url = self._VIDEO_PAGE_TEMPLATE % video_id if url.startswith('facebook
:') else url
851 return self._extract_from_url(real_url, video_id)
854 class FacebookPluginsVideoIE(InfoExtractor):
855 _VALID_URL = r'https?
://(?
:[\w
-]+\
.)?facebook\
.com
/plugins
/video\
.php
\?.*?
\bhref
=(?P
<id>https
.+)'
858 'url
': 'https
://www
.facebook
.com
/plugins
/video
.php?href
=https
%3A
%2F
%2Fwww
.facebook
.com
%2Fgov
.sg
%2Fvideos
%2F10154383743583686
%2F
&show_text
=0&width
=560',
859 'md5
': '5954e92cdfe51fe5782ae9bda7058a07
',
861 'id': '10154383743583686',
863 # TODO: Fix title, uploader
864 'title
': 'What to do during the haze?
',
865 'uploader
': 'Gov
.sg
',
866 'upload_date
': '20160826',
867 'timestamp
': 1472184808,
869 'add_ie
': [FacebookIE.ie_key()],
871 'url
': 'https
://www
.facebook
.com
/plugins
/video
.php?href
=https
%3A
%2F
%2Fwww
.facebook
.com
%2Fvideo
.php
%3Fv
%3D10204634152394104
',
872 'only_matching
': True,
874 'url
': 'https
://www
.facebook
.com
/plugins
/video
.php?href
=https
://www
.facebook
.com
/gov
.sg
/videos
/10154383743583686/&show_text
=0&width
=560',
875 'only_matching
': True,
878 def _real_extract(self, url):
879 return self.url_result(
880 urllib.parse.unquote(self._match_id(url)),
884 class FacebookRedirectURLIE(InfoExtractor):
885 IE_DESC = False # Do not list
886 _VALID_URL = r'https?
://(?
:[\w
-]+\
.)?facebook\
.com
/flx
/warn
[/?
]'
888 'url
': 'https
://www
.facebook
.com
/flx
/warn
/?h
=TAQHsoToz
&u
=https
%3A
%2F
%2Fwww
.youtube
.com
%2Fwatch
%3Fv
%3DpO8h3EaFRdo
&s
=1',
892 'title
': 'Tripeo Boiler Room x Dekmantel Festival DJ Set
',
893 'description
': 'md5
:2d713ccbb45b686a1888397b2c77ca6b
',
894 'channel_id
': 'UCGBpxWJr9FNOcFYA5GkKrMg
',
895 'playable_in_embed
': True,
896 'categories
': ['Music
'],
897 'channel
': 'Boiler Room
',
898 'uploader_id
': 'brtvofficial
',
899 'uploader
': 'Boiler Room
',
902 'live_status
': 'not_live
',
903 'thumbnail
': 'https
://i
.ytimg
.com
/vi
/pO8h3EaFRdo
/maxresdefault
.jpg
',
904 'channel_url
': 'https
://www
.youtube
.com
/channel
/UCGBpxWJr9FNOcFYA5GkKrMg
',
905 'availability
': 'public
',
906 'uploader_url
': 'http
://www
.youtube
.com
/user
/brtvofficial
',
907 'upload_date
': '20150917',
912 'add_ie
': ['Youtube
'],
913 'params
': {'skip_download': 'Youtube'},
916 def _real_extract(self, url):
917 redirect_url = url_or_none(parse_qs(url).get('u
', [None])[-1])
919 raise ExtractorError('Invalid facebook redirect URL
', expected=True)
920 return self.url_result(redirect_url)
923 class FacebookReelIE(InfoExtractor):
924 _VALID_URL = r'https?
://(?
:[\w
-]+\
.)?facebook\
.com
/reel
/(?P
<id>\d
+)'
925 IE_NAME = 'facebook
:reel
'
928 'url
': 'https
://www
.facebook
.com
/reel
/1195289147628387',
929 'md5
': 'f13dd37f2633595982db5ed8765474d3
',
931 'id': '1195289147628387',
933 'title
': 'md5
:b05800b5b1ad56c0ca78bd3807b6a61e
',
934 'description
': 'md5
:22f03309b216ac84720183961441d8db
',
935 'uploader
': 'md5
:723e6cb3091241160f20b3c5dc282af1
',
936 'uploader_id
': '100040874179269',
938 'timestamp
': 1637502609,
939 'upload_date
': '20211121',
940 'thumbnail
': r're
:^https?
://.*',
944 def _real_extract(self, url):
945 video_id = self._match_id(url)
946 return self.url_result(
947 f'https
://m
.facebook
.com
/watch
/?v
={video_id}
&_rdr
', FacebookIE, video_id)
950 class FacebookAdsIE(InfoExtractor):
951 _VALID_URL = r'https?
://(?
:[\w
-]+\
.)?facebook\
.com
/ads
/library
/?
\?(?
:[^
#]+&)?id=(?P<id>\d+)'
952 IE_NAME
= 'facebook:ads'
955 'url': 'https://www.facebook.com/ads/library/?id=899206155126718',
957 'id': '899206155126718',
959 'title': 'video by Kandao',
960 'uploader': 'Kandao',
961 'uploader_id': '774114102743284',
962 'uploader_url': r
're:^https?://.*',
963 'timestamp': 1702548330,
964 'thumbnail': r
're:^https?://.*',
965 'upload_date': '20231214',
969 'url': 'https://www.facebook.com/ads/library/?id=893637265423481',
971 'id': '893637265423481',
972 'title': 'Jusqu\u2019\u00e0 -25% sur une s\u00e9lection de vins p\u00e9tillants italiens ',
973 'uploader': 'Eataly Paris Marais',
974 'uploader_id': '2086668958314152',
975 'uploader_url': r
're:^https?://.*',
976 'timestamp': 1703571529,
977 'upload_date': '20231226',
982 'url': 'https://es-la.facebook.com/ads/library/?id=901230958115569',
983 'only_matching': True,
985 'url': 'https://m.facebook.com/ads/library/?id=901230958115569',
986 'only_matching': True,
990 'watermarked_video_sd_url': ('sd-wmk', 'SD, watermarked'),
991 'video_sd_url': ('sd', None),
992 'watermarked_video_hd_url': ('hd-wmk', 'HD, watermarked'),
993 'video_hd_url': ('hd', None),
996 def _extract_formats(self
, video_dict
):
998 for format_key
, format_url
in traverse_obj(video_dict
, (
999 {dict.items}
, lambda _
, v
: v
[0] in self
._FORMATS
_MAP
and url_or_none(v
[1]),
1002 'format_id': self
._FORMATS
_MAP
[format_key
][0],
1003 'format_note': self
._FORMATS
_MAP
[format_key
][1],
1006 'quality': qualities(tuple(self
._FORMATS
_MAP
))(format_key
),
1010 def _real_extract(self
, url
):
1011 video_id
= self
._match
_id
(url
)
1012 webpage
= self
._download
_webpage
(url
, video_id
)
1014 post_data
= [self
._parse
_json
(j
, video_id
, fatal
=False)
1015 for j
in re
.findall(r
's\.handle\(({.*})\);requireLazy\(', webpage
)]
1016 data
= traverse_obj(post_data
, (
1017 ..., 'require', ..., ..., ..., 'props', 'deeplinkAdCard', 'snapshot', {dict}
), get_all
=False)
1019 raise ExtractorError('Unable to extract ad data')
1021 title
= data
.get('title')
1022 if not title
or title
== '{{product.name}}':
1023 title
= join_nonempty('display_format', 'page_name', delim
=' by ', from_dict
=data
)
1025 info_dict
= traverse_obj(data
, {
1026 'description': ('link_description', {str}
, {lambda x: x if x != '{{product.description}
}' else None}),
1027 'uploader
': ('page_name
', {str}),
1028 'uploader_id
': ('page_id
', {str_or_none}),
1029 'uploader_url
': ('page_profile_uri
', {url_or_none}),
1030 'timestamp
': ('creation_time
', {int_or_none}),
1031 'like_count
': ('page_like_count
', {int_or_none}),
1035 for idx, entry in enumerate(traverse_obj(
1036 data, (('videos
', 'cards
'), lambda _, v: any(url_or_none(v[f]) for f in self._FORMATS_MAP))), 1,
1039 'id': f'{video_id}_{idx}
',
1040 'title
': entry.get('title
') or title,
1041 'description
': entry.get('link_description
') or info_dict.get('description
'),
1042 'thumbnail
': url_or_none(entry.get('video_preview_image_url
')),
1043 'formats
': self._extract_formats(entry),
1046 if len(entries) == 1:
1047 info_dict.update(entries[0])
1049 elif len(entries) > 1:
1051 'title
': entries[0]['title
'],
1053 '_type
': 'playlist
',
1056 info_dict['id'] = video_id