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