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,
26 class FacebookIE(InfoExtractor):
30 (?:[\w-]+\.)?facebook\.com/
39 )\?(?:.*?)(?:v|video_id|story_fbid)=|
40 [^/]+/videos/(?:[^/]+/)?|
42 groups/[^/]+/permalink/
48 _LOGIN_URL = 'https://www.facebook.com/login.php?next=http%3A%2F%2Ffacebook.com%2Fhome.php&login_attempt=1'
49 _CHECKPOINT_URL = 'https://www.facebook.com/checkpoint/?next=http%3A%2F%2Ffacebook.com%2Fhome.php&_fb_noscript=1'
50 _NETRC_MACHINE = 'facebook'
53 _CHROME_USER_AGENT = 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/48.0.2564.97 Safari/537.36'
55 _VIDEO_PAGE_TEMPLATE = 'https://www.facebook.com/video/video.php?v=%s'
58 'url': 'https://www.facebook.com/video.php?v=637842556329505&fref=nf',
59 'md5': '6a40d33c0eccbb1af76cf0485a052659',
61 'id': '637842556329505',
63 'title': 're:Did you know Kei Nishikori is the first Asian man to ever reach a Grand Slam',
64 'uploader': 'Tennis on Facebook',
65 'upload_date': '20140908',
66 'timestamp': 1410199200,
69 'note': 'Video without discernible title',
70 'url': 'https://www.facebook.com/video.php?v=274175099429670',
72 'id': '274175099429670',
74 'title': 'Facebook video #274175099429670',
75 'uploader': 'Asif Nawab Butt',
76 'upload_date': '20140506',
77 'timestamp': 1399398998,
79 'expected_warnings': [
83 'note': 'Video with DASH manifest',
84 'url': 'https://www.facebook.com/video.php?v=957955867617029',
85 'md5': 'b2c28d528273b323abe5c6ab59f0f030',
87 'id': '957955867617029',
89 'title': 'When you post epic content on instagram.com/433 8 million followers, this is ...',
90 'uploader': 'Demy de Zeeuw',
91 'upload_date': '20160110',
92 'timestamp': 1452431627,
95 'url': 'https://www.facebook.com/maxlayn/posts/10153807558977570',
96 'md5': '037b1fa7f3c2d02b7a0d7bc16031ecc6',
98 'id': '544765982287235',
100 'title': '"What are you doing running in the snow?"',
101 'uploader': 'FailArmy',
103 'skip': 'Video gone',
105 'url': 'https://m.facebook.com/story.php?story_fbid=1035862816472149&id=116132035111903',
106 'md5': '1deb90b6ac27f7efcf6d747c8a27f5e3',
108 'id': '1035862816472149',
110 'title': 'What the Flock Is Going On In New Zealand Credit: ViralHog',
111 'uploader': 'S. Saint',
113 'skip': 'Video gone',
115 'note': 'swf params escaped',
116 'url': 'https://www.facebook.com/barackobama/posts/10153664894881749',
117 'md5': '97ba073838964d12c70566e0085c2b91',
119 'id': '10153664894881749',
121 'title': 'Facebook video #10153664894881749',
124 # have 1080P, but only up to 720p in swf params
125 'url': 'https://www.facebook.com/cnn/videos/10155529876156509/',
126 'md5': '0d9813160b146b3bc8744e006027fcc6',
128 'id': '10155529876156509',
130 'title': 'Holocaust survivor becomes US citizen',
131 'timestamp': 1477818095,
132 'upload_date': '20161030',
136 'url': 'https://www.facebook.com/video.php?v=10204634152394104',
137 'only_matching': True,
139 'url': 'https://www.facebook.com/amogood/videos/1618742068337349/?fref=nf',
140 'only_matching': True,
142 'url': 'https://www.facebook.com/ChristyClarkForBC/videos/vb.22819070941/10153870694020942/?type=2&theater',
143 'only_matching': True,
145 'url': 'facebook:544765982287235',
146 'only_matching': True,
148 'url': 'https://www.facebook.com/groups/164828000315060/permalink/764967300301124/',
149 'only_matching': True,
151 'url': 'https://zh-hk.facebook.com/peoplespower/videos/1135894589806027/',
152 'only_matching': True,
156 def _extract_url(webpage):
158 r'<iframe[^>]+?src=(["\'])(?P<url>https://www\.facebook\.com/video/embed.+?)\1', webpage)
160 return mobj.group('url')
163 # see https://developers.facebook.com/docs/plugins/embedded-video-player
164 mobj = re.search(r'''(?x)<div[^>]+
165 class=(?P<q1>[\'"])[^\'"]*\bfb-(?:video|post)\b[^\'"]*(?P=q1)[^>]+
166 data-href=(?P<q2>[\'"])(?P<url>(?:https?:)?//(?:www\.)?facebook.com/.+?)(?P=q2)''', webpage)
168 return mobj.group('url')
171 (useremail, password) = self._get_login_info()
172 if useremail is None:
175 login_page_req = sanitized_Request(self._LOGIN_URL)
176 self._set_cookie('facebook.com', 'locale', 'en_US')
177 login_page = self._download_webpage(login_page_req, None,
178 note='Downloading login page',
179 errnote='Unable to download login page')
180 lsd = self._search_regex(
181 r'<input type="hidden" name="lsd" value="([^"]*)"',
183 lgnrnd = self._search_regex(r'name="lgnrnd" value="([^"]*?)"', login_page, 'lgnrnd')
190 'next': 'http://facebook.com/home.php',
191 'default_persistent': '0',
192 'legacy_return': '1',
196 request = sanitized_Request(self._LOGIN_URL, urlencode_postdata(login_form))
197 request.add_header('Content-Type', 'application/x-www-form-urlencoded')
199 login_results = self._download_webpage(request, None,
200 note='Logging in', errnote='unable to fetch login page')
201 if re.search(r'<form(.*)name="login"(.*)</form>', login_results) is not None:
202 error = self._html_search_regex(
203 r'(?s)<div[^>]+class=(["\']).*?login_error_box.*?\1[^>]*><div[^>]*>.*?</div><div[^>]*>(?P<error>.+?)</div>',
204 login_results, 'login error', default=None, group='error')
206 raise ExtractorError('Unable to login: %s' % error, expected=True)
207 self._downloader.report_warning('unable to log in: bad username/password, or exceeded login rate limit (~3/min). Check credentials or wait.')
210 fb_dtsg = self._search_regex(
211 r'name="fb_dtsg" value="(.+?)"', login_results, 'fb_dtsg', default=None)
212 h = self._search_regex(
213 r'name="h"\s+(?:\w+="[^"]+"\s+)*?value="([^"]+)"', login_results, 'h', default=None)
215 if not fb_dtsg or not h:
221 'name_action_selected': 'dont_save',
223 check_req = sanitized_Request(self._CHECKPOINT_URL, urlencode_postdata(check_form))
224 check_req.add_header('Content-Type', 'application/x-www-form-urlencoded')
225 check_response = self._download_webpage(check_req, None,
226 note='Confirming login')
227 if re.search(r'id="checkpointSubmitButton"', check_response) is not None:
228 self._downloader.report_warning('Unable to confirm login, you have to login in your browser and authorize the login.')
229 except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
230 self._downloader.report_warning('unable to log in: %s' % error_to_compat_str(err))
233 def _real_initialize(self):
236 def _extract_from_url(self, url, video_id, fatal_if_no_video=True):
237 req = sanitized_Request(url)
238 req.add_header('User-Agent', self._CHROME_USER_AGENT)
239 webpage = self._download_webpage(req, video_id)
243 server_js_data = self._parse_json(self._search_regex(
244 r'handleServerJS\(({.+})(?:\);|,")', webpage, 'server js data', default='{}'), video_id)
245 for item in server_js_data.get('instances', []):
246 if item[1][0] == 'VideoConfig':
247 video_data = item[2][0]['videoData']
251 if not fatal_if_no_video:
252 return webpage, False
253 m_msg = re.search(r'class="[^"]*uiInterstitialContent[^"]*"><div>(.*?)</div>', webpage)
254 if m_msg is not None:
255 raise ExtractorError(
256 'The video is not available, Facebook said: "%s"' % m_msg.group(1),
259 raise ExtractorError('Cannot parse data')
263 format_id = f['stream_type']
264 if f and isinstance(f, dict):
266 if not f or not isinstance(f, list):
268 for quality in ('sd', 'hd'):
269 for src_type in ('src', 'src_no_ratelimit'):
270 src = f[0].get('%s_%s' % (quality, src_type))
272 preference = -10 if format_id == 'progressive' else 0
276 'format_id': '%s_%s_%s' % (format_id, quality, src_type),
278 'preference': preference,
280 dash_manifest = f[0].get('dash_manifest')
282 formats.extend(self._parse_mpd_formats(
283 compat_etree_fromstring(compat_urllib_parse_unquote_plus(dash_manifest))))
285 raise ExtractorError('Cannot find video formats')
287 self._sort_formats(formats)
289 video_title = self._html_search_regex(
290 r'<h2\s+[^>]*class="uiHeaderTitle"[^>]*>([^<]*)</h2>', webpage, 'title',
293 video_title = self._html_search_regex(
294 r'(?s)<span class="fbPhotosPhotoCaption".*?id="fbPhotoPageCaption"><span class="hasCaption">(.*?)</span>',
295 webpage, 'alternative title', default=None)
296 video_title = limit_length(video_title, 80)
298 video_title = 'Facebook video #%s' % video_id
299 uploader = clean_html(get_element_by_id('fbPhotoPageAuthorName', webpage))
300 timestamp = int_or_none(self._search_regex(
301 r'<abbr[^>]+data-utime=["\'](\d+)', webpage,
302 'timestamp', default=None))
306 'title': video_title,
308 'uploader': uploader,
309 'timestamp': timestamp,
312 return webpage, info_dict
314 def _real_extract(self, url):
315 video_id = self._match_id(url)
317 real_url = self._VIDEO_PAGE_TEMPLATE % video_id if url.startswith('facebook:') else url
318 webpage, info_dict = self._extract_from_url(real_url, video_id, fatal_if_no_video=False)
325 self.url_result('facebook:%s' % vid, FacebookIE.ie_key())
326 for vid in self._parse_json(
328 r'(["\'])video_ids\1\s*:\s*(?P<ids>\[.+?\])',
329 webpage, 'video ids', group='ids'),
332 return self.playlist_result(entries, video_id)
334 _, info_dict = self._extract_from_url(
335 self._VIDEO_PAGE_TEMPLATE % video_id,
336 video_id, fatal_if_no_video=True)
340 class FacebookPluginsVideoIE(InfoExtractor):
341 _VALID_URL = r'https?://(?:[\w-]+\.)?facebook\.com/plugins/video\.php\?.*?\bhref=(?P<id>https.+)'
344 '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',
345 'md5': '5954e92cdfe51fe5782ae9bda7058a07',
347 'id': '10154383743583686',
349 'title': 'What to do during the haze?',
350 'uploader': 'Gov.sg',
351 'upload_date': '20160826',
352 'timestamp': 1472184808,
354 'add_ie': [FacebookIE.ie_key()],
356 'url': 'https://www.facebook.com/plugins/video.php?href=https%3A%2F%2Fwww.facebook.com%2Fvideo.php%3Fv%3D10204634152394104',
357 'only_matching': True,
359 'url': 'https://www.facebook.com/plugins/video.php?href=https://www.facebook.com/gov.sg/videos/10154383743583686/&show_text=0&width=560',
360 'only_matching': True,
363 def _real_extract(self, url):
364 return self.url_result(
365 compat_urllib_parse_unquote(self._match_id(url)),