Merge pull request #10819 from raleeper/adobepass
[youtube-dl] / youtube_dl / extractor / facebook.py
1 from __future__ import unicode_literals
2
3 import json
4 import re
5 import socket
6
7 from .common import InfoExtractor
8 from ..compat import (
9     compat_etree_fromstring,
10     compat_http_client,
11     compat_urllib_error,
12     compat_urllib_parse_unquote,
13     compat_urllib_parse_unquote_plus,
14 )
15 from ..utils import (
16     error_to_compat_str,
17     ExtractorError,
18     int_or_none,
19     limit_length,
20     sanitized_Request,
21     urlencode_postdata,
22     get_element_by_id,
23     clean_html,
24 )
25
26
27 class FacebookIE(InfoExtractor):
28     _VALID_URL = r'''(?x)
29                 (?:
30                     https?://
31                         (?:[\w-]+\.)?facebook\.com/
32                         (?:[^#]*?\#!/)?
33                         (?:
34                             (?:
35                                 video/video\.php|
36                                 photo\.php|
37                                 video\.php|
38                                 video/embed|
39                                 story\.php
40                             )\?(?:.*?)(?:v|video_id|story_fbid)=|
41                             [^/]+/videos/(?:[^/]+/)?|
42                             [^/]+/posts/|
43                             groups/[^/]+/permalink/
44                         )|
45                     facebook:
46                 )
47                 (?P<id>[0-9]+)
48                 '''
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'
52     IE_NAME = 'facebook'
53
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'
55
56     _VIDEO_PAGE_TEMPLATE = 'https://www.facebook.com/video/video.php?v=%s'
57
58     _TESTS = [{
59         'url': 'https://www.facebook.com/video.php?v=637842556329505&fref=nf',
60         'md5': '6a40d33c0eccbb1af76cf0485a052659',
61         'info_dict': {
62             'id': '637842556329505',
63             'ext': 'mp4',
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,
68         }
69     }, {
70         'note': 'Video without discernible title',
71         'url': 'https://www.facebook.com/video.php?v=274175099429670',
72         'info_dict': {
73             'id': '274175099429670',
74             'ext': 'mp4',
75             'title': 'Facebook video #274175099429670',
76             'uploader': 'Asif Nawab Butt',
77             'upload_date': '20140506',
78             'timestamp': 1399398998,
79         },
80         'expected_warnings': [
81             'title'
82         ]
83     }, {
84         'note': 'Video with DASH manifest',
85         'url': 'https://www.facebook.com/video.php?v=957955867617029',
86         'md5': 'b2c28d528273b323abe5c6ab59f0f030',
87         'info_dict': {
88             'id': '957955867617029',
89             'ext': 'mp4',
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,
94         },
95     }, {
96         'url': 'https://www.facebook.com/maxlayn/posts/10153807558977570',
97         'md5': '037b1fa7f3c2d02b7a0d7bc16031ecc6',
98         'info_dict': {
99             'id': '544765982287235',
100             'ext': 'mp4',
101             'title': '"What are you doing running in the snow?"',
102             'uploader': 'FailArmy',
103         }
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     }, {
114         'note': 'swf params escaped',
115         'url': 'https://www.facebook.com/barackobama/posts/10153664894881749',
116         'md5': '97ba073838964d12c70566e0085c2b91',
117         'info_dict': {
118             'id': '10153664894881749',
119             'ext': 'mp4',
120             'title': 'Facebook video #10153664894881749',
121         },
122     }, {
123         'url': 'https://www.facebook.com/video.php?v=10204634152394104',
124         'only_matching': True,
125     }, {
126         'url': 'https://www.facebook.com/amogood/videos/1618742068337349/?fref=nf',
127         'only_matching': True,
128     }, {
129         'url': 'https://www.facebook.com/ChristyClarkForBC/videos/vb.22819070941/10153870694020942/?type=2&theater',
130         'only_matching': True,
131     }, {
132         'url': 'facebook:544765982287235',
133         'only_matching': True,
134     }, {
135         'url': 'https://www.facebook.com/groups/164828000315060/permalink/764967300301124/',
136         'only_matching': True,
137     }, {
138         'url': 'https://zh-hk.facebook.com/peoplespower/videos/1135894589806027/',
139         'only_matching': True,
140     }]
141
142     @staticmethod
143     def _extract_url(webpage):
144         mobj = re.search(
145             r'<iframe[^>]+?src=(["\'])(?P<url>https://www\.facebook\.com/video/embed.+?)\1', webpage)
146         if mobj is not None:
147             return mobj.group('url')
148
149         # Facebook API embed
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)
154         if mobj is not None:
155             return mobj.group('url')
156
157     def _login(self):
158         (useremail, password) = self._get_login_info()
159         if useremail is None:
160             return
161
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="([^"]*)"',
169             login_page, 'lsd')
170         lgnrnd = self._search_regex(r'name="lgnrnd" value="([^"]*?)"', login_page, 'lgnrnd')
171
172         login_form = {
173             'email': useremail,
174             'pass': password,
175             'lsd': lsd,
176             'lgnrnd': lgnrnd,
177             'next': 'http://facebook.com/home.php',
178             'default_persistent': '0',
179             'legacy_return': '1',
180             'timezone': '-60',
181             'trynum': '1',
182         }
183         request = sanitized_Request(self._LOGIN_URL, urlencode_postdata(login_form))
184         request.add_header('Content-Type', 'application/x-www-form-urlencoded')
185         try:
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')
192                 if 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.')
195                 return
196
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)
201
202             if not fb_dtsg or not h:
203                 return
204
205             check_form = {
206                 'fb_dtsg': fb_dtsg,
207                 'h': h,
208                 'name_action_selected': 'dont_save',
209             }
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))
218             return
219
220     def _real_initialize(self):
221         self._login()
222
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)
227
228         video_data = None
229
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)
233
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():
240                 if not f:
241                     continue
242                 if isinstance(f, dict):
243                     f = [f]
244                 if not isinstance(f, list):
245                     continue
246                 if f[0].get('video_id') == video_id:
247                     video_data = video_data_candidate
248                     break
249             if video_data:
250                 break
251
252         def video_data_list2dict(video_data):
253             ret = {}
254             for item in video_data:
255                 format_id = item['stream_type']
256                 ret.setdefault(format_id, []).append(item)
257             return ret
258
259         if not video_data:
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'])
265                     break
266
267         if not video_data:
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),
274                     expected=True)
275             else:
276                 raise ExtractorError('Cannot parse data')
277
278         formats = []
279         for format_id, f in video_data.items():
280             if f and isinstance(f, dict):
281                 f = [f]
282             if not f or not isinstance(f, list):
283                 continue
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))
287                     if src:
288                         preference = -10 if format_id == 'progressive' else 0
289                         if quality == 'hd':
290                             preference += 5
291                         formats.append({
292                             'format_id': '%s_%s_%s' % (format_id, quality, src_type),
293                             'url': src,
294                             'preference': preference,
295                         })
296             dash_manifest = f[0].get('dash_manifest')
297             if dash_manifest:
298                 formats.extend(self._parse_mpd_formats(
299                     compat_etree_fromstring(compat_urllib_parse_unquote_plus(dash_manifest))))
300         if not formats:
301             raise ExtractorError('Cannot find video formats')
302
303         self._sort_formats(formats)
304
305         video_title = self._html_search_regex(
306             r'<h2\s+[^>]*class="uiHeaderTitle"[^>]*>([^<]*)</h2>', webpage, 'title',
307             default=None)
308         if not video_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)
313         if not video_title:
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))
319
320         info_dict = {
321             'id': video_id,
322             'title': video_title,
323             'formats': formats,
324             'uploader': uploader,
325             'timestamp': timestamp,
326         }
327
328         return webpage, info_dict
329
330     def _real_extract(self, url):
331         video_id = self._match_id(url)
332
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)
335
336         if info_dict:
337             return info_dict
338
339         if '/posts/' in url:
340             entries = [
341                 self.url_result('facebook:%s' % vid, FacebookIE.ie_key())
342                 for vid in self._parse_json(
343                     self._search_regex(
344                         r'(["\'])video_ids\1\s*:\s*(?P<ids>\[.+?\])',
345                         webpage, 'video ids', group='ids'),
346                     video_id)]
347
348             return self.playlist_result(entries, video_id)
349         else:
350             _, info_dict = self._extract_from_url(
351                 self._VIDEO_PAGE_TEMPLATE % video_id,
352                 video_id, fatal_if_no_video=True)
353             return info_dict
354
355
356 class FacebookPluginsVideoIE(InfoExtractor):
357     _VALID_URL = r'https?://(?:[\w-]+\.)?facebook\.com/plugins/video\.php\?.*?\bhref=(?P<id>https.+)'
358
359     _TESTS = [{
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',
362         'info_dict': {
363             'id': '10154383743583686',
364             'ext': 'mp4',
365             'title': 'What to do during the haze?',
366             'uploader': 'Gov.sg',
367             'upload_date': '20160826',
368             'timestamp': 1472184808,
369         },
370         'add_ie': [FacebookIE.ie_key()],
371     }, {
372         'url': 'https://www.facebook.com/plugins/video.php?href=https%3A%2F%2Fwww.facebook.com%2Fvideo.php%3Fv%3D10204634152394104',
373         'only_matching': True,
374     }, {
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,
377     }]
378
379     def _real_extract(self, url):
380         return self.url_result(
381             compat_urllib_parse_unquote(self._match_id(url)),
382             FacebookIE.ie_key())