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
38 class FacebookIE(InfoExtractor
):
42 (?:[\w-]+\.)?(?:facebook\.com|facebookwkhpilnemxj7asaniu7vnjjbiltxjqhye3mhbshg7kx5tfyd\.onion)/
52 )\?(?:.*?)(?:v|video_id|story_fbid)=|
53 [^/]+/videos/(?:[^/]+/)?|
55 groups/[^/]+/(?:permalink|posts)/|
60 (?P<id>pfbid[A-Za-z0-9]+|\d+)
63 r
'<iframe[^>]+?src=(["\'])(?P
<url
>https?
://www\
.facebook\
.com
/(?
:video
/embed|plugins
/video\
.php
).+?
)\
1',
64 # Facebook API embed https://developers.facebook.com/docs/plugins/embedded-video-player
66 class=(?P<q1>[\'"])[^\'"]*\bfb-(?:video|post)\b[^\'"]*(?P=q1)[^>]+
67 data-href=(?P<q2>[\'"])(?P<url>(?:https?:)?//(?:www\.)?facebook.com/.+?)(?P=q2)''',
69 _LOGIN_URL = 'https
://www
.facebook
.com
/login
.php?next
=http
%3A
%2F
%2Ffacebook
.com
%2Fhome
.php
&login_attempt
=1'
70 _CHECKPOINT_URL = 'https
://www
.facebook
.com
/checkpoint
/?next
=http
%3A
%2F
%2Ffacebook
.com
%2Fhome
.php
&_fb_noscript
=1'
71 _NETRC_MACHINE = 'facebook
'
74 _VIDEO_PAGE_TEMPLATE = 'https
://www
.facebook
.com
/video
/video
.php?v
=%s'
75 _VIDEO_PAGE_TAHOE_TEMPLATE = 'https
://www
.facebook
.com
/video
/tahoe
/async/%s/?chain
=true
&isvideo
=true
&payloadtype
=primary
'
78 'url
': 'https
://www
.facebook
.com
/radiokicksfm
/videos
/3676516585958356/',
80 'id': '3676516585958356',
82 'title
': 'dr Adam Przygoda
',
83 'description
': 'md5
:34675bda53336b1d16400265c2bb9b3b
',
84 'uploader
': 'RADIO KICKS FM
',
85 'upload_date
': '20230818',
86 'timestamp
': 1692346159,
87 'thumbnail
': r're
:^https?
://.*',
88 'uploader_id
': '100063551323670',
91 'concurrent_view_count
': 0,
94 'url
': 'https
://www
.facebook
.com
/video
.php?v
=637842556329505&fref
=nf
',
95 'md5
': '6a40d33c0eccbb1af76cf0485a052659
',
97 'id': '637842556329505',
99 'title
': 're
:Did you know Kei Nishikori
is the first Asian man to ever reach a Grand Slam
',
100 'uploader
': 'Tennis on Facebook
',
101 'upload_date
': '20140908',
102 'timestamp
': 1410199200,
104 'skip
': 'Requires logging
in',
107 'url
': 'https
://www
.facebook
.com
/video
.php?v
=274175099429670',
109 'id': '274175099429670',
113 'uploader
': 'Asif Nawab Butt
',
114 'upload_date
': '20140506',
115 'timestamp
': 1399398998,
116 'thumbnail
': r're
:^https?
://.*',
117 'uploader_id
': 'pfbid028wxorhX2ErLFJ578N6P3crHD3PHmXTCqCvfBpsnbSLmbokwSY75p5hWBjHGkG4zxl
',
119 'concurrent_view_count
': int,
122 'note
': 'Video
with DASH manifest
',
123 'url
': 'https
://www
.facebook
.com
/video
.php?v
=957955867617029',
124 'md5
': 'b2c28d528273b323abe5c6ab59f0f030
',
126 'id': '957955867617029',
128 'title
': 'When you post epic content on instagram
.com
/433 8 million followers
, this
is ...',
129 'uploader
': 'Demy de Zeeuw
',
130 'upload_date
': '20160110',
131 'timestamp
': 1452431627,
133 'skip
': 'Requires logging
in',
135 'url
': 'https
://www
.facebook
.com
/maxlayn
/posts
/10153807558977570',
136 'md5
': '037b1fa7f3c2d02b7a0d7bc16031ecc6
',
138 'id': '544765982287235',
140 'title
': '"What are you doing running in the snow?"',
141 'uploader
': 'FailArmy
',
143 'skip
': 'Video gone
',
145 'url
': 'https
://m
.facebook
.com
/story
.php?story_fbid
=1035862816472149&id=116132035111903',
146 'md5
': '1deb90b6ac27f7efcf6d747c8a27f5e3
',
148 'id': '1035862816472149',
150 'title
': 'What the Flock Is Going On In New Zealand Credit
: ViralHog
',
151 'uploader
': 'S
. Saint
',
153 'skip
': 'Video gone
',
155 'note
': 'swf params escaped
',
156 'url
': 'https
://www
.facebook
.com
/barackobama
/posts
/10153664894881749',
157 'md5
': '97ba073838964d12c70566e0085c2b91
',
159 'id': '10153664894881749',
161 'title
': 'Average time to confirm recent Supreme Court nominees
: 67 days Longest it
\'s t
...',
162 'thumbnail
': r're
:^https?
://.*',
163 'timestamp
': 1456259628,
164 'upload_date
': '20160223',
165 'uploader
': 'Barack Obama
',
167 'skip
': 'Gif on giphy
.com gone
',
169 # have 1080P, but only up to 720p in swf params
170 # data.video.story.attachments[].media
171 'url
': 'https
://www
.facebook
.com
/cnn
/videos
/10155529876156509/',
172 'md5
': 'ca63897a90c9452efee5f8c40d080e25
',
174 'id': '10155529876156509',
176 'title
': 'Holocaust survivor becomes US citizen
',
177 'description
': 'She survived the holocaust —
and years later
, she’s getting her citizenship so she can vote
for Hillary Clinton http
://cnn
.it
/2eERh5f
',
178 'timestamp
': 1477818095,
179 'upload_date
': '20161030',
181 'thumbnail
': r're
:^https?
://.*',
183 'uploader_id
': '100059479812265',
184 'concurrent_view_count
': int,
188 # bigPipe.onPageletArrive ... onPageletArrive pagelet_group_mall
189 # data.node.comet_sections.content.story.attachments[].style_type_renderer.attachment.media
190 'url
': 'https
://www
.facebook
.com
/yaroslav
.korpan
/videos
/1417995061575415/',
192 'id': '1417995061575415',
194 'title
': 'Довгоочікуване відео | By Yaroslav
- Facebook
',
195 'description
': 'Довгоочікуване відео
',
196 'timestamp
': 1486648217,
197 'upload_date
': '20170209',
198 'uploader
': 'Yaroslav Korpan
',
199 'uploader_id
': 'pfbid06AScABAWcW91qpiuGrLt99Ef9tvwHoXP6t8KeFYEqkSfreMtfa9nTveh8b2ZEVSWl
',
200 'concurrent_view_count
': int,
201 'thumbnail
': r're
:^https?
://.*',
203 'duration
': 11736.446,
206 'skip_download
': True,
210 'url
': 'https
://www
.facebook
.com
/LaGuiaDelVaron
/posts
/1072691702860471',
212 'id': '1072691702860471',
214 'title
': 'md5
:ae2d22a93fbb12dad20dc393a869739d
',
215 'timestamp
': 1477305000,
216 'upload_date
': '20161024',
217 'uploader
': 'La Guía Del Varón
',
218 'thumbnail
': r're
:^https?
://.*',
220 'skip
': 'Requires logging
in',
222 # data.node.comet_sections.content.story.attachments[].style_type_renderer.attachment.media
223 'url
': 'https
://www
.facebook
.com
/groups
/1024490957622648/permalink
/1396382447100162/',
225 'id': '202882990186699',
227 'title
': 'birb (O v O
") | Hello? Yes your uber ride is here',
228 'description': 'Hello? Yes your uber ride is here * Jukin Media Verified * Find this video and others like it by visiting...',
229 'timestamp': 1486035513,
230 'upload_date': '20170202',
231 'uploader': 'Elisabeth Ahtn',
232 'uploader_id': '100013949973717',
234 'skip': 'Requires logging in',
236 # data.node.comet_sections.content.story.attachments[].throwbackStyles.attachment_target_renderer.attachment.target.attachments[].styles.attachment.media
237 'url': 'https://www.facebook.com/groups/1645456212344334/posts/3737828833107051/',
239 'id': '1569199726448814',
241 'title': 'Pence MUST GO!',
242 'description': 'Vickie Gentry shared a memory.',
243 'timestamp': 1511548260,
244 'upload_date': '20171124',
245 'uploader': 'Vickie Gentry',
246 'uploader_id': 'pfbid0FuZhHCeWDAxWxEbr3yKPFaRstXvRxgsp9uCPG6GjD4J2AitB35NUAuJ4Q75KcjiDl',
247 'thumbnail': r're:^https?://.*',
251 'url': 'https://www.facebook.com/attn/posts/pfbid0j1Czf2gGDVqeQ8KiMLFm3pWN8GxsQmeRrVhimWDzMuKQoR8r4b1knNsejELmUgyhl',
253 'id': '6968553779868435',
255 'description': 'md5:2f2fcf93e97ac00244fe64521bbdb0cb',
257 'upload_date': '20231207',
260 'uploader_id': '100064451419378',
262 'thumbnail': r're:^https?://.*',
263 'timestamp': 1701975646,
266 'url': 'https://www.facebook.com/story.php?story_fbid=pfbid0Fnzhm8UuzjBYpPMNFzaSpFE9UmLdU4fJN8qTANi1Dmtj5q7DNrL5NERXfsAzDEV7l&id=100073071055552',
267 'only_matching': True,
269 'url': 'https://www.facebook.com/video.php?v=10204634152394104',
270 'only_matching': True,
272 'url': 'https://www.facebook.com/amogood/videos/1618742068337349/?fref=nf',
273 'only_matching': True,
275 # data.mediaset.currMedia.edges
276 'url': 'https://www.facebook.com/ChristyClarkForBC/videos/vb.22819070941/10153870694020942/?type=2&theater',
277 'only_matching': True,
279 # data.video.story.attachments[].media
280 'url': 'facebook:544765982287235',
281 'only_matching': True,
283 # data.node.comet_sections.content.story.attachments[].style_type_renderer.attachment.media
284 'url': 'https://www.facebook.com/groups/164828000315060/permalink/764967300301124/',
285 'only_matching': True,
287 # data.video.creation_story.attachments[].media
288 'url': 'https://zh-hk.facebook.com/peoplespower/videos/1135894589806027/',
289 'only_matching': True,
292 'url': 'https://www.facebookwkhpilnemxj7asaniu7vnjjbiltxjqhye3mhbshg7kx5tfyd.onion/video.php?v=274175099429670',
293 'only_matching': True,
296 'url': 'https://www.facebook.com/onlycleverentertainment/videos/1947995502095005/',
297 'only_matching': True,
300 'url': 'https://www.facebook.com/WatchESLOne/videos/359649331226507/',
302 'id': '359649331226507',
304 'title': 'Fnatic vs. EG - Group A - Opening Match - ESL One Birmingham Day 1',
305 'description': '#ESLOne VoD - Birmingham Finals Day#1 Fnatic vs. @Evil Geniuses',
306 'timestamp': 1527084179,
307 'upload_date': '20180523',
308 'uploader': 'ESL One Dota 2',
309 'uploader_id': '100066514874195',
310 'duration': 4524.212,
312 'thumbnail': r're:^https?://.*',
313 'concurrent_view_count': int,
316 'skip_download': True,
319 # data.node.comet_sections.content.story.attachments[].style_type_renderer.attachment.all_subattachments.nodes[].media
320 'url': 'https://www.facebook.com/100033620354545/videos/106560053808006/',
322 'id': '106560053808006',
325 'thumbnail': r're:^https?://.*',
326 'concurrent_view_count': int,
327 'uploader_id': 'pfbid0cibUN6tV7DYgdbJdsUFN46wc4jKpVSPAvJQhFofGqBGmVn3V3JtAs2tfUwziw2hUl',
328 'timestamp': 1549275572,
330 'uploader': 'Josef Novak',
332 'upload_date': '20190204',
335 # data.video.story.attachments[].media
336 'url': 'https://www.facebook.com/watch/?v=647537299265662',
337 'only_matching': True,
339 # FIXME: https://github.com/yt-dlp/yt-dlp/issues/542
340 # data.node.comet_sections.content.story.attachments[].style_type_renderer.attachment.all_subattachments.nodes[].media
341 'url': 'https://www.facebook.com/PankajShahLondon/posts/10157667649866271',
343 'id': '10157667649866271',
346 'skip': 'Requires logging in',
348 # data.nodes[].comet_sections.content.story.attachments[].style_type_renderer.attachment.media
349 'url': 'https://m.facebook.com/Alliance.Police.Department/posts/4048563708499330',
351 'id': '117576630041613',
353 # TODO: title can be extracted from video page
354 'title': 'Facebook video #117576630041613',
355 'uploader_id': '189393014416438',
356 'upload_date': '20201123',
357 'timestamp': 1606162592,
359 'skip': 'Requires logging in',
361 # node.comet_sections.content.story.attached_story.attachments.style_type_renderer.attachment.media
362 'url': 'https://www.facebook.com/groups/ateistiskselskab/permalink/10154930137678856/',
364 'id': '211567722618337',
366 'title': 'Facebook video #211567722618337',
367 'uploader_id': '127875227654254',
368 'upload_date': '20161122',
369 'timestamp': 1479793574,
373 # data.video.creation_story.attachments[].media
374 'url': 'https://www.facebook.com/watch/live/?v=1823658634322275',
375 'only_matching': True,
377 'url': 'https://www.facebook.com/watchparty/211641140192478',
379 'id': '211641140192478',
382 'skip': 'Requires logging in',
384 _SUPPORTED_PAGLETS_REGEX = r'(?:pagelet_group_mall|permalink_video_pagelet|hyperfeed_story_id_[0-9a-f]+)'
386 'graphURI': '/api/graphql/'
389 def _perform_login(self, username, password):
390 login_page_req = Request(self._LOGIN_URL)
391 self._set_cookie('facebook.com', 'locale', 'en_US')
392 login_page = self._download_webpage(login_page_req, None,
393 note='Downloading login page',
394 errnote='Unable to download login page')
395 lsd = self._search_regex(
396 r'<input type="hidden
" name="lsd
" value="([^
"]*)"',
398 lgnrnd = self._search_regex(r'name
="lgnrnd" value
="([^"]*?
)"', login_page, 'lgnrnd')
405 'next': 'http://facebook.com/home.php',
406 'default_persistent': '0',
407 'legacy_return': '1',
411 request = Request(self._LOGIN_URL, urlencode_postdata(login_form))
412 request.headers['Content-Type'] = 'application/x-www-form-urlencoded'
414 login_results = self._download_webpage(request, None,
415 note='Logging in', errnote='unable to fetch login page')
416 if re.search(r'<form(.*)name="login
"(.*)</form>', login_results) is not None:
417 error = self._html_search_regex(
418 r'(?s)<div[^>]+class=(["\']).*?login_error_box
.*?\
1[^
>]*><div
[^
>]*>.*?
</div
><div
[^
>]*>(?P
<error
>.+?
)</div
>',
419 login_results, 'login error
', default=None, group='error
')
421 raise ExtractorError('Unable to login
: %s' % error, expected=True)
422 self.report_warning('unable to log
in: bad username
/password
, or exceeded login rate
limit (~
3/min). Check credentials
or wait
.')
425 fb_dtsg = self._search_regex(
426 r'name
="fb_dtsg" value
="(.+?)"', login_results, 'fb_dtsg
', default=None)
427 h = self._search_regex(
428 r'name
="h"\s
+(?
:\w
+="[^"]+"\s+)*?value="([^
"]+)"', login_results, 'h
', default=None)
430 if not fb_dtsg or not h:
436 'name_action_selected
': 'dont_save
',
438 check_req = Request(self._CHECKPOINT_URL, urlencode_postdata(check_form))
439 check_req.headers['Content
-Type
'] = 'application
/x
-www
-form
-urlencoded
'
440 check_response = self._download_webpage(check_req, None,
441 note='Confirming login
')
442 if re.search(r'id="checkpointSubmitButton"', check_response) is not None:
443 self.report_warning('Unable to confirm login
, you have to login
in your browser
and authorize the login
.')
444 except network_exceptions as err:
445 self.report_warning('unable to log
in: %s' % error_to_compat_str(err))
448 def _extract_from_url(self, url, video_id):
449 webpage = self._download_webpage(
450 url.replace('://m
.facebook
.com
/', '://www
.facebook
.com
/'), video_id)
452 def extract_metadata(webpage):
453 post_data = [self._parse_json(j, video_id, fatal=False) for j in re.findall(
454 r'data
-sjs
>({.*?ScheduledServerJS.*?}
)</script
>', webpage)]
455 post = traverse_obj(post_data, (
456 ..., 'require
', ..., ..., ..., '__bbox
', 'require
', ..., ..., ..., '__bbox
', 'result
', 'data
'), expected_type=dict) or []
458 automatic_captions, subtitles = {}, {}
459 subs_data = traverse_obj(post, (..., 'video
', ..., 'attachments
', ..., lambda k, v: (
460 k == 'media
' and str(v['id']) == video_id and v['__typename
'] == 'Video
')))
461 is_video_broadcast = get_first(subs_data, 'is_video_broadcast
', expected_type=bool)
462 captions = get_first(subs_data, 'video_available_captions_locales
', 'captions_url
')
463 if url_or_none(captions): # if subs_data only had a 'captions_url
'
464 locale = self._html_search_meta(['og
:locale
', 'twitter
:locale
'], webpage, 'locale
', default='en_US
')
465 subtitles[locale] = [{'url': captions}]
466 # or else subs_data had 'video_available_captions_locales
', a list of dicts
467 for caption in traverse_obj(captions, (
468 {lambda x: sorted(x, key=lambda c: c['locale'])}, lambda _, v: v['captions_url
'])
470 lang = caption.get('localized_language
') or ''
472 'url
': caption['captions_url
'],
473 'name
': format_field(caption, 'localized_country
', f'{lang}
(%s)', default=lang),
475 if caption.get('localized_creation_method
') or is_video_broadcast:
476 automatic_captions.setdefault(caption['locale
'], []).append(subs)
478 subtitles.setdefault(caption['locale
'], []).append(subs)
480 media = traverse_obj(post, (..., 'attachments
', ..., lambda k, v: (
481 k == 'media
' and str(v['id']) == video_id and v['__typename
'] == 'Video
')), expected_type=dict)
482 title = get_first(media, ('title
', 'text
'))
483 description = get_first(media, ('creation_story
', 'comet_sections
', 'message
', 'story
', 'message
', 'text
'))
485 get_first(media, ('owner
', {dict}))
486 or get_first(post, (..., 'video
', lambda k, v: k == 'owner
' and v['name
']))
487 or get_first(post, ('node
', 'actors
', ..., {dict})) or {})
489 page_title = title or self._html_search_regex((
490 r'<h2\s
+[^
>]*class="uiHeaderTitle"[^
>]*>(?P
<content
>[^
<]*)</h2
>',
491 r'(?s
)<span
class="fbPhotosPhotoCaption".*?
id="fbPhotoPageCaption"><span
class="hasCaption">(?P
<content
>.*?
)</span
>',
492 self._meta_regex('og
:title
'), self._meta_regex('twitter
:title
'), r'<title
>(?P
<content
>.+?
)</title
>'
493 ), webpage, 'title
', default=None, group='content
')
494 description = description or self._html_search_meta(
495 ['description
', 'og
:description
', 'twitter
:description
'],
496 webpage, 'description
', default=None)
497 uploader = uploader_data.get('name
') or (
498 clean_html(get_element_by_id('fbPhotoPageAuthorName
', webpage))
499 or self._search_regex(
500 (r'ownerName\s
*:\s
*"([^"]+)"', *self._og_regexes('title')), webpage, 'uploader', fatal=False))
502 timestamp = int_or_none(self._search_regex(
503 r'<abbr[^>]+data-utime=["\'](\d
+)', webpage,
504 'timestamp
', default=None))
505 thumbnail = self._html_search_meta(
506 ['og
:image
', 'twitter
:image
'], webpage, 'thumbnail
', default=None)
507 # some webpages contain unretrievable thumbnail urls
508 # like https://lookaside.fbsbx.com/lookaside/crawler/media/?media_id=10155168902769113&get_thumbnail=1
509 # in https://www.facebook.com/yaroslav.korpan/videos/1417995061575415/
510 if thumbnail and not re.search(r'\
.(?
:jpg|png
)', thumbnail):
513 'description
': description,
514 'uploader
': uploader,
515 'uploader_id
': uploader_data.get('id'),
516 'timestamp
': timestamp,
517 'thumbnail
': thumbnail,
518 'view_count
': parse_count(self._search_regex(
519 (r'\bviewCount\s
*:\s
*["\']([\d,.]+)', r'video_view_count["\']\s
*:\s
*(\d
+)',),
520 webpage, 'view count
', default=None)),
521 'concurrent_view_count
': get_first(post, (
522 ('video
', (..., ..., 'attachments
', ..., 'media
')), 'liveViewerCount
', {int_or_none})),
523 'automatic_captions
': automatic_captions,
524 'subtitles
': subtitles,
527 info_json_ld = self._search_json_ld(webpage, video_id, default={})
528 info_json_ld['title
'] = (re.sub(r'\s
*\|\s
*Facebook$
', '', title or info_json_ld.get('title
') or page_title or '')
529 or (description or '').replace('\n', ' ') or f'Facebook video
#{video_id}')
530 return merge_dicts(info_json_ld
, info_dict
)
534 def extract_video_data(instances
):
536 for item
in instances
:
537 if try_get(item
, lambda x
: x
[1][0]) == 'VideoConfig':
538 video_item
= item
[2][0]
539 if video_item
.get('video_id'):
540 video_data
.append(video_item
['videoData'])
543 server_js_data
= self
._parse
_json
(self
._search
_regex
(
544 [r
'handleServerJS\(({.+})(?:\);|,")', r
'\bs\.handle\(({.+?})\);'],
545 webpage
, 'server js data', default
='{}'), video_id
, fatal
=False)
548 video_data
= extract_video_data(server_js_data
.get('instances', []))
550 def extract_from_jsmods_instances(js_data
):
552 return extract_video_data(try_get(
553 js_data
, lambda x
: x
['jsmods']['instances'], list) or [])
555 def extract_dash_manifest(video
, formats
):
556 dash_manifest
= video
.get('dash_manifest')
558 formats
.extend(self
._parse
_mpd
_formats
(
559 compat_etree_fromstring(urllib
.parse
.unquote_plus(dash_manifest
)),
560 mpd_url
=video
.get('dash_manifest_url')))
562 def process_formats(info
):
563 # Downloads with browser's User-Agent are rate limited. Working around
564 # with non-browser User-Agent.
565 for f
in info
['formats']:
566 f
.setdefault('http_headers', {})['User-Agent'] = 'facebookexternalhit/1.1'
568 def extract_relay_data(_filter
):
569 return self
._parse
_json
(self
._search
_regex
(
570 r
'data-sjs>({.*?%s.*?})</script>' % _filter
,
571 webpage
, 'replay data', default
='{}'), video_id, fatal=False) or {}
573 def extract_relay_prefetched_data(_filter):
574 return traverse_obj(extract_relay_data(_filter), (
575 'require
', (None, (..., ..., ..., '__bbox
', 'require
')),
576 lambda _, v: 'RelayPrefetchedStreamCache
' in v, ..., ...,
577 '__bbox
', 'result
', 'data
', {dict}), get_all=False) or {}
580 server_js_data = self._parse_json(self._search_regex([
581 r'bigPipe\
.onPageletArrive\
(({.+?}
)\
)\s
*;\s
*}\s
*\
)\s
*,\s
*["\']onPageletArrive\s+' + self._SUPPORTED_PAGLETS_REGEX,
582 r'bigPipe\.onPageletArrive\(({.*?id\s*:\s*"%s".*?})\);' % self._SUPPORTED_PAGLETS_REGEX
583 ], webpage, 'js data', default='{}'), video_id, js_to_json, False)
584 video_data = extract_from_jsmods_instances(server_js_data)
587 data = extract_relay_prefetched_data(
588 r'"(?
:dash_manifest|
playable_url(?
:_quality_hd
)?
)')
592 def parse_graphql_video(video):
593 v_id = video.get('videoId
') or video.get('id') or video_id
594 reel_info = traverse_obj(
595 video, ('creation_story
', 'short_form_video_context
', 'playback_video
', {dict}))
597 video = video['creation_story
']
598 video['owner
'] = traverse_obj(video, ('short_form_video_context
', 'video_owner
'))
599 video.update(reel_info)
601 q = qualities(['sd
', 'hd
'])
602 for key, format_id in (('playable_url
', 'sd
'), ('playable_url_quality_hd
', 'hd
'),
603 ('playable_url_dash
', ''), ('browser_native_hd_url
', 'hd
'),
604 ('browser_native_sd_url
', 'sd
')):
605 playable_url = video.get(key)
608 if determine_ext(playable_url) == 'mpd
':
609 formats.extend(self._extract_mpd_formats(playable_url, video_id))
612 'format_id
': format_id,
613 # sd, hd formats w/o resolution info should be deprioritized below DASH
614 'quality
': q(format_id) - 3,
617 extract_dash_manifest(video, formats)
621 'thumbnail
': traverse_obj(
622 video, ('thumbnailImage
', 'uri
'), ('preferred_thumbnail
', 'image
', 'uri
')),
623 'uploader_id
': traverse_obj(video, ('owner
', 'id', {str_or_none})),
624 'timestamp
': traverse_obj(video, 'publish_time
', 'creation_time
', expected_type=int_or_none),
625 'duration
': (float_or_none(video.get('playable_duration_in_ms
'), 1000)
626 or float_or_none(video.get('length_in_second
'))),
628 process_formats(info)
629 description = try_get(video, lambda x: x['savable_description
']['text
'])
630 title = video.get('name
')
634 'description
': description,
637 info['title
'] = description or 'Facebook video
#%s' % v_id
640 def parse_attachment(attachment
, key
='media'):
641 media
= attachment
.get(key
) or {}
642 if media
.get('__typename') == 'Video':
643 return parse_graphql_video(media
)
645 nodes
= variadic(traverse_obj(data
, 'nodes', 'node') or [])
646 attachments
= traverse_obj(nodes
, (
647 ..., 'comet_sections', 'content', 'story', (None, 'attached_story'), 'attachments',
648 ..., ('styles', 'style_type_renderer', ('throwbackStyles', 'attachment_target_renderer')),
649 'attachment', {dict}
))
650 for attachment
in attachments
:
651 ns
= traverse_obj(attachment
, ('all_subattachments', 'nodes', ..., {dict}
),
652 ('target', 'attachments', ..., 'styles', 'attachment', {dict}
))
655 parse_attachment(attachment
)
657 edges
= try_get(data
, lambda x
: x
['mediaset']['currMedia']['edges'], list) or []
659 parse_attachment(edge
, key
='node')
661 video
= data
.get('video') or {}
663 attachments
= try_get(video
, [
664 lambda x
: x
['story']['attachments'],
665 lambda x
: x
['creation_story']['attachments']
667 for attachment
in attachments
:
668 parse_attachment(attachment
)
670 parse_graphql_video(video
)
673 return self
.playlist_result(entries
, video_id
)
675 video_info
= entries
[0] if entries
else {'id': video_id}
676 webpage_info
= extract_metadata(webpage
)
677 # honor precise duration in video info
678 if video_info
.get('duration'):
679 webpage_info
['duration'] = video_info
['duration']
680 return merge_dicts(webpage_info
, video_info
)
683 m_msg
= re
.search(r
'class="[^"]*uiInterstitialContent[^"]*"><div>(.*?)</div>', webpage
)
684 if m_msg
is not None:
685 raise ExtractorError(
686 'The video is not available, Facebook said: "%s"' % m_msg
.group(1),
688 elif any(p
in webpage
for p
in (
689 '>You must log in to continue',
691 'id="loginbutton"')):
692 self
.raise_login_required()
694 if not video_data
and '/watchparty/' in url
:
696 'doc_id': 3731964053542869,
697 'variables': json
.dumps({
698 'livingRoomID': video_id
,
702 prefetched_data
= extract_relay_prefetched_data(r
'"login_data"\s*:\s*{')
704 lsd
= try_get(prefetched_data
, lambda x
: x
['login_data']['lsd'], dict)
706 post_data
[lsd
['name']] = lsd
['value']
708 relay_data
= extract_relay_data(r
'\[\s*"RelayAPIConfigDefaults"\s*,')
709 for define
in (relay_data
.get('define') or []):
710 if define
[0] == 'RelayAPIConfigDefaults':
711 self
._api
_config
= define
[2]
713 living_room
= self
._download
_json
(
714 urljoin(url
, self
._api
_config
['graphURI']), video_id
,
715 data
=urlencode_postdata(post_data
))['data']['living_room']
718 for edge
in (try_get(living_room
, lambda x
: x
['recap']['watched_content']['edges']) or []):
719 video
= try_get(edge
, lambda x
: x
['node']['video']) or {}
720 v_id
= video
.get('id')
723 v_id
= compat_str(v_id
)
724 entries
.append(self
.url_result(
725 self
._VIDEO
_PAGE
_TEMPLATE
% v_id
,
726 self
.ie_key(), v_id
, video
.get('name')))
728 return self
.playlist_result(entries
, video_id
)
731 # Video info not in first request, do a secondary request using
732 # tahoe player specific URL
733 tahoe_data
= self
._download
_webpage
(
734 self
._VIDEO
_PAGE
_TAHOE
_TEMPLATE
% video_id
, video_id
,
735 data
=urlencode_postdata({
737 '__pc': self
._search
_regex
(
738 r
'pkg_cohort["\']\s
*:\s
*["\'](.+?)["\']', webpage,
739 'pkg cohort
', default='PHASED
:DEFAULT
'),
740 '__rev
': self._search_regex(
741 r'client_revision
["\']\s*:\s*(\d+),', webpage,
742 'client revision', default='3944515'),
743 'fb_dtsg': self._search_regex(
744 r'"DTSGInitialData
"\s*,\s*\[\]\s*,\s*{\s*"token
"\s*:\s*"([^
"]+)"',
745 webpage, 'dtsg token
', default=''),
748 'Content
-Type
': 'application
/x
-www
-form
-urlencoded
',
750 tahoe_js_data = self._parse_json(
752 r'for\s
+\
(\s
*;\s
*;\s
*\
)\s
*;(.+)', tahoe_data,
753 'tahoe js data
', default='{}'),
754 video_id, fatal=False)
755 video_data = extract_from_jsmods_instances(tahoe_js_data)
758 raise ExtractorError('Cannot parse data
')
760 if len(video_data) > 1:
763 video_url = v[0].get('video_url
')
766 entries.append(self.url_result(urljoin(
767 url, video_url), self.ie_key(), v[0].get('video_id
')))
768 return self.playlist_result(entries, video_id)
769 video_data = video_data[0]
774 format_id = f['stream_type
']
775 if f and isinstance(f, dict):
777 if not f or not isinstance(f, list):
779 for quality in ('sd
', 'hd
'):
780 for src_type in ('src
', 'src_no_ratelimit
'):
781 src = f[0].get('%s_%s' % (quality, src_type))
783 # sd, hd formats w/o resolution info should be deprioritized below DASH
784 # TODO: investigate if progressive or src formats still exist
785 preference = -10 if format_id == 'progressive
' else -3
789 'format_id
': '%s_%s_%s' % (format_id, quality, src_type),
791 'quality
': preference,
792 'height
': 720 if quality == 'hd
' else None
794 extract_dash_manifest(f[0], formats)
795 subtitles_src = f[0].get('subtitles_src
')
797 subtitles.setdefault('en
', []).append({'url': subtitles_src})
802 'subtitles
': subtitles,
804 process_formats(info_dict)
805 info_dict.update(extract_metadata(webpage))
809 def _real_extract(self, url):
810 video_id = self._match_id(url)
812 real_url = self._VIDEO_PAGE_TEMPLATE % video_id if url.startswith('facebook
:') else url
813 return self._extract_from_url(real_url, video_id)
816 class FacebookPluginsVideoIE(InfoExtractor):
817 _VALID_URL = r'https?
://(?
:[\w
-]+\
.)?facebook\
.com
/plugins
/video\
.php
\?.*?
\bhref
=(?P
<id>https
.+)'
820 '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',
821 'md5
': '5954e92cdfe51fe5782ae9bda7058a07
',
823 'id': '10154383743583686',
825 # TODO: Fix title, uploader
826 'title
': 'What to do during the haze?
',
827 'uploader
': 'Gov
.sg
',
828 'upload_date
': '20160826',
829 'timestamp
': 1472184808,
831 'add_ie
': [FacebookIE.ie_key()],
833 'url
': 'https
://www
.facebook
.com
/plugins
/video
.php?href
=https
%3A
%2F
%2Fwww
.facebook
.com
%2Fvideo
.php
%3Fv
%3D10204634152394104
',
834 'only_matching
': True,
836 'url
': 'https
://www
.facebook
.com
/plugins
/video
.php?href
=https
://www
.facebook
.com
/gov
.sg
/videos
/10154383743583686/&show_text
=0&width
=560',
837 'only_matching
': True,
840 def _real_extract(self, url):
841 return self.url_result(
842 compat_urllib_parse_unquote(self._match_id(url)),
846 class FacebookRedirectURLIE(InfoExtractor):
847 IE_DESC = False # Do not list
848 _VALID_URL = r'https?
://(?
:[\w
-]+\
.)?facebook\
.com
/flx
/warn
[/?
]'
850 'url
': 'https
://www
.facebook
.com
/flx
/warn
/?h
=TAQHsoToz
&u
=https
%3A
%2F
%2Fwww
.youtube
.com
%2Fwatch
%3Fv
%3DpO8h3EaFRdo
&s
=1',
854 'title
': 'Tripeo Boiler Room x Dekmantel Festival DJ Set
',
855 'description
': 'md5
:2d713ccbb45b686a1888397b2c77ca6b
',
856 'channel_id
': 'UCGBpxWJr9FNOcFYA5GkKrMg
',
857 'playable_in_embed
': True,
858 'categories
': ['Music
'],
859 'channel
': 'Boiler Room
',
860 'uploader_id
': 'brtvofficial
',
861 'uploader
': 'Boiler Room
',
864 'live_status
': 'not_live
',
865 'thumbnail
': 'https
://i
.ytimg
.com
/vi
/pO8h3EaFRdo
/maxresdefault
.jpg
',
866 'channel_url
': 'https
://www
.youtube
.com
/channel
/UCGBpxWJr9FNOcFYA5GkKrMg
',
867 'availability
': 'public
',
868 'uploader_url
': 'http
://www
.youtube
.com
/user
/brtvofficial
',
869 'upload_date
': '20150917',
874 'add_ie
': ['Youtube
'],
875 'params
': {'skip_download': 'Youtube'},
878 def _real_extract(self, url):
879 redirect_url = url_or_none(parse_qs(url).get('u
', [None])[-1])
881 raise ExtractorError('Invalid facebook redirect URL
', expected=True)
882 return self.url_result(redirect_url)
885 class FacebookReelIE(InfoExtractor):
886 _VALID_URL = r'https?
://(?
:[\w
-]+\
.)?facebook\
.com
/reel
/(?P
<id>\d
+)'
887 IE_NAME = 'facebook
:reel
'
890 'url
': 'https
://www
.facebook
.com
/reel
/1195289147628387',
891 'md5
': 'f13dd37f2633595982db5ed8765474d3
',
893 'id': '1195289147628387',
895 'title
': 'md5
:b05800b5b1ad56c0ca78bd3807b6a61e
',
896 'description
': 'md5
:22f03309b216ac84720183961441d8db
',
897 'uploader
': 'md5
:723e6cb3091241160f20b3c5dc282af1
',
898 'uploader_id
': '100040874179269',
900 'timestamp
': 1637502609,
901 'upload_date
': '20211121',
902 'thumbnail
': r're
:^https?
://.*',
906 def _real_extract(self, url):
907 video_id = self._match_id(url)
908 return self.url_result(
909 f'https
://m
.facebook
.com
/watch
/?v
={video_id}
&_rdr
', FacebookIE, video_id)