]> Raphaƫl G. Git Repositories - youtubedl/blob - youtube_dl/extractor/facebook.py
debian/control: Remove mplayer2 from recommends. (Closes: #841187)
[youtubedl] / youtube_dl / extractor / facebook.py
1 from __future__ import unicode_literals
2
3 import re
4 import socket
5
6 from .common import InfoExtractor
7 from ..compat import (
8 compat_etree_fromstring,
9 compat_http_client,
10 compat_urllib_error,
11 compat_urllib_parse_unquote,
12 compat_urllib_parse_unquote_plus,
13 )
14 from ..utils import (
15 error_to_compat_str,
16 ExtractorError,
17 int_or_none,
18 limit_length,
19 sanitized_Request,
20 urlencode_postdata,
21 get_element_by_id,
22 clean_html,
23 )
24
25
26 class FacebookIE(InfoExtractor):
27 _VALID_URL = r'''(?x)
28 (?:
29 https?://
30 (?:[\w-]+\.)?facebook\.com/
31 (?:[^#]*?\#!/)?
32 (?:
33 (?:
34 video/video\.php|
35 photo\.php|
36 video\.php|
37 video/embed|
38 story\.php
39 )\?(?:.*?)(?:v|video_id|story_fbid)=|
40 [^/]+/videos/(?:[^/]+/)?|
41 [^/]+/posts/|
42 groups/[^/]+/permalink/
43 )|
44 facebook:
45 )
46 (?P<id>[0-9]+)
47 '''
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'
51 IE_NAME = 'facebook'
52
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'
54
55 _VIDEO_PAGE_TEMPLATE = 'https://www.facebook.com/video/video.php?v=%s'
56
57 _TESTS = [{
58 'url': 'https://www.facebook.com/video.php?v=637842556329505&fref=nf',
59 'md5': '6a40d33c0eccbb1af76cf0485a052659',
60 'info_dict': {
61 'id': '637842556329505',
62 'ext': 'mp4',
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,
67 }
68 }, {
69 'note': 'Video without discernible title',
70 'url': 'https://www.facebook.com/video.php?v=274175099429670',
71 'info_dict': {
72 'id': '274175099429670',
73 'ext': 'mp4',
74 'title': 'Facebook video #274175099429670',
75 'uploader': 'Asif Nawab Butt',
76 'upload_date': '20140506',
77 'timestamp': 1399398998,
78 },
79 'expected_warnings': [
80 'title'
81 ]
82 }, {
83 'note': 'Video with DASH manifest',
84 'url': 'https://www.facebook.com/video.php?v=957955867617029',
85 'md5': 'b2c28d528273b323abe5c6ab59f0f030',
86 'info_dict': {
87 'id': '957955867617029',
88 'ext': 'mp4',
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,
93 },
94 }, {
95 'url': 'https://www.facebook.com/maxlayn/posts/10153807558977570',
96 'md5': '037b1fa7f3c2d02b7a0d7bc16031ecc6',
97 'info_dict': {
98 'id': '544765982287235',
99 'ext': 'mp4',
100 'title': '"What are you doing running in the snow?"',
101 'uploader': 'FailArmy',
102 },
103 'skip': 'Video gone',
104 }, {
105 'url': 'https://m.facebook.com/story.php?story_fbid=1035862816472149&id=116132035111903',
106 'md5': '1deb90b6ac27f7efcf6d747c8a27f5e3',
107 'info_dict': {
108 'id': '1035862816472149',
109 'ext': 'mp4',
110 'title': 'What the Flock Is Going On In New Zealand Credit: ViralHog',
111 'uploader': 'S. Saint',
112 },
113 'skip': 'Video gone',
114 }, {
115 'note': 'swf params escaped',
116 'url': 'https://www.facebook.com/barackobama/posts/10153664894881749',
117 'md5': '97ba073838964d12c70566e0085c2b91',
118 'info_dict': {
119 'id': '10153664894881749',
120 'ext': 'mp4',
121 'title': 'Facebook video #10153664894881749',
122 },
123 }, {
124 # have 1080P, but only up to 720p in swf params
125 'url': 'https://www.facebook.com/cnn/videos/10155529876156509/',
126 'md5': '0d9813160b146b3bc8744e006027fcc6',
127 'info_dict': {
128 'id': '10155529876156509',
129 'ext': 'mp4',
130 'title': 'Holocaust survivor becomes US citizen',
131 'timestamp': 1477818095,
132 'upload_date': '20161030',
133 'uploader': 'CNN',
134 },
135 }, {
136 'url': 'https://www.facebook.com/video.php?v=10204634152394104',
137 'only_matching': True,
138 }, {
139 'url': 'https://www.facebook.com/amogood/videos/1618742068337349/?fref=nf',
140 'only_matching': True,
141 }, {
142 'url': 'https://www.facebook.com/ChristyClarkForBC/videos/vb.22819070941/10153870694020942/?type=2&theater',
143 'only_matching': True,
144 }, {
145 'url': 'facebook:544765982287235',
146 'only_matching': True,
147 }, {
148 'url': 'https://www.facebook.com/groups/164828000315060/permalink/764967300301124/',
149 'only_matching': True,
150 }, {
151 'url': 'https://zh-hk.facebook.com/peoplespower/videos/1135894589806027/',
152 'only_matching': True,
153 }]
154
155 @staticmethod
156 def _extract_url(webpage):
157 mobj = re.search(
158 r'<iframe[^>]+?src=(["\'])(?P<url>https://www\.facebook\.com/video/embed.+?)\1', webpage)
159 if mobj is not None:
160 return mobj.group('url')
161
162 # Facebook API embed
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)
167 if mobj is not None:
168 return mobj.group('url')
169
170 def _login(self):
171 (useremail, password) = self._get_login_info()
172 if useremail is None:
173 return
174
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="([^"]*)"',
182 login_page, 'lsd')
183 lgnrnd = self._search_regex(r'name="lgnrnd" value="([^"]*?)"', login_page, 'lgnrnd')
184
185 login_form = {
186 'email': useremail,
187 'pass': password,
188 'lsd': lsd,
189 'lgnrnd': lgnrnd,
190 'next': 'http://facebook.com/home.php',
191 'default_persistent': '0',
192 'legacy_return': '1',
193 'timezone': '-60',
194 'trynum': '1',
195 }
196 request = sanitized_Request(self._LOGIN_URL, urlencode_postdata(login_form))
197 request.add_header('Content-Type', 'application/x-www-form-urlencoded')
198 try:
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')
205 if 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.')
208 return
209
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)
214
215 if not fb_dtsg or not h:
216 return
217
218 check_form = {
219 'fb_dtsg': fb_dtsg,
220 'h': h,
221 'name_action_selected': 'dont_save',
222 }
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))
231 return
232
233 def _real_initialize(self):
234 self._login()
235
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)
240
241 video_data = None
242
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']
248 break
249
250 if not video_data:
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),
257 expected=True)
258 else:
259 raise ExtractorError('Cannot parse data')
260
261 formats = []
262 for f in video_data:
263 format_id = f['stream_type']
264 if f and isinstance(f, dict):
265 f = [f]
266 if not f or not isinstance(f, list):
267 continue
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))
271 if src:
272 preference = -10 if format_id == 'progressive' else 0
273 if quality == 'hd':
274 preference += 5
275 formats.append({
276 'format_id': '%s_%s_%s' % (format_id, quality, src_type),
277 'url': src,
278 'preference': preference,
279 })
280 dash_manifest = f[0].get('dash_manifest')
281 if dash_manifest:
282 formats.extend(self._parse_mpd_formats(
283 compat_etree_fromstring(compat_urllib_parse_unquote_plus(dash_manifest))))
284 if not formats:
285 raise ExtractorError('Cannot find video formats')
286
287 self._sort_formats(formats)
288
289 video_title = self._html_search_regex(
290 r'<h2\s+[^>]*class="uiHeaderTitle"[^>]*>([^<]*)</h2>', webpage, 'title',
291 default=None)
292 if not video_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)
297 if not video_title:
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))
303
304 info_dict = {
305 'id': video_id,
306 'title': video_title,
307 'formats': formats,
308 'uploader': uploader,
309 'timestamp': timestamp,
310 }
311
312 return webpage, info_dict
313
314 def _real_extract(self, url):
315 video_id = self._match_id(url)
316
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)
319
320 if info_dict:
321 return info_dict
322
323 if '/posts/' in url:
324 entries = [
325 self.url_result('facebook:%s' % vid, FacebookIE.ie_key())
326 for vid in self._parse_json(
327 self._search_regex(
328 r'(["\'])video_ids\1\s*:\s*(?P<ids>\[.+?\])',
329 webpage, 'video ids', group='ids'),
330 video_id)]
331
332 return self.playlist_result(entries, video_id)
333 else:
334 _, info_dict = self._extract_from_url(
335 self._VIDEO_PAGE_TEMPLATE % video_id,
336 video_id, fatal_if_no_video=True)
337 return info_dict
338
339
340 class FacebookPluginsVideoIE(InfoExtractor):
341 _VALID_URL = r'https?://(?:[\w-]+\.)?facebook\.com/plugins/video\.php\?.*?\bhref=(?P<id>https.+)'
342
343 _TESTS = [{
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',
346 'info_dict': {
347 'id': '10154383743583686',
348 'ext': 'mp4',
349 'title': 'What to do during the haze?',
350 'uploader': 'Gov.sg',
351 'upload_date': '20160826',
352 'timestamp': 1472184808,
353 },
354 'add_ie': [FacebookIE.ie_key()],
355 }, {
356 'url': 'https://www.facebook.com/plugins/video.php?href=https%3A%2F%2Fwww.facebook.com%2Fvideo.php%3Fv%3D10204634152394104',
357 'only_matching': True,
358 }, {
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,
361 }]
362
363 def _real_extract(self, url):
364 return self.url_result(
365 compat_urllib_parse_unquote(self._match_id(url)),
366 FacebookIE.ie_key())