1 from __future__ import unicode_literals
6 from .common import InfoExtractor
8 compat_etree_fromstring,
11 compat_urllib_parse_unquote,
12 compat_urllib_parse_unquote_plus,
28 class FacebookIE(InfoExtractor):
32 (?:[\w-]+\.)?(?:facebook\.com|facebookcorewwwi\.onion)/
41 )\?(?:.*?)(?:v|video_id|story_fbid)=|
42 [^/]+/videos/(?:[^/]+/)?|
44 groups/[^/]+/permalink/
50 _LOGIN_URL = 'https://www.facebook.com/login.php?next=http%3A%2F%2Ffacebook.com%2Fhome.php&login_attempt=1'
51 _CHECKPOINT_URL = 'https://www.facebook.com/checkpoint/?next=http%3A%2F%2Ffacebook.com%2Fhome.php&_fb_noscript=1'
52 _NETRC_MACHINE = 'facebook'
55 _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 _VIDEO_PAGE_TEMPLATE = 'https://www.facebook.com/video/video.php?v=%s'
60 'url': 'https://www.facebook.com/video.php?v=637842556329505&fref=nf',
61 'md5': '6a40d33c0eccbb1af76cf0485a052659',
63 'id': '637842556329505',
65 'title': 're:Did you know Kei Nishikori is the first Asian man to ever reach a Grand Slam',
66 'uploader': 'Tennis on Facebook',
67 'upload_date': '20140908',
68 'timestamp': 1410199200,
71 'note': 'Video without discernible title',
72 'url': 'https://www.facebook.com/video.php?v=274175099429670',
74 'id': '274175099429670',
76 'title': 'Asif Nawab Butt posted a video to his Timeline.',
77 'uploader': 'Asif Nawab Butt',
78 'upload_date': '20140506',
79 'timestamp': 1399398998,
81 'expected_warnings': [
85 'note': 'Video with DASH manifest',
86 'url': 'https://www.facebook.com/video.php?v=957955867617029',
87 'md5': 'b2c28d528273b323abe5c6ab59f0f030',
89 'id': '957955867617029',
91 'title': 'When you post epic content on instagram.com/433 8 million followers, this is ...',
92 'uploader': 'Demy de Zeeuw',
93 'upload_date': '20160110',
94 'timestamp': 1452431627,
97 'url': 'https://www.facebook.com/maxlayn/posts/10153807558977570',
98 'md5': '037b1fa7f3c2d02b7a0d7bc16031ecc6',
100 'id': '544765982287235',
102 'title': '"What are you doing running in the snow?"',
103 'uploader': 'FailArmy',
105 'skip': 'Video gone',
107 'url': 'https://m.facebook.com/story.php?story_fbid=1035862816472149&id=116132035111903',
108 'md5': '1deb90b6ac27f7efcf6d747c8a27f5e3',
110 'id': '1035862816472149',
112 'title': 'What the Flock Is Going On In New Zealand Credit: ViralHog',
113 'uploader': 'S. Saint',
115 'skip': 'Video gone',
117 'note': 'swf params escaped',
118 'url': 'https://www.facebook.com/barackobama/posts/10153664894881749',
119 'md5': '97ba073838964d12c70566e0085c2b91',
121 'id': '10153664894881749',
123 'title': 'Facebook video #10153664894881749',
126 # have 1080P, but only up to 720p in swf params
127 'url': 'https://www.facebook.com/cnn/videos/10155529876156509/',
128 'md5': '0d9813160b146b3bc8744e006027fcc6',
130 'id': '10155529876156509',
132 'title': 'Holocaust survivor becomes US citizen',
133 'timestamp': 1477818095,
134 'upload_date': '20161030',
138 # bigPipe.onPageletArrive ... onPageletArrive pagelet_group_mall
139 'url': 'https://www.facebook.com/yaroslav.korpan/videos/1417995061575415/',
141 'id': '1417995061575415',
143 'title': 'md5:a7b86ca673f51800cd54687b7f4012fe',
144 'timestamp': 1486648217,
145 'upload_date': '20170209',
146 'uploader': 'Yaroslav Korpan',
149 'skip_download': True,
152 'url': 'https://www.facebook.com/video.php?v=10204634152394104',
153 'only_matching': True,
155 'url': 'https://www.facebook.com/amogood/videos/1618742068337349/?fref=nf',
156 'only_matching': True,
158 'url': 'https://www.facebook.com/ChristyClarkForBC/videos/vb.22819070941/10153870694020942/?type=2&theater',
159 'only_matching': True,
161 'url': 'facebook:544765982287235',
162 'only_matching': True,
164 'url': 'https://www.facebook.com/groups/164828000315060/permalink/764967300301124/',
165 'only_matching': True,
167 'url': 'https://zh-hk.facebook.com/peoplespower/videos/1135894589806027/',
168 'only_matching': True,
170 'url': 'https://www.facebookcorewwwi.onion/video.php?v=274175099429670',
171 'only_matching': True,
175 def _extract_url(webpage):
177 r'<iframe[^>]+?src=(["\'])(?P<url>https://www\.facebook\.com/video/embed.+?)\1', webpage)
179 return mobj.group('url')
182 # see https://developers.facebook.com/docs/plugins/embedded-video-player
183 mobj = re.search(r'''(?x)<div[^>]+
184 class=(?P<q1>[\'"])[^\'"]*\bfb-(?:video|post)\b[^\'"]*(?P=q1)[^>]+
185 data-href=(?P<q2>[\'"])(?P<url>(?:https?:)?//(?:www\.)?facebook.com/.+?)(?P=q2)''', webpage)
187 return mobj.group('url')
190 (useremail, password) = self._get_login_info()
191 if useremail is None:
194 login_page_req = sanitized_Request(self._LOGIN_URL)
195 self._set_cookie('facebook.com', 'locale', 'en_US')
196 login_page = self._download_webpage(login_page_req, None,
197 note='Downloading login page',
198 errnote='Unable to download login page')
199 lsd = self._search_regex(
200 r'<input type="hidden" name="lsd" value="([^"]*)"',
202 lgnrnd = self._search_regex(r'name="lgnrnd" value="([^"]*?)"', login_page, 'lgnrnd')
209 'next': 'http://facebook.com/home.php',
210 'default_persistent': '0',
211 'legacy_return': '1',
215 request = sanitized_Request(self._LOGIN_URL, urlencode_postdata(login_form))
216 request.add_header('Content-Type', 'application/x-www-form-urlencoded')
218 login_results = self._download_webpage(request, None,
219 note='Logging in', errnote='unable to fetch login page')
220 if re.search(r'<form(.*)name="login"(.*)</form>', login_results) is not None:
221 error = self._html_search_regex(
222 r'(?s)<div[^>]+class=(["\']).*?login_error_box.*?\1[^>]*><div[^>]*>.*?</div><div[^>]*>(?P<error>.+?)</div>',
223 login_results, 'login error', default=None, group='error')
225 raise ExtractorError('Unable to login: %s' % error, expected=True)
226 self._downloader.report_warning('unable to log in: bad username/password, or exceeded login rate limit (~3/min). Check credentials or wait.')
229 fb_dtsg = self._search_regex(
230 r'name="fb_dtsg" value="(.+?)"', login_results, 'fb_dtsg', default=None)
231 h = self._search_regex(
232 r'name="h"\s+(?:\w+="[^"]+"\s+)*?value="([^"]+)"', login_results, 'h', default=None)
234 if not fb_dtsg or not h:
240 'name_action_selected': 'dont_save',
242 check_req = sanitized_Request(self._CHECKPOINT_URL, urlencode_postdata(check_form))
243 check_req.add_header('Content-Type', 'application/x-www-form-urlencoded')
244 check_response = self._download_webpage(check_req, None,
245 note='Confirming login')
246 if re.search(r'id="checkpointSubmitButton"', check_response) is not None:
247 self._downloader.report_warning('Unable to confirm login, you have to login in your browser and authorize the login.')
248 except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
249 self._downloader.report_warning('unable to log in: %s' % error_to_compat_str(err))
252 def _real_initialize(self):
255 def _extract_from_url(self, url, video_id, fatal_if_no_video=True):
256 req = sanitized_Request(url)
257 req.add_header('User-Agent', self._CHROME_USER_AGENT)
258 webpage = self._download_webpage(req, video_id)
262 def extract_video_data(instances):
263 for item in instances:
264 if item[1][0] == 'VideoConfig':
265 video_item = item[2][0]
266 if video_item.get('video_id') == video_id:
267 return video_item['videoData']
269 server_js_data = self._parse_json(self._search_regex(
270 r'handleServerJS\(({.+})(?:\);|,")', webpage,
271 'server js data', default='{}'), video_id, fatal=False)
274 video_data = extract_video_data(server_js_data.get('instances', []))
277 server_js_data = self._parse_json(
279 r'bigPipe\.onPageletArrive\(({.+?})\)\s*;\s*}\s*\)\s*,\s*["\']onPageletArrive\s+(?:stream_pagelet|pagelet_group_mall)',
280 webpage, 'js data', default='{}'),
281 video_id, transform_source=js_to_json, fatal=False)
283 video_data = extract_video_data(try_get(
284 server_js_data, lambda x: x['jsmods']['instances'],
288 if not fatal_if_no_video:
289 return webpage, False
290 m_msg = re.search(r'class="[^"]*uiInterstitialContent[^"]*"><div>(.*?)</div>', webpage)
291 if m_msg is not None:
292 raise ExtractorError(
293 'The video is not available, Facebook said: "%s"' % m_msg.group(1),
295 elif '>You must log in to continue' in webpage:
296 self.raise_login_required()
298 raise ExtractorError('Cannot parse data')
302 format_id = f['stream_type']
303 if f and isinstance(f, dict):
305 if not f or not isinstance(f, list):
307 for quality in ('sd', 'hd'):
308 for src_type in ('src', 'src_no_ratelimit'):
309 src = f[0].get('%s_%s' % (quality, src_type))
311 preference = -10 if format_id == 'progressive' else 0
315 'format_id': '%s_%s_%s' % (format_id, quality, src_type),
317 'preference': preference,
319 dash_manifest = f[0].get('dash_manifest')
321 formats.extend(self._parse_mpd_formats(
322 compat_etree_fromstring(compat_urllib_parse_unquote_plus(dash_manifest))))
324 raise ExtractorError('Cannot find video formats')
326 self._sort_formats(formats)
328 video_title = self._html_search_regex(
329 r'<h2\s+[^>]*class="uiHeaderTitle"[^>]*>([^<]*)</h2>', webpage, 'title',
332 video_title = self._html_search_regex(
333 r'(?s)<span class="fbPhotosPhotoCaption".*?id="fbPhotoPageCaption"><span class="hasCaption">(.*?)</span>',
334 webpage, 'alternative title', default=None)
336 video_title = self._html_search_meta(
337 'description', webpage, 'title')
339 video_title = limit_length(video_title, 80)
341 video_title = 'Facebook video #%s' % video_id
342 uploader = clean_html(get_element_by_id(
343 'fbPhotoPageAuthorName', webpage)) or self._search_regex(
344 r'ownerName\s*:\s*"([^"]+)"', webpage, 'uploader', fatal=False)
345 timestamp = int_or_none(self._search_regex(
346 r'<abbr[^>]+data-utime=["\'](\d+)', webpage,
347 'timestamp', default=None))
351 'title': video_title,
353 'uploader': uploader,
354 'timestamp': timestamp,
357 return webpage, info_dict
359 def _real_extract(self, url):
360 video_id = self._match_id(url)
362 real_url = self._VIDEO_PAGE_TEMPLATE % video_id if url.startswith('facebook:') else url
363 webpage, info_dict = self._extract_from_url(real_url, video_id, fatal_if_no_video=False)
370 self.url_result('facebook:%s' % vid, FacebookIE.ie_key())
371 for vid in self._parse_json(
373 r'(["\'])video_ids\1\s*:\s*(?P<ids>\[.+?\])',
374 webpage, 'video ids', group='ids'),
377 return self.playlist_result(entries, video_id)
379 _, info_dict = self._extract_from_url(
380 self._VIDEO_PAGE_TEMPLATE % video_id,
381 video_id, fatal_if_no_video=True)
385 class FacebookPluginsVideoIE(InfoExtractor):
386 _VALID_URL = r'https?://(?:[\w-]+\.)?facebook\.com/plugins/video\.php\?.*?\bhref=(?P<id>https.+)'
389 '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',
390 'md5': '5954e92cdfe51fe5782ae9bda7058a07',
392 'id': '10154383743583686',
394 'title': 'What to do during the haze?',
395 'uploader': 'Gov.sg',
396 'upload_date': '20160826',
397 'timestamp': 1472184808,
399 'add_ie': [FacebookIE.ie_key()],
401 'url': 'https://www.facebook.com/plugins/video.php?href=https%3A%2F%2Fwww.facebook.com%2Fvideo.php%3Fv%3D10204634152394104',
402 'only_matching': True,
404 'url': 'https://www.facebook.com/plugins/video.php?href=https://www.facebook.com/gov.sg/videos/10154383743583686/&show_text=0&width=560',
405 'only_matching': True,
408 def _real_extract(self, url):
409 return self.url_result(
410 compat_urllib_parse_unquote(self._match_id(url)),