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