[facebook] Recognize .onion URLs (closes #11443)
[youtube-dl] / 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|facebookcorewwwi\.onion)/
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         'url': 'https://www.facebookcorewwwi.onion/video.php?v=274175099429670',
155         'only_matching': True,
156     }]
157
158     @staticmethod
159     def _extract_url(webpage):
160         mobj = re.search(
161             r'<iframe[^>]+?src=(["\'])(?P<url>https://www\.facebook\.com/video/embed.+?)\1', webpage)
162         if mobj is not None:
163             return mobj.group('url')
164
165         # Facebook API embed
166         # see https://developers.facebook.com/docs/plugins/embedded-video-player
167         mobj = re.search(r'''(?x)<div[^>]+
168                 class=(?P<q1>[\'"])[^\'"]*\bfb-(?:video|post)\b[^\'"]*(?P=q1)[^>]+
169                 data-href=(?P<q2>[\'"])(?P<url>(?:https?:)?//(?:www\.)?facebook.com/.+?)(?P=q2)''', webpage)
170         if mobj is not None:
171             return mobj.group('url')
172
173     def _login(self):
174         (useremail, password) = self._get_login_info()
175         if useremail is None:
176             return
177
178         login_page_req = sanitized_Request(self._LOGIN_URL)
179         self._set_cookie('facebook.com', 'locale', 'en_US')
180         login_page = self._download_webpage(login_page_req, None,
181                                             note='Downloading login page',
182                                             errnote='Unable to download login page')
183         lsd = self._search_regex(
184             r'<input type="hidden" name="lsd" value="([^"]*)"',
185             login_page, 'lsd')
186         lgnrnd = self._search_regex(r'name="lgnrnd" value="([^"]*?)"', login_page, 'lgnrnd')
187
188         login_form = {
189             'email': useremail,
190             'pass': password,
191             'lsd': lsd,
192             'lgnrnd': lgnrnd,
193             'next': 'http://facebook.com/home.php',
194             'default_persistent': '0',
195             'legacy_return': '1',
196             'timezone': '-60',
197             'trynum': '1',
198         }
199         request = sanitized_Request(self._LOGIN_URL, urlencode_postdata(login_form))
200         request.add_header('Content-Type', 'application/x-www-form-urlencoded')
201         try:
202             login_results = self._download_webpage(request, None,
203                                                    note='Logging in', errnote='unable to fetch login page')
204             if re.search(r'<form(.*)name="login"(.*)</form>', login_results) is not None:
205                 error = self._html_search_regex(
206                     r'(?s)<div[^>]+class=(["\']).*?login_error_box.*?\1[^>]*><div[^>]*>.*?</div><div[^>]*>(?P<error>.+?)</div>',
207                     login_results, 'login error', default=None, group='error')
208                 if error:
209                     raise ExtractorError('Unable to login: %s' % error, expected=True)
210                 self._downloader.report_warning('unable to log in: bad username/password, or exceeded login rate limit (~3/min). Check credentials or wait.')
211                 return
212
213             fb_dtsg = self._search_regex(
214                 r'name="fb_dtsg" value="(.+?)"', login_results, 'fb_dtsg', default=None)
215             h = self._search_regex(
216                 r'name="h"\s+(?:\w+="[^"]+"\s+)*?value="([^"]+)"', login_results, 'h', default=None)
217
218             if not fb_dtsg or not h:
219                 return
220
221             check_form = {
222                 'fb_dtsg': fb_dtsg,
223                 'h': h,
224                 'name_action_selected': 'dont_save',
225             }
226             check_req = sanitized_Request(self._CHECKPOINT_URL, urlencode_postdata(check_form))
227             check_req.add_header('Content-Type', 'application/x-www-form-urlencoded')
228             check_response = self._download_webpage(check_req, None,
229                                                     note='Confirming login')
230             if re.search(r'id="checkpointSubmitButton"', check_response) is not None:
231                 self._downloader.report_warning('Unable to confirm login, you have to login in your browser and authorize the login.')
232         except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
233             self._downloader.report_warning('unable to log in: %s' % error_to_compat_str(err))
234             return
235
236     def _real_initialize(self):
237         self._login()
238
239     def _extract_from_url(self, url, video_id, fatal_if_no_video=True):
240         req = sanitized_Request(url)
241         req.add_header('User-Agent', self._CHROME_USER_AGENT)
242         webpage = self._download_webpage(req, video_id)
243
244         video_data = None
245
246         server_js_data = self._parse_json(self._search_regex(
247             r'handleServerJS\(({.+})(?:\);|,")', webpage, 'server js data', default='{}'), video_id)
248         for item in server_js_data.get('instances', []):
249             if item[1][0] == 'VideoConfig':
250                 video_item = item[2][0]
251                 if video_item.get('video_id') == video_id:
252                     video_data = video_item['videoData']
253                     break
254
255         if not video_data:
256             if not fatal_if_no_video:
257                 return webpage, False
258             m_msg = re.search(r'class="[^"]*uiInterstitialContent[^"]*"><div>(.*?)</div>', webpage)
259             if m_msg is not None:
260                 raise ExtractorError(
261                     'The video is not available, Facebook said: "%s"' % m_msg.group(1),
262                     expected=True)
263             elif '>You must log in to continue' in webpage:
264                 self.raise_login_required()
265             else:
266                 raise ExtractorError('Cannot parse data')
267
268         formats = []
269         for f in video_data:
270             format_id = f['stream_type']
271             if f and isinstance(f, dict):
272                 f = [f]
273             if not f or not isinstance(f, list):
274                 continue
275             for quality in ('sd', 'hd'):
276                 for src_type in ('src', 'src_no_ratelimit'):
277                     src = f[0].get('%s_%s' % (quality, src_type))
278                     if src:
279                         preference = -10 if format_id == 'progressive' else 0
280                         if quality == 'hd':
281                             preference += 5
282                         formats.append({
283                             'format_id': '%s_%s_%s' % (format_id, quality, src_type),
284                             'url': src,
285                             'preference': preference,
286                         })
287             dash_manifest = f[0].get('dash_manifest')
288             if dash_manifest:
289                 formats.extend(self._parse_mpd_formats(
290                     compat_etree_fromstring(compat_urllib_parse_unquote_plus(dash_manifest))))
291         if not formats:
292             raise ExtractorError('Cannot find video formats')
293
294         self._sort_formats(formats)
295
296         video_title = self._html_search_regex(
297             r'<h2\s+[^>]*class="uiHeaderTitle"[^>]*>([^<]*)</h2>', webpage, 'title',
298             default=None)
299         if not video_title:
300             video_title = self._html_search_regex(
301                 r'(?s)<span class="fbPhotosPhotoCaption".*?id="fbPhotoPageCaption"><span class="hasCaption">(.*?)</span>',
302                 webpage, 'alternative title', default=None)
303             video_title = limit_length(video_title, 80)
304         if not video_title:
305             video_title = 'Facebook video #%s' % video_id
306         uploader = clean_html(get_element_by_id('fbPhotoPageAuthorName', webpage))
307         timestamp = int_or_none(self._search_regex(
308             r'<abbr[^>]+data-utime=["\'](\d+)', webpage,
309             'timestamp', default=None))
310
311         info_dict = {
312             'id': video_id,
313             'title': video_title,
314             'formats': formats,
315             'uploader': uploader,
316             'timestamp': timestamp,
317         }
318
319         return webpage, info_dict
320
321     def _real_extract(self, url):
322         video_id = self._match_id(url)
323
324         real_url = self._VIDEO_PAGE_TEMPLATE % video_id if url.startswith('facebook:') else url
325         webpage, info_dict = self._extract_from_url(real_url, video_id, fatal_if_no_video=False)
326
327         if info_dict:
328             return info_dict
329
330         if '/posts/' in url:
331             entries = [
332                 self.url_result('facebook:%s' % vid, FacebookIE.ie_key())
333                 for vid in self._parse_json(
334                     self._search_regex(
335                         r'(["\'])video_ids\1\s*:\s*(?P<ids>\[.+?\])',
336                         webpage, 'video ids', group='ids'),
337                     video_id)]
338
339             return self.playlist_result(entries, video_id)
340         else:
341             _, info_dict = self._extract_from_url(
342                 self._VIDEO_PAGE_TEMPLATE % video_id,
343                 video_id, fatal_if_no_video=True)
344             return info_dict
345
346
347 class FacebookPluginsVideoIE(InfoExtractor):
348     _VALID_URL = r'https?://(?:[\w-]+\.)?facebook\.com/plugins/video\.php\?.*?\bhref=(?P<id>https.+)'
349
350     _TESTS = [{
351         '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',
352         'md5': '5954e92cdfe51fe5782ae9bda7058a07',
353         'info_dict': {
354             'id': '10154383743583686',
355             'ext': 'mp4',
356             'title': 'What to do during the haze?',
357             'uploader': 'Gov.sg',
358             'upload_date': '20160826',
359             'timestamp': 1472184808,
360         },
361         'add_ie': [FacebookIE.ie_key()],
362     }, {
363         'url': 'https://www.facebook.com/plugins/video.php?href=https%3A%2F%2Fwww.facebook.com%2Fvideo.php%3Fv%3D10204634152394104',
364         'only_matching': True,
365     }, {
366         'url': 'https://www.facebook.com/plugins/video.php?href=https://www.facebook.com/gov.sg/videos/10154383743583686/&show_text=0&width=560',
367         'only_matching': True,
368     }]
369
370     def _real_extract(self, url):
371         return self.url_result(
372             compat_urllib_parse_unquote(self._match_id(url)),
373             FacebookIE.ie_key())