]> jfr.im git - yt-dlp.git/blob - yt_dlp/extractor/facebook.py
50a750d3b127092e26d883ab4146c1bd77dbeced
[yt-dlp.git] / yt_dlp / extractor / facebook.py
1 import json
2 import re
3 import urllib.parse
4
5 from .common import InfoExtractor
6 from ..compat import (
7 compat_etree_fromstring,
8 compat_str,
9 compat_urllib_parse_unquote,
10 )
11 from ..networking import Request
12 from ..networking.exceptions import network_exceptions
13 from ..utils import (
14 ExtractorError,
15 clean_html,
16 determine_ext,
17 error_to_compat_str,
18 float_or_none,
19 get_element_by_id,
20 get_first,
21 int_or_none,
22 js_to_json,
23 merge_dicts,
24 parse_count,
25 parse_qs,
26 qualities,
27 str_or_none,
28 traverse_obj,
29 try_get,
30 url_or_none,
31 urlencode_postdata,
32 urljoin,
33 variadic,
34 )
35
36
37 class FacebookIE(InfoExtractor):
38 _VALID_URL = r'''(?x)
39 (?:
40 https?://
41 (?:[\w-]+\.)?(?:facebook\.com|facebookwkhpilnemxj7asaniu7vnjjbiltxjqhye3mhbshg7kx5tfyd\.onion)/
42 (?:[^#]*?\#!/)?
43 (?:
44 (?:
45 video/video\.php|
46 photo\.php|
47 video\.php|
48 video/embed|
49 story\.php|
50 watch(?:/live)?/?
51 )\?(?:.*?)(?:v|video_id|story_fbid)=|
52 [^/]+/videos/(?:[^/]+/)?|
53 [^/]+/posts/|
54 groups/[^/]+/permalink/|
55 watchparty/
56 )|
57 facebook:
58 )
59 (?P<id>[0-9]+)
60 '''
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 ]
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'
70 _NETRC_MACHINE = 'facebook'
71 IE_NAME = 'facebook'
72
73 _VIDEO_PAGE_TEMPLATE = 'https://www.facebook.com/video/video.php?v=%s'
74 _VIDEO_PAGE_TAHOE_TEMPLATE = 'https://www.facebook.com/video/tahoe/async/%s/?chain=true&isvideo=true&payloadtype=primary'
75
76 _TESTS = [{
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 }, {
93 'url': 'https://www.facebook.com/video.php?v=637842556329505&fref=nf',
94 'md5': '6a40d33c0eccbb1af76cf0485a052659',
95 'info_dict': {
96 'id': '637842556329505',
97 'ext': 'mp4',
98 'title': 're:Did you know Kei Nishikori is the first Asian man to ever reach a Grand Slam',
99 'uploader': 'Tennis on Facebook',
100 'upload_date': '20140908',
101 'timestamp': 1410199200,
102 },
103 'skip': 'Requires logging in',
104 }, {
105 # data.video
106 'url': 'https://www.facebook.com/video.php?v=274175099429670',
107 'info_dict': {
108 'id': '274175099429670',
109 'ext': 'mp4',
110 'title': 'Asif',
111 'description': '',
112 'uploader': 'Asif Nawab Butt',
113 'upload_date': '20140506',
114 'timestamp': 1399398998,
115 'thumbnail': r're:^https?://.*',
116 'uploader_id': 'pfbid028wxorhX2ErLFJ578N6P3crHD3PHmXTCqCvfBpsnbSLmbokwSY75p5hWBjHGkG4zxl',
117 'duration': 131.03,
118 'concurrent_view_count': int,
119 },
120 }, {
121 'note': 'Video with DASH manifest',
122 'url': 'https://www.facebook.com/video.php?v=957955867617029',
123 'md5': 'b2c28d528273b323abe5c6ab59f0f030',
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',
129 'upload_date': '20160110',
130 'timestamp': 1452431627,
131 },
132 'skip': 'Requires logging in',
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',
141 },
142 'skip': 'Video gone',
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 },
152 'skip': 'Video gone',
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',
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',
165 },
166 'skip': 'Gif on giphy.com gone',
167 }, {
168 # have 1080P, but only up to 720p in swf params
169 # data.video.story.attachments[].media
170 'url': 'https://www.facebook.com/cnn/videos/10155529876156509/',
171 'md5': 'ca63897a90c9452efee5f8c40d080e25',
172 'info_dict': {
173 'id': '10155529876156509',
174 'ext': 'mp4',
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',
177 'timestamp': 1477818095,
178 'upload_date': '20161030',
179 'uploader': 'CNN',
180 'thumbnail': r're:^https?://.*',
181 'view_count': int,
182 'uploader_id': '100059479812265',
183 'concurrent_view_count': int,
184 'duration': 44.478,
185 },
186 }, {
187 # bigPipe.onPageletArrive ... onPageletArrive pagelet_group_mall
188 # data.node.comet_sections.content.story.attachments[].style_type_renderer.attachment.media
189 'url': 'https://www.facebook.com/yaroslav.korpan/videos/1417995061575415/',
190 'info_dict': {
191 'id': '1417995061575415',
192 'ext': 'mp4',
193 'title': 'Довгоочікуване відео | By Yaroslav - Facebook',
194 'description': 'Довгоочікуване відео',
195 'timestamp': 1486648217,
196 'upload_date': '20170209',
197 'uploader': 'Yaroslav Korpan',
198 'uploader_id': 'pfbid06AScABAWcW91qpiuGrLt99Ef9tvwHoXP6t8KeFYEqkSfreMtfa9nTveh8b2ZEVSWl',
199 'concurrent_view_count': int,
200 'thumbnail': r're:^https?://.*',
201 'view_count': int,
202 'duration': 11736.446,
203 },
204 'params': {
205 'skip_download': True,
206 },
207 }, {
208 # FIXME
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',
217 'thumbnail': r're:^https?://.*',
218 },
219 'skip': 'Requires logging in',
220 }, {
221 # data.node.comet_sections.content.story.attachments[].style_type_renderer.attachment.media
222 'url': 'https://www.facebook.com/groups/1024490957622648/permalink/1396382447100162/',
223 'info_dict': {
224 'id': '202882990186699',
225 'ext': 'mp4',
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...',
228 'timestamp': 1486035513,
229 'upload_date': '20170202',
230 'uploader': 'Elisabeth Ahtn',
231 'uploader_id': '100013949973717',
232 },
233 'skip': 'Requires logging in',
234 }, {
235 'url': 'https://www.facebook.com/video.php?v=10204634152394104',
236 'only_matching': True,
237 }, {
238 'url': 'https://www.facebook.com/amogood/videos/1618742068337349/?fref=nf',
239 'only_matching': True,
240 }, {
241 # data.mediaset.currMedia.edges
242 'url': 'https://www.facebook.com/ChristyClarkForBC/videos/vb.22819070941/10153870694020942/?type=2&theater',
243 'only_matching': True,
244 }, {
245 # data.video.story.attachments[].media
246 'url': 'facebook:544765982287235',
247 'only_matching': True,
248 }, {
249 # data.node.comet_sections.content.story.attachments[].style_type_renderer.attachment.media
250 'url': 'https://www.facebook.com/groups/164828000315060/permalink/764967300301124/',
251 'only_matching': True,
252 }, {
253 # data.video.creation_story.attachments[].media
254 'url': 'https://zh-hk.facebook.com/peoplespower/videos/1135894589806027/',
255 'only_matching': True,
256 }, {
257 # data.video
258 'url': 'https://www.facebookwkhpilnemxj7asaniu7vnjjbiltxjqhye3mhbshg7kx5tfyd.onion/video.php?v=274175099429670',
259 'only_matching': True,
260 }, {
261 # no title
262 'url': 'https://www.facebook.com/onlycleverentertainment/videos/1947995502095005/',
263 'only_matching': True,
264 }, {
265 # data.video
266 'url': 'https://www.facebook.com/WatchESLOne/videos/359649331226507/',
267 'info_dict': {
268 'id': '359649331226507',
269 'ext': 'mp4',
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',
274 'uploader': 'ESL One Dota 2',
275 'uploader_id': '100066514874195',
276 'duration': 4524.212,
277 'view_count': int,
278 'thumbnail': r're:^https?://.*',
279 'concurrent_view_count': int,
280 },
281 'params': {
282 'skip_download': True,
283 },
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',
289 'ext': 'mp4',
290 'title': 'Josef',
291 'thumbnail': r're:^https?://.*',
292 'concurrent_view_count': int,
293 'uploader_id': 'pfbid0cibUN6tV7DYgdbJdsUFN46wc4jKpVSPAvJQhFofGqBGmVn3V3JtAs2tfUwziw2hUl',
294 'timestamp': 1549275572,
295 'duration': 3.413,
296 'uploader': 'Josef Novak',
297 'description': '',
298 'upload_date': '20190204',
299 },
300 }, {
301 # data.video.story.attachments[].media
302 'url': 'https://www.facebook.com/watch/?v=647537299265662',
303 'only_matching': True,
304 }, {
305 # FIXME: https://github.com/yt-dlp/yt-dlp/issues/542
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,
312 'skip': 'Requires logging in',
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 },
337 'skip': 'No video',
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',
349 }]
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 }
354
355 def _perform_login(self, username, password):
356 login_page_req = Request(self._LOGIN_URL)
357 self._set_cookie('facebook.com', 'locale', 'en_US')
358 login_page = self._download_webpage(login_page_req, None,
359 note='Downloading login page',
360 errnote='Unable to download login page')
361 lsd = self._search_regex(
362 r'<input type="hidden" name="lsd" value="([^"]*)"',
363 login_page, 'lsd')
364 lgnrnd = self._search_regex(r'name="lgnrnd" value="([^"]*?)"', login_page, 'lgnrnd')
365
366 login_form = {
367 'email': username,
368 'pass': password,
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',
376 }
377 request = Request(self._LOGIN_URL, urlencode_postdata(login_form))
378 request.headers['Content-Type'] = 'application/x-www-form-urlencoded'
379 try:
380 login_results = self._download_webpage(request, None,
381 note='Logging in', errnote='unable to fetch login page')
382 if re.search(r'<form(.*)name="login"(.*)</form>', login_results) is not None:
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)
388 self.report_warning('unable to log in: bad username/password, or exceeded login rate limit (~3/min). Check credentials or wait.')
389 return
390
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
399 check_form = {
400 'fb_dtsg': fb_dtsg,
401 'h': h,
402 'name_action_selected': 'dont_save',
403 }
404 check_req = Request(self._CHECKPOINT_URL, urlencode_postdata(check_form))
405 check_req.headers['Content-Type'] = 'application/x-www-form-urlencoded'
406 check_response = self._download_webpage(check_req, None,
407 note='Confirming login')
408 if re.search(r'id="checkpointSubmitButton"', check_response) is not None:
409 self.report_warning('Unable to confirm login, you have to login in your browser and authorize the login.')
410 except network_exceptions as err:
411 self.report_warning('unable to log in: %s' % error_to_compat_str(err))
412 return
413
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)
417
418 def extract_metadata(webpage):
419 post_data = [self._parse_json(j, video_id, fatal=False) for j in re.findall(
420 r'data-sjs>({.*?ScheduledServerJS.*?})</script>', webpage)]
421 post = traverse_obj(post_data, (
422 ..., 'require', ..., ..., ..., '__bbox', 'require', ..., ..., ..., '__bbox', 'result', 'data'), expected_type=dict) or []
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)
425 title = get_first(media, ('title', 'text'))
426 description = get_first(media, ('creation_story', 'comet_sections', 'message', 'story', 'message', 'text'))
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 {})
431
432 page_title = title or self._html_search_regex((
433 r'<h2\s+[^>]*class="uiHeaderTitle"[^>]*>(?P<content>[^<]*)</h2>',
434 r'(?s)<span class="fbPhotosPhotoCaption".*?id="fbPhotoPageCaption"><span class="hasCaption">(?P<content>.*?)</span>',
435 self._meta_regex('og:title'), self._meta_regex('twitter:title'), r'<title>(?P<content>.+?)</title>'
436 ), webpage, 'title', default=None, group='content')
437 description = description or self._html_search_meta(
438 ['description', 'og:description', 'twitter:description'],
439 webpage, 'description', default=None)
440 uploader = uploader_data.get('name') or (
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
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
455 info_dict = {
456 'description': description,
457 'uploader': uploader,
458 'uploader_id': uploader_data.get('id'),
459 'timestamp': timestamp,
460 'thumbnail': thumbnail,
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})),
466 }
467
468 info_json_ld = self._search_json_ld(webpage, video_id, default={})
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}')
471 return merge_dicts(info_json_ld, info_dict)
472
473 video_data = None
474
475 def extract_video_data(instances):
476 video_data = []
477 for item in instances:
478 if try_get(item, lambda x: x[1][0]) == 'VideoConfig':
479 video_item = item[2][0]
480 if video_item.get('video_id'):
481 video_data.append(video_item['videoData'])
482 return video_data
483
484 server_js_data = self._parse_json(self._search_regex(
485 [r'handleServerJS\(({.+})(?:\);|,")', r'\bs\.handle\(({.+?})\);'],
486 webpage, 'server js data', default='{}'), video_id, fatal=False)
487
488 if server_js_data:
489 video_data = extract_video_data(server_js_data.get('instances', []))
490
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
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(
500 compat_etree_fromstring(urllib.parse.unquote_plus(dash_manifest)),
501 mpd_url=video.get('dash_manifest_url')))
502
503 def process_formats(info):
504 # Downloads with browser's User-Agent are rate limited. Working around
505 # with non-browser User-Agent.
506 for f in info['formats']:
507 f.setdefault('http_headers', {})['User-Agent'] = 'facebookexternalhit/1.1'
508
509 def extract_relay_data(_filter):
510 return self._parse_json(self._search_regex(
511 r'data-sjs>({.*?%s.*?})</script>' % _filter,
512 webpage, 'replay data', default='{}'), video_id, fatal=False) or {}
513
514 def extract_relay_prefetched_data(_filter):
515 return traverse_obj(extract_relay_data(_filter), (
516 'require', (None, (..., ..., ..., '__bbox', 'require')),
517 lambda _, v: 'RelayPrefetchedStreamCache' in v, ..., ...,
518 '__bbox', 'result', 'data', {dict}), get_all=False) or {}
519
520 if not video_data:
521 server_js_data = self._parse_json(self._search_regex([
522 r'bigPipe\.onPageletArrive\(({.+?})\)\s*;\s*}\s*\)\s*,\s*["\']onPageletArrive\s+' + self._SUPPORTED_PAGLETS_REGEX,
523 r'bigPipe\.onPageletArrive\(({.*?id\s*:\s*"%s".*?})\);' % self._SUPPORTED_PAGLETS_REGEX
524 ], webpage, 'js data', default='{}'), video_id, js_to_json, False)
525 video_data = extract_from_jsmods_instances(server_js_data)
526
527 if not video_data:
528 data = extract_relay_prefetched_data(
529 r'"(?:dash_manifest|playable_url(?:_quality_hd)?)')
530 if data:
531 entries = []
532
533 def parse_graphql_video(video):
534 v_id = video.get('videoId') or video.get('id') or video_id
535 reel_info = traverse_obj(
536 video, ('creation_story', 'short_form_video_context', 'playback_video', {dict}))
537 if reel_info:
538 video = video['creation_story']
539 video['owner'] = traverse_obj(video, ('short_form_video_context', 'video_owner'))
540 video.update(reel_info)
541 formats = []
542 q = qualities(['sd', 'hd'])
543 for key, format_id in (('playable_url', 'sd'), ('playable_url_quality_hd', 'hd'),
544 ('playable_url_dash', ''), ('browser_native_hd_url', 'hd'),
545 ('browser_native_sd_url', 'sd')):
546 playable_url = video.get(key)
547 if not playable_url:
548 continue
549 if determine_ext(playable_url) == 'mpd':
550 formats.extend(self._extract_mpd_formats(playable_url, video_id))
551 else:
552 formats.append({
553 'format_id': format_id,
554 # sd, hd formats w/o resolution info should be deprioritized below DASH
555 'quality': q(format_id) - 3,
556 'url': playable_url,
557 })
558 extract_dash_manifest(video, formats)
559 info = {
560 'id': v_id,
561 'formats': formats,
562 'thumbnail': traverse_obj(
563 video, ('thumbnailImage', 'uri'), ('preferred_thumbnail', 'image', 'uri')),
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'))),
568 }
569 process_formats(info)
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
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)
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
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)
620
621 if not video_data:
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)
627 elif any(p in webpage for p in (
628 '>You must log in to continue',
629 'id="login_form"',
630 'id="loginbutton"')):
631 self.raise_login_required()
632
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:
670 # Video info not in first request, do a secondary request using
671 # tahoe player specific URL
672 tahoe_data = self._download_webpage(
673 self._VIDEO_PAGE_TAHOE_TEMPLATE % video_id, video_id,
674 data=urlencode_postdata({
675 '__a': 1,
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'),
682 'fb_dtsg': self._search_regex(
683 r'"DTSGInitialData"\s*,\s*\[\]\s*,\s*{\s*"token"\s*:\s*"([^"]+)"',
684 webpage, 'dtsg token', default=''),
685 }),
686 headers={
687 'Content-Type': 'application/x-www-form-urlencoded',
688 })
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)
695
696 if not video_data:
697 raise ExtractorError('Cannot parse data')
698
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
710 formats = []
711 subtitles = {}
712 for f in video_data:
713 format_id = f['stream_type']
714 if f and isinstance(f, dict):
715 f = [f]
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:
722 # sd, hd formats w/o resolution info should be deprioritized below DASH
723 # TODO: investigate if progressive or src formats still exist
724 preference = -10 if format_id == 'progressive' else -3
725 if quality == 'hd':
726 preference += 1
727 formats.append({
728 'format_id': '%s_%s_%s' % (format_id, quality, src_type),
729 'url': src,
730 'quality': preference,
731 'height': 720 if quality == 'hd' else None
732 })
733 extract_dash_manifest(f[0], formats)
734 subtitles_src = f[0].get('subtitles_src')
735 if subtitles_src:
736 subtitles.setdefault('en', []).append({'url': subtitles_src})
737
738 info_dict = {
739 'id': video_id,
740 'formats': formats,
741 'subtitles': subtitles,
742 }
743 process_formats(info_dict)
744 info_dict.update(extract_metadata(webpage))
745
746 return info_dict
747
748 def _real_extract(self, url):
749 video_id = self._match_id(url)
750
751 real_url = self._VIDEO_PAGE_TEMPLATE % video_id if url.startswith('facebook:') else url
752 return self._extract_from_url(real_url, video_id)
753
754
755 class FacebookPluginsVideoIE(InfoExtractor):
756 _VALID_URL = r'https?://(?:[\w-]+\.)?facebook\.com/plugins/video\.php\?.*?\bhref=(?P<id>https.+)'
757
758 _TESTS = [{
759 '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',
760 'md5': '5954e92cdfe51fe5782ae9bda7058a07',
761 'info_dict': {
762 'id': '10154383743583686',
763 'ext': 'mp4',
764 # TODO: Fix title, uploader
765 'title': 'What to do during the haze?',
766 'uploader': 'Gov.sg',
767 'upload_date': '20160826',
768 'timestamp': 1472184808,
769 },
770 'add_ie': [FacebookIE.ie_key()],
771 }, {
772 'url': 'https://www.facebook.com/plugins/video.php?href=https%3A%2F%2Fwww.facebook.com%2Fvideo.php%3Fv%3D10204634152394104',
773 'only_matching': True,
774 }, {
775 'url': 'https://www.facebook.com/plugins/video.php?href=https://www.facebook.com/gov.sg/videos/10154383743583686/&show_text=0&width=560',
776 'only_matching': True,
777 }]
778
779 def _real_extract(self, url):
780 return self.url_result(
781 compat_urllib_parse_unquote(self._match_id(url)),
782 FacebookIE.ie_key())
783
784
785 class FacebookRedirectURLIE(InfoExtractor):
786 IE_DESC = False # Do not list
787 _VALID_URL = r'https?://(?:[\w-]+\.)?facebook\.com/flx/warn[/?]'
788 _TESTS = [{
789 'url': 'https://www.facebook.com/flx/warn/?h=TAQHsoToz&u=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DpO8h3EaFRdo&s=1',
790 'info_dict': {
791 'id': 'pO8h3EaFRdo',
792 'ext': 'mp4',
793 'title': 'Tripeo Boiler Room x Dekmantel Festival DJ Set',
794 'description': 'md5:2d713ccbb45b686a1888397b2c77ca6b',
795 'channel_id': 'UCGBpxWJr9FNOcFYA5GkKrMg',
796 'playable_in_embed': True,
797 'categories': ['Music'],
798 'channel': 'Boiler Room',
799 'uploader_id': 'brtvofficial',
800 'uploader': 'Boiler Room',
801 'tags': 'count:11',
802 'duration': 3332,
803 'live_status': 'not_live',
804 'thumbnail': 'https://i.ytimg.com/vi/pO8h3EaFRdo/maxresdefault.jpg',
805 'channel_url': 'https://www.youtube.com/channel/UCGBpxWJr9FNOcFYA5GkKrMg',
806 'availability': 'public',
807 'uploader_url': 'http://www.youtube.com/user/brtvofficial',
808 'upload_date': '20150917',
809 'age_limit': 0,
810 'view_count': int,
811 'like_count': int,
812 },
813 'add_ie': ['Youtube'],
814 'params': {'skip_download': 'Youtube'},
815 }]
816
817 def _real_extract(self, url):
818 redirect_url = url_or_none(parse_qs(url).get('u', [None])[-1])
819 if not redirect_url:
820 raise ExtractorError('Invalid facebook redirect URL', expected=True)
821 return self.url_result(redirect_url)
822
823
824 class FacebookReelIE(InfoExtractor):
825 _VALID_URL = r'https?://(?:[\w-]+\.)?facebook\.com/reel/(?P<id>\d+)'
826 IE_NAME = 'facebook:reel'
827
828 _TESTS = [{
829 'url': 'https://www.facebook.com/reel/1195289147628387',
830 'md5': 'f13dd37f2633595982db5ed8765474d3',
831 'info_dict': {
832 'id': '1195289147628387',
833 'ext': 'mp4',
834 'title': 'md5:b05800b5b1ad56c0ca78bd3807b6a61e',
835 'description': 'md5:22f03309b216ac84720183961441d8db',
836 'uploader': 'md5:723e6cb3091241160f20b3c5dc282af1',
837 'uploader_id': '100040874179269',
838 'duration': 9.579,
839 'timestamp': 1637502609,
840 'upload_date': '20211121',
841 'thumbnail': r're:^https?://.*',
842 }
843 }]
844
845 def _real_extract(self, url):
846 video_id = self._match_id(url)
847 return self.url_result(
848 f'https://m.facebook.com/watch/?v={video_id}&_rdr', FacebookIE, video_id)