]> Raphaƫl G. Git Repositories - youtubedl/blob - youtube_dl/extractor/facebook.py
debian/changelog: Annotate bugs to close.
[youtubedl] / 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_http_client,
10 compat_str,
11 compat_urllib_error,
12 compat_urllib_parse,
13 compat_urllib_request,
14 )
15 from ..utils import (
16 ExtractorError,
17 int_or_none,
18 limit_length,
19 urlencode_postdata,
20 )
21
22
23 class FacebookIE(InfoExtractor):
24 _VALID_URL = r'''(?x)
25 https?://(?:\w+\.)?facebook\.com/
26 (?:[^#]*?\#!/)?
27 (?:
28 (?:video/video\.php|photo\.php|video\.php|video/embed)\?(?:.*?)
29 (?:v|video_id)=|
30 [^/]+/videos/(?:[^/]+/)?
31 )
32 (?P<id>[0-9]+)
33 (?:.*)'''
34 _LOGIN_URL = 'https://www.facebook.com/login.php?next=http%3A%2F%2Ffacebook.com%2Fhome.php&login_attempt=1'
35 _CHECKPOINT_URL = 'https://www.facebook.com/checkpoint/?next=http%3A%2F%2Ffacebook.com%2Fhome.php&_fb_noscript=1'
36 _NETRC_MACHINE = 'facebook'
37 IE_NAME = 'facebook'
38 _TESTS = [{
39 'url': 'https://www.facebook.com/video.php?v=637842556329505&fref=nf',
40 'md5': '6a40d33c0eccbb1af76cf0485a052659',
41 'info_dict': {
42 'id': '637842556329505',
43 'ext': 'mp4',
44 'title': 're:Did you know Kei Nishikori is the first Asian man to ever reach a Grand Slam',
45 }
46 }, {
47 'note': 'Video without discernible title',
48 'url': 'https://www.facebook.com/video.php?v=274175099429670',
49 'info_dict': {
50 'id': '274175099429670',
51 'ext': 'mp4',
52 'title': 'Facebook video #274175099429670',
53 },
54 'expected_warnings': [
55 'title'
56 ]
57 }, {
58 'url': 'https://www.facebook.com/video.php?v=10204634152394104',
59 'only_matching': True,
60 }, {
61 'url': 'https://www.facebook.com/amogood/videos/1618742068337349/?fref=nf',
62 'only_matching': True,
63 }, {
64 'url': 'https://www.facebook.com/ChristyClarkForBC/videos/vb.22819070941/10153870694020942/?type=2&theater',
65 'only_matching': True,
66 }]
67
68 def _login(self):
69 (useremail, password) = self._get_login_info()
70 if useremail is None:
71 return
72
73 login_page_req = compat_urllib_request.Request(self._LOGIN_URL)
74 login_page_req.add_header('Cookie', 'locale=en_US')
75 login_page = self._download_webpage(login_page_req, None,
76 note='Downloading login page',
77 errnote='Unable to download login page')
78 lsd = self._search_regex(
79 r'<input type="hidden" name="lsd" value="([^"]*)"',
80 login_page, 'lsd')
81 lgnrnd = self._search_regex(r'name="lgnrnd" value="([^"]*?)"', login_page, 'lgnrnd')
82
83 login_form = {
84 'email': useremail,
85 'pass': password,
86 'lsd': lsd,
87 'lgnrnd': lgnrnd,
88 'next': 'http://facebook.com/home.php',
89 'default_persistent': '0',
90 'legacy_return': '1',
91 'timezone': '-60',
92 'trynum': '1',
93 }
94 request = compat_urllib_request.Request(self._LOGIN_URL, urlencode_postdata(login_form))
95 request.add_header('Content-Type', 'application/x-www-form-urlencoded')
96 try:
97 login_results = self._download_webpage(request, None,
98 note='Logging in', errnote='unable to fetch login page')
99 if re.search(r'<form(.*)name="login"(.*)</form>', login_results) is not None:
100 self._downloader.report_warning('unable to log in: bad username/password, or exceded login rate limit (~3/min). Check credentials or wait.')
101 return
102
103 check_form = {
104 'fb_dtsg': self._search_regex(r'name="fb_dtsg" value="(.+?)"', login_results, 'fb_dtsg'),
105 'h': self._search_regex(
106 r'name="h"\s+(?:\w+="[^"]+"\s+)*?value="([^"]+)"', login_results, 'h'),
107 'name_action_selected': 'dont_save',
108 }
109 check_req = compat_urllib_request.Request(self._CHECKPOINT_URL, urlencode_postdata(check_form))
110 check_req.add_header('Content-Type', 'application/x-www-form-urlencoded')
111 check_response = self._download_webpage(check_req, None,
112 note='Confirming login')
113 if re.search(r'id="checkpointSubmitButton"', check_response) is not None:
114 self._downloader.report_warning('Unable to confirm login, you have to login in your brower and authorize the login.')
115 except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
116 self._downloader.report_warning('unable to log in: %s' % compat_str(err))
117 return
118
119 def _real_initialize(self):
120 self._login()
121
122 def _real_extract(self, url):
123 video_id = self._match_id(url)
124 url = 'https://www.facebook.com/video/video.php?v=%s' % video_id
125 webpage = self._download_webpage(url, video_id)
126
127 BEFORE = '{swf.addParam(param[0], param[1]);});\n'
128 AFTER = '.forEach(function(variable) {swf.addVariable(variable[0], variable[1]);});'
129 m = re.search(re.escape(BEFORE) + '(.*?)' + re.escape(AFTER), webpage)
130 if not m:
131 m_msg = re.search(r'class="[^"]*uiInterstitialContent[^"]*"><div>(.*?)</div>', webpage)
132 if m_msg is not None:
133 raise ExtractorError(
134 'The video is not available, Facebook said: "%s"' % m_msg.group(1),
135 expected=True)
136 else:
137 raise ExtractorError('Cannot parse data')
138 data = dict(json.loads(m.group(1)))
139 params_raw = compat_urllib_parse.unquote(data['params'])
140 params = json.loads(params_raw)
141 video_data = params['video_data'][0]
142
143 formats = []
144 for quality in ['sd', 'hd']:
145 src = video_data.get('%s_src' % quality)
146 if src is not None:
147 formats.append({
148 'format_id': quality,
149 'url': src,
150 })
151 if not formats:
152 raise ExtractorError('Cannot find video formats')
153
154 video_title = self._html_search_regex(
155 r'<h2\s+[^>]*class="uiHeaderTitle"[^>]*>([^<]*)</h2>', webpage, 'title',
156 default=None)
157 if not video_title:
158 video_title = self._html_search_regex(
159 r'(?s)<span class="fbPhotosPhotoCaption".*?id="fbPhotoPageCaption"><span class="hasCaption">(.*?)</span>',
160 webpage, 'alternative title', fatal=False)
161 video_title = limit_length(video_title, 80)
162 if not video_title:
163 video_title = 'Facebook video #%s' % video_id
164
165 return {
166 'id': video_id,
167 'title': video_title,
168 'formats': formats,
169 'duration': int_or_none(video_data.get('video_duration')),
170 'thumbnail': video_data.get('thumbnail_src'),
171 }