[facebook] Fix login process
[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 ..utils import (
9     compat_http_client,
10     compat_str,
11     compat_urllib_error,
12     compat_urllib_parse,
13     compat_urllib_request,
14     urlencode_postdata,
15
16     ExtractorError,
17 )
18
19
20 class FacebookIE(InfoExtractor):
21     """Information Extractor for Facebook"""
22
23     _VALID_URL = r'''(?x)
24         (?:https?://)?(?:\w+\.)?facebook\.com/
25         (?:[^#?]*\#!/)?
26         (?:video/video\.php|photo\.php|video/embed)\?(?:.*?)
27         (?:v|video_id)=(?P<id>[0-9]+)
28         (?:.*)'''
29     _LOGIN_URL = 'https://www.facebook.com/login.php?next=http%3A%2F%2Ffacebook.com%2Fhome.php&login_attempt=1'
30     _CHECKPOINT_URL = 'https://www.facebook.com/checkpoint/?next=http%3A%2F%2Ffacebook.com%2Fhome.php&_fb_noscript=1'
31     _NETRC_MACHINE = 'facebook'
32     IE_NAME = 'facebook'
33     _TEST = {
34         'url': 'https://www.facebook.com/photo.php?v=120708114770723',
35         'md5': '48975a41ccc4b7a581abd68651c1a5a8',
36         'info_dict': {
37             'id': '120708114770723',
38             'ext': 'mp4',
39             'duration': 279,
40             'title': 'PEOPLE ARE AWESOME 2013'
41         }
42     }
43
44     def report_login(self):
45         """Report attempt to log in."""
46         self.to_screen('Logging in')
47
48     def _login(self):
49         (useremail, password) = self._get_login_info()
50         if useremail is None:
51             return
52
53         login_page_req = compat_urllib_request.Request(self._LOGIN_URL)
54         login_page_req.add_header('Cookie', 'locale=en_US')
55         login_page = self._download_webpage(login_page_req, None,
56             note='Downloading login page',
57             errnote='Unable to download login page')
58         lsd = self._search_regex(
59             r'<input type="hidden" name="lsd" value="([^"]*)"',
60             login_page, 'lsd')
61         lgnrnd = self._search_regex(r'name="lgnrnd" value="([^"]*?)"', login_page, 'lgnrnd')
62
63         login_form = {
64             'email': useremail,
65             'pass': password,
66             'lsd': lsd,
67             'lgnrnd': lgnrnd,
68             'next': 'http://facebook.com/home.php',
69             'default_persistent': '0',
70             'legacy_return': '1',
71             'timezone': '-60',
72             'trynum': '1',
73             }
74         request = compat_urllib_request.Request(self._LOGIN_URL, urlencode_postdata(login_form))
75         request.add_header('Content-Type', 'application/x-www-form-urlencoded')
76         try:
77             login_results = self._download_webpage(request, None,
78                 note='Logging in', errnote='unable to fetch login page')
79             if re.search(r'<form(.*)name="login"(.*)</form>', login_results) is not None:
80                 self._downloader.report_warning('unable to log in: bad username/password, or exceded login rate limit (~3/min). Check credentials or wait.')
81                 return
82
83             check_form = {
84                 'fb_dtsg': self._search_regex(r'name="fb_dtsg" value="(.+?)"', login_results, 'fb_dtsg'),
85                 'nh': self._search_regex(r'name="nh" value="(\w*?)"', login_results, 'nh'),
86                 'name_action_selected': 'dont_save',
87                 'submit[Continue]': self._search_regex(r'<button[^>]+value="(.*?)"[^>]+name="submit\[Continue\]"', login_results, 'continue'),
88             }
89             check_req = compat_urllib_request.Request(self._CHECKPOINT_URL, urlencode_postdata(check_form))
90             check_req.add_header('Content-Type', 'application/x-www-form-urlencoded')
91             check_response = self._download_webpage(check_req, None,
92                 note='Confirming login')
93             if re.search(r'id="checkpointSubmitButton"', check_response) is not None:
94                 self._downloader.report_warning('Unable to confirm login, you have to login in your brower and authorize the login.')
95         except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
96             self._downloader.report_warning('unable to log in: %s' % compat_str(err))
97             return
98
99     def _real_initialize(self):
100         self._login()
101
102     def _real_extract(self, url):
103         mobj = re.match(self._VALID_URL, url)
104         if mobj is None:
105             raise ExtractorError('Invalid URL: %s' % url)
106         video_id = mobj.group('id')
107
108         url = 'https://www.facebook.com/video/video.php?v=%s' % video_id
109         webpage = self._download_webpage(url, video_id)
110
111         BEFORE = '{swf.addParam(param[0], param[1]);});\n'
112         AFTER = '.forEach(function(variable) {swf.addVariable(variable[0], variable[1]);});'
113         m = re.search(re.escape(BEFORE) + '(.*?)' + re.escape(AFTER), webpage)
114         if not m:
115             m_msg = re.search(r'class="[^"]*uiInterstitialContent[^"]*"><div>(.*?)</div>', webpage)
116             if m_msg is not None:
117                 raise ExtractorError(
118                     'The video is not available, Facebook said: "%s"' % m_msg.group(1),
119                     expected=True)
120             else:
121                 raise ExtractorError('Cannot parse data')
122         data = dict(json.loads(m.group(1)))
123         params_raw = compat_urllib_parse.unquote(data['params'])
124         params = json.loads(params_raw)
125         video_data = params['video_data'][0]
126         video_url = video_data.get('hd_src')
127         if not video_url:
128             video_url = video_data['sd_src']
129         if not video_url:
130             raise ExtractorError('Cannot find video URL')
131         video_duration = int(video_data['video_duration'])
132         thumbnail = video_data['thumbnail_src']
133
134         video_title = self._html_search_regex(
135             r'<h2 class="uiHeaderTitle">([^<]*)</h2>', webpage, 'title')
136
137         info = {
138             'id': video_id,
139             'title': video_title,
140             'url': video_url,
141             'ext': 'mp4',
142             'duration': video_duration,
143             'thumbnail': thumbnail,
144         }
145         return [info]