1 from __future__ import unicode_literals
7 from .common import InfoExtractor
9 compat_etree_fromstring,
12 compat_urllib_parse_unquote,
13 compat_urllib_parse_unquote_plus,
27 class FacebookIE(InfoExtractor):
31 (?:[\w-]+\.)?facebook\.com/
40 )\?(?:.*?)(?:v|video_id|story_fbid)=|
41 [^/]+/videos/(?:[^/]+/)?|
43 groups/[^/]+/permalink/
49 _LOGIN_URL = 'https://www.facebook.com/login.php?next=http%3A%2F%2Ffacebook.com%2Fhome.php&login_attempt=1'
50 _CHECKPOINT_URL = 'https://www.facebook.com/checkpoint/?next=http%3A%2F%2Ffacebook.com%2Fhome.php&_fb_noscript=1'
51 _NETRC_MACHINE = 'facebook'
54 _CHROME_USER_AGENT = 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/48.0.2564.97 Safari/537.36'
56 _VIDEO_PAGE_TEMPLATE = 'https://www.facebook.com/video/video.php?v=%s'
59 'url': 'https://www.facebook.com/video.php?v=637842556329505&fref=nf',
60 'md5': '6a40d33c0eccbb1af76cf0485a052659',
62 'id': '637842556329505',
64 'title': 're:Did you know Kei Nishikori is the first Asian man to ever reach a Grand Slam',
65 'uploader': 'Tennis on Facebook',
66 'upload_date': '20140908',
67 'timestamp': 1410199200,
70 'note': 'Video without discernible title',
71 'url': 'https://www.facebook.com/video.php?v=274175099429670',
73 'id': '274175099429670',
75 'title': 'Facebook video #274175099429670',
76 'uploader': 'Asif Nawab Butt',
77 'upload_date': '20140506',
78 'timestamp': 1399398998,
80 'expected_warnings': [
84 'note': 'Video with DASH manifest',
85 'url': 'https://www.facebook.com/video.php?v=957955867617029',
86 'md5': 'b2c28d528273b323abe5c6ab59f0f030',
88 'id': '957955867617029',
90 'title': 'When you post epic content on instagram.com/433 8 million followers, this is ...',
91 'uploader': 'Demy de Zeeuw',
92 'upload_date': '20160110',
93 'timestamp': 1452431627,
96 'url': 'https://www.facebook.com/maxlayn/posts/10153807558977570',
97 'md5': '037b1fa7f3c2d02b7a0d7bc16031ecc6',
99 'id': '544765982287235',
101 'title': '"What are you doing running in the snow?"',
102 'uploader': 'FailArmy',
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',
114 'note': 'swf params escaped',
115 'url': 'https://www.facebook.com/barackobama/posts/10153664894881749',
116 'md5': '97ba073838964d12c70566e0085c2b91',
118 'id': '10153664894881749',
120 'title': 'Facebook video #10153664894881749',
123 'url': 'https://www.facebook.com/video.php?v=10204634152394104',
124 'only_matching': True,
126 'url': 'https://www.facebook.com/amogood/videos/1618742068337349/?fref=nf',
127 'only_matching': True,
129 'url': 'https://www.facebook.com/ChristyClarkForBC/videos/vb.22819070941/10153870694020942/?type=2&theater',
130 'only_matching': True,
132 'url': 'facebook:544765982287235',
133 'only_matching': True,
135 'url': 'https://www.facebook.com/groups/164828000315060/permalink/764967300301124/',
136 'only_matching': True,
138 'url': 'https://zh-hk.facebook.com/peoplespower/videos/1135894589806027/',
139 'only_matching': True,
143 def _extract_url(webpage):
145 r'<iframe[^>]+?src=(["\'])(?P<url>https://www\.facebook\.com/video/embed.+?)\1', webpage)
147 return mobj.group('url')
150 # see https://developers.facebook.com/docs/plugins/embedded-video-player
151 mobj = re.search(r'''(?x)<div[^>]+
152 class=(?P<q1>[\'"])[^\'"]*\bfb-(?:video|post)\b[^\'"]*(?P=q1)[^>]+
153 data-href=(?P<q2>[\'"])(?P<url>(?:https?:)?//(?:www\.)?facebook.com/.+?)(?P=q2)''', webpage)
155 return mobj.group('url')
158 (useremail, password) = self._get_login_info()
159 if useremail is None:
162 login_page_req = sanitized_Request(self._LOGIN_URL)
163 self._set_cookie('facebook.com', 'locale', 'en_US')
164 login_page = self._download_webpage(login_page_req, None,
165 note='Downloading login page',
166 errnote='Unable to download login page')
167 lsd = self._search_regex(
168 r'<input type="hidden" name="lsd" value="([^"]*)"',
170 lgnrnd = self._search_regex(r'name="lgnrnd" value="([^"]*?)"', login_page, 'lgnrnd')
177 'next': 'http://facebook.com/home.php',
178 'default_persistent': '0',
179 'legacy_return': '1',
183 request = sanitized_Request(self._LOGIN_URL, urlencode_postdata(login_form))
184 request.add_header('Content-Type', 'application/x-www-form-urlencoded')
186 login_results = self._download_webpage(request, None,
187 note='Logging in', errnote='unable to fetch login page')
188 if re.search(r'<form(.*)name="login"(.*)</form>', login_results) is not None:
189 error = self._html_search_regex(
190 r'(?s)<div[^>]+class=(["\']).*?login_error_box.*?\1[^>]*><div[^>]*>.*?</div><div[^>]*>(?P<error>.+?)</div>',
191 login_results, 'login error', default=None, group='error')
193 raise ExtractorError('Unable to login: %s' % error, expected=True)
194 self._downloader.report_warning('unable to log in: bad username/password, or exceeded login rate limit (~3/min). Check credentials or wait.')
197 fb_dtsg = self._search_regex(
198 r'name="fb_dtsg" value="(.+?)"', login_results, 'fb_dtsg', default=None)
199 h = self._search_regex(
200 r'name="h"\s+(?:\w+="[^"]+"\s+)*?value="([^"]+)"', login_results, 'h', default=None)
202 if not fb_dtsg or not h:
208 'name_action_selected': 'dont_save',
210 check_req = sanitized_Request(self._CHECKPOINT_URL, urlencode_postdata(check_form))
211 check_req.add_header('Content-Type', 'application/x-www-form-urlencoded')
212 check_response = self._download_webpage(check_req, None,
213 note='Confirming login')
214 if re.search(r'id="checkpointSubmitButton"', check_response) is not None:
215 self._downloader.report_warning('Unable to confirm login, you have to login in your browser and authorize the login.')
216 except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
217 self._downloader.report_warning('unable to log in: %s' % error_to_compat_str(err))
220 def _real_initialize(self):
223 def _extract_from_url(self, url, video_id, fatal_if_no_video=True):
224 req = sanitized_Request(url)
225 req.add_header('User-Agent', self._CHROME_USER_AGENT)
226 webpage = self._download_webpage(req, video_id)
230 BEFORE = '{swf.addParam(param[0], param[1]);});'
231 AFTER = '.forEach(function(variable) {swf.addVariable(variable[0], variable[1]);});'
232 PATTERN = re.escape(BEFORE) + '(?:\n|\\\\n)(.*?)' + re.escape(AFTER)
234 for m in re.findall(PATTERN, webpage):
235 swf_params = m.replace('\\\\', '\\').replace('\\"', '"')
236 data = dict(json.loads(swf_params))
237 params_raw = compat_urllib_parse_unquote(data['params'])
238 video_data_candidate = json.loads(params_raw)['video_data']
239 for _, f in video_data_candidate.items():
242 if isinstance(f, dict):
244 if not isinstance(f, list):
246 if f[0].get('video_id') == video_id:
247 video_data = video_data_candidate
252 def video_data_list2dict(video_data):
254 for item in video_data:
255 format_id = item['stream_type']
256 ret.setdefault(format_id, []).append(item)
260 server_js_data = self._parse_json(self._search_regex(
261 r'handleServerJS\(({.+})\);', webpage, 'server js data', default='{}'), video_id)
262 for item in server_js_data.get('instances', []):
263 if item[1][0] == 'VideoConfig':
264 video_data = video_data_list2dict(item[2][0]['videoData'])
268 if not fatal_if_no_video:
269 return webpage, False
270 m_msg = re.search(r'class="[^"]*uiInterstitialContent[^"]*"><div>(.*?)</div>', webpage)
271 if m_msg is not None:
272 raise ExtractorError(
273 'The video is not available, Facebook said: "%s"' % m_msg.group(1),
276 raise ExtractorError('Cannot parse data')
279 for format_id, f in video_data.items():
280 if f and isinstance(f, dict):
282 if not f or not isinstance(f, list):
284 for quality in ('sd', 'hd'):
285 for src_type in ('src', 'src_no_ratelimit'):
286 src = f[0].get('%s_%s' % (quality, src_type))
288 preference = -10 if format_id == 'progressive' else 0
292 'format_id': '%s_%s_%s' % (format_id, quality, src_type),
294 'preference': preference,
296 dash_manifest = f[0].get('dash_manifest')
298 formats.extend(self._parse_mpd_formats(
299 compat_etree_fromstring(compat_urllib_parse_unquote_plus(dash_manifest))))
301 raise ExtractorError('Cannot find video formats')
303 self._sort_formats(formats)
305 video_title = self._html_search_regex(
306 r'<h2\s+[^>]*class="uiHeaderTitle"[^>]*>([^<]*)</h2>', webpage, 'title',
309 video_title = self._html_search_regex(
310 r'(?s)<span class="fbPhotosPhotoCaption".*?id="fbPhotoPageCaption"><span class="hasCaption">(.*?)</span>',
311 webpage, 'alternative title', default=None)
312 video_title = limit_length(video_title, 80)
314 video_title = 'Facebook video #%s' % video_id
315 uploader = clean_html(get_element_by_id('fbPhotoPageAuthorName', webpage))
316 timestamp = int_or_none(self._search_regex(
317 r'<abbr[^>]+data-utime=["\'](\d+)', webpage,
318 'timestamp', default=None))
322 'title': video_title,
324 'uploader': uploader,
325 'timestamp': timestamp,
328 return webpage, info_dict
330 def _real_extract(self, url):
331 video_id = self._match_id(url)
333 real_url = self._VIDEO_PAGE_TEMPLATE % video_id if url.startswith('facebook:') else url
334 webpage, info_dict = self._extract_from_url(real_url, video_id, fatal_if_no_video=False)
341 self.url_result('facebook:%s' % vid, FacebookIE.ie_key())
342 for vid in self._parse_json(
344 r'(["\'])video_ids\1\s*:\s*(?P<ids>\[.+?\])',
345 webpage, 'video ids', group='ids'),
348 return self.playlist_result(entries, video_id)
350 _, info_dict = self._extract_from_url(
351 self._VIDEO_PAGE_TEMPLATE % video_id,
352 video_id, fatal_if_no_video=True)
356 class FacebookPluginsVideoIE(InfoExtractor):
357 _VALID_URL = r'https?://(?:[\w-]+\.)?facebook\.com/plugins/video\.php\?.*?\bhref=(?P<id>https.+)'
360 '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',
361 'md5': '5954e92cdfe51fe5782ae9bda7058a07',
363 'id': '10154383743583686',
365 'title': 'What to do during the haze?',
366 'uploader': 'Gov.sg',
367 'upload_date': '20160826',
368 'timestamp': 1472184808,
370 'add_ie': [FacebookIE.ie_key()],
372 'url': 'https://www.facebook.com/plugins/video.php?href=https%3A%2F%2Fwww.facebook.com%2Fvideo.php%3Fv%3D10204634152394104',
373 'only_matching': True,
375 'url': 'https://www.facebook.com/plugins/video.php?href=https://www.facebook.com/gov.sg/videos/10154383743583686/&show_text=0&width=560',
376 'only_matching': True,
379 def _real_extract(self, url):
380 return self.url_result(
381 compat_urllib_parse_unquote(self._match_id(url)),