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/(?:[^/]+/)?|
57 groups/[^/]+/(?:permalink|posts)/|
62 (?P<id>pfbid[A-Za-z0-9]+|\d+)
65 r
'<iframe[^>]+?src=(["\'])(?P
<url
>https?
://www\
.facebook\
.com
/(?
:video
/embed|plugins
/video\
.php
).+?
)\
1',
66 # Facebook API embed https://developers.facebook.com/docs/plugins/embedded-video-player
68 class=(?P<q1>[\'"])[^\'"]*\bfb-(?:video|post)\b[^\'"]*(?P=q1)[^>]+
69 data-href=(?P<q2>[\'"])(?P<url>(?:https?:)?//(?:www\.)?facebook.com/.+?)(?P=q2)''',
71 _LOGIN_URL = 'https
://www
.facebook
.com
/login
.php?next
=http
%3A
%2F
%2Ffacebook
.com
%2Fhome
.php
&login_attempt
=1'
72 _CHECKPOINT_URL = 'https
://www
.facebook
.com
/checkpoint
/?next
=http
%3A
%2F
%2Ffacebook
.com
%2Fhome
.php
&_fb_noscript
=1'
73 _NETRC_MACHINE = 'facebook
'
76 _VIDEO_PAGE_TEMPLATE = 'https
://www
.facebook
.com
/video
/video
.php?v
=%s'
77 _VIDEO_PAGE_TAHOE_TEMPLATE = 'https
://www
.facebook
.com
/video
/tahoe
/async/%s/?chain
=true
&isvideo
=true
&payloadtype
=primary
'
80 'url
': 'https
://www
.facebook
.com
/radiokicksfm
/videos
/3676516585958356/',
82 'id': '3676516585958356',
84 'title
': 'dr Adam Przygoda
',
85 'description
': 'md5
:34675bda53336b1d16400265c2bb9b3b
',
86 'uploader
': 'RADIO KICKS FM
',
87 'upload_date
': '20230818',
88 'timestamp
': 1692346159,
89 'thumbnail
': r're
:^https?
://.*',
90 'uploader_id
': '100063551323670',
93 'concurrent_view_count
': 0,
96 'url
': 'https
://www
.facebook
.com
/video
.php?v
=637842556329505&fref
=nf
',
97 'md5
': '6a40d33c0eccbb1af76cf0485a052659
',
99 'id': '637842556329505',
101 'title
': 're
:Did you know Kei Nishikori
is the first Asian man to ever reach a Grand Slam
',
102 'uploader
': 'Tennis on Facebook
',
103 'upload_date
': '20140908',
104 'timestamp
': 1410199200,
106 'skip
': 'Requires logging
in',
109 'url
': 'https
://www
.facebook
.com
/video
.php?v
=274175099429670',
111 'id': '274175099429670',
115 'uploader
': 'Asif Nawab Butt
',
116 'upload_date
': '20140506',
117 'timestamp
': 1399398998,
118 'thumbnail
': r're
:^https?
://.*',
119 'uploader_id
': 'pfbid028wxorhX2ErLFJ578N6P3crHD3PHmXTCqCvfBpsnbSLmbokwSY75p5hWBjHGkG4zxl
',
121 'concurrent_view_count
': int,
124 'note
': 'Video
with DASH manifest
',
125 'url
': 'https
://www
.facebook
.com
/video
.php?v
=957955867617029',
126 'md5
': 'b2c28d528273b323abe5c6ab59f0f030
',
128 'id': '957955867617029',
130 'title
': 'When you post epic content on instagram
.com
/433 8 million followers
, this
is ...',
131 'uploader
': 'Demy de Zeeuw
',
132 'upload_date
': '20160110',
133 'timestamp
': 1452431627,
135 'skip
': 'Requires logging
in',
137 'url
': 'https
://www
.facebook
.com
/maxlayn
/posts
/10153807558977570',
138 'md5
': '037b1fa7f3c2d02b7a0d7bc16031ecc6
',
140 'id': '544765982287235',
142 'title
': '"What are you doing running in the snow?"',
143 'uploader
': 'FailArmy
',
145 'skip
': 'Video gone
',
147 'url
': 'https
://m
.facebook
.com
/story
.php?story_fbid
=1035862816472149&id=116132035111903',
148 'md5
': '1deb90b6ac27f7efcf6d747c8a27f5e3
',
150 'id': '1035862816472149',
152 'title
': 'What the Flock Is Going On In New Zealand Credit
: ViralHog
',
153 'uploader
': 'S
. Saint
',
155 'skip
': 'Video gone
',
157 'note
': 'swf params escaped
',
158 'url
': 'https
://www
.facebook
.com
/barackobama
/posts
/10153664894881749',
159 'md5
': '97ba073838964d12c70566e0085c2b91
',
161 'id': '10153664894881749',
163 'title
': 'Average time to confirm recent Supreme Court nominees
: 67 days Longest it
\'s t
...',
164 'thumbnail
': r're
:^https?
://.*',
165 'timestamp
': 1456259628,
166 'upload_date
': '20160223',
167 'uploader
': 'Barack Obama
',
169 'skip
': 'Gif on giphy
.com gone
',
171 # have 1080P, but only up to 720p in swf params
172 # data.video.story.attachments[].media
173 'url
': 'https
://www
.facebook
.com
/cnn
/videos
/10155529876156509/',
174 'md5
': 'ca63897a90c9452efee5f8c40d080e25
',
176 'id': '10155529876156509',
178 'title
': 'Holocaust survivor becomes US citizen
',
179 'description
': 'She survived the holocaust —
and years later
, she’s getting her citizenship so she can vote
for Hillary Clinton http
://cnn
.it
/2eERh5f
',
180 'timestamp
': 1477818095,
181 'upload_date
': '20161030',
183 'thumbnail
': r're
:^https?
://.*',
185 'uploader_id
': '100059479812265',
186 'concurrent_view_count
': int,
190 # bigPipe.onPageletArrive ... onPageletArrive pagelet_group_mall
191 # data.node.comet_sections.content.story.attachments[].style_type_renderer.attachment.media
192 'url
': 'https
://www
.facebook
.com
/yaroslav
.korpan
/videos
/1417995061575415/',
194 'id': '1417995061575415',
196 'title
': 'Довгоочікуване відео | By Yaroslav
- Facebook
',
197 'description
': 'Довгоочікуване відео
',
198 'timestamp
': 1486648217,
199 'upload_date
': '20170209',
200 'uploader
': 'Yaroslav Korpan
',
201 'uploader_id
': 'pfbid06AScABAWcW91qpiuGrLt99Ef9tvwHoXP6t8KeFYEqkSfreMtfa9nTveh8b2ZEVSWl
',
202 'concurrent_view_count
': int,
203 'thumbnail
': r're
:^https?
://.*',
205 'duration
': 11736.446,
208 'skip_download
': True,
212 'url
': 'https
://www
.facebook
.com
/LaGuiaDelVaron
/posts
/1072691702860471',
214 'id': '1072691702860471',
216 'title
': 'md5
:ae2d22a93fbb12dad20dc393a869739d
',
217 'timestamp
': 1477305000,
218 'upload_date
': '20161024',
219 'uploader
': 'La Guía Del Varón
',
220 'thumbnail
': r're
:^https?
://.*',
222 'skip
': 'Requires logging
in',
224 # data.node.comet_sections.content.story.attachments[].style_type_renderer.attachment.media
225 'url
': 'https
://www
.facebook
.com
/groups
/1024490957622648/permalink
/1396382447100162/',
227 'id': '202882990186699',
229 'title
': 'birb (O v O
") | Hello? Yes your uber ride is here',
230 'description': 'Hello? Yes your uber ride is here * Jukin Media Verified * Find this video and others like it by visiting...',
231 'timestamp': 1486035513,
232 'upload_date': '20170202',
233 'uploader': 'Elisabeth Ahtn',
234 'uploader_id': '100013949973717',
236 'skip': 'Requires logging in',
238 # data.node.comet_sections.content.story.attachments[].throwbackStyles.attachment_target_renderer.attachment.target.attachments[].styles.attachment.media
239 'url': 'https://www.facebook.com/groups/1645456212344334/posts/3737828833107051/',
241 'id': '1569199726448814',
243 'title': 'Pence MUST GO!',
244 'description': 'Vickie Gentry shared a memory.',
245 'timestamp': 1511548260,
246 'upload_date': '20171124',
247 'uploader': 'Vickie Gentry',
248 'uploader_id': 'pfbid0FuZhHCeWDAxWxEbr3yKPFaRstXvRxgsp9uCPG6GjD4J2AitB35NUAuJ4Q75KcjiDl',
249 'thumbnail': r're:^https?://.*',
253 # data.node.comet_sections.content.story.attachments[].styles.attachment.media
254 'url': 'https://www.facebook.com/attn/posts/pfbid0j1Czf2gGDVqeQ8KiMLFm3pWN8GxsQmeRrVhimWDzMuKQoR8r4b1knNsejELmUgyhl',
256 'id': '6968553779868435',
258 'description': 'md5:2f2fcf93e97ac00244fe64521bbdb0cb',
260 'upload_date': '20231207',
263 'uploader_id': '100064451419378',
265 'thumbnail': r're:^https?://.*',
266 'timestamp': 1701975646,
269 # data.node.comet_sections.content.story.attachments[].styles.attachment.media
270 'url': 'https://www.facebook.com/permalink.php?story_fbid=pfbid0fqQuVEQyXRa9Dp4RcaTR14KHU3uULHV1EK7eckNXSH63JMuoALsAvVCJ97zAGitil&id=100068861234290',
272 'id': '270103405756416',
274 'title': 'Lela Evans',
275 'description': 'Today Makkovik\'s own Pilot Mandy Smith made her inaugural landing on the airstrip in her hometown. What a proud moment as we all cheered and...',
276 'thumbnail': r're:^https?://.*',
277 'uploader': 'Lela Evans',
278 'uploader_id': 'pfbid0shZJipuigyy5mqrUJn9ub5LJFWNHvan5prtyi3LrDuuuJ4NwrURgnQHYR9fywBepl',
279 'upload_date': '20231228',
280 'timestamp': 1703804085,
285 'url': 'https://www.facebook.com/story.php?story_fbid=pfbid0Fnzhm8UuzjBYpPMNFzaSpFE9UmLdU4fJN8qTANi1Dmtj5q7DNrL5NERXfsAzDEV7l&id=100073071055552',
286 'only_matching': True,
288 'url': 'https://www.facebook.com/video.php?v=10204634152394104',
289 'only_matching': True,
291 'url': 'https://www.facebook.com/amogood/videos/1618742068337349/?fref=nf',
292 'only_matching': True,
294 # data.mediaset.currMedia.edges
295 'url': 'https://www.facebook.com/ChristyClarkForBC/videos/vb.22819070941/10153870694020942/?type=2&theater',
296 'only_matching': True,
298 # data.video.story.attachments[].media
299 'url': 'facebook:544765982287235',
300 'only_matching': True,
302 # data.node.comet_sections.content.story.attachments[].style_type_renderer.attachment.media
303 'url': 'https://www.facebook.com/groups/164828000315060/permalink/764967300301124/',
304 'only_matching': True,
306 # data.video.creation_story.attachments[].media
307 'url': 'https://zh-hk.facebook.com/peoplespower/videos/1135894589806027/',
308 'only_matching': True,
311 'url': 'https://www.facebookwkhpilnemxj7asaniu7vnjjbiltxjqhye3mhbshg7kx5tfyd.onion/video.php?v=274175099429670',
312 'only_matching': True,
315 'url': 'https://www.facebook.com/onlycleverentertainment/videos/1947995502095005/',
316 'only_matching': True,
319 'url': 'https://www.facebook.com/WatchESLOne/videos/359649331226507/',
321 'id': '359649331226507',
323 'title': 'Fnatic vs. EG - Group A - Opening Match - ESL One Birmingham Day 1',
324 'description': '#ESLOne VoD - Birmingham Finals Day#1 Fnatic vs. @Evil Geniuses',
325 'timestamp': 1527084179,
326 'upload_date': '20180523',
327 'uploader': 'ESL One Dota 2',
328 'uploader_id': '100066514874195',
329 'duration': 4524.212,
331 'thumbnail': r're:^https?://.*',
332 'concurrent_view_count': int,
335 'skip_download': True,
338 # data.node.comet_sections.content.story.attachments[].style_type_renderer.attachment.all_subattachments.nodes[].media
339 'url': 'https://www.facebook.com/100033620354545/videos/106560053808006/',
341 'id': '106560053808006',
344 'thumbnail': r're:^https?://.*',
345 'concurrent_view_count': int,
346 'uploader_id': 'pfbid0cibUN6tV7DYgdbJdsUFN46wc4jKpVSPAvJQhFofGqBGmVn3V3JtAs2tfUwziw2hUl',
347 'timestamp': 1549275572,
349 'uploader': 'Josef Novak',
351 'upload_date': '20190204',
354 # data.video.story.attachments[].media
355 'url': 'https://www.facebook.com/watch/?v=647537299265662',
356 'only_matching': True,
358 # FIXME: https://github.com/yt-dlp/yt-dlp/issues/542
359 # data.node.comet_sections.content.story.attachments[].style_type_renderer.attachment.all_subattachments.nodes[].media
360 'url': 'https://www.facebook.com/PankajShahLondon/posts/10157667649866271',
362 'id': '10157667649866271',
365 'skip': 'Requires logging in',
367 # data.nodes[].comet_sections.content.story.attachments[].style_type_renderer.attachment.media
368 'url': 'https://m.facebook.com/Alliance.Police.Department/posts/4048563708499330',
370 'id': '117576630041613',
372 # TODO: title can be extracted from video page
373 'title': 'Facebook video #117576630041613',
374 'uploader_id': '189393014416438',
375 'upload_date': '20201123',
376 'timestamp': 1606162592,
378 'skip': 'Requires logging in',
380 # node.comet_sections.content.story.attached_story.attachments.style_type_renderer.attachment.media
381 'url': 'https://www.facebook.com/groups/ateistiskselskab/permalink/10154930137678856/',
383 'id': '211567722618337',
385 'title': 'Facebook video #211567722618337',
386 'uploader_id': '127875227654254',
387 'upload_date': '20161122',
388 'timestamp': 1479793574,
392 # data.video.creation_story.attachments[].media
393 'url': 'https://www.facebook.com/watch/live/?v=1823658634322275',
394 'only_matching': True,
396 'url': 'https://www.facebook.com/watchparty/211641140192478',
398 'id': '211641140192478',
401 'skip': 'Requires logging in',
403 _SUPPORTED_PAGLETS_REGEX = r'(?:pagelet_group_mall|permalink_video_pagelet|hyperfeed_story_id_[0-9a-f]+)'
405 'graphURI': '/api/graphql/'
408 def _perform_login(self, username, password):
409 login_page_req = Request(self._LOGIN_URL)
410 self._set_cookie('facebook.com', 'locale', 'en_US')
411 login_page = self._download_webpage(login_page_req, None,
412 note='Downloading login page',
413 errnote='Unable to download login page')
414 lsd = self._search_regex(
415 r'<input type="hidden
" name="lsd
" value="([^
"]*)"',
417 lgnrnd = self._search_regex(r'name
="lgnrnd" value
="([^"]*?
)"', login_page, 'lgnrnd')
424 'next': 'http://facebook.com/home.php',
425 'default_persistent': '0',
426 'legacy_return': '1',
430 request = Request(self._LOGIN_URL, urlencode_postdata(login_form))
431 request.headers['Content-Type'] = 'application/x-www-form-urlencoded'
433 login_results = self._download_webpage(request, None,
434 note='Logging in', errnote='unable to fetch login page')
435 if re.search(r'<form(.*)name="login
"(.*)</form>', login_results) is not None:
436 error = self._html_search_regex(
437 r'(?s)<div[^>]+class=(["\']).*?login_error_box
.*?\
1[^
>]*><div
[^
>]*>.*?
</div
><div
[^
>]*>(?P
<error
>.+?
)</div
>',
438 login_results, 'login error
', default=None, group='error
')
440 raise ExtractorError('Unable to login
: %s' % error, expected=True)
441 self.report_warning('unable to log
in: bad username
/password
, or exceeded login rate
limit (~
3/min). Check credentials
or wait
.')
444 fb_dtsg = self._search_regex(
445 r'name
="fb_dtsg" value
="(.+?)"', login_results, 'fb_dtsg
', default=None)
446 h = self._search_regex(
447 r'name
="h"\s
+(?
:\w
+="[^"]+"\s+)*?value="([^
"]+)"', login_results, 'h
', default=None)
449 if not fb_dtsg or not h:
455 'name_action_selected
': 'dont_save
',
457 check_req = Request(self._CHECKPOINT_URL, urlencode_postdata(check_form))
458 check_req.headers['Content
-Type
'] = 'application
/x
-www
-form
-urlencoded
'
459 check_response = self._download_webpage(check_req, None,
460 note='Confirming login
')
461 if re.search(r'id="checkpointSubmitButton"', check_response) is not None:
462 self.report_warning('Unable to confirm login
, you have to login
in your browser
and authorize the login
.')
463 except network_exceptions as err:
464 self.report_warning('unable to log
in: %s' % error_to_compat_str(err))
467 def _extract_from_url(self, url, video_id):
468 webpage = self._download_webpage(
469 url.replace('://m
.facebook
.com
/', '://www
.facebook
.com
/'), video_id)
471 def extract_metadata(webpage):
472 post_data = [self._parse_json(j, video_id, fatal=False) for j in re.findall(
473 r'data
-sjs
>({.*?ScheduledServerJS.*?}
)</script
>', webpage)]
474 post = traverse_obj(post_data, (
475 ..., 'require
', ..., ..., ..., '__bbox
', 'require
', ..., ..., ..., '__bbox
', 'result
', 'data
'), expected_type=dict) or []
477 automatic_captions, subtitles = {}, {}
478 subs_data = traverse_obj(post, (..., 'video
', ..., 'attachments
', ..., lambda k, v: (
479 k == 'media
' and str(v['id']) == video_id and v['__typename
'] == 'Video
')))
480 is_video_broadcast = get_first(subs_data, 'is_video_broadcast
', expected_type=bool)
481 captions = get_first(subs_data, 'video_available_captions_locales
', 'captions_url
')
482 if url_or_none(captions): # if subs_data only had a 'captions_url
'
483 locale = self._html_search_meta(['og
:locale
', 'twitter
:locale
'], webpage, 'locale
', default='en_US
')
484 subtitles[locale] = [{'url': captions}]
485 # or else subs_data had 'video_available_captions_locales
', a list of dicts
486 for caption in traverse_obj(captions, (
487 {lambda x: sorted(x, key=lambda c: c['locale'])}, lambda _, v: v['captions_url
'])
489 lang = caption.get('localized_language
') or ''
491 'url
': caption['captions_url
'],
492 'name
': format_field(caption, 'localized_country
', f'{lang}
(%s)', default=lang),
494 if caption.get('localized_creation_method
') or is_video_broadcast:
495 automatic_captions.setdefault(caption['locale
'], []).append(subs)
497 subtitles.setdefault(caption['locale
'], []).append(subs)
499 media = traverse_obj(post, (..., 'attachments
', ..., lambda k, v: (
500 k == 'media
' and str(v['id']) == video_id and v['__typename
'] == 'Video
')), expected_type=dict)
501 title = get_first(media, ('title
', 'text
'))
502 description = get_first(media, ('creation_story
', 'comet_sections
', 'message
', 'story
', 'message
', 'text
'))
504 get_first(media, ('owner
', {dict}))
505 or get_first(post, (..., 'video
', lambda k, v: k == 'owner
' and v['name
']))
506 or get_first(post, ('node
', 'actors
', ..., {dict})) or {})
508 page_title = title or self._html_search_regex((
509 r'<h2\s
+[^
>]*class="uiHeaderTitle"[^
>]*>(?P
<content
>[^
<]*)</h2
>',
510 r'(?s
)<span
class="fbPhotosPhotoCaption".*?
id="fbPhotoPageCaption"><span
class="hasCaption">(?P
<content
>.*?
)</span
>',
511 self._meta_regex('og
:title
'), self._meta_regex('twitter
:title
'), r'<title
>(?P
<content
>.+?
)</title
>'
512 ), webpage, 'title
', default=None, group='content
')
513 description = description or self._html_search_meta(
514 ['description
', 'og
:description
', 'twitter
:description
'],
515 webpage, 'description
', default=None)
516 uploader = uploader_data.get('name
') or (
517 clean_html(get_element_by_id('fbPhotoPageAuthorName
', webpage))
518 or self._search_regex(
519 (r'ownerName\s
*:\s
*"([^"]+)"', *self._og_regexes('title')), webpage, 'uploader', fatal=False))
521 timestamp = int_or_none(self._search_regex(
522 r'<abbr[^>]+data-utime=["\'](\d
+)', webpage,
523 'timestamp
', default=None))
524 thumbnail = self._html_search_meta(
525 ['og
:image
', 'twitter
:image
'], webpage, 'thumbnail
', default=None)
526 # some webpages contain unretrievable thumbnail urls
527 # like https://lookaside.fbsbx.com/lookaside/crawler/media/?media_id=10155168902769113&get_thumbnail=1
528 # in https://www.facebook.com/yaroslav.korpan/videos/1417995061575415/
529 if thumbnail and not re.search(r'\
.(?
:jpg|png
)', thumbnail):
532 'description
': description,
533 'uploader
': uploader,
534 'uploader_id
': uploader_data.get('id'),
535 'timestamp
': timestamp,
536 'thumbnail
': thumbnail,
537 'view_count
': parse_count(self._search_regex(
538 (r'\bviewCount\s
*:\s
*["\']([\d,.]+)', r'video_view_count["\']\s
*:\s
*(\d
+)',),
539 webpage, 'view count
', default=None)),
540 'concurrent_view_count
': get_first(post, (
541 ('video
', (..., ..., 'attachments
', ..., 'media
')), 'liveViewerCount
', {int_or_none})),
542 'automatic_captions
': automatic_captions,
543 'subtitles
': subtitles,
546 info_json_ld = self._search_json_ld(webpage, video_id, default={})
547 info_json_ld['title
'] = (re.sub(r'\s
*\|\s
*Facebook$
', '', title or info_json_ld.get('title
') or page_title or '')
548 or (description or '').replace('\n', ' ') or f'Facebook video
#{video_id}')
549 return merge_dicts(info_json_ld
, info_dict
)
553 def extract_video_data(instances
):
555 for item
in instances
:
556 if try_get(item
, lambda x
: x
[1][0]) == 'VideoConfig':
557 video_item
= item
[2][0]
558 if video_item
.get('video_id'):
559 video_data
.append(video_item
['videoData'])
562 server_js_data
= self
._parse
_json
(self
._search
_regex
(
563 [r
'handleServerJS\(({.+})(?:\);|,")', r
'\bs\.handle\(({.+?})\);'],
564 webpage
, 'server js data', default
='{}'), video_id
, fatal
=False)
567 video_data
= extract_video_data(server_js_data
.get('instances', []))
569 def extract_from_jsmods_instances(js_data
):
571 return extract_video_data(try_get(
572 js_data
, lambda x
: x
['jsmods']['instances'], list) or [])
574 def extract_dash_manifest(video
, formats
):
575 dash_manifest
= video
.get('dash_manifest')
577 formats
.extend(self
._parse
_mpd
_formats
(
578 compat_etree_fromstring(urllib
.parse
.unquote_plus(dash_manifest
)),
579 mpd_url
=video
.get('dash_manifest_url')))
581 def process_formats(info
):
582 # Downloads with browser's User-Agent are rate limited. Working around
583 # with non-browser User-Agent.
584 for f
in info
['formats']:
585 # Downloads with browser's User-Agent are rate limited. Working around
586 # with non-browser User-Agent.
587 f
.setdefault('http_headers', {})['User-Agent'] = 'facebookexternalhit/1.1'
588 # Formats larger than ~500MB will return error 403 unless chunk size is regulated
589 f
.setdefault('downloader_options', {})['http_chunk_size'] = 250 << 20
591 def extract_relay_data(_filter
):
592 return self
._parse
_json
(self
._search
_regex
(
593 r
'data-sjs>({.*?%s.*?})</script>' % _filter
,
594 webpage
, 'replay data', default
='{}'), video_id, fatal=False) or {}
596 def extract_relay_prefetched_data(_filter):
597 return traverse_obj(extract_relay_data(_filter), (
598 'require
', (None, (..., ..., ..., '__bbox
', 'require
')),
599 lambda _, v: 'RelayPrefetchedStreamCache
' in v, ..., ...,
600 '__bbox
', 'result
', 'data
', {dict}), get_all=False) or {}
603 server_js_data = self._parse_json(self._search_regex([
604 r'bigPipe\
.onPageletArrive\
(({.+?}
)\
)\s
*;\s
*}\s
*\
)\s
*,\s
*["\']onPageletArrive\s+' + self._SUPPORTED_PAGLETS_REGEX,
605 r'bigPipe\.onPageletArrive\(({.*?id\s*:\s*"%s".*?})\);' % self._SUPPORTED_PAGLETS_REGEX
606 ], webpage, 'js data', default='{}'), video_id, js_to_json, False)
607 video_data = extract_from_jsmods_instances(server_js_data)
610 data = extract_relay_prefetched_data(
611 r'"(?
:dash_manifest|
playable_url(?
:_quality_hd
)?
)')
615 def parse_graphql_video(video):
616 v_id = video.get('videoId
') or video.get('id') or video_id
617 reel_info = traverse_obj(
618 video, ('creation_story
', 'short_form_video_context
', 'playback_video
', {dict}))
620 video = video['creation_story
']
621 video['owner
'] = traverse_obj(video, ('short_form_video_context
', 'video_owner
'))
622 video.update(reel_info)
624 q = qualities(['sd
', 'hd
'])
625 for key, format_id in (('playable_url
', 'sd
'), ('playable_url_quality_hd
', 'hd
'),
626 ('playable_url_dash
', ''), ('browser_native_hd_url
', 'hd
'),
627 ('browser_native_sd_url
', 'sd
')):
628 playable_url = video.get(key)
631 if determine_ext(playable_url) == 'mpd
':
632 formats.extend(self._extract_mpd_formats(playable_url, video_id))
635 'format_id
': format_id,
636 # sd, hd formats w/o resolution info should be deprioritized below DASH
637 'quality
': q(format_id) - 3,
640 extract_dash_manifest(video, formats)
644 'thumbnail
': traverse_obj(
645 video, ('thumbnailImage
', 'uri
'), ('preferred_thumbnail
', 'image
', 'uri
')),
646 'uploader_id
': traverse_obj(video, ('owner
', 'id', {str_or_none})),
647 'timestamp
': traverse_obj(video, 'publish_time
', 'creation_time
', expected_type=int_or_none),
648 'duration
': (float_or_none(video.get('playable_duration_in_ms
'), 1000)
649 or float_or_none(video.get('length_in_second
'))),
651 process_formats(info)
652 description = try_get(video, lambda x: x['savable_description
']['text
'])
653 title = video.get('name
')
657 'description
': description,
660 info['title
'] = description or 'Facebook video
#%s' % v_id
663 def parse_attachment(attachment
, key
='media'):
664 media
= attachment
.get(key
) or {}
665 if media
.get('__typename') == 'Video':
666 return parse_graphql_video(media
)
668 nodes
= variadic(traverse_obj(data
, 'nodes', 'node') or [])
669 attachments
= traverse_obj(nodes
, (
670 ..., 'comet_sections', 'content', 'story', (None, 'attached_story'), 'attachments',
671 ..., ('styles', 'style_type_renderer', ('throwbackStyles', 'attachment_target_renderer')),
672 'attachment', {dict}
))
673 for attachment
in attachments
:
674 ns
= traverse_obj(attachment
, ('all_subattachments', 'nodes', ..., {dict}
),
675 ('target', 'attachments', ..., 'styles', 'attachment', {dict}
))
678 parse_attachment(attachment
)
680 edges
= try_get(data
, lambda x
: x
['mediaset']['currMedia']['edges'], list) or []
682 parse_attachment(edge
, key
='node')
684 video
= data
.get('video') or {}
686 attachments
= try_get(video
, [
687 lambda x
: x
['story']['attachments'],
688 lambda x
: x
['creation_story']['attachments']
690 for attachment
in attachments
:
691 parse_attachment(attachment
)
693 parse_graphql_video(video
)
696 return self
.playlist_result(entries
, video_id
)
698 video_info
= entries
[0] if entries
else {'id': video_id}
699 webpage_info
= extract_metadata(webpage
)
700 # honor precise duration in video info
701 if video_info
.get('duration'):
702 webpage_info
['duration'] = video_info
['duration']
703 # preserve preferred_thumbnail in video info
704 if video_info
.get('thumbnail'):
705 webpage_info
['thumbnail'] = video_info
['thumbnail']
706 return merge_dicts(webpage_info
, video_info
)
709 m_msg
= re
.search(r
'class="[^"]*uiInterstitialContent[^"]*"><div>(.*?)</div>', webpage
)
710 if m_msg
is not None:
711 raise ExtractorError(
712 'The video is not available, Facebook said: "%s"' % m_msg
.group(1),
714 elif any(p
in webpage
for p
in (
715 '>You must log in to continue',
717 'id="loginbutton"')):
718 self
.raise_login_required()
720 if not video_data
and '/watchparty/' in url
:
722 'doc_id': 3731964053542869,
723 'variables': json
.dumps({
724 'livingRoomID': video_id
,
728 prefetched_data
= extract_relay_prefetched_data(r
'"login_data"\s*:\s*{')
730 lsd
= try_get(prefetched_data
, lambda x
: x
['login_data']['lsd'], dict)
732 post_data
[lsd
['name']] = lsd
['value']
734 relay_data
= extract_relay_data(r
'\[\s*"RelayAPIConfigDefaults"\s*,')
735 for define
in (relay_data
.get('define') or []):
736 if define
[0] == 'RelayAPIConfigDefaults':
737 self
._api
_config
= define
[2]
739 living_room
= self
._download
_json
(
740 urljoin(url
, self
._api
_config
['graphURI']), video_id
,
741 data
=urlencode_postdata(post_data
))['data']['living_room']
744 for edge
in (try_get(living_room
, lambda x
: x
['recap']['watched_content']['edges']) or []):
745 video
= try_get(edge
, lambda x
: x
['node']['video']) or {}
746 v_id
= video
.get('id')
749 v_id
= compat_str(v_id
)
750 entries
.append(self
.url_result(
751 self
._VIDEO
_PAGE
_TEMPLATE
% v_id
,
752 self
.ie_key(), v_id
, video
.get('name')))
754 return self
.playlist_result(entries
, video_id
)
757 # Video info not in first request, do a secondary request using
758 # tahoe player specific URL
759 tahoe_data
= self
._download
_webpage
(
760 self
._VIDEO
_PAGE
_TAHOE
_TEMPLATE
% video_id
, video_id
,
761 data
=urlencode_postdata({
763 '__pc': self
._search
_regex
(
764 r
'pkg_cohort["\']\s
*:\s
*["\'](.+?)["\']', webpage,
765 'pkg cohort
', default='PHASED
:DEFAULT
'),
766 '__rev
': self._search_regex(
767 r'client_revision
["\']\s*:\s*(\d+),', webpage,
768 'client revision', default='3944515'),
769 'fb_dtsg': self._search_regex(
770 r'"DTSGInitialData
"\s*,\s*\[\]\s*,\s*{\s*"token
"\s*:\s*"([^
"]+)"',
771 webpage, 'dtsg token
', default=''),
774 'Content
-Type
': 'application
/x
-www
-form
-urlencoded
',
776 tahoe_js_data = self._parse_json(
778 r'for\s
+\
(\s
*;\s
*;\s
*\
)\s
*;(.+)', tahoe_data,
779 'tahoe js data
', default='{}'),
780 video_id, fatal=False)
781 video_data = extract_from_jsmods_instances(tahoe_js_data)
784 raise ExtractorError('Cannot parse data
')
786 if len(video_data) > 1:
789 video_url = v[0].get('video_url
')
792 entries.append(self.url_result(urljoin(
793 url, video_url), self.ie_key(), v[0].get('video_id
')))
794 return self.playlist_result(entries, video_id)
795 video_data = video_data[0]
800 format_id = f['stream_type
']
801 if f and isinstance(f, dict):
803 if not f or not isinstance(f, list):
805 for quality in ('sd
', 'hd
'):
806 for src_type in ('src
', 'src_no_ratelimit
'):
807 src = f[0].get('%s_%s' % (quality, src_type))
809 # sd, hd formats w/o resolution info should be deprioritized below DASH
810 # TODO: investigate if progressive or src formats still exist
811 preference = -10 if format_id == 'progressive
' else -3
815 'format_id
': '%s_%s_%s' % (format_id, quality, src_type),
817 'quality
': preference,
818 'height
': 720 if quality == 'hd
' else None
820 extract_dash_manifest(f[0], formats)
821 subtitles_src = f[0].get('subtitles_src
')
823 subtitles.setdefault('en
', []).append({'url': subtitles_src})
828 'subtitles
': subtitles,
830 process_formats(info_dict)
831 info_dict.update(extract_metadata(webpage))
835 def _real_extract(self, url):
836 video_id = self._match_id(url)
838 real_url = self._VIDEO_PAGE_TEMPLATE % video_id if url.startswith('facebook
:') else url
839 return self._extract_from_url(real_url, video_id)
842 class FacebookPluginsVideoIE(InfoExtractor):
843 _VALID_URL = r'https?
://(?
:[\w
-]+\
.)?facebook\
.com
/plugins
/video\
.php
\?.*?
\bhref
=(?P
<id>https
.+)'
846 'url
': 'https
://www
.facebook
.com
/plugins
/video
.php?href
=https
%3A
%2F
%2Fwww
.facebook
.com
%2Fgov
.sg
%2Fvideos
%2F10154383743583686
%2F
&show_text
=0&width
=560',
847 'md5
': '5954e92cdfe51fe5782ae9bda7058a07
',
849 'id': '10154383743583686',
851 # TODO: Fix title, uploader
852 'title
': 'What to do during the haze?
',
853 'uploader
': 'Gov
.sg
',
854 'upload_date
': '20160826',
855 'timestamp
': 1472184808,
857 'add_ie
': [FacebookIE.ie_key()],
859 'url
': 'https
://www
.facebook
.com
/plugins
/video
.php?href
=https
%3A
%2F
%2Fwww
.facebook
.com
%2Fvideo
.php
%3Fv
%3D10204634152394104
',
860 'only_matching
': True,
862 'url
': 'https
://www
.facebook
.com
/plugins
/video
.php?href
=https
://www
.facebook
.com
/gov
.sg
/videos
/10154383743583686/&show_text
=0&width
=560',
863 'only_matching
': True,
866 def _real_extract(self, url):
867 return self.url_result(
868 compat_urllib_parse_unquote(self._match_id(url)),
872 class FacebookRedirectURLIE(InfoExtractor):
873 IE_DESC = False # Do not list
874 _VALID_URL = r'https?
://(?
:[\w
-]+\
.)?facebook\
.com
/flx
/warn
[/?
]'
876 'url
': 'https
://www
.facebook
.com
/flx
/warn
/?h
=TAQHsoToz
&u
=https
%3A
%2F
%2Fwww
.youtube
.com
%2Fwatch
%3Fv
%3DpO8h3EaFRdo
&s
=1',
880 'title
': 'Tripeo Boiler Room x Dekmantel Festival DJ Set
',
881 'description
': 'md5
:2d713ccbb45b686a1888397b2c77ca6b
',
882 'channel_id
': 'UCGBpxWJr9FNOcFYA5GkKrMg
',
883 'playable_in_embed
': True,
884 'categories
': ['Music
'],
885 'channel
': 'Boiler Room
',
886 'uploader_id
': 'brtvofficial
',
887 'uploader
': 'Boiler Room
',
890 'live_status
': 'not_live
',
891 'thumbnail
': 'https
://i
.ytimg
.com
/vi
/pO8h3EaFRdo
/maxresdefault
.jpg
',
892 'channel_url
': 'https
://www
.youtube
.com
/channel
/UCGBpxWJr9FNOcFYA5GkKrMg
',
893 'availability
': 'public
',
894 'uploader_url
': 'http
://www
.youtube
.com
/user
/brtvofficial
',
895 'upload_date
': '20150917',
900 'add_ie
': ['Youtube
'],
901 'params
': {'skip_download': 'Youtube'},
904 def _real_extract(self, url):
905 redirect_url = url_or_none(parse_qs(url).get('u
', [None])[-1])
907 raise ExtractorError('Invalid facebook redirect URL
', expected=True)
908 return self.url_result(redirect_url)
911 class FacebookReelIE(InfoExtractor):
912 _VALID_URL = r'https?
://(?
:[\w
-]+\
.)?facebook\
.com
/reel
/(?P
<id>\d
+)'
913 IE_NAME = 'facebook
:reel
'
916 'url
': 'https
://www
.facebook
.com
/reel
/1195289147628387',
917 'md5
': 'f13dd37f2633595982db5ed8765474d3
',
919 'id': '1195289147628387',
921 'title
': 'md5
:b05800b5b1ad56c0ca78bd3807b6a61e
',
922 'description
': 'md5
:22f03309b216ac84720183961441d8db
',
923 'uploader
': 'md5
:723e6cb3091241160f20b3c5dc282af1
',
924 'uploader_id
': '100040874179269',
926 'timestamp
': 1637502609,
927 'upload_date
': '20211121',
928 'thumbnail
': r're
:^https?
://.*',
932 def _real_extract(self, url):
933 video_id = self._match_id(url)
934 return self.url_result(
935 f'https
://m
.facebook
.com
/watch
/?v
={video_id}
&_rdr
', FacebookIE, video_id)
938 class FacebookAdsIE(InfoExtractor):
939 _VALID_URL = r'https?
://(?
:[\w
-]+\
.)?facebook\
.com
/ads
/library
/?
\?(?
:[^
#]+&)?id=(?P<id>\d+)'
940 IE_NAME
= 'facebook:ads'
943 'url': 'https://www.facebook.com/ads/library/?id=899206155126718',
945 'id': '899206155126718',
947 'title': 'video by Kandao',
948 'uploader': 'Kandao',
949 'uploader_id': '774114102743284',
950 'uploader_url': r
're:^https?://.*',
951 'timestamp': 1702548330,
952 'thumbnail': r
're:^https?://.*',
953 'upload_date': '20231214',
957 'url': 'https://www.facebook.com/ads/library/?id=893637265423481',
959 'id': '893637265423481',
960 'title': 'Jusqu\u2019\u00e0 -25% sur une s\u00e9lection de vins p\u00e9tillants italiens ',
961 'uploader': 'Eataly Paris Marais',
962 'uploader_id': '2086668958314152',
963 'uploader_url': r
're:^https?://.*',
964 'timestamp': 1703571529,
965 'upload_date': '20231226',
970 'url': 'https://es-la.facebook.com/ads/library/?id=901230958115569',
971 'only_matching': True,
973 'url': 'https://m.facebook.com/ads/library/?id=901230958115569',
974 'only_matching': True,
978 'watermarked_video_sd_url': ('sd-wmk', 'SD, watermarked'),
979 'video_sd_url': ('sd', None),
980 'watermarked_video_hd_url': ('hd-wmk', 'HD, watermarked'),
981 'video_hd_url': ('hd', None),
984 def _extract_formats(self
, video_dict
):
986 for format_key
, format_url
in traverse_obj(video_dict
, (
987 {dict.items}
, lambda _
, v
: v
[0] in self
._FORMATS
_MAP
and url_or_none(v
[1])
990 'format_id': self
._FORMATS
_MAP
[format_key
][0],
991 'format_note': self
._FORMATS
_MAP
[format_key
][1],
994 'quality': qualities(tuple(self
._FORMATS
_MAP
))(format_key
),
998 def _real_extract(self
, url
):
999 video_id
= self
._match
_id
(url
)
1000 webpage
= self
._download
_webpage
(url
, video_id
)
1002 post_data
= [self
._parse
_json
(j
, video_id
, fatal
=False)
1003 for j
in re
.findall(r
's\.handle\(({.*})\);requireLazy\(', webpage
)]
1004 data
= traverse_obj(post_data
, (
1005 ..., 'require', ..., ..., ..., 'props', 'deeplinkAdCard', 'snapshot', {dict}
), get_all
=False)
1007 raise ExtractorError('Unable to extract ad data')
1009 title
= data
.get('title')
1010 if not title
or title
== '{{product.name}}':
1011 title
= join_nonempty('display_format', 'page_name', delim
=' by ', from_dict
=data
)
1013 info_dict
= traverse_obj(data
, {
1014 'description': ('link_description', {str}
, {lambda x: x if x != '{{product.description}
}' else None}),
1015 'uploader
': ('page_name
', {str}),
1016 'uploader_id
': ('page_id
', {str_or_none}),
1017 'uploader_url
': ('page_profile_uri
', {url_or_none}),
1018 'timestamp
': ('creation_time
', {int_or_none}),
1019 'like_count
': ('page_like_count
', {int_or_none}),
1023 for idx, entry in enumerate(traverse_obj(
1024 data, (('videos
', 'cards
'), lambda _, v: any([url_or_none(v[f]) for f in self._FORMATS_MAP]))), 1
1027 'id': f'{video_id}_{idx}
',
1028 'title
': entry.get('title
') or title,
1029 'description
': entry.get('link_description
') or info_dict.get('description
'),
1030 'thumbnail
': url_or_none(entry.get('video_preview_image_url
')),
1031 'formats
': self._extract_formats(entry),
1034 if len(entries) == 1:
1035 info_dict.update(entries[0])
1037 elif len(entries) > 1:
1039 'title
': entries[0]['title
'],
1041 '_type
': 'playlist
',
1044 info_dict['id'] = video_id