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/(?:[^/]+/)?
46 _LOGIN_URL = 'https://www.facebook.com/login.php?next=http%3A%2F%2Ffacebook.com%2Fhome.php&login_attempt=1'
47 _CHECKPOINT_URL = 'https://www.facebook.com/checkpoint/?next=http%3A%2F%2Ffacebook.com%2Fhome.php&_fb_noscript=1'
48 _NETRC_MACHINE = 'facebook'
51 _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 'url': 'https://www.facebook.com/video.php?v=637842556329505&fref=nf',
55 'md5': '6a40d33c0eccbb1af76cf0485a052659',
57 'id': '637842556329505',
59 'title': 're:Did you know Kei Nishikori is the first Asian man to ever reach a Grand Slam',
60 'uploader': 'Tennis on Facebook',
63 'note': 'Video without discernible title',
64 'url': 'https://www.facebook.com/video.php?v=274175099429670',
66 'id': '274175099429670',
68 'title': 'Facebook video #274175099429670',
69 'uploader': 'Asif Nawab Butt',
71 'expected_warnings': [
75 'note': 'Video with DASH manifest',
76 'url': 'https://www.facebook.com/video.php?v=957955867617029',
77 'md5': '54706e4db4f5ad58fbad82dde1f1213f',
79 'id': '957955867617029',
81 'title': 'When you post epic content on instagram.com/433 8 million followers, this is ...',
82 'uploader': 'Demy de Zeeuw',
85 'url': 'https://www.facebook.com/video.php?v=10204634152394104',
86 'only_matching': True,
88 'url': 'https://www.facebook.com/amogood/videos/1618742068337349/?fref=nf',
89 'only_matching': True,
91 'url': 'https://www.facebook.com/ChristyClarkForBC/videos/vb.22819070941/10153870694020942/?type=2&theater',
92 'only_matching': True,
94 'url': 'facebook:544765982287235',
95 'only_matching': True,
97 'url': 'https://m.facebook.com/story.php?story_fbid=1035862816472149&id=116132035111903',
98 'only_matching': True,
102 (useremail, password) = self._get_login_info()
103 if useremail is None:
106 login_page_req = sanitized_Request(self._LOGIN_URL)
107 self._set_cookie('facebook.com', 'locale', 'en_US')
108 login_page = self._download_webpage(login_page_req, None,
109 note='Downloading login page',
110 errnote='Unable to download login page')
111 lsd = self._search_regex(
112 r'<input type="hidden" name="lsd" value="([^"]*)"',
114 lgnrnd = self._search_regex(r'name="lgnrnd" value="([^"]*?)"', login_page, 'lgnrnd')
121 'next': 'http://facebook.com/home.php',
122 'default_persistent': '0',
123 'legacy_return': '1',
127 request = sanitized_Request(self._LOGIN_URL, urlencode_postdata(login_form))
128 request.add_header('Content-Type', 'application/x-www-form-urlencoded')
130 login_results = self._download_webpage(request, None,
131 note='Logging in', errnote='unable to fetch login page')
132 if re.search(r'<form(.*)name="login"(.*)</form>', login_results) is not None:
133 error = self._html_search_regex(
134 r'(?s)<div[^>]+class=(["\']).*?login_error_box.*?\1[^>]*><div[^>]*>.*?</div><div[^>]*>(?P<error>.+?)</div>',
135 login_results, 'login error', default=None, group='error')
137 raise ExtractorError('Unable to login: %s' % error, expected=True)
138 self._downloader.report_warning('unable to log in: bad username/password, or exceeded login rate limit (~3/min). Check credentials or wait.')
141 fb_dtsg = self._search_regex(
142 r'name="fb_dtsg" value="(.+?)"', login_results, 'fb_dtsg', default=None)
143 h = self._search_regex(
144 r'name="h"\s+(?:\w+="[^"]+"\s+)*?value="([^"]+)"', login_results, 'h', default=None)
146 if not fb_dtsg or not h:
152 'name_action_selected': 'dont_save',
154 check_req = sanitized_Request(self._CHECKPOINT_URL, urlencode_postdata(check_form))
155 check_req.add_header('Content-Type', 'application/x-www-form-urlencoded')
156 check_response = self._download_webpage(check_req, None,
157 note='Confirming login')
158 if re.search(r'id="checkpointSubmitButton"', check_response) is not None:
159 self._downloader.report_warning('Unable to confirm login, you have to login in your browser and authorize the login.')
160 except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
161 self._downloader.report_warning('unable to log in: %s' % error_to_compat_str(err))
164 def _real_initialize(self):
167 def _real_extract(self, url):
168 video_id = self._match_id(url)
169 req = sanitized_Request('https://www.facebook.com/video/video.php?v=%s' % video_id)
170 req.add_header('User-Agent', self._CHROME_USER_AGENT)
171 webpage = self._download_webpage(req, video_id)
175 BEFORE = '{swf.addParam(param[0], param[1]);});\n'
176 AFTER = '.forEach(function(variable) {swf.addVariable(variable[0], variable[1]);});'
177 m = re.search(re.escape(BEFORE) + '(.*?)' + re.escape(AFTER), webpage)
179 data = dict(json.loads(m.group(1)))
180 params_raw = compat_urllib_parse_unquote(data['params'])
181 video_data = json.loads(params_raw)['video_data']
183 def video_data_list2dict(video_data):
185 for item in video_data:
186 format_id = item['stream_type']
187 ret.setdefault(format_id, []).append(item)
191 server_js_data = self._parse_json(self._search_regex(
192 r'handleServerJS\(({.+})\);', webpage, 'server js data'), video_id)
193 for item in server_js_data.get('instances', []):
194 if item[1][0] == 'VideoConfig':
195 video_data = video_data_list2dict(item[2][0]['videoData'])
199 m_msg = re.search(r'class="[^"]*uiInterstitialContent[^"]*"><div>(.*?)</div>', webpage)
200 if m_msg is not None:
201 raise ExtractorError(
202 'The video is not available, Facebook said: "%s"' % m_msg.group(1),
205 raise ExtractorError('Cannot parse data')
208 for format_id, f in video_data.items():
209 if not f or not isinstance(f, list):
211 for quality in ('sd', 'hd'):
212 for src_type in ('src', 'src_no_ratelimit'):
213 src = f[0].get('%s_%s' % (quality, src_type))
215 preference = -10 if format_id == 'progressive' else 0
219 'format_id': '%s_%s_%s' % (format_id, quality, src_type),
221 'preference': preference,
223 dash_manifest = f[0].get('dash_manifest')
225 formats.extend(self._parse_mpd_formats(
226 compat_etree_fromstring(compat_urllib_parse_unquote_plus(dash_manifest))))
228 raise ExtractorError('Cannot find video formats')
230 self._sort_formats(formats)
232 video_title = self._html_search_regex(
233 r'<h2\s+[^>]*class="uiHeaderTitle"[^>]*>([^<]*)</h2>', webpage, 'title',
236 video_title = self._html_search_regex(
237 r'(?s)<span class="fbPhotosPhotoCaption".*?id="fbPhotoPageCaption"><span class="hasCaption">(.*?)</span>',
238 webpage, 'alternative title', default=None)
239 video_title = limit_length(video_title, 80)
241 video_title = 'Facebook video #%s' % video_id
242 uploader = clean_html(get_element_by_id('fbPhotoPageAuthorName', webpage))
246 'title': video_title,
248 'uploader': uploader,
252 class FacebookPostIE(InfoExtractor):
253 IE_NAME = 'facebook:post'
254 _VALID_URL = r'https?://(?:\w+\.)?facebook\.com/[^/]+/posts/(?P<id>\d+)'
256 'url': 'https://www.facebook.com/maxlayn/posts/10153807558977570',
257 'md5': '037b1fa7f3c2d02b7a0d7bc16031ecc6',
259 'id': '544765982287235',
261 'title': '"What are you doing running in the snow?"',
262 'uploader': 'FailArmy',
266 def _real_extract(self, url):
267 post_id = self._match_id(url)
269 webpage = self._download_webpage(url, post_id)
272 self.url_result('facebook:%s' % video_id, FacebookIE.ie_key())
273 for video_id in self._parse_json(
275 r'(["\'])video_ids\1\s*:\s*(?P<ids>\[.+?\])',
276 webpage, 'video ids', group='ids'),
279 return self.playlist_result(entries, post_id)