]> jfr.im git - yt-dlp.git/blame - yt_dlp/extractor/facebook.py
[ie/Facebook] Fix Memories extraction (#8681)
[yt-dlp.git] / yt_dlp / extractor / facebook.py
CommitLineData
29f7c58a 1import json
9eae41dd 2import re
ac668111 3import urllib.parse
9eae41dd
PH
4
5from .common import InfoExtractor
8c25f81b 6from ..compat import (
0803753f 7 compat_etree_fromstring,
29f7c58a 8 compat_str,
d7011316 9 compat_urllib_parse_unquote,
8c25f81b 10)
3d2623a8 11from ..networking import Request
12from ..networking.exceptions import network_exceptions
8c25f81b 13from ..utils import (
ac668111 14 ExtractorError,
b83ef507 15 clean_html,
b8e976a4 16 determine_ext,
9b9c5355 17 error_to_compat_str,
29f7c58a 18 float_or_none,
9cafb9ff 19 format_field,
b83ef507 20 get_element_by_id,
ff91cf74 21 get_first,
196c6ba0 22 int_or_none,
b83ef507 23 js_to_json,
a181cd0c 24 merge_dicts,
11330f51 25 parse_count,
5f549d49 26 parse_qs,
29f7c58a 27 qualities,
bb5d84c9 28 str_or_none,
80fa6e53 29 traverse_obj,
b83ef507 30 try_get,
5f549d49 31 url_or_none,
2fc9f2b4 32 urlencode_postdata,
29f7c58a 33 urljoin,
b2db8102 34 variadic,
9eae41dd
PH
35)
36
37
38class FacebookIE(InfoExtractor):
9834872b 39 _VALID_URL = r'''(?x)
2e6e742c
S
40 (?:
41 https?://
61bfacb2 42 (?:[\w-]+\.)?(?:facebook\.com|facebookwkhpilnemxj7asaniu7vnjjbiltxjqhye3mhbshg7kx5tfyd\.onion)/
2e6e742c
S
43 (?:[^#]*?\#!/)?
44 (?:
45 (?:
46 video/video\.php|
47 photo\.php|
48 video\.php|
efbeddea 49 video/embed|
29f7c58a 50 story\.php|
51 watch(?:/live)?/?
efbeddea 52 )\?(?:.*?)(?:v|video_id|story_fbid)=|
9c7b509b 53 [^/]+/videos/(?:[^/]+/)?|
e738e433 54 [^/]+/posts/|
c39358a5 55 groups/[^/]+/(?:permalink|posts)/|
29f7c58a 56 watchparty/
2e6e742c
S
57 )|
58 facebook:
59 )
60 (?P<id>[0-9]+)
61 '''
bfd973ec 62 _EMBED_REGEX = [
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
65 r'''(?x)<div[^>]+
66 class=(?P<q1>[\'"])[^\'"]*\bfb-(?:video|post)\b[^\'"]*(?P=q1)[^>]+
67 data-href=(?P<q2>[\'"])(?P<url>(?:https?:)?//(?:www\.)?facebook.com/.+?)(?P=q2)''',
68 ]
67874aef
JMF
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'
9eae41dd 71 _NETRC_MACHINE = 'facebook'
cb3bb2cf 72 IE_NAME = 'facebook'
0803753f 73
9c7b509b 74 _VIDEO_PAGE_TEMPLATE = 'https://www.facebook.com/video/video.php?v=%s'
0df514f0 75 _VIDEO_PAGE_TAHOE_TEMPLATE = 'https://www.facebook.com/video/tahoe/async/%s/?chain=true&isvideo=true&payloadtype=primary'
9c7b509b 76
60ac04e5 77 _TESTS = [{
d3d81cc9 78 'url': 'https://www.facebook.com/radiokicksfm/videos/3676516585958356/',
79 'info_dict': {
80 'id': '3676516585958356',
81 'ext': 'mp4',
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',
89 'duration': 3132.184,
90 'view_count': int,
91 'concurrent_view_count': 0,
92 },
93 }, {
50317dbb
PH
94 'url': 'https://www.facebook.com/video.php?v=637842556329505&fref=nf',
95 'md5': '6a40d33c0eccbb1af76cf0485a052659',
cb3bb2cf 96 'info_dict': {
50317dbb 97 'id': '637842556329505',
cb3bb2cf 98 'ext': 'mp4',
5e4f0619 99 'title': 're:Did you know Kei Nishikori is the first Asian man to ever reach a Grand Slam',
67b8a28a 100 'uploader': 'Tennis on Facebook',
196c6ba0
S
101 'upload_date': '20140908',
102 'timestamp': 1410199200,
01c742ec
YCH
103 },
104 'skip': 'Requires logging in',
a020a0dc 105 }, {
29f7c58a 106 # data.video
a020a0dc
PH
107 'url': 'https://www.facebook.com/video.php?v=274175099429670',
108 'info_dict': {
109 'id': '274175099429670',
110 'ext': 'mp4',
bb5d84c9
VA
111 'title': 'Asif',
112 'description': '',
67b8a28a 113 'uploader': 'Asif Nawab Butt',
196c6ba0
S
114 'upload_date': '20140506',
115 'timestamp': 1399398998,
01c742ec 116 'thumbnail': r're:^https?://.*',
d3d81cc9 117 'uploader_id': 'pfbid028wxorhX2ErLFJ578N6P3crHD3PHmXTCqCvfBpsnbSLmbokwSY75p5hWBjHGkG4zxl',
bb5d84c9
VA
118 'duration': 131.03,
119 'concurrent_view_count': int,
db3ca364 120 },
0803753f
YCH
121 }, {
122 'note': 'Video with DASH manifest',
123 'url': 'https://www.facebook.com/video.php?v=957955867617029',
196c6ba0 124 'md5': 'b2c28d528273b323abe5c6ab59f0f030',
0803753f
YCH
125 'info_dict': {
126 'id': '957955867617029',
127 'ext': 'mp4',
128 'title': 'When you post epic content on instagram.com/433 8 million followers, this is ...',
129 'uploader': 'Demy de Zeeuw',
196c6ba0
S
130 'upload_date': '20160110',
131 'timestamp': 1452431627,
0803753f 132 },
01c742ec 133 'skip': 'Requires logging in',
9c7b509b
YCH
134 }, {
135 'url': 'https://www.facebook.com/maxlayn/posts/10153807558977570',
136 'md5': '037b1fa7f3c2d02b7a0d7bc16031ecc6',
137 'info_dict': {
138 'id': '544765982287235',
139 'ext': 'mp4',
140 'title': '"What are you doing running in the snow?"',
141 'uploader': 'FailArmy',
d9ee2e5c
YCH
142 },
143 'skip': 'Video gone',
98801241
YCH
144 }, {
145 'url': 'https://m.facebook.com/story.php?story_fbid=1035862816472149&id=116132035111903',
146 'md5': '1deb90b6ac27f7efcf6d747c8a27f5e3',
147 'info_dict': {
148 'id': '1035862816472149',
149 'ext': 'mp4',
150 'title': 'What the Flock Is Going On In New Zealand Credit: ViralHog',
151 'uploader': 'S. Saint',
152 },
d9ee2e5c 153 'skip': 'Video gone',
5080cbf9
YCH
154 }, {
155 'note': 'swf params escaped',
156 'url': 'https://www.facebook.com/barackobama/posts/10153664894881749',
157 'md5': '97ba073838964d12c70566e0085c2b91',
158 'info_dict': {
159 'id': '10153664894881749',
160 'ext': 'mp4',
01c742ec
YCH
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',
5080cbf9 166 },
a181cd0c 167 'skip': 'Gif on giphy.com gone',
d9ee2e5c
YCH
168 }, {
169 # have 1080P, but only up to 720p in swf params
29f7c58a 170 # data.video.story.attachments[].media
d9ee2e5c 171 'url': 'https://www.facebook.com/cnn/videos/10155529876156509/',
bb5d84c9 172 'md5': 'ca63897a90c9452efee5f8c40d080e25',
d9ee2e5c
YCH
173 'info_dict': {
174 'id': '10155529876156509',
175 'ext': 'mp4',
a181cd0c 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',
d9ee2e5c
YCH
178 'timestamp': 1477818095,
179 'upload_date': '20161030',
180 'uploader': 'CNN',
01c742ec 181 'thumbnail': r're:^https?://.*',
11330f51 182 'view_count': int,
bb5d84c9
VA
183 'uploader_id': '100059479812265',
184 'concurrent_view_count': int,
185 'duration': 44.478,
d9ee2e5c 186 },
78ef214d
S
187 }, {
188 # bigPipe.onPageletArrive ... onPageletArrive pagelet_group_mall
29f7c58a 189 # data.node.comet_sections.content.story.attachments[].style_type_renderer.attachment.media
78ef214d
S
190 'url': 'https://www.facebook.com/yaroslav.korpan/videos/1417995061575415/',
191 'info_dict': {
192 'id': '1417995061575415',
193 'ext': 'mp4',
bb5d84c9 194 'title': 'Довгоочікуване відео | By Yaroslav - Facebook',
a181cd0c 195 'description': 'Довгоочікуване відео',
bb5d84c9 196 'timestamp': 1486648217,
78ef214d
S
197 'upload_date': '20170209',
198 'uploader': 'Yaroslav Korpan',
d3d81cc9 199 'uploader_id': 'pfbid06AScABAWcW91qpiuGrLt99Ef9tvwHoXP6t8KeFYEqkSfreMtfa9nTveh8b2ZEVSWl',
bb5d84c9
VA
200 'concurrent_view_count': int,
201 'thumbnail': r're:^https?://.*',
202 'view_count': int,
203 'duration': 11736.446,
78ef214d
S
204 },
205 'params': {
206 'skip_download': True,
207 },
71cdd756 208 }, {
a181cd0c 209 # FIXME
71cdd756
S
210 'url': 'https://www.facebook.com/LaGuiaDelVaron/posts/1072691702860471',
211 'info_dict': {
212 'id': '1072691702860471',
213 'ext': 'mp4',
214 'title': 'md5:ae2d22a93fbb12dad20dc393a869739d',
215 'timestamp': 1477305000,
216 'upload_date': '20161024',
217 'uploader': 'La Guía Del Varón',
01c742ec 218 'thumbnail': r're:^https?://.*',
71cdd756 219 },
bb5d84c9 220 'skip': 'Requires logging in',
71cdd756 221 }, {
29f7c58a 222 # data.node.comet_sections.content.story.attachments[].style_type_renderer.attachment.media
71cdd756
S
223 'url': 'https://www.facebook.com/groups/1024490957622648/permalink/1396382447100162/',
224 'info_dict': {
a181cd0c 225 'id': '202882990186699',
71cdd756 226 'ext': 'mp4',
b2db8102 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...',
a181cd0c 229 'timestamp': 1486035513,
71cdd756
S
230 'upload_date': '20170202',
231 'uploader': 'Elisabeth Ahtn',
a181cd0c 232 'uploader_id': '100013949973717',
71cdd756 233 },
bb5d84c9 234 'skip': 'Requires logging in',
c39358a5 235 }, {
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/',
238 'info_dict': {
239 'id': '1569199726448814',
240 'ext': 'mp4',
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?://.*',
248 'duration': 148.435,
249 },
60ac04e5
PH
250 }, {
251 'url': 'https://www.facebook.com/video.php?v=10204634152394104',
252 'only_matching': True,
c6256697
YCH
253 }, {
254 'url': 'https://www.facebook.com/amogood/videos/1618742068337349/?fref=nf',
255 'only_matching': True,
53faa3ca 256 }, {
29f7c58a 257 # data.mediaset.currMedia.edges
53faa3ca
YCH
258 'url': 'https://www.facebook.com/ChristyClarkForBC/videos/vb.22819070941/10153870694020942/?type=2&theater',
259 'only_matching': True,
2e6e742c 260 }, {
29f7c58a 261 # data.video.story.attachments[].media
2e6e742c
S
262 'url': 'facebook:544765982287235',
263 'only_matching': True,
e738e433 264 }, {
29f7c58a 265 # data.node.comet_sections.content.story.attachments[].style_type_renderer.attachment.media
e738e433
YCH
266 'url': 'https://www.facebook.com/groups/164828000315060/permalink/764967300301124/',
267 'only_matching': True,
b4a131e1 268 }, {
29f7c58a 269 # data.video.creation_story.attachments[].media
b4a131e1
S
270 'url': 'https://zh-hk.facebook.com/peoplespower/videos/1135894589806027/',
271 'only_matching': True,
30918999 272 }, {
29f7c58a 273 # data.video
61bfacb2 274 'url': 'https://www.facebookwkhpilnemxj7asaniu7vnjjbiltxjqhye3mhbshg7kx5tfyd.onion/video.php?v=274175099429670',
30918999 275 'only_matching': True,
66bf351f
S
276 }, {
277 # no title
278 'url': 'https://www.facebook.com/onlycleverentertainment/videos/1947995502095005/',
279 'only_matching': True,
9d082e7c 280 }, {
29f7c58a 281 # data.video
9d082e7c
NR
282 'url': 'https://www.facebook.com/WatchESLOne/videos/359649331226507/',
283 'info_dict': {
284 'id': '359649331226507',
285 'ext': 'mp4',
a181cd0c 286 'title': 'Fnatic vs. EG - Group A - Opening Match - ESL One Birmingham Day 1',
287 'description': '#ESLOne VoD - Birmingham Finals Day#1 Fnatic vs. @Evil Geniuses',
288 'timestamp': 1527084179,
289 'upload_date': '20180523',
9d082e7c 290 'uploader': 'ESL One Dota 2',
bb5d84c9
VA
291 'uploader_id': '100066514874195',
292 'duration': 4524.212,
293 'view_count': int,
294 'thumbnail': r're:^https?://.*',
295 'concurrent_view_count': int,
9d082e7c
NR
296 },
297 'params': {
298 'skip_download': True,
299 },
29f7c58a 300 }, {
301 # data.node.comet_sections.content.story.attachments[].style_type_renderer.attachment.all_subattachments.nodes[].media
302 'url': 'https://www.facebook.com/100033620354545/videos/106560053808006/',
303 'info_dict': {
304 'id': '106560053808006',
bb5d84c9
VA
305 'ext': 'mp4',
306 'title': 'Josef',
307 'thumbnail': r're:^https?://.*',
308 'concurrent_view_count': int,
d3d81cc9 309 'uploader_id': 'pfbid0cibUN6tV7DYgdbJdsUFN46wc4jKpVSPAvJQhFofGqBGmVn3V3JtAs2tfUwziw2hUl',
bb5d84c9
VA
310 'timestamp': 1549275572,
311 'duration': 3.413,
312 'uploader': 'Josef Novak',
313 'description': '',
314 'upload_date': '20190204',
29f7c58a 315 },
29f7c58a 316 }, {
317 # data.video.story.attachments[].media
318 'url': 'https://www.facebook.com/watch/?v=647537299265662',
319 'only_matching': True,
320 }, {
a181cd0c 321 # FIXME: https://github.com/yt-dlp/yt-dlp/issues/542
29f7c58a 322 # data.node.comet_sections.content.story.attachments[].style_type_renderer.attachment.all_subattachments.nodes[].media
323 'url': 'https://www.facebook.com/PankajShahLondon/posts/10157667649866271',
324 'info_dict': {
325 'id': '10157667649866271',
326 },
327 'playlist_count': 3,
bb5d84c9 328 'skip': 'Requires logging in',
29f7c58a 329 }, {
330 # data.nodes[].comet_sections.content.story.attachments[].style_type_renderer.attachment.media
331 'url': 'https://m.facebook.com/Alliance.Police.Department/posts/4048563708499330',
332 'info_dict': {
333 'id': '117576630041613',
334 'ext': 'mp4',
335 # TODO: title can be extracted from video page
336 'title': 'Facebook video #117576630041613',
337 'uploader_id': '189393014416438',
338 'upload_date': '20201123',
339 'timestamp': 1606162592,
340 },
341 'skip': 'Requires logging in',
342 }, {
343 # node.comet_sections.content.story.attached_story.attachments.style_type_renderer.attachment.media
344 'url': 'https://www.facebook.com/groups/ateistiskselskab/permalink/10154930137678856/',
345 'info_dict': {
346 'id': '211567722618337',
347 'ext': 'mp4',
348 'title': 'Facebook video #211567722618337',
349 'uploader_id': '127875227654254',
350 'upload_date': '20161122',
351 'timestamp': 1479793574,
352 },
a181cd0c 353 'skip': 'No video',
29f7c58a 354 }, {
355 # data.video.creation_story.attachments[].media
356 'url': 'https://www.facebook.com/watch/live/?v=1823658634322275',
357 'only_matching': True,
358 }, {
359 'url': 'https://www.facebook.com/watchparty/211641140192478',
360 'info_dict': {
361 'id': '211641140192478',
362 },
363 'playlist_count': 1,
364 'skip': 'Requires logging in',
60ac04e5 365 }]
29f7c58a 366 _SUPPORTED_PAGLETS_REGEX = r'(?:pagelet_group_mall|permalink_video_pagelet|hyperfeed_story_id_[0-9a-f]+)'
367 _api_config = {
368 'graphURI': '/api/graphql/'
369 }
9eae41dd 370
52efa4b3 371 def _perform_login(self, username, password):
3d2623a8 372 login_page_req = Request(self._LOGIN_URL)
c1f49e16 373 self._set_cookie('facebook.com', 'locale', 'en_US')
b74fa8cd 374 login_page = self._download_webpage(login_page_req, None,
9e1a5b84
JW
375 note='Downloading login page',
376 errnote='Unable to download login page')
b37b9450 377 lsd = self._search_regex(
d0ff8384 378 r'<input type="hidden" name="lsd" value="([^"]*)"',
b37b9450 379 login_page, 'lsd')
cb3bb2cf 380 lgnrnd = self._search_regex(r'name="lgnrnd" value="([^"]*?)"', login_page, 'lgnrnd')
67874aef 381
9eae41dd 382 login_form = {
52efa4b3 383 'email': username,
9eae41dd 384 'pass': password,
67874aef
JMF
385 'lsd': lsd,
386 'lgnrnd': lgnrnd,
387 'next': 'http://facebook.com/home.php',
388 'default_persistent': '0',
389 'legacy_return': '1',
390 'timezone': '-60',
391 'trynum': '1',
b74e86f4 392 }
3d2623a8 393 request = Request(self._LOGIN_URL, urlencode_postdata(login_form))
394 request.headers['Content-Type'] = 'application/x-www-form-urlencoded'
9eae41dd 395 try:
b74fa8cd 396 login_results = self._download_webpage(request, None,
9e1a5b84 397 note='Logging in', errnote='unable to fetch login page')
9eae41dd 398 if re.search(r'<form(.*)name="login"(.*)</form>', login_results) is not None:
9f66931e
S
399 error = self._html_search_regex(
400 r'(?s)<div[^>]+class=(["\']).*?login_error_box.*?\1[^>]*><div[^>]*>.*?</div><div[^>]*>(?P<error>.+?)</div>',
401 login_results, 'login error', default=None, group='error')
402 if error:
403 raise ExtractorError('Unable to login: %s' % error, expected=True)
6a39ee13 404 self.report_warning('unable to log in: bad username/password, or exceeded login rate limit (~3/min). Check credentials or wait.')
9eae41dd 405 return
67874aef 406
c1f49e16
S
407 fb_dtsg = self._search_regex(
408 r'name="fb_dtsg" value="(.+?)"', login_results, 'fb_dtsg', default=None)
409 h = self._search_regex(
410 r'name="h"\s+(?:\w+="[^"]+"\s+)*?value="([^"]+)"', login_results, 'h', default=None)
411
412 if not fb_dtsg or not h:
413 return
414
67874aef 415 check_form = {
c1f49e16
S
416 'fb_dtsg': fb_dtsg,
417 'h': h,
67874aef 418 'name_action_selected': 'dont_save',
67874aef 419 }
3d2623a8 420 check_req = Request(self._CHECKPOINT_URL, urlencode_postdata(check_form))
421 check_req.headers['Content-Type'] = 'application/x-www-form-urlencoded'
b74fa8cd 422 check_response = self._download_webpage(check_req, None,
9e1a5b84 423 note='Confirming login')
67874aef 424 if re.search(r'id="checkpointSubmitButton"', check_response) is not None:
6a39ee13 425 self.report_warning('Unable to confirm login, you have to login in your browser and authorize the login.')
3158150c 426 except network_exceptions as err:
6a39ee13 427 self.report_warning('unable to log in: %s' % error_to_compat_str(err))
9eae41dd
PH
428 return
429
29f7c58a 430 def _extract_from_url(self, url, video_id):
431 webpage = self._download_webpage(
432 url.replace('://m.facebook.com/', '://www.facebook.com/'), video_id)
9eae41dd 433
a181cd0c 434 def extract_metadata(webpage):
b2db8102 435 post_data = [self._parse_json(j, video_id, fatal=False) for j in re.findall(
d3d81cc9 436 r'data-sjs>({.*?ScheduledServerJS.*?})</script>', webpage)]
b2db8102 437 post = traverse_obj(post_data, (
d3d81cc9 438 ..., 'require', ..., ..., ..., '__bbox', 'require', ..., ..., ..., '__bbox', 'result', 'data'), expected_type=dict) or []
9cafb9ff 439
440 automatic_captions, subtitles = {}, {}
441 subs_data = traverse_obj(post, (..., 'video', ..., 'attachments', ..., lambda k, v: (
442 k == 'media' and str(v['id']) == video_id and v['__typename'] == 'Video')))
443 is_video_broadcast = get_first(subs_data, 'is_video_broadcast', expected_type=bool)
444 captions = get_first(subs_data, 'video_available_captions_locales', 'captions_url')
445 if url_or_none(captions): # if subs_data only had a 'captions_url'
446 locale = self._html_search_meta(['og:locale', 'twitter:locale'], webpage, 'locale', default='en_US')
447 subtitles[locale] = [{'url': captions}]
448 # or else subs_data had 'video_available_captions_locales', a list of dicts
449 for caption in traverse_obj(captions, (
450 {lambda x: sorted(x, key=lambda c: c['locale'])}, lambda _, v: v['captions_url'])
451 ):
452 lang = caption.get('localized_language') or ''
453 subs = {
454 'url': caption['captions_url'],
455 'name': format_field(caption, 'localized_country', f'{lang} (%s)', default=lang),
456 }
457 if caption.get('localized_creation_method') or is_video_broadcast:
458 automatic_captions.setdefault(caption['locale'], []).append(subs)
459 else:
460 subtitles.setdefault(caption['locale'], []).append(subs)
461
1e9969f4 462 media = traverse_obj(post, (..., 'attachments', ..., lambda k, v: (
463 k == 'media' and str(v['id']) == video_id and v['__typename'] == 'Video')), expected_type=dict)
ff91cf74 464 title = get_first(media, ('title', 'text'))
465 description = get_first(media, ('creation_story', 'comet_sections', 'message', 'story', 'message', 'text'))
3b52a606 466 uploader_data = (
467 get_first(media, ('owner', {dict}))
468 or get_first(post, (..., 'video', lambda k, v: k == 'owner' and v['name']))
469 or get_first(post, ('node', 'actors', ..., {dict})) or {})
80fa6e53 470
b2db8102 471 page_title = title or self._html_search_regex((
80fa6e53 472 r'<h2\s+[^>]*class="uiHeaderTitle"[^>]*>(?P<content>[^<]*)</h2>',
473 r'(?s)<span class="fbPhotosPhotoCaption".*?id="fbPhotoPageCaption"><span class="hasCaption">(?P<content>.*?)</span>',
b2db8102 474 self._meta_regex('og:title'), self._meta_regex('twitter:title'), r'<title>(?P<content>.+?)</title>'
80fa6e53 475 ), webpage, 'title', default=None, group='content')
476 description = description or self._html_search_meta(
a181cd0c 477 ['description', 'og:description', 'twitter:description'],
478 webpage, 'description', default=None)
b2db8102 479 uploader = uploader_data.get('name') or (
80fa6e53 480 clean_html(get_element_by_id('fbPhotoPageAuthorName', webpage))
481 or self._search_regex(
482 (r'ownerName\s*:\s*"([^"]+)"', *self._og_regexes('title')), webpage, 'uploader', fatal=False))
483
a181cd0c 484 timestamp = int_or_none(self._search_regex(
485 r'<abbr[^>]+data-utime=["\'](\d+)', webpage,
486 'timestamp', default=None))
487 thumbnail = self._html_search_meta(
488 ['og:image', 'twitter:image'], webpage, 'thumbnail', default=None)
489 # some webpages contain unretrievable thumbnail urls
490 # like https://lookaside.fbsbx.com/lookaside/crawler/media/?media_id=10155168902769113&get_thumbnail=1
491 # in https://www.facebook.com/yaroslav.korpan/videos/1417995061575415/
492 if thumbnail and not re.search(r'\.(?:jpg|png)', thumbnail):
493 thumbnail = None
a181cd0c 494 info_dict = {
a181cd0c 495 'description': description,
496 'uploader': uploader,
b2db8102 497 'uploader_id': uploader_data.get('id'),
a181cd0c 498 'timestamp': timestamp,
499 'thumbnail': thumbnail,
3b52a606 500 'view_count': parse_count(self._search_regex(
501 (r'\bviewCount\s*:\s*["\']([\d,.]+)', r'video_view_count["\']\s*:\s*(\d+)',),
502 webpage, 'view count', default=None)),
503 'concurrent_view_count': get_first(post, (
504 ('video', (..., ..., 'attachments', ..., 'media')), 'liveViewerCount', {int_or_none})),
9cafb9ff 505 'automatic_captions': automatic_captions,
506 'subtitles': subtitles,
a181cd0c 507 }
b2db8102 508
a181cd0c 509 info_json_ld = self._search_json_ld(webpage, video_id, default={})
b2db8102 510 info_json_ld['title'] = (re.sub(r'\s*\|\s*Facebook$', '', title or info_json_ld.get('title') or page_title or '')
511 or (description or '').replace('\n', ' ') or f'Facebook video #{video_id}')
a181cd0c 512 return merge_dicts(info_json_ld, info_dict)
513
c1406299
YCH
514 video_data = None
515
b83ef507 516 def extract_video_data(instances):
29f7c58a 517 video_data = []
b83ef507 518 for item in instances:
29f7c58a 519 if try_get(item, lambda x: x[1][0]) == 'VideoConfig':
b83ef507 520 video_item = item[2][0]
71cdd756 521 if video_item.get('video_id'):
29f7c58a 522 video_data.append(video_item['videoData'])
523 return video_data
b83ef507 524
d9ee2e5c 525 server_js_data = self._parse_json(self._search_regex(
29f7c58a 526 [r'handleServerJS\(({.+})(?:\);|,")', r'\bs\.handle\(({.+?})\);'],
527 webpage, 'server js data', default='{}'), video_id, fatal=False)
b83ef507
S
528
529 if server_js_data:
530 video_data = extract_video_data(server_js_data.get('instances', []))
531
9b89daef
S
532 def extract_from_jsmods_instances(js_data):
533 if js_data:
534 return extract_video_data(try_get(
535 js_data, lambda x: x['jsmods']['instances'], list) or [])
536
29f7c58a 537 def extract_dash_manifest(video, formats):
538 dash_manifest = video.get('dash_manifest')
539 if dash_manifest:
540 formats.extend(self._parse_mpd_formats(
a854fbec 541 compat_etree_fromstring(urllib.parse.unquote_plus(dash_manifest)),
542 mpd_url=video.get('dash_manifest_url')))
29f7c58a 543
9f14daf2 544 def process_formats(info):
29f7c58a 545 # Downloads with browser's User-Agent are rate limited. Working around
546 # with non-browser User-Agent.
9f14daf2 547 for f in info['formats']:
29f7c58a 548 f.setdefault('http_headers', {})['User-Agent'] = 'facebookexternalhit/1.1'
29f7c58a 549
550 def extract_relay_data(_filter):
551 return self._parse_json(self._search_regex(
d3d81cc9 552 r'data-sjs>({.*?%s.*?})</script>' % _filter,
29f7c58a 553 webpage, 'replay data', default='{}'), video_id, fatal=False) or {}
554
555 def extract_relay_prefetched_data(_filter):
d3d81cc9 556 return traverse_obj(extract_relay_data(_filter), (
557 'require', (None, (..., ..., ..., '__bbox', 'require')),
558 lambda _, v: 'RelayPrefetchedStreamCache' in v, ..., ...,
559 '__bbox', 'result', 'data', {dict}), get_all=False) or {}
29f7c58a 560
b83ef507 561 if not video_data:
29f7c58a 562 server_js_data = self._parse_json(self._search_regex([
563 r'bigPipe\.onPageletArrive\(({.+?})\)\s*;\s*}\s*\)\s*,\s*["\']onPageletArrive\s+' + self._SUPPORTED_PAGLETS_REGEX,
564 r'bigPipe\.onPageletArrive\(({.*?id\s*:\s*"%s".*?})\);' % self._SUPPORTED_PAGLETS_REGEX
565 ], webpage, 'js data', default='{}'), video_id, js_to_json, False)
9b89daef 566 video_data = extract_from_jsmods_instances(server_js_data)
c1406299 567
9d082e7c 568 if not video_data:
29f7c58a 569 data = extract_relay_prefetched_data(
d3d81cc9 570 r'"(?:dash_manifest|playable_url(?:_quality_hd)?)')
29f7c58a 571 if data:
572 entries = []
573
574 def parse_graphql_video(video):
bb5d84c9
VA
575 v_id = video.get('videoId') or video.get('id') or video_id
576 reel_info = traverse_obj(
577 video, ('creation_story', 'short_form_video_context', 'playback_video', {dict}))
578 if reel_info:
579 video = video['creation_story']
580 video['owner'] = traverse_obj(video, ('short_form_video_context', 'video_owner'))
581 video.update(reel_info)
29f7c58a 582 formats = []
583 q = qualities(['sd', 'hd'])
b8e976a4 584 for key, format_id in (('playable_url', 'sd'), ('playable_url_quality_hd', 'hd'),
d3d81cc9 585 ('playable_url_dash', ''), ('browser_native_hd_url', 'hd'),
586 ('browser_native_sd_url', 'sd')):
b8e976a4 587 playable_url = video.get(key)
29f7c58a 588 if not playable_url:
589 continue
b8e976a4 590 if determine_ext(playable_url) == 'mpd':
591 formats.extend(self._extract_mpd_formats(playable_url, video_id))
592 else:
593 formats.append({
594 'format_id': format_id,
30893661 595 # sd, hd formats w/o resolution info should be deprioritized below DASH
596 'quality': q(format_id) - 3,
b8e976a4 597 'url': playable_url,
598 })
29f7c58a 599 extract_dash_manifest(video, formats)
29f7c58a 600 info = {
601 'id': v_id,
602 'formats': formats,
cda1bc51
A
603 'thumbnail': traverse_obj(
604 video, ('thumbnailImage', 'uri'), ('preferred_thumbnail', 'image', 'uri')),
bb5d84c9
VA
605 'uploader_id': traverse_obj(video, ('owner', 'id', {str_or_none})),
606 'timestamp': traverse_obj(video, 'publish_time', 'creation_time', expected_type=int_or_none),
607 'duration': (float_or_none(video.get('playable_duration_in_ms'), 1000)
608 or float_or_none(video.get('length_in_second'))),
29f7c58a 609 }
9f14daf2 610 process_formats(info)
29f7c58a 611 description = try_get(video, lambda x: x['savable_description']['text'])
612 title = video.get('name')
613 if title:
614 info.update({
615 'title': title,
616 'description': description,
617 })
618 else:
619 info['title'] = description or 'Facebook video #%s' % v_id
620 entries.append(info)
621
622 def parse_attachment(attachment, key='media'):
623 media = attachment.get(key) or {}
624 if media.get('__typename') == 'Video':
625 return parse_graphql_video(media)
626
b2db8102 627 nodes = variadic(traverse_obj(data, 'nodes', 'node') or [])
628 attachments = traverse_obj(nodes, (
629 ..., 'comet_sections', 'content', 'story', (None, 'attached_story'), 'attachments',
c39358a5 630 ..., ('styles', 'style_type_renderer', ('throwbackStyles', 'attachment_target_renderer')),
631 'attachment', {dict}))
b2db8102 632 for attachment in attachments:
c39358a5 633 ns = traverse_obj(attachment, ('all_subattachments', 'nodes', ..., {dict}),
634 ('target', 'attachments', ..., 'styles', 'attachment', {dict}))
b2db8102 635 for n in ns:
636 parse_attachment(n)
637 parse_attachment(attachment)
29f7c58a 638
639 edges = try_get(data, lambda x: x['mediaset']['currMedia']['edges'], list) or []
640 for edge in edges:
641 parse_attachment(edge, key='node')
642
643 video = data.get('video') or {}
644 if video:
645 attachments = try_get(video, [
646 lambda x: x['story']['attachments'],
647 lambda x: x['creation_story']['attachments']
648 ], list) or []
649 for attachment in attachments:
650 parse_attachment(attachment)
651 if not entries:
652 parse_graphql_video(video)
653
a181cd0c 654 if len(entries) > 1:
655 return self.playlist_result(entries, video_id)
656
c39358a5 657 video_info = entries[0] if entries else {'id': video_id}
a181cd0c 658 webpage_info = extract_metadata(webpage)
659 # honor precise duration in video info
660 if video_info.get('duration'):
661 webpage_info['duration'] = video_info['duration']
662 return merge_dicts(webpage_info, video_info)
29f7c58a 663
664 if not video_data:
9b89daef
S
665 m_msg = re.search(r'class="[^"]*uiInterstitialContent[^"]*"><div>(.*?)</div>', webpage)
666 if m_msg is not None:
667 raise ExtractorError(
668 'The video is not available, Facebook said: "%s"' % m_msg.group(1),
669 expected=True)
46358f64 670 elif any(p in webpage for p in (
671 '>You must log in to continue',
672 'id="login_form"',
673 'id="loginbutton"')):
9b89daef
S
674 self.raise_login_required()
675
29f7c58a 676 if not video_data and '/watchparty/' in url:
677 post_data = {
678 'doc_id': 3731964053542869,
679 'variables': json.dumps({
680 'livingRoomID': video_id,
681 }),
682 }
683
684 prefetched_data = extract_relay_prefetched_data(r'"login_data"\s*:\s*{')
685 if prefetched_data:
686 lsd = try_get(prefetched_data, lambda x: x['login_data']['lsd'], dict)
687 if lsd:
688 post_data[lsd['name']] = lsd['value']
689
690 relay_data = extract_relay_data(r'\[\s*"RelayAPIConfigDefaults"\s*,')
691 for define in (relay_data.get('define') or []):
692 if define[0] == 'RelayAPIConfigDefaults':
693 self._api_config = define[2]
694
695 living_room = self._download_json(
696 urljoin(url, self._api_config['graphURI']), video_id,
697 data=urlencode_postdata(post_data))['data']['living_room']
698
699 entries = []
700 for edge in (try_get(living_room, lambda x: x['recap']['watched_content']['edges']) or []):
701 video = try_get(edge, lambda x: x['node']['video']) or {}
702 v_id = video.get('id')
703 if not v_id:
704 continue
705 v_id = compat_str(v_id)
706 entries.append(self.url_result(
707 self._VIDEO_PAGE_TEMPLATE % v_id,
708 self.ie_key(), v_id, video.get('name')))
709
710 return self.playlist_result(entries, video_id)
711
712 if not video_data:
9b89daef
S
713 # Video info not in first request, do a secondary request using
714 # tahoe player specific URL
9d082e7c
NR
715 tahoe_data = self._download_webpage(
716 self._VIDEO_PAGE_TAHOE_TEMPLATE % video_id, video_id,
717 data=urlencode_postdata({
9d082e7c 718 '__a': 1,
9b89daef
S
719 '__pc': self._search_regex(
720 r'pkg_cohort["\']\s*:\s*["\'](.+?)["\']', webpage,
721 'pkg cohort', default='PHASED:DEFAULT'),
722 '__rev': self._search_regex(
723 r'client_revision["\']\s*:\s*(\d+),', webpage,
724 'client revision', default='3944515'),
631f93ee
RA
725 'fb_dtsg': self._search_regex(
726 r'"DTSGInitialData"\s*,\s*\[\]\s*,\s*{\s*"token"\s*:\s*"([^"]+)"',
727 webpage, 'dtsg token', default=''),
9d082e7c
NR
728 }),
729 headers={
730 'Content-Type': 'application/x-www-form-urlencoded',
731 })
9b89daef
S
732 tahoe_js_data = self._parse_json(
733 self._search_regex(
734 r'for\s+\(\s*;\s*;\s*\)\s*;(.+)', tahoe_data,
735 'tahoe js data', default='{}'),
736 video_id, fatal=False)
737 video_data = extract_from_jsmods_instances(tahoe_js_data)
9d082e7c 738
c1406299 739 if not video_data:
9b89daef 740 raise ExtractorError('Cannot parse data')
ffdf972b 741
29f7c58a 742 if len(video_data) > 1:
743 entries = []
744 for v in video_data:
745 video_url = v[0].get('video_url')
746 if not video_url:
747 continue
748 entries.append(self.url_result(urljoin(
749 url, video_url), self.ie_key(), v[0].get('video_id')))
750 return self.playlist_result(entries, video_id)
751 video_data = video_data[0]
752
ffdf972b 753 formats = []
29f7c58a 754 subtitles = {}
d9ee2e5c
YCH
755 for f in video_data:
756 format_id = f['stream_type']
ca74c90b
SC
757 if f and isinstance(f, dict):
758 f = [f]
44d6dd08
S
759 if not f or not isinstance(f, list):
760 continue
761 for quality in ('sd', 'hd'):
762 for src_type in ('src', 'src_no_ratelimit'):
763 src = f[0].get('%s_%s' % (quality, src_type))
764 if src:
30893661 765 # sd, hd formats w/o resolution info should be deprioritized below DASH
766 # TODO: investigate if progressive or src formats still exist
767 preference = -10 if format_id == 'progressive' else -3
c24883a1 768 if quality == 'hd':
30893661 769 preference += 1
44d6dd08
S
770 formats.append({
771 'format_id': '%s_%s_%s' % (format_id, quality, src_type),
772 'url': src,
f983b875 773 'quality': preference,
8a2d9923 774 'height': 720 if quality == 'hd' else None
44d6dd08 775 })
29f7c58a 776 extract_dash_manifest(f[0], formats)
07154c79
RA
777 subtitles_src = f[0].get('subtitles_src')
778 if subtitles_src:
779 subtitles.setdefault('en', []).append({'url': subtitles_src})
9eae41dd 780
9c7b509b 781 info_dict = {
9eae41dd 782 'id': video_id,
ffdf972b 783 'formats': formats,
07154c79 784 'subtitles': subtitles,
9eae41dd 785 }
9f14daf2 786 process_formats(info_dict)
a181cd0c 787 info_dict.update(extract_metadata(webpage))
de691a49 788
29f7c58a 789 return info_dict
de691a49
S
790
791 def _real_extract(self, url):
9c7b509b
YCH
792 video_id = self._match_id(url)
793
794 real_url = self._VIDEO_PAGE_TEMPLATE % video_id if url.startswith('facebook:') else url
29f7c58a 795 return self._extract_from_url(real_url, video_id)
349fc5c7
S
796
797
798class FacebookPluginsVideoIE(InfoExtractor):
799 _VALID_URL = r'https?://(?:[\w-]+\.)?facebook\.com/plugins/video\.php\?.*?\bhref=(?P<id>https.+)'
800
801 _TESTS = [{
802 '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',
803 'md5': '5954e92cdfe51fe5782ae9bda7058a07',
804 'info_dict': {
805 'id': '10154383743583686',
806 'ext': 'mp4',
b2db8102 807 # TODO: Fix title, uploader
349fc5c7
S
808 'title': 'What to do during the haze?',
809 'uploader': 'Gov.sg',
810 'upload_date': '20160826',
811 'timestamp': 1472184808,
812 },
813 'add_ie': [FacebookIE.ie_key()],
814 }, {
815 'url': 'https://www.facebook.com/plugins/video.php?href=https%3A%2F%2Fwww.facebook.com%2Fvideo.php%3Fv%3D10204634152394104',
816 'only_matching': True,
817 }, {
818 'url': 'https://www.facebook.com/plugins/video.php?href=https://www.facebook.com/gov.sg/videos/10154383743583686/&show_text=0&width=560',
819 'only_matching': True,
820 }]
821
822 def _real_extract(self, url):
823 return self.url_result(
824 compat_urllib_parse_unquote(self._match_id(url)),
825 FacebookIE.ie_key())
5f549d49 826
827
828class FacebookRedirectURLIE(InfoExtractor):
829 IE_DESC = False # Do not list
830 _VALID_URL = r'https?://(?:[\w-]+\.)?facebook\.com/flx/warn[/?]'
831 _TESTS = [{
832 'url': 'https://www.facebook.com/flx/warn/?h=TAQHsoToz&u=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DpO8h3EaFRdo&s=1',
833 'info_dict': {
834 'id': 'pO8h3EaFRdo',
835 'ext': 'mp4',
836 'title': 'Tripeo Boiler Room x Dekmantel Festival DJ Set',
837 'description': 'md5:2d713ccbb45b686a1888397b2c77ca6b',
838 'channel_id': 'UCGBpxWJr9FNOcFYA5GkKrMg',
839 'playable_in_embed': True,
840 'categories': ['Music'],
841 'channel': 'Boiler Room',
842 'uploader_id': 'brtvofficial',
843 'uploader': 'Boiler Room',
844 'tags': 'count:11',
845 'duration': 3332,
846 'live_status': 'not_live',
847 'thumbnail': 'https://i.ytimg.com/vi/pO8h3EaFRdo/maxresdefault.jpg',
848 'channel_url': 'https://www.youtube.com/channel/UCGBpxWJr9FNOcFYA5GkKrMg',
849 'availability': 'public',
850 'uploader_url': 'http://www.youtube.com/user/brtvofficial',
851 'upload_date': '20150917',
852 'age_limit': 0,
853 'view_count': int,
854 'like_count': int,
855 },
856 'add_ie': ['Youtube'],
857 'params': {'skip_download': 'Youtube'},
858 }]
859
860 def _real_extract(self, url):
861 redirect_url = url_or_none(parse_qs(url).get('u', [None])[-1])
862 if not redirect_url:
863 raise ExtractorError('Invalid facebook redirect URL', expected=True)
864 return self.url_result(redirect_url)
63be30e3 865
866
867class FacebookReelIE(InfoExtractor):
868 _VALID_URL = r'https?://(?:[\w-]+\.)?facebook\.com/reel/(?P<id>\d+)'
869 IE_NAME = 'facebook:reel'
870
871 _TESTS = [{
872 'url': 'https://www.facebook.com/reel/1195289147628387',
bb5d84c9 873 'md5': 'f13dd37f2633595982db5ed8765474d3',
63be30e3 874 'info_dict': {
875 'id': '1195289147628387',
876 'ext': 'mp4',
bb5d84c9
VA
877 'title': 'md5:b05800b5b1ad56c0ca78bd3807b6a61e',
878 'description': 'md5:22f03309b216ac84720183961441d8db',
879 'uploader': 'md5:723e6cb3091241160f20b3c5dc282af1',
880 'uploader_id': '100040874179269',
881 'duration': 9.579,
882 'timestamp': 1637502609,
63be30e3 883 'upload_date': '20211121',
bb5d84c9 884 'thumbnail': r're:^https?://.*',
63be30e3 885 }
886 }]
887
888 def _real_extract(self, url):
889 video_id = self._match_id(url)
890 return self.url_result(
891 f'https://m.facebook.com/watch/?v={video_id}&_rdr', FacebookIE, video_id)