[facebook] Use consistent quotes
[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             'duration': 279,
39             'title': '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(
58             r'<input type="hidden" name="lsd" value="([^"]*)"',
59             login_page, 'lsd')
60         lgnrnd = self._search_regex(r'name="lgnrnd" value="([^"]*?)"', login_page, 'lgnrnd')
61
62         login_form = {
63             'email': useremail,
64             'pass': password,
65             'lsd': lsd,
66             'lgnrnd': lgnrnd,
67             'next': 'http://facebook.com/home.php',
68             'default_persistent': '0',
69             'legacy_return': '1',
70             'timezone': '-60',
71             'trynum': '1',
72             }
73         request = compat_urllib_request.Request(self._LOGIN_URL, compat_urllib_parse.urlencode(login_form))
74         request.add_header('Content-Type', 'application/x-www-form-urlencoded')
75         try:
76             login_results = compat_urllib_request.urlopen(request).read()
77             if re.search(r'<form(.*)name="login"(.*)</form>', login_results) is not None:
78                 self._downloader.report_warning('unable to log in: bad username/password, or exceded login rate limit (~3/min). Check credentials or wait.')
79                 return
80
81             check_form = {
82                 'fb_dtsg': self._search_regex(r'"fb_dtsg":"(.*?)"', login_results, 'fb_dtsg'),
83                 'nh': self._search_regex(r'name="nh" value="(\w*?)"', login_results, 'nh'),
84                 'name_action_selected': 'dont_save',
85                 'submit[Continue]': self._search_regex(r'<input value="(.*?)" name="submit\[Continue\]"', login_results, 'continue'),
86             }
87             check_req = compat_urllib_request.Request(self._CHECKPOINT_URL, compat_urllib_parse.urlencode(check_form))
88             check_req.add_header('Content-Type', 'application/x-www-form-urlencoded')
89             check_response = compat_urllib_request.urlopen(check_req).read()
90             if re.search(r'id="checkpointSubmitButton"', check_response) is not None:
91                 self._downloader.report_warning('Unable to confirm login, you have to login in your brower and authorize the login.')
92         except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
93             self._downloader.report_warning('unable to log in: %s' % compat_str(err))
94             return
95
96     def _real_initialize(self):
97         self._login()
98
99     def _real_extract(self, url):
100         mobj = re.match(self._VALID_URL, url)
101         if mobj is None:
102             raise ExtractorError('Invalid URL: %s' % url)
103         video_id = mobj.group('id')
104
105         url = 'https://www.facebook.com/video/video.php?v=%s' % video_id
106         webpage = self._download_webpage(url, video_id)
107
108         BEFORE = '{swf.addParam(param[0], param[1]);});\n'
109         AFTER = '.forEach(function(variable) {swf.addVariable(variable[0], variable[1]);});'
110         m = re.search(re.escape(BEFORE) + '(.*?)' + re.escape(AFTER), webpage)
111         if not m:
112             m_msg = re.search(r'class="[^"]*uiInterstitialContent[^"]*"><div>(.*?)</div>', webpage)
113             if m_msg is not None:
114                 raise ExtractorError(
115                     'The video is not available, Facebook said: "%s"' % m_msg.group(1),
116                     expected=True)
117             else:
118                 raise ExtractorError('Cannot parse data')
119         data = dict(json.loads(m.group(1)))
120         params_raw = compat_urllib_parse.unquote(data['params'])
121         params = json.loads(params_raw)
122         video_data = params['video_data'][0]
123         video_url = video_data.get('hd_src')
124         if not video_url:
125             video_url = video_data['sd_src']
126         if not video_url:
127             raise ExtractorError('Cannot find video URL')
128         video_duration = int(video_data['video_duration'])
129         thumbnail = video_data['thumbnail_src']
130
131         video_title = self._html_search_regex(
132             r'<h2 class="uiHeaderTitle">([^<]*)</h2>', webpage, 'title')
133
134         info = {
135             'id': video_id,
136             'title': video_title,
137             'url': video_url,
138             'ext': 'mp4',
139             'duration': video_duration,
140             'thumbnail': thumbnail,
141         }
142         return [info]