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