]> jfr.im git - yt-dlp.git/blame - yt_dlp/extractor/facebook.py
[cleanup] Add more ruff rules (#10149)
[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
add96eb9 6from ..compat import compat_etree_fromstring
3d2623a8 7from ..networking import Request
8from ..networking.exceptions import network_exceptions
8c25f81b 9from ..utils import (
ac668111 10 ExtractorError,
b83ef507 11 clean_html,
b8e976a4 12 determine_ext,
29f7c58a 13 float_or_none,
9cafb9ff 14 format_field,
b83ef507 15 get_element_by_id,
ff91cf74 16 get_first,
196c6ba0 17 int_or_none,
a40b0070 18 join_nonempty,
b83ef507 19 js_to_json,
a181cd0c 20 merge_dicts,
11330f51 21 parse_count,
5f549d49 22 parse_qs,
29f7c58a 23 qualities,
bb5d84c9 24 str_or_none,
80fa6e53 25 traverse_obj,
b83ef507 26 try_get,
5f549d49 27 url_or_none,
2fc9f2b4 28 urlencode_postdata,
29f7c58a 29 urljoin,
b2db8102 30 variadic,
9eae41dd
PH
31)
32
33
34class FacebookIE(InfoExtractor):
9834872b 35 _VALID_URL = r'''(?x)
2e6e742c
S
36 (?:
37 https?://
61bfacb2 38 (?:[\w-]+\.)?(?:facebook\.com|facebookwkhpilnemxj7asaniu7vnjjbiltxjqhye3mhbshg7kx5tfyd\.onion)/
2e6e742c
S
39 (?:[^#]*?\#!/)?
40 (?:
41 (?:
87286e93 42 permalink\.php|
2e6e742c
S
43 video/video\.php|
44 photo\.php|
45 video\.php|
efbeddea 46 video/embed|
29f7c58a 47 story\.php|
48 watch(?:/live)?/?
efbeddea 49 )\?(?:.*?)(?:v|video_id|story_fbid)=|
9c7b509b 50 [^/]+/videos/(?:[^/]+/)?|
e738e433 51 [^/]+/posts/|
9b5efaf8 52 events/(?:[^/]+/)?|
c39358a5 53 groups/[^/]+/(?:permalink|posts)/|
29f7c58a 54 watchparty/
2e6e742c
S
55 )|
56 facebook:
57 )
cf9af2c7 58 (?P<id>pfbid[A-Za-z0-9]+|\d+)
2e6e742c 59 '''
bfd973ec 60 _EMBED_REGEX = [
61 r'<iframe[^>]+?src=(["\'])(?P<url>https?://www\.facebook\.com/(?:video/embed|plugins/video\.php).+?)\1',
62 # Facebook API embed https://developers.facebook.com/docs/plugins/embedded-video-player
63 r'''(?x)<div[^>]+
64 class=(?P<q1>[\'"])[^\'"]*\bfb-(?:video|post)\b[^\'"]*(?P=q1)[^>]+
65 data-href=(?P<q2>[\'"])(?P<url>(?:https?:)?//(?:www\.)?facebook.com/.+?)(?P=q2)''',
66 ]
67874aef
JMF
67 _LOGIN_URL = 'https://www.facebook.com/login.php?next=http%3A%2F%2Ffacebook.com%2Fhome.php&login_attempt=1'
68 _CHECKPOINT_URL = 'https://www.facebook.com/checkpoint/?next=http%3A%2F%2Ffacebook.com%2Fhome.php&_fb_noscript=1'
9eae41dd 69 _NETRC_MACHINE = 'facebook'
cb3bb2cf 70 IE_NAME = 'facebook'
0803753f 71
9c7b509b 72 _VIDEO_PAGE_TEMPLATE = 'https://www.facebook.com/video/video.php?v=%s'
0df514f0 73 _VIDEO_PAGE_TAHOE_TEMPLATE = 'https://www.facebook.com/video/tahoe/async/%s/?chain=true&isvideo=true&payloadtype=primary'
9c7b509b 74
60ac04e5 75 _TESTS = [{
d3d81cc9 76 'url': 'https://www.facebook.com/radiokicksfm/videos/3676516585958356/',
77 'info_dict': {
78 'id': '3676516585958356',
79 'ext': 'mp4',
80 'title': 'dr Adam Przygoda',
81 'description': 'md5:34675bda53336b1d16400265c2bb9b3b',
82 'uploader': 'RADIO KICKS FM',
83 'upload_date': '20230818',
84 'timestamp': 1692346159,
85 'thumbnail': r're:^https?://.*',
86 'uploader_id': '100063551323670',
87 'duration': 3132.184,
88 'view_count': int,
89 'concurrent_view_count': 0,
90 },
91 }, {
50317dbb
PH
92 'url': 'https://www.facebook.com/video.php?v=637842556329505&fref=nf',
93 'md5': '6a40d33c0eccbb1af76cf0485a052659',
cb3bb2cf 94 'info_dict': {
50317dbb 95 'id': '637842556329505',
cb3bb2cf 96 'ext': 'mp4',
5e4f0619 97 'title': 're:Did you know Kei Nishikori is the first Asian man to ever reach a Grand Slam',
67b8a28a 98 'uploader': 'Tennis on Facebook',
196c6ba0
S
99 'upload_date': '20140908',
100 'timestamp': 1410199200,
01c742ec
YCH
101 },
102 'skip': 'Requires logging in',
a020a0dc 103 }, {
29f7c58a 104 # data.video
a020a0dc
PH
105 'url': 'https://www.facebook.com/video.php?v=274175099429670',
106 'info_dict': {
107 'id': '274175099429670',
108 'ext': 'mp4',
bb5d84c9
VA
109 'title': 'Asif',
110 'description': '',
67b8a28a 111 'uploader': 'Asif Nawab Butt',
196c6ba0
S
112 'upload_date': '20140506',
113 'timestamp': 1399398998,
01c742ec 114 'thumbnail': r're:^https?://.*',
d3d81cc9 115 'uploader_id': 'pfbid028wxorhX2ErLFJ578N6P3crHD3PHmXTCqCvfBpsnbSLmbokwSY75p5hWBjHGkG4zxl',
bb5d84c9
VA
116 'duration': 131.03,
117 'concurrent_view_count': int,
db3ca364 118 },
0803753f
YCH
119 }, {
120 'note': 'Video with DASH manifest',
121 'url': 'https://www.facebook.com/video.php?v=957955867617029',
196c6ba0 122 'md5': 'b2c28d528273b323abe5c6ab59f0f030',
0803753f
YCH
123 'info_dict': {
124 'id': '957955867617029',
125 'ext': 'mp4',
126 'title': 'When you post epic content on instagram.com/433 8 million followers, this is ...',
127 'uploader': 'Demy de Zeeuw',
196c6ba0
S
128 'upload_date': '20160110',
129 'timestamp': 1452431627,
0803753f 130 },
01c742ec 131 'skip': 'Requires logging in',
9c7b509b
YCH
132 }, {
133 'url': 'https://www.facebook.com/maxlayn/posts/10153807558977570',
134 'md5': '037b1fa7f3c2d02b7a0d7bc16031ecc6',
135 'info_dict': {
136 'id': '544765982287235',
137 'ext': 'mp4',
138 'title': '"What are you doing running in the snow?"',
139 'uploader': 'FailArmy',
d9ee2e5c
YCH
140 },
141 'skip': 'Video gone',
98801241
YCH
142 }, {
143 'url': 'https://m.facebook.com/story.php?story_fbid=1035862816472149&id=116132035111903',
144 'md5': '1deb90b6ac27f7efcf6d747c8a27f5e3',
145 'info_dict': {
146 'id': '1035862816472149',
147 'ext': 'mp4',
148 'title': 'What the Flock Is Going On In New Zealand Credit: ViralHog',
149 'uploader': 'S. Saint',
150 },
d9ee2e5c 151 'skip': 'Video gone',
5080cbf9
YCH
152 }, {
153 'note': 'swf params escaped',
154 'url': 'https://www.facebook.com/barackobama/posts/10153664894881749',
155 'md5': '97ba073838964d12c70566e0085c2b91',
156 'info_dict': {
157 'id': '10153664894881749',
158 'ext': 'mp4',
01c742ec
YCH
159 'title': 'Average time to confirm recent Supreme Court nominees: 67 days Longest it\'s t...',
160 'thumbnail': r're:^https?://.*',
161 'timestamp': 1456259628,
162 'upload_date': '20160223',
163 'uploader': 'Barack Obama',
5080cbf9 164 },
a181cd0c 165 'skip': 'Gif on giphy.com gone',
d9ee2e5c
YCH
166 }, {
167 # have 1080P, but only up to 720p in swf params
29f7c58a 168 # data.video.story.attachments[].media
d9ee2e5c 169 'url': 'https://www.facebook.com/cnn/videos/10155529876156509/',
bb5d84c9 170 'md5': 'ca63897a90c9452efee5f8c40d080e25',
d9ee2e5c
YCH
171 'info_dict': {
172 'id': '10155529876156509',
173 'ext': 'mp4',
a181cd0c 174 'title': 'Holocaust survivor becomes US citizen',
175 'description': 'She survived the holocaust — and years later, she’s getting her citizenship so she can vote for Hillary Clinton http://cnn.it/2eERh5f',
d9ee2e5c
YCH
176 'timestamp': 1477818095,
177 'upload_date': '20161030',
178 'uploader': 'CNN',
01c742ec 179 'thumbnail': r're:^https?://.*',
11330f51 180 'view_count': int,
bb5d84c9
VA
181 'uploader_id': '100059479812265',
182 'concurrent_view_count': int,
183 'duration': 44.478,
d9ee2e5c 184 },
78ef214d
S
185 }, {
186 # bigPipe.onPageletArrive ... onPageletArrive pagelet_group_mall
29f7c58a 187 # data.node.comet_sections.content.story.attachments[].style_type_renderer.attachment.media
78ef214d
S
188 'url': 'https://www.facebook.com/yaroslav.korpan/videos/1417995061575415/',
189 'info_dict': {
190 'id': '1417995061575415',
191 'ext': 'mp4',
bb5d84c9 192 'title': 'Довгоочікуване відео | By Yaroslav - Facebook',
a181cd0c 193 'description': 'Довгоочікуване відео',
bb5d84c9 194 'timestamp': 1486648217,
78ef214d
S
195 'upload_date': '20170209',
196 'uploader': 'Yaroslav Korpan',
d3d81cc9 197 'uploader_id': 'pfbid06AScABAWcW91qpiuGrLt99Ef9tvwHoXP6t8KeFYEqkSfreMtfa9nTveh8b2ZEVSWl',
bb5d84c9
VA
198 'concurrent_view_count': int,
199 'thumbnail': r're:^https?://.*',
200 'view_count': int,
201 'duration': 11736.446,
78ef214d
S
202 },
203 'params': {
204 'skip_download': True,
205 },
71cdd756 206 }, {
add96eb9 207 # FIXME: Cannot parse data error
71cdd756
S
208 'url': 'https://www.facebook.com/LaGuiaDelVaron/posts/1072691702860471',
209 'info_dict': {
210 'id': '1072691702860471',
211 'ext': 'mp4',
212 'title': 'md5:ae2d22a93fbb12dad20dc393a869739d',
213 'timestamp': 1477305000,
214 'upload_date': '20161024',
215 'uploader': 'La Guía Del Varón',
01c742ec 216 'thumbnail': r're:^https?://.*',
71cdd756 217 },
bb5d84c9 218 'skip': 'Requires logging in',
71cdd756 219 }, {
29f7c58a 220 # data.node.comet_sections.content.story.attachments[].style_type_renderer.attachment.media
71cdd756
S
221 'url': 'https://www.facebook.com/groups/1024490957622648/permalink/1396382447100162/',
222 'info_dict': {
a181cd0c 223 'id': '202882990186699',
71cdd756 224 'ext': 'mp4',
b2db8102 225 'title': 'birb (O v O") | Hello? Yes your uber ride is here',
226 'description': 'Hello? Yes your uber ride is here * Jukin Media Verified * Find this video and others like it by visiting...',
a181cd0c 227 'timestamp': 1486035513,
71cdd756
S
228 'upload_date': '20170202',
229 'uploader': 'Elisabeth Ahtn',
a181cd0c 230 'uploader_id': '100013949973717',
71cdd756 231 },
bb5d84c9 232 'skip': 'Requires logging in',
c39358a5 233 }, {
234 # data.node.comet_sections.content.story.attachments[].throwbackStyles.attachment_target_renderer.attachment.target.attachments[].styles.attachment.media
235 'url': 'https://www.facebook.com/groups/1645456212344334/posts/3737828833107051/',
236 'info_dict': {
237 'id': '1569199726448814',
238 'ext': 'mp4',
239 'title': 'Pence MUST GO!',
240 'description': 'Vickie Gentry shared a memory.',
241 'timestamp': 1511548260,
242 'upload_date': '20171124',
243 'uploader': 'Vickie Gentry',
244 'uploader_id': 'pfbid0FuZhHCeWDAxWxEbr3yKPFaRstXvRxgsp9uCPG6GjD4J2AitB35NUAuJ4Q75KcjiDl',
245 'thumbnail': r're:^https?://.*',
246 'duration': 148.435,
247 },
cf9af2c7 248 }, {
87286e93 249 # data.node.comet_sections.content.story.attachments[].styles.attachment.media
cf9af2c7
A
250 'url': 'https://www.facebook.com/attn/posts/pfbid0j1Czf2gGDVqeQ8KiMLFm3pWN8GxsQmeRrVhimWDzMuKQoR8r4b1knNsejELmUgyhl',
251 'info_dict': {
252 'id': '6968553779868435',
253 'ext': 'mp4',
254 'description': 'md5:2f2fcf93e97ac00244fe64521bbdb0cb',
255 'uploader': 'ATTN:',
256 'upload_date': '20231207',
257 'title': 'ATTN:',
258 'duration': 132.675,
259 'uploader_id': '100064451419378',
260 'view_count': int,
261 'thumbnail': r're:^https?://.*',
262 'timestamp': 1701975646,
263 },
87286e93 264 }, {
265 # data.node.comet_sections.content.story.attachments[].styles.attachment.media
266 'url': 'https://www.facebook.com/permalink.php?story_fbid=pfbid0fqQuVEQyXRa9Dp4RcaTR14KHU3uULHV1EK7eckNXSH63JMuoALsAvVCJ97zAGitil&id=100068861234290',
267 'info_dict': {
268 'id': '270103405756416',
269 'ext': 'mp4',
270 'title': 'Lela Evans',
271 'description': 'Today Makkovik\'s own Pilot Mandy Smith made her inaugural landing on the airstrip in her hometown. What a proud moment as we all cheered and...',
272 'thumbnail': r're:^https?://.*',
273 'uploader': 'Lela Evans',
274 'uploader_id': 'pfbid0shZJipuigyy5mqrUJn9ub5LJFWNHvan5prtyi3LrDuuuJ4NwrURgnQHYR9fywBepl',
275 'upload_date': '20231228',
276 'timestamp': 1703804085,
277 'duration': 394.347,
278 'view_count': int,
279 },
cf9af2c7
A
280 }, {
281 'url': 'https://www.facebook.com/story.php?story_fbid=pfbid0Fnzhm8UuzjBYpPMNFzaSpFE9UmLdU4fJN8qTANi1Dmtj5q7DNrL5NERXfsAzDEV7l&id=100073071055552',
282 'only_matching': True,
60ac04e5
PH
283 }, {
284 'url': 'https://www.facebook.com/video.php?v=10204634152394104',
285 'only_matching': True,
c6256697
YCH
286 }, {
287 'url': 'https://www.facebook.com/amogood/videos/1618742068337349/?fref=nf',
288 'only_matching': True,
53faa3ca 289 }, {
29f7c58a 290 # data.mediaset.currMedia.edges
53faa3ca
YCH
291 'url': 'https://www.facebook.com/ChristyClarkForBC/videos/vb.22819070941/10153870694020942/?type=2&theater',
292 'only_matching': True,
2e6e742c 293 }, {
29f7c58a 294 # data.video.story.attachments[].media
2e6e742c
S
295 'url': 'facebook:544765982287235',
296 'only_matching': True,
e738e433 297 }, {
29f7c58a 298 # data.node.comet_sections.content.story.attachments[].style_type_renderer.attachment.media
e738e433
YCH
299 'url': 'https://www.facebook.com/groups/164828000315060/permalink/764967300301124/',
300 'only_matching': True,
b4a131e1 301 }, {
29f7c58a 302 # data.video.creation_story.attachments[].media
b4a131e1
S
303 'url': 'https://zh-hk.facebook.com/peoplespower/videos/1135894589806027/',
304 'only_matching': True,
30918999 305 }, {
29f7c58a 306 # data.video
61bfacb2 307 'url': 'https://www.facebookwkhpilnemxj7asaniu7vnjjbiltxjqhye3mhbshg7kx5tfyd.onion/video.php?v=274175099429670',
30918999 308 'only_matching': True,
66bf351f
S
309 }, {
310 # no title
311 'url': 'https://www.facebook.com/onlycleverentertainment/videos/1947995502095005/',
312 'only_matching': True,
9d082e7c 313 }, {
29f7c58a 314 # data.video
9d082e7c
NR
315 'url': 'https://www.facebook.com/WatchESLOne/videos/359649331226507/',
316 'info_dict': {
317 'id': '359649331226507',
318 'ext': 'mp4',
a181cd0c 319 'title': 'Fnatic vs. EG - Group A - Opening Match - ESL One Birmingham Day 1',
320 'description': '#ESLOne VoD - Birmingham Finals Day#1 Fnatic vs. @Evil Geniuses',
321 'timestamp': 1527084179,
322 'upload_date': '20180523',
9d082e7c 323 'uploader': 'ESL One Dota 2',
bb5d84c9
VA
324 'uploader_id': '100066514874195',
325 'duration': 4524.212,
326 'view_count': int,
327 'thumbnail': r're:^https?://.*',
328 'concurrent_view_count': int,
9d082e7c
NR
329 },
330 'params': {
331 'skip_download': True,
332 },
29f7c58a 333 }, {
334 # data.node.comet_sections.content.story.attachments[].style_type_renderer.attachment.all_subattachments.nodes[].media
335 'url': 'https://www.facebook.com/100033620354545/videos/106560053808006/',
336 'info_dict': {
337 'id': '106560053808006',
bb5d84c9
VA
338 'ext': 'mp4',
339 'title': 'Josef',
340 'thumbnail': r're:^https?://.*',
341 'concurrent_view_count': int,
d3d81cc9 342 'uploader_id': 'pfbid0cibUN6tV7DYgdbJdsUFN46wc4jKpVSPAvJQhFofGqBGmVn3V3JtAs2tfUwziw2hUl',
bb5d84c9
VA
343 'timestamp': 1549275572,
344 'duration': 3.413,
345 'uploader': 'Josef Novak',
346 'description': '',
347 'upload_date': '20190204',
29f7c58a 348 },
29f7c58a 349 }, {
350 # data.video.story.attachments[].media
351 'url': 'https://www.facebook.com/watch/?v=647537299265662',
352 'only_matching': True,
353 }, {
a181cd0c 354 # FIXME: https://github.com/yt-dlp/yt-dlp/issues/542
29f7c58a 355 # data.node.comet_sections.content.story.attachments[].style_type_renderer.attachment.all_subattachments.nodes[].media
356 'url': 'https://www.facebook.com/PankajShahLondon/posts/10157667649866271',
357 'info_dict': {
358 'id': '10157667649866271',
359 },
360 'playlist_count': 3,
bb5d84c9 361 'skip': 'Requires logging in',
29f7c58a 362 }, {
363 # data.nodes[].comet_sections.content.story.attachments[].style_type_renderer.attachment.media
364 'url': 'https://m.facebook.com/Alliance.Police.Department/posts/4048563708499330',
365 'info_dict': {
366 'id': '117576630041613',
367 'ext': 'mp4',
368 # TODO: title can be extracted from video page
369 'title': 'Facebook video #117576630041613',
370 'uploader_id': '189393014416438',
371 'upload_date': '20201123',
372 'timestamp': 1606162592,
373 },
374 'skip': 'Requires logging in',
375 }, {
376 # node.comet_sections.content.story.attached_story.attachments.style_type_renderer.attachment.media
377 'url': 'https://www.facebook.com/groups/ateistiskselskab/permalink/10154930137678856/',
378 'info_dict': {
379 'id': '211567722618337',
380 'ext': 'mp4',
381 'title': 'Facebook video #211567722618337',
382 'uploader_id': '127875227654254',
383 'upload_date': '20161122',
384 'timestamp': 1479793574,
385 },
a181cd0c 386 'skip': 'No video',
29f7c58a 387 }, {
388 # data.video.creation_story.attachments[].media
389 'url': 'https://www.facebook.com/watch/live/?v=1823658634322275',
390 'only_matching': True,
391 }, {
392 'url': 'https://www.facebook.com/watchparty/211641140192478',
393 'info_dict': {
394 'id': '211641140192478',
395 },
396 'playlist_count': 1,
397 'skip': 'Requires logging in',
9b5efaf8 398 }, {
399 # data.event.cover_media_renderer.cover_video
400 'url': 'https://m.facebook.com/events/1509582499515440',
401 'info_dict': {
402 'id': '637246984455045',
403 'ext': 'mp4',
404 'title': 'ANALISI IN CAMPO OSCURO " Coaguli nel sangue dei vaccinati"',
405 'description': 'Other event by Comitato Liberi Pensatori on Tuesday, October 18 2022',
406 'thumbnail': r're:^https?://.*',
407 'uploader': 'Comitato Liberi Pensatori',
408 'uploader_id': '100065709540881',
409 },
60ac04e5 410 }]
29f7c58a 411 _SUPPORTED_PAGLETS_REGEX = r'(?:pagelet_group_mall|permalink_video_pagelet|hyperfeed_story_id_[0-9a-f]+)'
412 _api_config = {
add96eb9 413 'graphURI': '/api/graphql/',
29f7c58a 414 }
9eae41dd 415
52efa4b3 416 def _perform_login(self, username, password):
3d2623a8 417 login_page_req = Request(self._LOGIN_URL)
c1f49e16 418 self._set_cookie('facebook.com', 'locale', 'en_US')
b74fa8cd 419 login_page = self._download_webpage(login_page_req, None,
9e1a5b84
JW
420 note='Downloading login page',
421 errnote='Unable to download login page')
b37b9450 422 lsd = self._search_regex(
d0ff8384 423 r'<input type="hidden" name="lsd" value="([^"]*)"',
b37b9450 424 login_page, 'lsd')
cb3bb2cf 425 lgnrnd = self._search_regex(r'name="lgnrnd" value="([^"]*?)"', login_page, 'lgnrnd')
67874aef 426
9eae41dd 427 login_form = {
52efa4b3 428 'email': username,
9eae41dd 429 'pass': password,
67874aef
JMF
430 'lsd': lsd,
431 'lgnrnd': lgnrnd,
432 'next': 'http://facebook.com/home.php',
433 'default_persistent': '0',
434 'legacy_return': '1',
435 'timezone': '-60',
436 'trynum': '1',
b74e86f4 437 }
3d2623a8 438 request = Request(self._LOGIN_URL, urlencode_postdata(login_form))
439 request.headers['Content-Type'] = 'application/x-www-form-urlencoded'
9eae41dd 440 try:
b74fa8cd 441 login_results = self._download_webpage(request, None,
9e1a5b84 442 note='Logging in', errnote='unable to fetch login page')
9eae41dd 443 if re.search(r'<form(.*)name="login"(.*)</form>', login_results) is not None:
9f66931e
S
444 error = self._html_search_regex(
445 r'(?s)<div[^>]+class=(["\']).*?login_error_box.*?\1[^>]*><div[^>]*>.*?</div><div[^>]*>(?P<error>.+?)</div>',
446 login_results, 'login error', default=None, group='error')
447 if error:
add96eb9 448 raise ExtractorError(f'Unable to login: {error}', expected=True)
6a39ee13 449 self.report_warning('unable to log in: bad username/password, or exceeded login rate limit (~3/min). Check credentials or wait.')
9eae41dd 450 return
67874aef 451
c1f49e16
S
452 fb_dtsg = self._search_regex(
453 r'name="fb_dtsg" value="(.+?)"', login_results, 'fb_dtsg', default=None)
454 h = self._search_regex(
455 r'name="h"\s+(?:\w+="[^"]+"\s+)*?value="([^"]+)"', login_results, 'h', default=None)
456
457 if not fb_dtsg or not h:
458 return
459
67874aef 460 check_form = {
c1f49e16
S
461 'fb_dtsg': fb_dtsg,
462 'h': h,
67874aef 463 'name_action_selected': 'dont_save',
67874aef 464 }
3d2623a8 465 check_req = Request(self._CHECKPOINT_URL, urlencode_postdata(check_form))
466 check_req.headers['Content-Type'] = 'application/x-www-form-urlencoded'
b74fa8cd 467 check_response = self._download_webpage(check_req, None,
9e1a5b84 468 note='Confirming login')
67874aef 469 if re.search(r'id="checkpointSubmitButton"', check_response) is not None:
6a39ee13 470 self.report_warning('Unable to confirm login, you have to login in your browser and authorize the login.')
3158150c 471 except network_exceptions as err:
add96eb9 472 self.report_warning(f'unable to log in: {err}')
9eae41dd
PH
473 return
474
29f7c58a 475 def _extract_from_url(self, url, video_id):
476 webpage = self._download_webpage(
477 url.replace('://m.facebook.com/', '://www.facebook.com/'), video_id)
9eae41dd 478
a181cd0c 479 def extract_metadata(webpage):
b2db8102 480 post_data = [self._parse_json(j, video_id, fatal=False) for j in re.findall(
d3d81cc9 481 r'data-sjs>({.*?ScheduledServerJS.*?})</script>', webpage)]
b2db8102 482 post = traverse_obj(post_data, (
d3d81cc9 483 ..., 'require', ..., ..., ..., '__bbox', 'require', ..., ..., ..., '__bbox', 'result', 'data'), expected_type=dict) or []
1e9969f4 484 media = traverse_obj(post, (..., 'attachments', ..., lambda k, v: (
485 k == 'media' and str(v['id']) == video_id and v['__typename'] == 'Video')), expected_type=dict)
ff91cf74 486 title = get_first(media, ('title', 'text'))
487 description = get_first(media, ('creation_story', 'comet_sections', 'message', 'story', 'message', 'text'))
b2db8102 488 page_title = title or self._html_search_regex((
80fa6e53 489 r'<h2\s+[^>]*class="uiHeaderTitle"[^>]*>(?P<content>[^<]*)</h2>',
490 r'(?s)<span class="fbPhotosPhotoCaption".*?id="fbPhotoPageCaption"><span class="hasCaption">(?P<content>.*?)</span>',
add96eb9 491 self._meta_regex('og:title'), self._meta_regex('twitter:title'), r'<title>(?P<content>.+?)</title>',
80fa6e53 492 ), webpage, 'title', default=None, group='content')
493 description = description or self._html_search_meta(
a181cd0c 494 ['description', 'og:description', 'twitter:description'],
495 webpage, 'description', default=None)
9b5efaf8 496 uploader_data = (
497 get_first(media, ('owner', {dict}))
2e30b556 498 or get_first(post, ('video', 'creation_story', 'attachments', ..., 'media', lambda k, v: k == 'owner' and v['name']))
9b5efaf8 499 or get_first(post, (..., 'video', lambda k, v: k == 'owner' and v['name']))
500 or get_first(post, ('node', 'actors', ..., {dict}))
501 or get_first(post, ('event', 'event_creator', {dict})) or {})
b2db8102 502 uploader = uploader_data.get('name') or (
80fa6e53 503 clean_html(get_element_by_id('fbPhotoPageAuthorName', webpage))
504 or self._search_regex(
505 (r'ownerName\s*:\s*"([^"]+)"', *self._og_regexes('title')), webpage, 'uploader', fatal=False))
a181cd0c 506 timestamp = int_or_none(self._search_regex(
507 r'<abbr[^>]+data-utime=["\'](\d+)', webpage,
508 'timestamp', default=None))
509 thumbnail = self._html_search_meta(
510 ['og:image', 'twitter:image'], webpage, 'thumbnail', default=None)
511 # some webpages contain unretrievable thumbnail urls
512 # like https://lookaside.fbsbx.com/lookaside/crawler/media/?media_id=10155168902769113&get_thumbnail=1
513 # in https://www.facebook.com/yaroslav.korpan/videos/1417995061575415/
514 if thumbnail and not re.search(r'\.(?:jpg|png)', thumbnail):
515 thumbnail = None
a181cd0c 516 info_dict = {
a181cd0c 517 'description': description,
518 'uploader': uploader,
b2db8102 519 'uploader_id': uploader_data.get('id'),
a181cd0c 520 'timestamp': timestamp,
521 'thumbnail': thumbnail,
3b52a606 522 'view_count': parse_count(self._search_regex(
add96eb9 523 (r'\bviewCount\s*:\s*["\']([\d,.]+)', r'video_view_count["\']\s*:\s*(\d+)'),
3b52a606 524 webpage, 'view count', default=None)),
525 'concurrent_view_count': get_first(post, (
526 ('video', (..., ..., 'attachments', ..., 'media')), 'liveViewerCount', {int_or_none})),
a181cd0c 527 }
b2db8102 528
a181cd0c 529 info_json_ld = self._search_json_ld(webpage, video_id, default={})
b2db8102 530 info_json_ld['title'] = (re.sub(r'\s*\|\s*Facebook$', '', title or info_json_ld.get('title') or page_title or '')
531 or (description or '').replace('\n', ' ') or f'Facebook video #{video_id}')
a181cd0c 532 return merge_dicts(info_json_ld, info_dict)
533
c1406299
YCH
534 video_data = None
535
b83ef507 536 def extract_video_data(instances):
29f7c58a 537 video_data = []
b83ef507 538 for item in instances:
29f7c58a 539 if try_get(item, lambda x: x[1][0]) == 'VideoConfig':
b83ef507 540 video_item = item[2][0]
71cdd756 541 if video_item.get('video_id'):
29f7c58a 542 video_data.append(video_item['videoData'])
543 return video_data
b83ef507 544
d9ee2e5c 545 server_js_data = self._parse_json(self._search_regex(
29f7c58a 546 [r'handleServerJS\(({.+})(?:\);|,")', r'\bs\.handle\(({.+?})\);'],
547 webpage, 'server js data', default='{}'), video_id, fatal=False)
b83ef507
S
548
549 if server_js_data:
550 video_data = extract_video_data(server_js_data.get('instances', []))
551
9b89daef
S
552 def extract_from_jsmods_instances(js_data):
553 if js_data:
554 return extract_video_data(try_get(
555 js_data, lambda x: x['jsmods']['instances'], list) or [])
556
29f7c58a 557 def extract_dash_manifest(video, formats):
e3b42d8b 558 dash_manifest = traverse_obj(video, 'dash_manifest', 'playlist', expected_type=str)
29f7c58a 559 if dash_manifest:
560 formats.extend(self._parse_mpd_formats(
a854fbec 561 compat_etree_fromstring(urllib.parse.unquote_plus(dash_manifest)),
562 mpd_url=video.get('dash_manifest_url')))
29f7c58a 563
9f14daf2 564 def process_formats(info):
29f7c58a 565 # Downloads with browser's User-Agent are rate limited. Working around
566 # with non-browser User-Agent.
9f14daf2 567 for f in info['formats']:
5b68c478 568 # Downloads with browser's User-Agent are rate limited. Working around
569 # with non-browser User-Agent.
29f7c58a 570 f.setdefault('http_headers', {})['User-Agent'] = 'facebookexternalhit/1.1'
5b68c478 571 # Formats larger than ~500MB will return error 403 unless chunk size is regulated
572 f.setdefault('downloader_options', {})['http_chunk_size'] = 250 << 20
29f7c58a 573
574 def extract_relay_data(_filter):
575 return self._parse_json(self._search_regex(
add96eb9 576 rf'data-sjs>({{.*?{_filter}.*?}})</script>',
29f7c58a 577 webpage, 'replay data', default='{}'), video_id, fatal=False) or {}
578
579 def extract_relay_prefetched_data(_filter):
d3d81cc9 580 return traverse_obj(extract_relay_data(_filter), (
581 'require', (None, (..., ..., ..., '__bbox', 'require')),
2e30b556 582 lambda _, v: any(key.startswith('RelayPrefetchedStreamCache') for key in v),
583 ..., ..., '__bbox', 'result', 'data', {dict}), get_all=False) or {}
29f7c58a 584
b83ef507 585 if not video_data:
29f7c58a 586 server_js_data = self._parse_json(self._search_regex([
587 r'bigPipe\.onPageletArrive\(({.+?})\)\s*;\s*}\s*\)\s*,\s*["\']onPageletArrive\s+' + self._SUPPORTED_PAGLETS_REGEX,
add96eb9 588 rf'bigPipe\.onPageletArrive\(({{.*?id\s*:\s*"{self._SUPPORTED_PAGLETS_REGEX}".*?}})\);',
29f7c58a 589 ], webpage, 'js data', default='{}'), video_id, js_to_json, False)
9b89daef 590 video_data = extract_from_jsmods_instances(server_js_data)
c1406299 591
9d082e7c 592 if not video_data:
29f7c58a 593 data = extract_relay_prefetched_data(
d3d81cc9 594 r'"(?:dash_manifest|playable_url(?:_quality_hd)?)')
29f7c58a 595 if data:
596 entries = []
597
598 def parse_graphql_video(video):
bb5d84c9
VA
599 v_id = video.get('videoId') or video.get('id') or video_id
600 reel_info = traverse_obj(
601 video, ('creation_story', 'short_form_video_context', 'playback_video', {dict}))
602 if reel_info:
603 video = video['creation_story']
604 video['owner'] = traverse_obj(video, ('short_form_video_context', 'video_owner'))
605 video.update(reel_info)
29f7c58a 606 formats = []
607 q = qualities(['sd', 'hd'])
b8e976a4 608 for key, format_id in (('playable_url', 'sd'), ('playable_url_quality_hd', 'hd'),
d3d81cc9 609 ('playable_url_dash', ''), ('browser_native_hd_url', 'hd'),
610 ('browser_native_sd_url', 'sd')):
b8e976a4 611 playable_url = video.get(key)
29f7c58a 612 if not playable_url:
613 continue
b8e976a4 614 if determine_ext(playable_url) == 'mpd':
615 formats.extend(self._extract_mpd_formats(playable_url, video_id))
616 else:
617 formats.append({
618 'format_id': format_id,
30893661 619 # sd, hd formats w/o resolution info should be deprioritized below DASH
620 'quality': q(format_id) - 3,
b8e976a4 621 'url': playable_url,
622 })
29f7c58a 623 extract_dash_manifest(video, formats)
9b5efaf8 624
625 automatic_captions, subtitles = {}, {}
626 is_broadcast = traverse_obj(video, ('is_video_broadcast', {bool}))
627 for caption in traverse_obj(video, (
628 'video_available_captions_locales',
629 {lambda x: sorted(x, key=lambda c: c['locale'])},
add96eb9 630 lambda _, v: url_or_none(v['captions_url']),
9b5efaf8 631 )):
632 lang = caption.get('localized_language') or 'und'
633 subs = {
634 'url': caption['captions_url'],
635 'name': format_field(caption, 'localized_country', f'{lang} (%s)', default=lang),
636 }
637 if caption.get('localized_creation_method') or is_broadcast:
638 automatic_captions.setdefault(caption['locale'], []).append(subs)
639 else:
640 subtitles.setdefault(caption['locale'], []).append(subs)
641 captions_url = traverse_obj(video, ('captions_url', {url_or_none}))
642 if captions_url and not automatic_captions and not subtitles:
643 locale = self._html_search_meta(
644 ['og:locale', 'twitter:locale'], webpage, 'locale', default='en_US')
645 (automatic_captions if is_broadcast else subtitles)[locale] = [{'url': captions_url}]
646
29f7c58a 647 info = {
648 'id': v_id,
649 'formats': formats,
cda1bc51
A
650 'thumbnail': traverse_obj(
651 video, ('thumbnailImage', 'uri'), ('preferred_thumbnail', 'image', 'uri')),
bb5d84c9
VA
652 'uploader_id': traverse_obj(video, ('owner', 'id', {str_or_none})),
653 'timestamp': traverse_obj(video, 'publish_time', 'creation_time', expected_type=int_or_none),
654 'duration': (float_or_none(video.get('playable_duration_in_ms'), 1000)
655 or float_or_none(video.get('length_in_second'))),
9b5efaf8 656 'automatic_captions': automatic_captions,
657 'subtitles': subtitles,
29f7c58a 658 }
9f14daf2 659 process_formats(info)
29f7c58a 660 description = try_get(video, lambda x: x['savable_description']['text'])
661 title = video.get('name')
662 if title:
663 info.update({
664 'title': title,
665 'description': description,
666 })
667 else:
add96eb9 668 info['title'] = description or f'Facebook video #{v_id}'
29f7c58a 669 entries.append(info)
670
671 def parse_attachment(attachment, key='media'):
672 media = attachment.get(key) or {}
673 if media.get('__typename') == 'Video':
674 return parse_graphql_video(media)
675
b2db8102 676 nodes = variadic(traverse_obj(data, 'nodes', 'node') or [])
677 attachments = traverse_obj(nodes, (
678 ..., 'comet_sections', 'content', 'story', (None, 'attached_story'), 'attachments',
c39358a5 679 ..., ('styles', 'style_type_renderer', ('throwbackStyles', 'attachment_target_renderer')),
680 'attachment', {dict}))
b2db8102 681 for attachment in attachments:
c39358a5 682 ns = traverse_obj(attachment, ('all_subattachments', 'nodes', ..., {dict}),
683 ('target', 'attachments', ..., 'styles', 'attachment', {dict}))
b2db8102 684 for n in ns:
685 parse_attachment(n)
686 parse_attachment(attachment)
29f7c58a 687
688 edges = try_get(data, lambda x: x['mediaset']['currMedia']['edges'], list) or []
689 for edge in edges:
690 parse_attachment(edge, key='node')
691
9b5efaf8 692 video = traverse_obj(data, (
693 'event', 'cover_media_renderer', 'cover_video'), 'video', expected_type=dict) or {}
29f7c58a 694 if video:
695 attachments = try_get(video, [
696 lambda x: x['story']['attachments'],
add96eb9 697 lambda x: x['creation_story']['attachments'],
29f7c58a 698 ], list) or []
699 for attachment in attachments:
700 parse_attachment(attachment)
701 if not entries:
702 parse_graphql_video(video)
703
a181cd0c 704 if len(entries) > 1:
705 return self.playlist_result(entries, video_id)
706
c39358a5 707 video_info = entries[0] if entries else {'id': video_id}
a181cd0c 708 webpage_info = extract_metadata(webpage)
709 # honor precise duration in video info
710 if video_info.get('duration'):
711 webpage_info['duration'] = video_info['duration']
3c4d3ee4 712 # preserve preferred_thumbnail in video info
713 if video_info.get('thumbnail'):
714 webpage_info['thumbnail'] = video_info['thumbnail']
a181cd0c 715 return merge_dicts(webpage_info, video_info)
29f7c58a 716
717 if not video_data:
9b89daef
S
718 m_msg = re.search(r'class="[^"]*uiInterstitialContent[^"]*"><div>(.*?)</div>', webpage)
719 if m_msg is not None:
720 raise ExtractorError(
add96eb9 721 f'The video is not available, Facebook said: "{m_msg.group(1)}"',
9b89daef 722 expected=True)
46358f64 723 elif any(p in webpage for p in (
724 '>You must log in to continue',
725 'id="login_form"',
726 'id="loginbutton"')):
9b89daef
S
727 self.raise_login_required()
728
29f7c58a 729 if not video_data and '/watchparty/' in url:
730 post_data = {
731 'doc_id': 3731964053542869,
732 'variables': json.dumps({
733 'livingRoomID': video_id,
734 }),
735 }
736
737 prefetched_data = extract_relay_prefetched_data(r'"login_data"\s*:\s*{')
738 if prefetched_data:
739 lsd = try_get(prefetched_data, lambda x: x['login_data']['lsd'], dict)
740 if lsd:
741 post_data[lsd['name']] = lsd['value']
742
743 relay_data = extract_relay_data(r'\[\s*"RelayAPIConfigDefaults"\s*,')
744 for define in (relay_data.get('define') or []):
745 if define[0] == 'RelayAPIConfigDefaults':
746 self._api_config = define[2]
747
748 living_room = self._download_json(
749 urljoin(url, self._api_config['graphURI']), video_id,
750 data=urlencode_postdata(post_data))['data']['living_room']
751
752 entries = []
753 for edge in (try_get(living_room, lambda x: x['recap']['watched_content']['edges']) or []):
754 video = try_get(edge, lambda x: x['node']['video']) or {}
755 v_id = video.get('id')
756 if not v_id:
757 continue
add96eb9 758 v_id = str(v_id)
29f7c58a 759 entries.append(self.url_result(
760 self._VIDEO_PAGE_TEMPLATE % v_id,
761 self.ie_key(), v_id, video.get('name')))
762
763 return self.playlist_result(entries, video_id)
764
765 if not video_data:
9b89daef
S
766 # Video info not in first request, do a secondary request using
767 # tahoe player specific URL
9d082e7c
NR
768 tahoe_data = self._download_webpage(
769 self._VIDEO_PAGE_TAHOE_TEMPLATE % video_id, video_id,
770 data=urlencode_postdata({
9d082e7c 771 '__a': 1,
9b89daef
S
772 '__pc': self._search_regex(
773 r'pkg_cohort["\']\s*:\s*["\'](.+?)["\']', webpage,
774 'pkg cohort', default='PHASED:DEFAULT'),
775 '__rev': self._search_regex(
776 r'client_revision["\']\s*:\s*(\d+),', webpage,
777 'client revision', default='3944515'),
631f93ee
RA
778 'fb_dtsg': self._search_regex(
779 r'"DTSGInitialData"\s*,\s*\[\]\s*,\s*{\s*"token"\s*:\s*"([^"]+)"',
780 webpage, 'dtsg token', default=''),
9d082e7c
NR
781 }),
782 headers={
783 'Content-Type': 'application/x-www-form-urlencoded',
784 })
9b89daef
S
785 tahoe_js_data = self._parse_json(
786 self._search_regex(
787 r'for\s+\(\s*;\s*;\s*\)\s*;(.+)', tahoe_data,
788 'tahoe js data', default='{}'),
789 video_id, fatal=False)
790 video_data = extract_from_jsmods_instances(tahoe_js_data)
9d082e7c 791
c1406299 792 if not video_data:
9b89daef 793 raise ExtractorError('Cannot parse data')
ffdf972b 794
29f7c58a 795 if len(video_data) > 1:
796 entries = []
797 for v in video_data:
798 video_url = v[0].get('video_url')
799 if not video_url:
800 continue
801 entries.append(self.url_result(urljoin(
802 url, video_url), self.ie_key(), v[0].get('video_id')))
803 return self.playlist_result(entries, video_id)
804 video_data = video_data[0]
805
ffdf972b 806 formats = []
29f7c58a 807 subtitles = {}
d9ee2e5c
YCH
808 for f in video_data:
809 format_id = f['stream_type']
ca74c90b
SC
810 if f and isinstance(f, dict):
811 f = [f]
44d6dd08
S
812 if not f or not isinstance(f, list):
813 continue
814 for quality in ('sd', 'hd'):
815 for src_type in ('src', 'src_no_ratelimit'):
add96eb9 816 src = f[0].get(f'{quality}_{src_type}')
44d6dd08 817 if src:
30893661 818 # sd, hd formats w/o resolution info should be deprioritized below DASH
819 # TODO: investigate if progressive or src formats still exist
820 preference = -10 if format_id == 'progressive' else -3
c24883a1 821 if quality == 'hd':
30893661 822 preference += 1
44d6dd08 823 formats.append({
add96eb9 824 'format_id': f'{format_id}_{quality}_{src_type}',
44d6dd08 825 'url': src,
f983b875 826 'quality': preference,
add96eb9 827 'height': 720 if quality == 'hd' else None,
44d6dd08 828 })
29f7c58a 829 extract_dash_manifest(f[0], formats)
07154c79
RA
830 subtitles_src = f[0].get('subtitles_src')
831 if subtitles_src:
832 subtitles.setdefault('en', []).append({'url': subtitles_src})
9eae41dd 833
9c7b509b 834 info_dict = {
9eae41dd 835 'id': video_id,
ffdf972b 836 'formats': formats,
07154c79 837 'subtitles': subtitles,
9eae41dd 838 }
9f14daf2 839 process_formats(info_dict)
a181cd0c 840 info_dict.update(extract_metadata(webpage))
de691a49 841
29f7c58a 842 return info_dict
de691a49
S
843
844 def _real_extract(self, url):
9c7b509b
YCH
845 video_id = self._match_id(url)
846
847 real_url = self._VIDEO_PAGE_TEMPLATE % video_id if url.startswith('facebook:') else url
29f7c58a 848 return self._extract_from_url(real_url, video_id)
349fc5c7
S
849
850
851class FacebookPluginsVideoIE(InfoExtractor):
852 _VALID_URL = r'https?://(?:[\w-]+\.)?facebook\.com/plugins/video\.php\?.*?\bhref=(?P<id>https.+)'
853
854 _TESTS = [{
855 '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',
856 'md5': '5954e92cdfe51fe5782ae9bda7058a07',
857 'info_dict': {
858 'id': '10154383743583686',
859 'ext': 'mp4',
b2db8102 860 # TODO: Fix title, uploader
349fc5c7
S
861 'title': 'What to do during the haze?',
862 'uploader': 'Gov.sg',
863 'upload_date': '20160826',
864 'timestamp': 1472184808,
865 },
866 'add_ie': [FacebookIE.ie_key()],
867 }, {
868 'url': 'https://www.facebook.com/plugins/video.php?href=https%3A%2F%2Fwww.facebook.com%2Fvideo.php%3Fv%3D10204634152394104',
869 'only_matching': True,
870 }, {
871 'url': 'https://www.facebook.com/plugins/video.php?href=https://www.facebook.com/gov.sg/videos/10154383743583686/&show_text=0&width=560',
872 'only_matching': True,
873 }]
874
875 def _real_extract(self, url):
876 return self.url_result(
add96eb9 877 urllib.parse.unquote(self._match_id(url)),
349fc5c7 878 FacebookIE.ie_key())
5f549d49 879
880
881class FacebookRedirectURLIE(InfoExtractor):
882 IE_DESC = False # Do not list
883 _VALID_URL = r'https?://(?:[\w-]+\.)?facebook\.com/flx/warn[/?]'
884 _TESTS = [{
885 'url': 'https://www.facebook.com/flx/warn/?h=TAQHsoToz&u=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DpO8h3EaFRdo&s=1',
886 'info_dict': {
887 'id': 'pO8h3EaFRdo',
888 'ext': 'mp4',
889 'title': 'Tripeo Boiler Room x Dekmantel Festival DJ Set',
890 'description': 'md5:2d713ccbb45b686a1888397b2c77ca6b',
891 'channel_id': 'UCGBpxWJr9FNOcFYA5GkKrMg',
892 'playable_in_embed': True,
893 'categories': ['Music'],
894 'channel': 'Boiler Room',
895 'uploader_id': 'brtvofficial',
896 'uploader': 'Boiler Room',
897 'tags': 'count:11',
898 'duration': 3332,
899 'live_status': 'not_live',
900 'thumbnail': 'https://i.ytimg.com/vi/pO8h3EaFRdo/maxresdefault.jpg',
901 'channel_url': 'https://www.youtube.com/channel/UCGBpxWJr9FNOcFYA5GkKrMg',
902 'availability': 'public',
903 'uploader_url': 'http://www.youtube.com/user/brtvofficial',
904 'upload_date': '20150917',
905 'age_limit': 0,
906 'view_count': int,
907 'like_count': int,
908 },
909 'add_ie': ['Youtube'],
910 'params': {'skip_download': 'Youtube'},
911 }]
912
913 def _real_extract(self, url):
914 redirect_url = url_or_none(parse_qs(url).get('u', [None])[-1])
915 if not redirect_url:
916 raise ExtractorError('Invalid facebook redirect URL', expected=True)
917 return self.url_result(redirect_url)
63be30e3 918
919
920class FacebookReelIE(InfoExtractor):
921 _VALID_URL = r'https?://(?:[\w-]+\.)?facebook\.com/reel/(?P<id>\d+)'
922 IE_NAME = 'facebook:reel'
923
924 _TESTS = [{
925 'url': 'https://www.facebook.com/reel/1195289147628387',
bb5d84c9 926 'md5': 'f13dd37f2633595982db5ed8765474d3',
63be30e3 927 'info_dict': {
928 'id': '1195289147628387',
929 'ext': 'mp4',
bb5d84c9
VA
930 'title': 'md5:b05800b5b1ad56c0ca78bd3807b6a61e',
931 'description': 'md5:22f03309b216ac84720183961441d8db',
932 'uploader': 'md5:723e6cb3091241160f20b3c5dc282af1',
933 'uploader_id': '100040874179269',
934 'duration': 9.579,
935 'timestamp': 1637502609,
63be30e3 936 'upload_date': '20211121',
bb5d84c9 937 'thumbnail': r're:^https?://.*',
add96eb9 938 },
63be30e3 939 }]
940
941 def _real_extract(self, url):
942 video_id = self._match_id(url)
943 return self.url_result(
944 f'https://m.facebook.com/watch/?v={video_id}&_rdr', FacebookIE, video_id)
a40b0070 945
946
947class FacebookAdsIE(InfoExtractor):
948 _VALID_URL = r'https?://(?:[\w-]+\.)?facebook\.com/ads/library/?\?(?:[^#]+&)?id=(?P<id>\d+)'
949 IE_NAME = 'facebook:ads'
950
951 _TESTS = [{
952 'url': 'https://www.facebook.com/ads/library/?id=899206155126718',
953 'info_dict': {
954 'id': '899206155126718',
955 'ext': 'mp4',
956 'title': 'video by Kandao',
957 'uploader': 'Kandao',
958 'uploader_id': '774114102743284',
959 'uploader_url': r're:^https?://.*',
960 'timestamp': 1702548330,
961 'thumbnail': r're:^https?://.*',
962 'upload_date': '20231214',
963 'like_count': int,
add96eb9 964 },
a40b0070 965 }, {
966 'url': 'https://www.facebook.com/ads/library/?id=893637265423481',
967 'info_dict': {
968 'id': '893637265423481',
969 'title': 'Jusqu\u2019\u00e0 -25% sur une s\u00e9lection de vins p\u00e9tillants italiens ',
970 'uploader': 'Eataly Paris Marais',
971 'uploader_id': '2086668958314152',
972 'uploader_url': r're:^https?://.*',
973 'timestamp': 1703571529,
974 'upload_date': '20231226',
975 'like_count': int,
976 },
977 'playlist_count': 3,
978 }, {
979 'url': 'https://es-la.facebook.com/ads/library/?id=901230958115569',
980 'only_matching': True,
981 }, {
982 'url': 'https://m.facebook.com/ads/library/?id=901230958115569',
983 'only_matching': True,
984 }]
985
986 _FORMATS_MAP = {
987 'watermarked_video_sd_url': ('sd-wmk', 'SD, watermarked'),
988 'video_sd_url': ('sd', None),
989 'watermarked_video_hd_url': ('hd-wmk', 'HD, watermarked'),
990 'video_hd_url': ('hd', None),
991 }
992
993 def _extract_formats(self, video_dict):
994 formats = []
995 for format_key, format_url in traverse_obj(video_dict, (
add96eb9 996 {dict.items}, lambda _, v: v[0] in self._FORMATS_MAP and url_or_none(v[1]),
a40b0070 997 )):
998 formats.append({
999 'format_id': self._FORMATS_MAP[format_key][0],
1000 'format_note': self._FORMATS_MAP[format_key][1],
1001 'url': format_url,
1002 'ext': 'mp4',
1003 'quality': qualities(tuple(self._FORMATS_MAP))(format_key),
1004 })
1005 return formats
1006
1007 def _real_extract(self, url):
1008 video_id = self._match_id(url)
1009 webpage = self._download_webpage(url, video_id)
1010
1011 post_data = [self._parse_json(j, video_id, fatal=False)
1012 for j in re.findall(r's\.handle\(({.*})\);requireLazy\(', webpage)]
1013 data = traverse_obj(post_data, (
1014 ..., 'require', ..., ..., ..., 'props', 'deeplinkAdCard', 'snapshot', {dict}), get_all=False)
1015 if not data:
1016 raise ExtractorError('Unable to extract ad data')
1017
1018 title = data.get('title')
1019 if not title or title == '{{product.name}}':
1020 title = join_nonempty('display_format', 'page_name', delim=' by ', from_dict=data)
1021
1022 info_dict = traverse_obj(data, {
1023 'description': ('link_description', {str}, {lambda x: x if x != '{{product.description}}' else None}),
1024 'uploader': ('page_name', {str}),
1025 'uploader_id': ('page_id', {str_or_none}),
1026 'uploader_url': ('page_profile_uri', {url_or_none}),
1027 'timestamp': ('creation_time', {int_or_none}),
1028 'like_count': ('page_like_count', {int_or_none}),
1029 })
1030
1031 entries = []
1032 for idx, entry in enumerate(traverse_obj(
add96eb9 1033 data, (('videos', 'cards'), lambda _, v: any(url_or_none(v[f]) for f in self._FORMATS_MAP))), 1,
a40b0070 1034 ):
1035 entries.append({
1036 'id': f'{video_id}_{idx}',
1037 'title': entry.get('title') or title,
1038 'description': entry.get('link_description') or info_dict.get('description'),
1039 'thumbnail': url_or_none(entry.get('video_preview_image_url')),
1040 'formats': self._extract_formats(entry),
1041 })
1042
1043 if len(entries) == 1:
1044 info_dict.update(entries[0])
1045
1046 elif len(entries) > 1:
1047 info_dict.update({
1048 'title': entries[0]['title'],
1049 'entries': entries,
1050 '_type': 'playlist',
1051 })
1052
1053 info_dict['id'] = video_id
1054
1055 return info_dict