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