]> jfr.im git - yt-dlp.git/blame - youtube_dl/extractor/facebook.py
[bbc] Add support for bbcthree (closes #16612)
[yt-dlp.git] / youtube_dl / extractor / facebook.py
CommitLineData
624c4b92 1# coding: utf-8
cb3bb2cf
PH
2from __future__ import unicode_literals
3
9eae41dd
PH
4import re
5import socket
6
7from .common import InfoExtractor
8c25f81b 8from ..compat import (
0803753f 9 compat_etree_fromstring,
9eae41dd 10 compat_http_client,
9eae41dd 11 compat_urllib_error,
d7011316 12 compat_urllib_parse_unquote,
0803753f 13 compat_urllib_parse_unquote_plus,
8c25f81b
PH
14)
15from ..utils import (
b83ef507 16 clean_html,
9b9c5355 17 error_to_compat_str,
9eae41dd 18 ExtractorError,
b83ef507 19 get_element_by_id,
196c6ba0 20 int_or_none,
b83ef507 21 js_to_json,
a020a0dc 22 limit_length,
5c2266df 23 sanitized_Request,
b83ef507 24 try_get,
2fc9f2b4 25 urlencode_postdata,
9eae41dd
PH
26)
27
28
29class FacebookIE(InfoExtractor):
9834872b 30 _VALID_URL = r'''(?x)
2e6e742c
S
31 (?:
32 https?://
30918999 33 (?:[\w-]+\.)?(?:facebook\.com|facebookcorewwwi\.onion)/
2e6e742c
S
34 (?:[^#]*?\#!/)?
35 (?:
36 (?:
37 video/video\.php|
38 photo\.php|
39 video\.php|
efbeddea
YCH
40 video/embed|
41 story\.php
42 )\?(?:.*?)(?:v|video_id|story_fbid)=|
9c7b509b 43 [^/]+/videos/(?:[^/]+/)?|
e738e433
YCH
44 [^/]+/posts/|
45 groups/[^/]+/permalink/
2e6e742c
S
46 )|
47 facebook:
48 )
49 (?P<id>[0-9]+)
50 '''
67874aef
JMF
51 _LOGIN_URL = 'https://www.facebook.com/login.php?next=http%3A%2F%2Ffacebook.com%2Fhome.php&login_attempt=1'
52 _CHECKPOINT_URL = 'https://www.facebook.com/checkpoint/?next=http%3A%2F%2Ffacebook.com%2Fhome.php&_fb_noscript=1'
9eae41dd 53 _NETRC_MACHINE = 'facebook'
cb3bb2cf 54 IE_NAME = 'facebook'
0803753f
YCH
55
56 _CHROME_USER_AGENT = 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/48.0.2564.97 Safari/537.36'
57
9c7b509b 58 _VIDEO_PAGE_TEMPLATE = 'https://www.facebook.com/video/video.php?v=%s'
9d082e7c 59 _VIDEO_PAGE_TAHOE_TEMPLATE = 'https://www.facebook.com/video/tahoe/async/%s/?chain=true&isvideo=true'
9c7b509b 60
60ac04e5 61 _TESTS = [{
50317dbb
PH
62 'url': 'https://www.facebook.com/video.php?v=637842556329505&fref=nf',
63 'md5': '6a40d33c0eccbb1af76cf0485a052659',
cb3bb2cf 64 'info_dict': {
50317dbb 65 'id': '637842556329505',
cb3bb2cf 66 'ext': 'mp4',
5e4f0619 67 'title': 're:Did you know Kei Nishikori is the first Asian man to ever reach a Grand Slam',
67b8a28a 68 'uploader': 'Tennis on Facebook',
196c6ba0
S
69 'upload_date': '20140908',
70 'timestamp': 1410199200,
01c742ec
YCH
71 },
72 'skip': 'Requires logging in',
a020a0dc 73 }, {
a020a0dc
PH
74 'url': 'https://www.facebook.com/video.php?v=274175099429670',
75 'info_dict': {
76 'id': '274175099429670',
77 'ext': 'mp4',
5a116e13 78 'title': 'Asif Nawab Butt posted a video to his Timeline.',
67b8a28a 79 'uploader': 'Asif Nawab Butt',
196c6ba0
S
80 'upload_date': '20140506',
81 'timestamp': 1399398998,
01c742ec 82 'thumbnail': r're:^https?://.*',
db3ca364
YCH
83 },
84 'expected_warnings': [
85 'title'
86 ]
0803753f
YCH
87 }, {
88 'note': 'Video with DASH manifest',
89 'url': 'https://www.facebook.com/video.php?v=957955867617029',
196c6ba0 90 'md5': 'b2c28d528273b323abe5c6ab59f0f030',
0803753f
YCH
91 'info_dict': {
92 'id': '957955867617029',
93 'ext': 'mp4',
94 'title': 'When you post epic content on instagram.com/433 8 million followers, this is ...',
95 'uploader': 'Demy de Zeeuw',
196c6ba0
S
96 'upload_date': '20160110',
97 'timestamp': 1452431627,
0803753f 98 },
01c742ec 99 'skip': 'Requires logging in',
9c7b509b
YCH
100 }, {
101 'url': 'https://www.facebook.com/maxlayn/posts/10153807558977570',
102 'md5': '037b1fa7f3c2d02b7a0d7bc16031ecc6',
103 'info_dict': {
104 'id': '544765982287235',
105 'ext': 'mp4',
106 'title': '"What are you doing running in the snow?"',
107 'uploader': 'FailArmy',
d9ee2e5c
YCH
108 },
109 'skip': 'Video gone',
98801241
YCH
110 }, {
111 'url': 'https://m.facebook.com/story.php?story_fbid=1035862816472149&id=116132035111903',
112 'md5': '1deb90b6ac27f7efcf6d747c8a27f5e3',
113 'info_dict': {
114 'id': '1035862816472149',
115 'ext': 'mp4',
116 'title': 'What the Flock Is Going On In New Zealand Credit: ViralHog',
117 'uploader': 'S. Saint',
118 },
d9ee2e5c 119 'skip': 'Video gone',
5080cbf9
YCH
120 }, {
121 'note': 'swf params escaped',
122 'url': 'https://www.facebook.com/barackobama/posts/10153664894881749',
123 'md5': '97ba073838964d12c70566e0085c2b91',
124 'info_dict': {
125 'id': '10153664894881749',
126 'ext': 'mp4',
01c742ec
YCH
127 'title': 'Average time to confirm recent Supreme Court nominees: 67 days Longest it\'s t...',
128 'thumbnail': r're:^https?://.*',
129 'timestamp': 1456259628,
130 'upload_date': '20160223',
131 'uploader': 'Barack Obama',
5080cbf9 132 },
d9ee2e5c
YCH
133 }, {
134 # have 1080P, but only up to 720p in swf params
135 'url': 'https://www.facebook.com/cnn/videos/10155529876156509/',
136 'md5': '0d9813160b146b3bc8744e006027fcc6',
137 'info_dict': {
138 'id': '10155529876156509',
139 'ext': 'mp4',
01c742ec 140 'title': 'She survived the holocaust — and years later, she’s getting her citizenship s...',
d9ee2e5c
YCH
141 'timestamp': 1477818095,
142 'upload_date': '20161030',
143 'uploader': 'CNN',
01c742ec 144 'thumbnail': r're:^https?://.*',
d9ee2e5c 145 },
78ef214d
S
146 }, {
147 # bigPipe.onPageletArrive ... onPageletArrive pagelet_group_mall
148 'url': 'https://www.facebook.com/yaroslav.korpan/videos/1417995061575415/',
149 'info_dict': {
150 'id': '1417995061575415',
151 'ext': 'mp4',
152 'title': 'md5:a7b86ca673f51800cd54687b7f4012fe',
153 'timestamp': 1486648217,
154 'upload_date': '20170209',
155 'uploader': 'Yaroslav Korpan',
156 },
157 'params': {
158 'skip_download': True,
159 },
71cdd756
S
160 }, {
161 'url': 'https://www.facebook.com/LaGuiaDelVaron/posts/1072691702860471',
162 'info_dict': {
163 'id': '1072691702860471',
164 'ext': 'mp4',
165 'title': 'md5:ae2d22a93fbb12dad20dc393a869739d',
166 'timestamp': 1477305000,
167 'upload_date': '20161024',
168 'uploader': 'La Guía Del Varón',
01c742ec 169 'thumbnail': r're:^https?://.*',
71cdd756
S
170 },
171 'params': {
172 'skip_download': True,
173 },
174 }, {
175 'url': 'https://www.facebook.com/groups/1024490957622648/permalink/1396382447100162/',
176 'info_dict': {
177 'id': '1396382447100162',
178 'ext': 'mp4',
179 'title': 'md5:e2d2700afdf84e121f5d0f999bad13a3',
180 'timestamp': 1486035494,
181 'upload_date': '20170202',
182 'uploader': 'Elisabeth Ahtn',
183 },
184 'params': {
185 'skip_download': True,
186 },
60ac04e5
PH
187 }, {
188 'url': 'https://www.facebook.com/video.php?v=10204634152394104',
189 'only_matching': True,
c6256697
YCH
190 }, {
191 'url': 'https://www.facebook.com/amogood/videos/1618742068337349/?fref=nf',
192 'only_matching': True,
53faa3ca
YCH
193 }, {
194 'url': 'https://www.facebook.com/ChristyClarkForBC/videos/vb.22819070941/10153870694020942/?type=2&theater',
195 'only_matching': True,
2e6e742c
S
196 }, {
197 'url': 'facebook:544765982287235',
198 'only_matching': True,
e738e433
YCH
199 }, {
200 'url': 'https://www.facebook.com/groups/164828000315060/permalink/764967300301124/',
201 'only_matching': True,
b4a131e1
S
202 }, {
203 'url': 'https://zh-hk.facebook.com/peoplespower/videos/1135894589806027/',
204 'only_matching': True,
30918999
YCH
205 }, {
206 'url': 'https://www.facebookcorewwwi.onion/video.php?v=274175099429670',
207 'only_matching': True,
66bf351f
S
208 }, {
209 # no title
210 'url': 'https://www.facebook.com/onlycleverentertainment/videos/1947995502095005/',
211 'only_matching': True,
9d082e7c
NR
212 }, {
213 'url': 'https://www.facebook.com/WatchESLOne/videos/359649331226507/',
214 'info_dict': {
215 'id': '359649331226507',
216 'ext': 'mp4',
217 'title': '#ESLOne VoD - Birmingham Finals Day#1 Fnatic vs. @Evil Geniuses',
218 'uploader': 'ESL One Dota 2',
219 },
220 'params': {
221 'skip_download': True,
222 },
60ac04e5 223 }]
9eae41dd 224
fd6ca382 225 @staticmethod
0646e34c
S
226 def _extract_urls(webpage):
227 urls = []
228 for mobj in re.finditer(
229 r'<iframe[^>]+?src=(["\'])(?P<url>https?://www\.facebook\.com/(?:video/embed|plugins/video\.php).+?)\1',
230 webpage):
231 urls.append(mobj.group('url'))
fd6ca382
YCH
232 # Facebook API embed
233 # see https://developers.facebook.com/docs/plugins/embedded-video-player
0646e34c 234 for mobj in re.finditer(r'''(?x)<div[^>]+
369bb062 235 class=(?P<q1>[\'"])[^\'"]*\bfb-(?:video|post)\b[^\'"]*(?P=q1)[^>]+
0646e34c
S
236 data-href=(?P<q2>[\'"])(?P<url>(?:https?:)?//(?:www\.)?facebook.com/.+?)(?P=q2)''', webpage):
237 urls.append(mobj.group('url'))
238 return urls
fd6ca382 239
67874aef 240 def _login(self):
68217024 241 useremail, password = self._get_login_info()
9eae41dd
PH
242 if useremail is None:
243 return
244
5c2266df 245 login_page_req = sanitized_Request(self._LOGIN_URL)
c1f49e16 246 self._set_cookie('facebook.com', 'locale', 'en_US')
b74fa8cd 247 login_page = self._download_webpage(login_page_req, None,
9e1a5b84
JW
248 note='Downloading login page',
249 errnote='Unable to download login page')
b37b9450 250 lsd = self._search_regex(
d0ff8384 251 r'<input type="hidden" name="lsd" value="([^"]*)"',
b37b9450 252 login_page, 'lsd')
cb3bb2cf 253 lgnrnd = self._search_regex(r'name="lgnrnd" value="([^"]*?)"', login_page, 'lgnrnd')
67874aef 254
9eae41dd
PH
255 login_form = {
256 'email': useremail,
257 'pass': password,
67874aef
JMF
258 'lsd': lsd,
259 'lgnrnd': lgnrnd,
260 'next': 'http://facebook.com/home.php',
261 'default_persistent': '0',
262 'legacy_return': '1',
263 'timezone': '-60',
264 'trynum': '1',
b74e86f4 265 }
5c2266df 266 request = sanitized_Request(self._LOGIN_URL, urlencode_postdata(login_form))
67874aef 267 request.add_header('Content-Type', 'application/x-www-form-urlencoded')
9eae41dd 268 try:
b74fa8cd 269 login_results = self._download_webpage(request, None,
9e1a5b84 270 note='Logging in', errnote='unable to fetch login page')
9eae41dd 271 if re.search(r'<form(.*)name="login"(.*)</form>', login_results) is not None:
9f66931e
S
272 error = self._html_search_regex(
273 r'(?s)<div[^>]+class=(["\']).*?login_error_box.*?\1[^>]*><div[^>]*>.*?</div><div[^>]*>(?P<error>.+?)</div>',
274 login_results, 'login error', default=None, group='error')
275 if error:
276 raise ExtractorError('Unable to login: %s' % error, expected=True)
dfb1b146 277 self._downloader.report_warning('unable to log in: bad username/password, or exceeded login rate limit (~3/min). Check credentials or wait.')
9eae41dd 278 return
67874aef 279
c1f49e16
S
280 fb_dtsg = self._search_regex(
281 r'name="fb_dtsg" value="(.+?)"', login_results, 'fb_dtsg', default=None)
282 h = self._search_regex(
283 r'name="h"\s+(?:\w+="[^"]+"\s+)*?value="([^"]+)"', login_results, 'h', default=None)
284
285 if not fb_dtsg or not h:
286 return
287
67874aef 288 check_form = {
c1f49e16
S
289 'fb_dtsg': fb_dtsg,
290 'h': h,
67874aef 291 'name_action_selected': 'dont_save',
67874aef 292 }
5c2266df 293 check_req = sanitized_Request(self._CHECKPOINT_URL, urlencode_postdata(check_form))
67874aef 294 check_req.add_header('Content-Type', 'application/x-www-form-urlencoded')
b74fa8cd 295 check_response = self._download_webpage(check_req, None,
9e1a5b84 296 note='Confirming login')
67874aef 297 if re.search(r'id="checkpointSubmitButton"', check_response) is not None:
dfb1b146 298 self._downloader.report_warning('Unable to confirm login, you have to login in your browser and authorize the login.')
9eae41dd 299 except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
9b9c5355 300 self._downloader.report_warning('unable to log in: %s' % error_to_compat_str(err))
9eae41dd
PH
301 return
302
67874aef
JMF
303 def _real_initialize(self):
304 self._login()
305
9c7b509b
YCH
306 def _extract_from_url(self, url, video_id, fatal_if_no_video=True):
307 req = sanitized_Request(url)
0803753f
YCH
308 req.add_header('User-Agent', self._CHROME_USER_AGENT)
309 webpage = self._download_webpage(req, video_id)
9eae41dd 310
c1406299
YCH
311 video_data = None
312
b83ef507
S
313 def extract_video_data(instances):
314 for item in instances:
315 if item[1][0] == 'VideoConfig':
316 video_item = item[2][0]
71cdd756 317 if video_item.get('video_id'):
b83ef507
S
318 return video_item['videoData']
319
d9ee2e5c 320 server_js_data = self._parse_json(self._search_regex(
b83ef507
S
321 r'handleServerJS\(({.+})(?:\);|,")', webpage,
322 'server js data', default='{}'), video_id, fatal=False)
323
324 if server_js_data:
325 video_data = extract_video_data(server_js_data.get('instances', []))
326
9b89daef
S
327 def extract_from_jsmods_instances(js_data):
328 if js_data:
329 return extract_video_data(try_get(
330 js_data, lambda x: x['jsmods']['instances'], list) or [])
331
b83ef507
S
332 if not video_data:
333 server_js_data = self._parse_json(
334 self._search_regex(
11bb6ad1 335 r'bigPipe\.onPageletArrive\(({.+?})\)\s*;\s*}\s*\)\s*,\s*["\']onPageletArrive\s+(?:stream_pagelet|pagelet_group_mall|permalink_video_pagelet)',
b83ef507
S
336 webpage, 'js data', default='{}'),
337 video_id, transform_source=js_to_json, fatal=False)
9b89daef 338 video_data = extract_from_jsmods_instances(server_js_data)
c1406299 339
9d082e7c 340 if not video_data:
9b89daef
S
341 if not fatal_if_no_video:
342 return webpage, False
343 m_msg = re.search(r'class="[^"]*uiInterstitialContent[^"]*"><div>(.*?)</div>', webpage)
344 if m_msg is not None:
345 raise ExtractorError(
346 'The video is not available, Facebook said: "%s"' % m_msg.group(1),
347 expected=True)
348 elif '>You must log in to continue' in webpage:
349 self.raise_login_required()
350
351 # Video info not in first request, do a secondary request using
352 # tahoe player specific URL
9d082e7c
NR
353 tahoe_data = self._download_webpage(
354 self._VIDEO_PAGE_TAHOE_TEMPLATE % video_id, video_id,
355 data=urlencode_postdata({
356 '__user': 0,
357 '__a': 1,
9b89daef
S
358 '__pc': self._search_regex(
359 r'pkg_cohort["\']\s*:\s*["\'](.+?)["\']', webpage,
360 'pkg cohort', default='PHASED:DEFAULT'),
361 '__rev': self._search_regex(
362 r'client_revision["\']\s*:\s*(\d+),', webpage,
363 'client revision', default='3944515'),
9d082e7c
NR
364 }),
365 headers={
366 'Content-Type': 'application/x-www-form-urlencoded',
367 })
9b89daef
S
368 tahoe_js_data = self._parse_json(
369 self._search_regex(
370 r'for\s+\(\s*;\s*;\s*\)\s*;(.+)', tahoe_data,
371 'tahoe js data', default='{}'),
372 video_id, fatal=False)
373 video_data = extract_from_jsmods_instances(tahoe_js_data)
9d082e7c 374
c1406299 375 if not video_data:
9b89daef 376 raise ExtractorError('Cannot parse data')
ffdf972b
JMF
377
378 formats = []
d9ee2e5c
YCH
379 for f in video_data:
380 format_id = f['stream_type']
ca74c90b
SC
381 if f and isinstance(f, dict):
382 f = [f]
44d6dd08
S
383 if not f or not isinstance(f, list):
384 continue
385 for quality in ('sd', 'hd'):
386 for src_type in ('src', 'src_no_ratelimit'):
387 src = f[0].get('%s_%s' % (quality, src_type))
388 if src:
c24883a1
YCH
389 preference = -10 if format_id == 'progressive' else 0
390 if quality == 'hd':
391 preference += 5
44d6dd08
S
392 formats.append({
393 'format_id': '%s_%s_%s' % (format_id, quality, src_type),
394 'url': src,
c24883a1 395 'preference': preference,
44d6dd08 396 })
0803753f
YCH
397 dash_manifest = f[0].get('dash_manifest')
398 if dash_manifest:
91cb6b50 399 formats.extend(self._parse_mpd_formats(
c11875b3 400 compat_etree_fromstring(compat_urllib_parse_unquote_plus(dash_manifest))))
ffdf972b
JMF
401 if not formats:
402 raise ExtractorError('Cannot find video formats')
9eae41dd 403
0803753f
YCH
404 self._sort_formats(formats)
405
81ec7c79 406 video_title = self._html_search_regex(
66bf351f
S
407 r'<h2\s+[^>]*class="uiHeaderTitle"[^>]*>([^<]*)</h2>', webpage,
408 'title', default=None)
50317dbb
PH
409 if not video_title:
410 video_title = self._html_search_regex(
411 r'(?s)<span class="fbPhotosPhotoCaption".*?id="fbPhotoPageCaption"><span class="hasCaption">(.*?)</span>',
59ee8a86 412 webpage, 'alternative title', default=None)
50317dbb 413 if not video_title:
5a116e13 414 video_title = self._html_search_meta(
66bf351f 415 'description', webpage, 'title', default=None)
5a116e13
S
416 if video_title:
417 video_title = limit_length(video_title, 80)
418 else:
50317dbb 419 video_title = 'Facebook video #%s' % video_id
9b89daef
S
420 uploader = clean_html(get_element_by_id(
421 'fbPhotoPageAuthorName', webpage)) or self._search_regex(
422 r'ownerName\s*:\s*"([^"]+)"', webpage, 'uploader',
423 fatal=False) or self._og_search_title(webpage, fatal=False)
196c6ba0
S
424 timestamp = int_or_none(self._search_regex(
425 r'<abbr[^>]+data-utime=["\'](\d+)', webpage,
426 'timestamp', default=None))
01c742ec 427 thumbnail = self._og_search_thumbnail(webpage)
9eae41dd 428
9c7b509b 429 info_dict = {
9eae41dd
PH
430 'id': video_id,
431 'title': video_title,
ffdf972b 432 'formats': formats,
51a57515 433 'uploader': uploader,
196c6ba0 434 'timestamp': timestamp,
01c742ec 435 'thumbnail': thumbnail,
9eae41dd 436 }
de691a49 437
9c7b509b 438 return webpage, info_dict
de691a49
S
439
440 def _real_extract(self, url):
9c7b509b
YCH
441 video_id = self._match_id(url)
442
443 real_url = self._VIDEO_PAGE_TEMPLATE % video_id if url.startswith('facebook:') else url
444 webpage, info_dict = self._extract_from_url(real_url, video_id, fatal_if_no_video=False)
de691a49 445
9c7b509b
YCH
446 if info_dict:
447 return info_dict
de691a49 448
9c7b509b
YCH
449 if '/posts/' in url:
450 entries = [
f6f6217a
JMF
451 self.url_result('facebook:%s' % vid, FacebookIE.ie_key())
452 for vid in self._parse_json(
9c7b509b
YCH
453 self._search_regex(
454 r'(["\'])video_ids\1\s*:\s*(?P<ids>\[.+?\])',
455 webpage, 'video ids', group='ids'),
456 video_id)]
de691a49 457
9c7b509b
YCH
458 return self.playlist_result(entries, video_id)
459 else:
460 _, info_dict = self._extract_from_url(
461 self._VIDEO_PAGE_TEMPLATE % video_id,
462 video_id, fatal_if_no_video=True)
463 return info_dict
349fc5c7
S
464
465
466class FacebookPluginsVideoIE(InfoExtractor):
467 _VALID_URL = r'https?://(?:[\w-]+\.)?facebook\.com/plugins/video\.php\?.*?\bhref=(?P<id>https.+)'
468
469 _TESTS = [{
470 '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',
471 'md5': '5954e92cdfe51fe5782ae9bda7058a07',
472 'info_dict': {
473 'id': '10154383743583686',
474 'ext': 'mp4',
475 'title': 'What to do during the haze?',
476 'uploader': 'Gov.sg',
477 'upload_date': '20160826',
478 'timestamp': 1472184808,
479 },
480 'add_ie': [FacebookIE.ie_key()],
481 }, {
482 'url': 'https://www.facebook.com/plugins/video.php?href=https%3A%2F%2Fwww.facebook.com%2Fvideo.php%3Fv%3D10204634152394104',
483 'only_matching': True,
484 }, {
485 'url': 'https://www.facebook.com/plugins/video.php?href=https://www.facebook.com/gov.sg/videos/10154383743583686/&show_text=0&width=560',
486 'only_matching': True,
487 }]
488
489 def _real_extract(self, url):
490 return self.url_result(
491 compat_urllib_parse_unquote(self._match_id(url)),
492 FacebookIE.ie_key())