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,
26 class FacebookIE(InfoExtractor):
30 (?:\w+\.)?facebook\.com/
39 )\?(?:.*?)(?:v|video_id|story_fbid)=|
40 [^/]+/videos/(?:[^/]+/)?|
47 _LOGIN_URL = 'https://www.facebook.com/login.php?next=http%3A%2F%2Ffacebook.com%2Fhome.php&login_attempt=1'
48 _CHECKPOINT_URL = 'https://www.facebook.com/checkpoint/?next=http%3A%2F%2Ffacebook.com%2Fhome.php&_fb_noscript=1'
49 _NETRC_MACHINE = 'facebook'
52 _CHROME_USER_AGENT = 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/48.0.2564.97 Safari/537.36'
54 _VIDEO_PAGE_TEMPLATE = 'https://www.facebook.com/video/video.php?v=%s'
57 'url': 'https://www.facebook.com/video.php?v=637842556329505&fref=nf',
58 'md5': '6a40d33c0eccbb1af76cf0485a052659',
60 'id': '637842556329505',
62 'title': 're:Did you know Kei Nishikori is the first Asian man to ever reach a Grand Slam',
63 'uploader': 'Tennis on Facebook',
66 'note': 'Video without discernible title',
67 'url': 'https://www.facebook.com/video.php?v=274175099429670',
69 'id': '274175099429670',
71 'title': 'Facebook video #274175099429670',
72 'uploader': 'Asif Nawab Butt',
74 'expected_warnings': [
78 'note': 'Video with DASH manifest',
79 'url': 'https://www.facebook.com/video.php?v=957955867617029',
80 'md5': '54706e4db4f5ad58fbad82dde1f1213f',
82 'id': '957955867617029',
84 'title': 'When you post epic content on instagram.com/433 8 million followers, this is ...',
85 'uploader': 'Demy de Zeeuw',
88 'url': 'https://www.facebook.com/maxlayn/posts/10153807558977570',
89 'md5': '037b1fa7f3c2d02b7a0d7bc16031ecc6',
91 'id': '544765982287235',
93 'title': '"What are you doing running in the snow?"',
94 'uploader': 'FailArmy',
97 'url': 'https://www.facebook.com/video.php?v=10204634152394104',
98 'only_matching': True,
100 'url': 'https://www.facebook.com/amogood/videos/1618742068337349/?fref=nf',
101 'only_matching': True,
103 'url': 'https://www.facebook.com/ChristyClarkForBC/videos/vb.22819070941/10153870694020942/?type=2&theater',
104 'only_matching': True,
106 'url': 'facebook:544765982287235',
107 'only_matching': True,
109 'url': 'https://m.facebook.com/story.php?story_fbid=1035862816472149&id=116132035111903',
110 'only_matching': True,
114 (useremail, password) = self._get_login_info()
115 if useremail is None:
118 login_page_req = sanitized_Request(self._LOGIN_URL)
119 self._set_cookie('facebook.com', 'locale', 'en_US')
120 login_page = self._download_webpage(login_page_req, None,
121 note='Downloading login page',
122 errnote='Unable to download login page')
123 lsd = self._search_regex(
124 r'<input type="hidden" name="lsd" value="([^"]*)"',
126 lgnrnd = self._search_regex(r'name="lgnrnd" value="([^"]*?)"', login_page, 'lgnrnd')
133 'next': 'http://facebook.com/home.php',
134 'default_persistent': '0',
135 'legacy_return': '1',
139 request = sanitized_Request(self._LOGIN_URL, urlencode_postdata(login_form))
140 request.add_header('Content-Type', 'application/x-www-form-urlencoded')
142 login_results = self._download_webpage(request, None,
143 note='Logging in', errnote='unable to fetch login page')
144 if re.search(r'<form(.*)name="login"(.*)</form>', login_results) is not None:
145 error = self._html_search_regex(
146 r'(?s)<div[^>]+class=(["\']).*?login_error_box.*?\1[^>]*><div[^>]*>.*?</div><div[^>]*>(?P<error>.+?)</div>',
147 login_results, 'login error', default=None, group='error')
149 raise ExtractorError('Unable to login: %s' % error, expected=True)
150 self._downloader.report_warning('unable to log in: bad username/password, or exceeded login rate limit (~3/min). Check credentials or wait.')
153 fb_dtsg = self._search_regex(
154 r'name="fb_dtsg" value="(.+?)"', login_results, 'fb_dtsg', default=None)
155 h = self._search_regex(
156 r'name="h"\s+(?:\w+="[^"]+"\s+)*?value="([^"]+)"', login_results, 'h', default=None)
158 if not fb_dtsg or not h:
164 'name_action_selected': 'dont_save',
166 check_req = sanitized_Request(self._CHECKPOINT_URL, urlencode_postdata(check_form))
167 check_req.add_header('Content-Type', 'application/x-www-form-urlencoded')
168 check_response = self._download_webpage(check_req, None,
169 note='Confirming login')
170 if re.search(r'id="checkpointSubmitButton"', check_response) is not None:
171 self._downloader.report_warning('Unable to confirm login, you have to login in your browser and authorize the login.')
172 except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
173 self._downloader.report_warning('unable to log in: %s' % error_to_compat_str(err))
176 def _real_initialize(self):
179 def _extract_from_url(self, url, video_id, fatal_if_no_video=True):
180 req = sanitized_Request(url)
181 req.add_header('User-Agent', self._CHROME_USER_AGENT)
182 webpage = self._download_webpage(req, video_id)
186 BEFORE = '{swf.addParam(param[0], param[1]);});\n'
187 AFTER = '.forEach(function(variable) {swf.addVariable(variable[0], variable[1]);});'
188 m = re.search(re.escape(BEFORE) + '(.*?)' + re.escape(AFTER), webpage)
190 data = dict(json.loads(m.group(1)))
191 params_raw = compat_urllib_parse_unquote(data['params'])
192 video_data = json.loads(params_raw)['video_data']
194 def video_data_list2dict(video_data):
196 for item in video_data:
197 format_id = item['stream_type']
198 ret.setdefault(format_id, []).append(item)
202 server_js_data = self._parse_json(self._search_regex(
203 r'handleServerJS\(({.+})\);', webpage, 'server js data'), video_id)
204 for item in server_js_data.get('instances', []):
205 if item[1][0] == 'VideoConfig':
206 video_data = video_data_list2dict(item[2][0]['videoData'])
210 if not fatal_if_no_video:
211 return webpage, False
212 m_msg = re.search(r'class="[^"]*uiInterstitialContent[^"]*"><div>(.*?)</div>', webpage)
213 if m_msg is not None:
214 raise ExtractorError(
215 'The video is not available, Facebook said: "%s"' % m_msg.group(1),
218 raise ExtractorError('Cannot parse data')
221 for format_id, f in video_data.items():
222 if not f or not isinstance(f, list):
224 for quality in ('sd', 'hd'):
225 for src_type in ('src', 'src_no_ratelimit'):
226 src = f[0].get('%s_%s' % (quality, src_type))
228 preference = -10 if format_id == 'progressive' else 0
232 'format_id': '%s_%s_%s' % (format_id, quality, src_type),
234 'preference': preference,
236 dash_manifest = f[0].get('dash_manifest')
238 formats.extend(self._parse_mpd_formats(
239 compat_etree_fromstring(compat_urllib_parse_unquote_plus(dash_manifest))))
241 raise ExtractorError('Cannot find video formats')
243 self._sort_formats(formats)
245 video_title = self._html_search_regex(
246 r'<h2\s+[^>]*class="uiHeaderTitle"[^>]*>([^<]*)</h2>', webpage, 'title',
249 video_title = self._html_search_regex(
250 r'(?s)<span class="fbPhotosPhotoCaption".*?id="fbPhotoPageCaption"><span class="hasCaption">(.*?)</span>',
251 webpage, 'alternative title', default=None)
252 video_title = limit_length(video_title, 80)
254 video_title = 'Facebook video #%s' % video_id
255 uploader = clean_html(get_element_by_id('fbPhotoPageAuthorName', webpage))
259 'title': video_title,
261 'uploader': uploader,
264 return webpage, info_dict
266 def _real_extract(self, url):
267 video_id = self._match_id(url)
269 real_url = self._VIDEO_PAGE_TEMPLATE % video_id if url.startswith('facebook:') else url
270 webpage, info_dict = self._extract_from_url(real_url, video_id, fatal_if_no_video=False)
277 self.url_result('facebook:%s' % video_id, FacebookIE.ie_key())
278 for video_id in self._parse_json(
280 r'(["\'])video_ids\1\s*:\s*(?P<ids>\[.+?\])',
281 webpage, 'video ids', group='ids'),
284 return self.playlist_result(entries, video_id)
286 _, info_dict = self._extract_from_url(
287 self._VIDEO_PAGE_TEMPLATE % video_id,
288 video_id, fatal_if_no_video=True)