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