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)/
53 )\?(?:.*?)(?:v|video_id|story_fbid)=|
54 [^/]+/videos/(?:[^/]+/)?|
56 groups/[^/]+/(?:permalink|posts)/|
61 (?P<id>pfbid[A-Za-z0-9]+|\d+)
64 r
'<iframe[^>]+?src=(["\'])(?P
<url
>https?
://www\
.facebook\
.com
/(?
:video
/embed|plugins
/video\
.php
).+?
)\
1',
65 # Facebook API embed https://developers.facebook.com/docs/plugins/embedded-video-player
67 class=(?P<q1>[\'"])[^\'"]*\bfb-(?:video|post)\b[^\'"]*(?P=q1)[^>]+
68 data-href=(?P<q2>[\'"])(?P<url>(?:https?:)?//(?:www\.)?facebook.com/.+?)(?P=q2)''',
70 _LOGIN_URL = 'https
://www
.facebook
.com
/login
.php?next
=http
%3A
%2F
%2Ffacebook
.com
%2Fhome
.php
&login_attempt
=1'
71 _CHECKPOINT_URL = 'https
://www
.facebook
.com
/checkpoint
/?next
=http
%3A
%2F
%2Ffacebook
.com
%2Fhome
.php
&_fb_noscript
=1'
72 _NETRC_MACHINE = 'facebook
'
75 _VIDEO_PAGE_TEMPLATE = 'https
://www
.facebook
.com
/video
/video
.php?v
=%s'
76 _VIDEO_PAGE_TAHOE_TEMPLATE = 'https
://www
.facebook
.com
/video
/tahoe
/async/%s/?chain
=true
&isvideo
=true
&payloadtype
=primary
'
79 'url
': 'https
://www
.facebook
.com
/radiokicksfm
/videos
/3676516585958356/',
81 'id': '3676516585958356',
83 'title
': 'dr Adam Przygoda
',
84 'description
': 'md5
:34675bda53336b1d16400265c2bb9b3b
',
85 'uploader
': 'RADIO KICKS FM
',
86 'upload_date
': '20230818',
87 'timestamp
': 1692346159,
88 'thumbnail
': r're
:^https?
://.*',
89 'uploader_id
': '100063551323670',
92 'concurrent_view_count
': 0,
95 'url
': 'https
://www
.facebook
.com
/video
.php?v
=637842556329505&fref
=nf
',
96 'md5
': '6a40d33c0eccbb1af76cf0485a052659
',
98 'id': '637842556329505',
100 'title
': 're
:Did you know Kei Nishikori
is the first Asian man to ever reach a Grand Slam
',
101 'uploader
': 'Tennis on Facebook
',
102 'upload_date
': '20140908',
103 'timestamp
': 1410199200,
105 'skip
': 'Requires logging
in',
108 'url
': 'https
://www
.facebook
.com
/video
.php?v
=274175099429670',
110 'id': '274175099429670',
114 'uploader
': 'Asif Nawab Butt
',
115 'upload_date
': '20140506',
116 'timestamp
': 1399398998,
117 'thumbnail
': r're
:^https?
://.*',
118 'uploader_id
': 'pfbid028wxorhX2ErLFJ578N6P3crHD3PHmXTCqCvfBpsnbSLmbokwSY75p5hWBjHGkG4zxl
',
120 'concurrent_view_count
': int,
123 'note
': 'Video
with DASH manifest
',
124 'url
': 'https
://www
.facebook
.com
/video
.php?v
=957955867617029',
125 'md5
': 'b2c28d528273b323abe5c6ab59f0f030
',
127 'id': '957955867617029',
129 'title
': 'When you post epic content on instagram
.com
/433 8 million followers
, this
is ...',
130 'uploader
': 'Demy de Zeeuw
',
131 'upload_date
': '20160110',
132 'timestamp
': 1452431627,
134 'skip
': 'Requires logging
in',
136 'url
': 'https
://www
.facebook
.com
/maxlayn
/posts
/10153807558977570',
137 'md5
': '037b1fa7f3c2d02b7a0d7bc16031ecc6
',
139 'id': '544765982287235',
141 'title
': '"What are you doing running in the snow?"',
142 'uploader
': 'FailArmy
',
144 'skip
': 'Video gone
',
146 'url
': 'https
://m
.facebook
.com
/story
.php?story_fbid
=1035862816472149&id=116132035111903',
147 'md5
': '1deb90b6ac27f7efcf6d747c8a27f5e3
',
149 'id': '1035862816472149',
151 'title
': 'What the Flock Is Going On In New Zealand Credit
: ViralHog
',
152 'uploader
': 'S
. Saint
',
154 'skip
': 'Video gone
',
156 'note
': 'swf params escaped
',
157 'url
': 'https
://www
.facebook
.com
/barackobama
/posts
/10153664894881749',
158 'md5
': '97ba073838964d12c70566e0085c2b91
',
160 'id': '10153664894881749',
162 'title
': 'Average time to confirm recent Supreme Court nominees
: 67 days Longest it
\'s t
...',
163 'thumbnail
': r're
:^https?
://.*',
164 'timestamp
': 1456259628,
165 'upload_date
': '20160223',
166 'uploader
': 'Barack Obama
',
168 'skip
': 'Gif on giphy
.com gone
',
170 # have 1080P, but only up to 720p in swf params
171 # data.video.story.attachments[].media
172 'url
': 'https
://www
.facebook
.com
/cnn
/videos
/10155529876156509/',
173 'md5
': 'ca63897a90c9452efee5f8c40d080e25
',
175 'id': '10155529876156509',
177 'title
': 'Holocaust survivor becomes US citizen
',
178 'description
': 'She survived the holocaust —
and years later
, she’s getting her citizenship so she can vote
for Hillary Clinton http
://cnn
.it
/2eERh5f
',
179 'timestamp
': 1477818095,
180 'upload_date
': '20161030',
182 'thumbnail
': r're
:^https?
://.*',
184 'uploader_id
': '100059479812265',
185 'concurrent_view_count
': int,
189 # bigPipe.onPageletArrive ... onPageletArrive pagelet_group_mall
190 # data.node.comet_sections.content.story.attachments[].style_type_renderer.attachment.media
191 'url
': 'https
://www
.facebook
.com
/yaroslav
.korpan
/videos
/1417995061575415/',
193 'id': '1417995061575415',
195 'title
': 'Довгоочікуване відео | By Yaroslav
- Facebook
',
196 'description
': 'Довгоочікуване відео
',
197 'timestamp
': 1486648217,
198 'upload_date
': '20170209',
199 'uploader
': 'Yaroslav Korpan
',
200 'uploader_id
': 'pfbid06AScABAWcW91qpiuGrLt99Ef9tvwHoXP6t8KeFYEqkSfreMtfa9nTveh8b2ZEVSWl
',
201 'concurrent_view_count
': int,
202 'thumbnail
': r're
:^https?
://.*',
204 'duration
': 11736.446,
207 'skip_download
': True,
211 'url
': 'https
://www
.facebook
.com
/LaGuiaDelVaron
/posts
/1072691702860471',
213 'id': '1072691702860471',
215 'title
': 'md5
:ae2d22a93fbb12dad20dc393a869739d
',
216 'timestamp
': 1477305000,
217 'upload_date
': '20161024',
218 'uploader
': 'La Guía Del Varón
',
219 'thumbnail
': r're
:^https?
://.*',
221 'skip
': 'Requires logging
in',
223 # data.node.comet_sections.content.story.attachments[].style_type_renderer.attachment.media
224 'url
': 'https
://www
.facebook
.com
/groups
/1024490957622648/permalink
/1396382447100162/',
226 'id': '202882990186699',
228 'title
': 'birb (O v O
") | Hello? Yes your uber ride is here',
229 'description': 'Hello? Yes your uber ride is here * Jukin Media Verified * Find this video and others like it by visiting...',
230 'timestamp': 1486035513,
231 'upload_date': '20170202',
232 'uploader': 'Elisabeth Ahtn',
233 'uploader_id': '100013949973717',
235 'skip': 'Requires logging in',
237 # data.node.comet_sections.content.story.attachments[].throwbackStyles.attachment_target_renderer.attachment.target.attachments[].styles.attachment.media
238 'url': 'https://www.facebook.com/groups/1645456212344334/posts/3737828833107051/',
240 'id': '1569199726448814',
242 'title': 'Pence MUST GO!',
243 'description': 'Vickie Gentry shared a memory.',
244 'timestamp': 1511548260,
245 'upload_date': '20171124',
246 'uploader': 'Vickie Gentry',
247 'uploader_id': 'pfbid0FuZhHCeWDAxWxEbr3yKPFaRstXvRxgsp9uCPG6GjD4J2AitB35NUAuJ4Q75KcjiDl',
248 'thumbnail': r're:^https?://.*',
252 'url': 'https://www.facebook.com/attn/posts/pfbid0j1Czf2gGDVqeQ8KiMLFm3pWN8GxsQmeRrVhimWDzMuKQoR8r4b1knNsejELmUgyhl',
254 'id': '6968553779868435',
256 'description': 'md5:2f2fcf93e97ac00244fe64521bbdb0cb',
258 'upload_date': '20231207',
261 'uploader_id': '100064451419378',
263 'thumbnail': r're:^https?://.*',
264 'timestamp': 1701975646,
267 'url': 'https://www.facebook.com/story.php?story_fbid=pfbid0Fnzhm8UuzjBYpPMNFzaSpFE9UmLdU4fJN8qTANi1Dmtj5q7DNrL5NERXfsAzDEV7l&id=100073071055552',
268 'only_matching': True,
270 'url': 'https://www.facebook.com/video.php?v=10204634152394104',
271 'only_matching': True,
273 'url': 'https://www.facebook.com/amogood/videos/1618742068337349/?fref=nf',
274 'only_matching': True,
276 # data.mediaset.currMedia.edges
277 'url': 'https://www.facebook.com/ChristyClarkForBC/videos/vb.22819070941/10153870694020942/?type=2&theater',
278 'only_matching': True,
280 # data.video.story.attachments[].media
281 'url': 'facebook:544765982287235',
282 'only_matching': True,
284 # data.node.comet_sections.content.story.attachments[].style_type_renderer.attachment.media
285 'url': 'https://www.facebook.com/groups/164828000315060/permalink/764967300301124/',
286 'only_matching': True,
288 # data.video.creation_story.attachments[].media
289 'url': 'https://zh-hk.facebook.com/peoplespower/videos/1135894589806027/',
290 'only_matching': True,
293 'url': 'https://www.facebookwkhpilnemxj7asaniu7vnjjbiltxjqhye3mhbshg7kx5tfyd.onion/video.php?v=274175099429670',
294 'only_matching': True,
297 'url': 'https://www.facebook.com/onlycleverentertainment/videos/1947995502095005/',
298 'only_matching': True,
301 'url': 'https://www.facebook.com/WatchESLOne/videos/359649331226507/',
303 'id': '359649331226507',
305 'title': 'Fnatic vs. EG - Group A - Opening Match - ESL One Birmingham Day 1',
306 'description': '#ESLOne VoD - Birmingham Finals Day#1 Fnatic vs. @Evil Geniuses',
307 'timestamp': 1527084179,
308 'upload_date': '20180523',
309 'uploader': 'ESL One Dota 2',
310 'uploader_id': '100066514874195',
311 'duration': 4524.212,
313 'thumbnail': r're:^https?://.*',
314 'concurrent_view_count': int,
317 'skip_download': True,
320 # data.node.comet_sections.content.story.attachments[].style_type_renderer.attachment.all_subattachments.nodes[].media
321 'url': 'https://www.facebook.com/100033620354545/videos/106560053808006/',
323 'id': '106560053808006',
326 'thumbnail': r're:^https?://.*',
327 'concurrent_view_count': int,
328 'uploader_id': 'pfbid0cibUN6tV7DYgdbJdsUFN46wc4jKpVSPAvJQhFofGqBGmVn3V3JtAs2tfUwziw2hUl',
329 'timestamp': 1549275572,
331 'uploader': 'Josef Novak',
333 'upload_date': '20190204',
336 # data.video.story.attachments[].media
337 'url': 'https://www.facebook.com/watch/?v=647537299265662',
338 'only_matching': True,
340 # FIXME: https://github.com/yt-dlp/yt-dlp/issues/542
341 # data.node.comet_sections.content.story.attachments[].style_type_renderer.attachment.all_subattachments.nodes[].media
342 'url': 'https://www.facebook.com/PankajShahLondon/posts/10157667649866271',
344 'id': '10157667649866271',
347 'skip': 'Requires logging in',
349 # data.nodes[].comet_sections.content.story.attachments[].style_type_renderer.attachment.media
350 'url': 'https://m.facebook.com/Alliance.Police.Department/posts/4048563708499330',
352 'id': '117576630041613',
354 # TODO: title can be extracted from video page
355 'title': 'Facebook video #117576630041613',
356 'uploader_id': '189393014416438',
357 'upload_date': '20201123',
358 'timestamp': 1606162592,
360 'skip': 'Requires logging in',
362 # node.comet_sections.content.story.attached_story.attachments.style_type_renderer.attachment.media
363 'url': 'https://www.facebook.com/groups/ateistiskselskab/permalink/10154930137678856/',
365 'id': '211567722618337',
367 'title': 'Facebook video #211567722618337',
368 'uploader_id': '127875227654254',
369 'upload_date': '20161122',
370 'timestamp': 1479793574,
374 # data.video.creation_story.attachments[].media
375 'url': 'https://www.facebook.com/watch/live/?v=1823658634322275',
376 'only_matching': True,
378 'url': 'https://www.facebook.com/watchparty/211641140192478',
380 'id': '211641140192478',
383 'skip': 'Requires logging in',
385 _SUPPORTED_PAGLETS_REGEX = r'(?:pagelet_group_mall|permalink_video_pagelet|hyperfeed_story_id_[0-9a-f]+)'
387 'graphURI': '/api/graphql/'
390 def _perform_login(self, username, password):
391 login_page_req = Request(self._LOGIN_URL)
392 self._set_cookie('facebook.com', 'locale', 'en_US')
393 login_page = self._download_webpage(login_page_req, None,
394 note='Downloading login page',
395 errnote='Unable to download login page')
396 lsd = self._search_regex(
397 r'<input type="hidden
" name="lsd
" value="([^
"]*)"',
399 lgnrnd = self._search_regex(r'name
="lgnrnd" value
="([^"]*?
)"', login_page, 'lgnrnd')
406 'next': 'http://facebook.com/home.php',
407 'default_persistent': '0',
408 'legacy_return': '1',
412 request = Request(self._LOGIN_URL, urlencode_postdata(login_form))
413 request.headers['Content-Type'] = 'application/x-www-form-urlencoded'
415 login_results = self._download_webpage(request, None,
416 note='Logging in', errnote='unable to fetch login page')
417 if re.search(r'<form(.*)name="login
"(.*)</form>', login_results) is not None:
418 error = self._html_search_regex(
419 r'(?s)<div[^>]+class=(["\']).*?login_error_box
.*?\
1[^
>]*><div
[^
>]*>.*?
</div
><div
[^
>]*>(?P
<error
>.+?
)</div
>',
420 login_results, 'login error
', default=None, group='error
')
422 raise ExtractorError('Unable to login
: %s' % error, expected=True)
423 self.report_warning('unable to log
in: bad username
/password
, or exceeded login rate
limit (~
3/min). Check credentials
or wait
.')
426 fb_dtsg = self._search_regex(
427 r'name
="fb_dtsg" value
="(.+?)"', login_results, 'fb_dtsg
', default=None)
428 h = self._search_regex(
429 r'name
="h"\s
+(?
:\w
+="[^"]+"\s+)*?value="([^
"]+)"', login_results, 'h
', default=None)
431 if not fb_dtsg or not h:
437 'name_action_selected
': 'dont_save
',
439 check_req = Request(self._CHECKPOINT_URL, urlencode_postdata(check_form))
440 check_req.headers['Content
-Type
'] = 'application
/x
-www
-form
-urlencoded
'
441 check_response = self._download_webpage(check_req, None,
442 note='Confirming login
')
443 if re.search(r'id="checkpointSubmitButton"', check_response) is not None:
444 self.report_warning('Unable to confirm login
, you have to login
in your browser
and authorize the login
.')
445 except network_exceptions as err:
446 self.report_warning('unable to log
in: %s' % error_to_compat_str(err))
449 def _extract_from_url(self, url, video_id):
450 webpage = self._download_webpage(
451 url.replace('://m
.facebook
.com
/', '://www
.facebook
.com
/'), video_id)
453 def extract_metadata(webpage):
454 post_data = [self._parse_json(j, video_id, fatal=False) for j in re.findall(
455 r'data
-sjs
>({.*?ScheduledServerJS.*?}
)</script
>', webpage)]
456 post = traverse_obj(post_data, (
457 ..., 'require
', ..., ..., ..., '__bbox
', 'require
', ..., ..., ..., '__bbox
', 'result
', 'data
'), expected_type=dict) or []
459 automatic_captions, subtitles = {}, {}
460 subs_data = traverse_obj(post, (..., 'video
', ..., 'attachments
', ..., lambda k, v: (
461 k == 'media
' and str(v['id']) == video_id and v['__typename
'] == 'Video
')))
462 is_video_broadcast = get_first(subs_data, 'is_video_broadcast
', expected_type=bool)
463 captions = get_first(subs_data, 'video_available_captions_locales
', 'captions_url
')
464 if url_or_none(captions): # if subs_data only had a 'captions_url
'
465 locale = self._html_search_meta(['og
:locale
', 'twitter
:locale
'], webpage, 'locale
', default='en_US
')
466 subtitles[locale] = [{'url': captions}]
467 # or else subs_data had 'video_available_captions_locales
', a list of dicts
468 for caption in traverse_obj(captions, (
469 {lambda x: sorted(x, key=lambda c: c['locale'])}, lambda _, v: v['captions_url
'])
471 lang = caption.get('localized_language
') or ''
473 'url
': caption['captions_url
'],
474 'name
': format_field(caption, 'localized_country
', f'{lang}
(%s)', default=lang),
476 if caption.get('localized_creation_method
') or is_video_broadcast:
477 automatic_captions.setdefault(caption['locale
'], []).append(subs)
479 subtitles.setdefault(caption['locale
'], []).append(subs)
481 media = traverse_obj(post, (..., 'attachments
', ..., lambda k, v: (
482 k == 'media
' and str(v['id']) == video_id and v['__typename
'] == 'Video
')), expected_type=dict)
483 title = get_first(media, ('title
', 'text
'))
484 description = get_first(media, ('creation_story
', 'comet_sections
', 'message
', 'story
', 'message
', 'text
'))
486 get_first(media, ('owner
', {dict}))
487 or get_first(post, (..., 'video
', lambda k, v: k == 'owner
' and v['name
']))
488 or get_first(post, ('node
', 'actors
', ..., {dict})) or {})
490 page_title = title or self._html_search_regex((
491 r'<h2\s
+[^
>]*class="uiHeaderTitle"[^
>]*>(?P
<content
>[^
<]*)</h2
>',
492 r'(?s
)<span
class="fbPhotosPhotoCaption".*?
id="fbPhotoPageCaption"><span
class="hasCaption">(?P
<content
>.*?
)</span
>',
493 self._meta_regex('og
:title
'), self._meta_regex('twitter
:title
'), r'<title
>(?P
<content
>.+?
)</title
>'
494 ), webpage, 'title
', default=None, group='content
')
495 description = description or self._html_search_meta(
496 ['description
', 'og
:description
', 'twitter
:description
'],
497 webpage, 'description
', default=None)
498 uploader = uploader_data.get('name
') or (
499 clean_html(get_element_by_id('fbPhotoPageAuthorName
', webpage))
500 or self._search_regex(
501 (r'ownerName\s
*:\s
*"([^"]+)"', *self._og_regexes('title')), webpage, 'uploader', fatal=False))
503 timestamp = int_or_none(self._search_regex(
504 r'<abbr[^>]+data-utime=["\'](\d
+)', webpage,
505 'timestamp
', default=None))
506 thumbnail = self._html_search_meta(
507 ['og
:image
', 'twitter
:image
'], webpage, 'thumbnail
', default=None)
508 # some webpages contain unretrievable thumbnail urls
509 # like https://lookaside.fbsbx.com/lookaside/crawler/media/?media_id=10155168902769113&get_thumbnail=1
510 # in https://www.facebook.com/yaroslav.korpan/videos/1417995061575415/
511 if thumbnail and not re.search(r'\
.(?
:jpg|png
)', thumbnail):
514 'description
': description,
515 'uploader
': uploader,
516 'uploader_id
': uploader_data.get('id'),
517 'timestamp
': timestamp,
518 'thumbnail
': thumbnail,
519 'view_count
': parse_count(self._search_regex(
520 (r'\bviewCount\s
*:\s
*["\']([\d,.]+)', r'video_view_count["\']\s
*:\s
*(\d
+)',),
521 webpage, 'view count
', default=None)),
522 'concurrent_view_count
': get_first(post, (
523 ('video
', (..., ..., 'attachments
', ..., 'media
')), 'liveViewerCount
', {int_or_none})),
524 'automatic_captions
': automatic_captions,
525 'subtitles
': subtitles,
528 info_json_ld = self._search_json_ld(webpage, video_id, default={})
529 info_json_ld['title
'] = (re.sub(r'\s
*\|\s
*Facebook$
', '', title or info_json_ld.get('title
') or page_title or '')
530 or (description or '').replace('\n', ' ') or f'Facebook video
#{video_id}')
531 return merge_dicts(info_json_ld
, info_dict
)
535 def extract_video_data(instances
):
537 for item
in instances
:
538 if try_get(item
, lambda x
: x
[1][0]) == 'VideoConfig':
539 video_item
= item
[2][0]
540 if video_item
.get('video_id'):
541 video_data
.append(video_item
['videoData'])
544 server_js_data
= self
._parse
_json
(self
._search
_regex
(
545 [r
'handleServerJS\(({.+})(?:\);|,")', r
'\bs\.handle\(({.+?})\);'],
546 webpage
, 'server js data', default
='{}'), video_id
, fatal
=False)
549 video_data
= extract_video_data(server_js_data
.get('instances', []))
551 def extract_from_jsmods_instances(js_data
):
553 return extract_video_data(try_get(
554 js_data
, lambda x
: x
['jsmods']['instances'], list) or [])
556 def extract_dash_manifest(video
, formats
):
557 dash_manifest
= video
.get('dash_manifest')
559 formats
.extend(self
._parse
_mpd
_formats
(
560 compat_etree_fromstring(urllib
.parse
.unquote_plus(dash_manifest
)),
561 mpd_url
=video
.get('dash_manifest_url')))
563 def process_formats(info
):
564 # Downloads with browser's User-Agent are rate limited. Working around
565 # with non-browser User-Agent.
566 for f
in info
['formats']:
567 # Downloads with browser's User-Agent are rate limited. Working around
568 # with non-browser User-Agent.
569 f
.setdefault('http_headers', {})['User-Agent'] = 'facebookexternalhit/1.1'
570 # Formats larger than ~500MB will return error 403 unless chunk size is regulated
571 f
.setdefault('downloader_options', {})['http_chunk_size'] = 250 << 20
573 def extract_relay_data(_filter
):
574 return self
._parse
_json
(self
._search
_regex
(
575 r
'data-sjs>({.*?%s.*?})</script>' % _filter
,
576 webpage
, 'replay data', default
='{}'), video_id, fatal=False) or {}
578 def extract_relay_prefetched_data(_filter):
579 return traverse_obj(extract_relay_data(_filter), (
580 'require
', (None, (..., ..., ..., '__bbox
', 'require
')),
581 lambda _, v: 'RelayPrefetchedStreamCache
' in v, ..., ...,
582 '__bbox
', 'result
', 'data
', {dict}), get_all=False) or {}
585 server_js_data = self._parse_json(self._search_regex([
586 r'bigPipe\
.onPageletArrive\
(({.+?}
)\
)\s
*;\s
*}\s
*\
)\s
*,\s
*["\']onPageletArrive\s+' + self._SUPPORTED_PAGLETS_REGEX,
587 r'bigPipe\.onPageletArrive\(({.*?id\s*:\s*"%s".*?})\);' % self._SUPPORTED_PAGLETS_REGEX
588 ], webpage, 'js data', default='{}'), video_id, js_to_json, False)
589 video_data = extract_from_jsmods_instances(server_js_data)
592 data = extract_relay_prefetched_data(
593 r'"(?
:dash_manifest|
playable_url(?
:_quality_hd
)?
)')
597 def parse_graphql_video(video):
598 v_id = video.get('videoId
') or video.get('id') or video_id
599 reel_info = traverse_obj(
600 video, ('creation_story
', 'short_form_video_context
', 'playback_video
', {dict}))
602 video = video['creation_story
']
603 video['owner
'] = traverse_obj(video, ('short_form_video_context
', 'video_owner
'))
604 video.update(reel_info)
606 q = qualities(['sd
', 'hd
'])
607 for key, format_id in (('playable_url
', 'sd
'), ('playable_url_quality_hd
', 'hd
'),
608 ('playable_url_dash
', ''), ('browser_native_hd_url
', 'hd
'),
609 ('browser_native_sd_url
', 'sd
')):
610 playable_url = video.get(key)
613 if determine_ext(playable_url) == 'mpd
':
614 formats.extend(self._extract_mpd_formats(playable_url, video_id))
617 'format_id
': format_id,
618 # sd, hd formats w/o resolution info should be deprioritized below DASH
619 'quality
': q(format_id) - 3,
622 extract_dash_manifest(video, formats)
626 'thumbnail
': traverse_obj(
627 video, ('thumbnailImage
', 'uri
'), ('preferred_thumbnail
', 'image
', 'uri
')),
628 'uploader_id
': traverse_obj(video, ('owner
', 'id', {str_or_none})),
629 'timestamp
': traverse_obj(video, 'publish_time
', 'creation_time
', expected_type=int_or_none),
630 'duration
': (float_or_none(video.get('playable_duration_in_ms
'), 1000)
631 or float_or_none(video.get('length_in_second
'))),
633 process_formats(info)
634 description = try_get(video, lambda x: x['savable_description
']['text
'])
635 title = video.get('name
')
639 'description
': description,
642 info['title
'] = description or 'Facebook video
#%s' % v_id
645 def parse_attachment(attachment
, key
='media'):
646 media
= attachment
.get(key
) or {}
647 if media
.get('__typename') == 'Video':
648 return parse_graphql_video(media
)
650 nodes
= variadic(traverse_obj(data
, 'nodes', 'node') or [])
651 attachments
= traverse_obj(nodes
, (
652 ..., 'comet_sections', 'content', 'story', (None, 'attached_story'), 'attachments',
653 ..., ('styles', 'style_type_renderer', ('throwbackStyles', 'attachment_target_renderer')),
654 'attachment', {dict}
))
655 for attachment
in attachments
:
656 ns
= traverse_obj(attachment
, ('all_subattachments', 'nodes', ..., {dict}
),
657 ('target', 'attachments', ..., 'styles', 'attachment', {dict}
))
660 parse_attachment(attachment
)
662 edges
= try_get(data
, lambda x
: x
['mediaset']['currMedia']['edges'], list) or []
664 parse_attachment(edge
, key
='node')
666 video
= data
.get('video') or {}
668 attachments
= try_get(video
, [
669 lambda x
: x
['story']['attachments'],
670 lambda x
: x
['creation_story']['attachments']
672 for attachment
in attachments
:
673 parse_attachment(attachment
)
675 parse_graphql_video(video
)
678 return self
.playlist_result(entries
, video_id
)
680 video_info
= entries
[0] if entries
else {'id': video_id}
681 webpage_info
= extract_metadata(webpage
)
682 # honor precise duration in video info
683 if video_info
.get('duration'):
684 webpage_info
['duration'] = video_info
['duration']
685 return merge_dicts(webpage_info
, video_info
)
688 m_msg
= re
.search(r
'class="[^"]*uiInterstitialContent[^"]*"><div>(.*?)</div>', webpage
)
689 if m_msg
is not None:
690 raise ExtractorError(
691 'The video is not available, Facebook said: "%s"' % m_msg
.group(1),
693 elif any(p
in webpage
for p
in (
694 '>You must log in to continue',
696 'id="loginbutton"')):
697 self
.raise_login_required()
699 if not video_data
and '/watchparty/' in url
:
701 'doc_id': 3731964053542869,
702 'variables': json
.dumps({
703 'livingRoomID': video_id
,
707 prefetched_data
= extract_relay_prefetched_data(r
'"login_data"\s*:\s*{')
709 lsd
= try_get(prefetched_data
, lambda x
: x
['login_data']['lsd'], dict)
711 post_data
[lsd
['name']] = lsd
['value']
713 relay_data
= extract_relay_data(r
'\[\s*"RelayAPIConfigDefaults"\s*,')
714 for define
in (relay_data
.get('define') or []):
715 if define
[0] == 'RelayAPIConfigDefaults':
716 self
._api
_config
= define
[2]
718 living_room
= self
._download
_json
(
719 urljoin(url
, self
._api
_config
['graphURI']), video_id
,
720 data
=urlencode_postdata(post_data
))['data']['living_room']
723 for edge
in (try_get(living_room
, lambda x
: x
['recap']['watched_content']['edges']) or []):
724 video
= try_get(edge
, lambda x
: x
['node']['video']) or {}
725 v_id
= video
.get('id')
728 v_id
= compat_str(v_id
)
729 entries
.append(self
.url_result(
730 self
._VIDEO
_PAGE
_TEMPLATE
% v_id
,
731 self
.ie_key(), v_id
, video
.get('name')))
733 return self
.playlist_result(entries
, video_id
)
736 # Video info not in first request, do a secondary request using
737 # tahoe player specific URL
738 tahoe_data
= self
._download
_webpage
(
739 self
._VIDEO
_PAGE
_TAHOE
_TEMPLATE
% video_id
, video_id
,
740 data
=urlencode_postdata({
742 '__pc': self
._search
_regex
(
743 r
'pkg_cohort["\']\s
*:\s
*["\'](.+?)["\']', webpage,
744 'pkg cohort
', default='PHASED
:DEFAULT
'),
745 '__rev
': self._search_regex(
746 r'client_revision
["\']\s*:\s*(\d+),', webpage,
747 'client revision', default='3944515'),
748 'fb_dtsg': self._search_regex(
749 r'"DTSGInitialData
"\s*,\s*\[\]\s*,\s*{\s*"token
"\s*:\s*"([^
"]+)"',
750 webpage, 'dtsg token
', default=''),
753 'Content
-Type
': 'application
/x
-www
-form
-urlencoded
',
755 tahoe_js_data = self._parse_json(
757 r'for\s
+\
(\s
*;\s
*;\s
*\
)\s
*;(.+)', tahoe_data,
758 'tahoe js data
', default='{}'),
759 video_id, fatal=False)
760 video_data = extract_from_jsmods_instances(tahoe_js_data)
763 raise ExtractorError('Cannot parse data
')
765 if len(video_data) > 1:
768 video_url = v[0].get('video_url
')
771 entries.append(self.url_result(urljoin(
772 url, video_url), self.ie_key(), v[0].get('video_id
')))
773 return self.playlist_result(entries, video_id)
774 video_data = video_data[0]
779 format_id = f['stream_type
']
780 if f and isinstance(f, dict):
782 if not f or not isinstance(f, list):
784 for quality in ('sd
', 'hd
'):
785 for src_type in ('src
', 'src_no_ratelimit
'):
786 src = f[0].get('%s_%s' % (quality, src_type))
788 # sd, hd formats w/o resolution info should be deprioritized below DASH
789 # TODO: investigate if progressive or src formats still exist
790 preference = -10 if format_id == 'progressive
' else -3
794 'format_id
': '%s_%s_%s' % (format_id, quality, src_type),
796 'quality
': preference,
797 'height
': 720 if quality == 'hd
' else None
799 extract_dash_manifest(f[0], formats)
800 subtitles_src = f[0].get('subtitles_src
')
802 subtitles.setdefault('en
', []).append({'url': subtitles_src})
807 'subtitles
': subtitles,
809 process_formats(info_dict)
810 info_dict.update(extract_metadata(webpage))
814 def _real_extract(self, url):
815 video_id = self._match_id(url)
817 real_url = self._VIDEO_PAGE_TEMPLATE % video_id if url.startswith('facebook
:') else url
818 return self._extract_from_url(real_url, video_id)
821 class FacebookPluginsVideoIE(InfoExtractor):
822 _VALID_URL = r'https?
://(?
:[\w
-]+\
.)?facebook\
.com
/plugins
/video\
.php
\?.*?
\bhref
=(?P
<id>https
.+)'
825 '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',
826 'md5
': '5954e92cdfe51fe5782ae9bda7058a07
',
828 'id': '10154383743583686',
830 # TODO: Fix title, uploader
831 'title
': 'What to do during the haze?
',
832 'uploader
': 'Gov
.sg
',
833 'upload_date
': '20160826',
834 'timestamp
': 1472184808,
836 'add_ie
': [FacebookIE.ie_key()],
838 'url
': 'https
://www
.facebook
.com
/plugins
/video
.php?href
=https
%3A
%2F
%2Fwww
.facebook
.com
%2Fvideo
.php
%3Fv
%3D10204634152394104
',
839 'only_matching
': True,
841 'url
': 'https
://www
.facebook
.com
/plugins
/video
.php?href
=https
://www
.facebook
.com
/gov
.sg
/videos
/10154383743583686/&show_text
=0&width
=560',
842 'only_matching
': True,
845 def _real_extract(self, url):
846 return self.url_result(
847 compat_urllib_parse_unquote(self._match_id(url)),
851 class FacebookRedirectURLIE(InfoExtractor):
852 IE_DESC = False # Do not list
853 _VALID_URL = r'https?
://(?
:[\w
-]+\
.)?facebook\
.com
/flx
/warn
[/?
]'
855 'url
': 'https
://www
.facebook
.com
/flx
/warn
/?h
=TAQHsoToz
&u
=https
%3A
%2F
%2Fwww
.youtube
.com
%2Fwatch
%3Fv
%3DpO8h3EaFRdo
&s
=1',
859 'title
': 'Tripeo Boiler Room x Dekmantel Festival DJ Set
',
860 'description
': 'md5
:2d713ccbb45b686a1888397b2c77ca6b
',
861 'channel_id
': 'UCGBpxWJr9FNOcFYA5GkKrMg
',
862 'playable_in_embed
': True,
863 'categories
': ['Music
'],
864 'channel
': 'Boiler Room
',
865 'uploader_id
': 'brtvofficial
',
866 'uploader
': 'Boiler Room
',
869 'live_status
': 'not_live
',
870 'thumbnail
': 'https
://i
.ytimg
.com
/vi
/pO8h3EaFRdo
/maxresdefault
.jpg
',
871 'channel_url
': 'https
://www
.youtube
.com
/channel
/UCGBpxWJr9FNOcFYA5GkKrMg
',
872 'availability
': 'public
',
873 'uploader_url
': 'http
://www
.youtube
.com
/user
/brtvofficial
',
874 'upload_date
': '20150917',
879 'add_ie
': ['Youtube
'],
880 'params
': {'skip_download': 'Youtube'},
883 def _real_extract(self, url):
884 redirect_url = url_or_none(parse_qs(url).get('u
', [None])[-1])
886 raise ExtractorError('Invalid facebook redirect URL
', expected=True)
887 return self.url_result(redirect_url)
890 class FacebookReelIE(InfoExtractor):
891 _VALID_URL = r'https?
://(?
:[\w
-]+\
.)?facebook\
.com
/reel
/(?P
<id>\d
+)'
892 IE_NAME = 'facebook
:reel
'
895 'url
': 'https
://www
.facebook
.com
/reel
/1195289147628387',
896 'md5
': 'f13dd37f2633595982db5ed8765474d3
',
898 'id': '1195289147628387',
900 'title
': 'md5
:b05800b5b1ad56c0ca78bd3807b6a61e
',
901 'description
': 'md5
:22f03309b216ac84720183961441d8db
',
902 'uploader
': 'md5
:723e6cb3091241160f20b3c5dc282af1
',
903 'uploader_id
': '100040874179269',
905 'timestamp
': 1637502609,
906 'upload_date
': '20211121',
907 'thumbnail
': r're
:^https?
://.*',
911 def _real_extract(self, url):
912 video_id = self._match_id(url)
913 return self.url_result(
914 f'https
://m
.facebook
.com
/watch
/?v
={video_id}
&_rdr
', FacebookIE, video_id)
917 class FacebookAdsIE(InfoExtractor):
918 _VALID_URL = r'https?
://(?
:[\w
-]+\
.)?facebook\
.com
/ads
/library
/?
\?(?
:[^
#]+&)?id=(?P<id>\d+)'
919 IE_NAME
= 'facebook:ads'
922 'url': 'https://www.facebook.com/ads/library/?id=899206155126718',
924 'id': '899206155126718',
926 'title': 'video by Kandao',
927 'uploader': 'Kandao',
928 'uploader_id': '774114102743284',
929 'uploader_url': r
're:^https?://.*',
930 'timestamp': 1702548330,
931 'thumbnail': r
're:^https?://.*',
932 'upload_date': '20231214',
936 'url': 'https://www.facebook.com/ads/library/?id=893637265423481',
938 'id': '893637265423481',
939 'title': 'Jusqu\u2019\u00e0 -25% sur une s\u00e9lection de vins p\u00e9tillants italiens ',
940 'uploader': 'Eataly Paris Marais',
941 'uploader_id': '2086668958314152',
942 'uploader_url': r
're:^https?://.*',
943 'timestamp': 1703571529,
944 'upload_date': '20231226',
949 'url': 'https://es-la.facebook.com/ads/library/?id=901230958115569',
950 'only_matching': True,
952 'url': 'https://m.facebook.com/ads/library/?id=901230958115569',
953 'only_matching': True,
957 'watermarked_video_sd_url': ('sd-wmk', 'SD, watermarked'),
958 'video_sd_url': ('sd', None),
959 'watermarked_video_hd_url': ('hd-wmk', 'HD, watermarked'),
960 'video_hd_url': ('hd', None),
963 def _extract_formats(self
, video_dict
):
965 for format_key
, format_url
in traverse_obj(video_dict
, (
966 {dict.items}
, lambda _
, v
: v
[0] in self
._FORMATS
_MAP
and url_or_none(v
[1])
969 'format_id': self
._FORMATS
_MAP
[format_key
][0],
970 'format_note': self
._FORMATS
_MAP
[format_key
][1],
973 'quality': qualities(tuple(self
._FORMATS
_MAP
))(format_key
),
977 def _real_extract(self
, url
):
978 video_id
= self
._match
_id
(url
)
979 webpage
= self
._download
_webpage
(url
, video_id
)
981 post_data
= [self
._parse
_json
(j
, video_id
, fatal
=False)
982 for j
in re
.findall(r
's\.handle\(({.*})\);requireLazy\(', webpage
)]
983 data
= traverse_obj(post_data
, (
984 ..., 'require', ..., ..., ..., 'props', 'deeplinkAdCard', 'snapshot', {dict}
), get_all
=False)
986 raise ExtractorError('Unable to extract ad data')
988 title
= data
.get('title')
989 if not title
or title
== '{{product.name}}':
990 title
= join_nonempty('display_format', 'page_name', delim
=' by ', from_dict
=data
)
992 info_dict
= traverse_obj(data
, {
993 'description': ('link_description', {str}
, {lambda x: x if x != '{{product.description}
}' else None}),
994 'uploader
': ('page_name
', {str}),
995 'uploader_id
': ('page_id
', {str_or_none}),
996 'uploader_url
': ('page_profile_uri
', {url_or_none}),
997 'timestamp
': ('creation_time
', {int_or_none}),
998 'like_count
': ('page_like_count
', {int_or_none}),
1002 for idx, entry in enumerate(traverse_obj(
1003 data, (('videos
', 'cards
'), lambda _, v: any([url_or_none(v[f]) for f in self._FORMATS_MAP]))), 1
1006 'id': f'{video_id}_{idx}
',
1007 'title
': entry.get('title
') or title,
1008 'description
': entry.get('link_description
') or info_dict.get('description
'),
1009 'thumbnail
': url_or_none(entry.get('video_preview_image_url
')),
1010 'formats
': self._extract_formats(entry),
1013 if len(entries) == 1:
1014 info_dict.update(entries[0])
1016 elif len(entries) > 1:
1018 'title
': entries[0]['title
'],
1020 '_type
': 'playlist
',
1023 info_dict['id'] = video_id