]> jfr.im git - yt-dlp.git/blame - youtube_dl/extractor/facebook.py
[youtube:watchlater] Improve _VALID_URL (Closes #8594)
[yt-dlp.git] / youtube_dl / extractor / facebook.py
CommitLineData
cb3bb2cf
PH
1from __future__ import unicode_literals
2
9eae41dd 3import json
9eae41dd
PH
4import re
5import socket
6
7from .common import InfoExtractor
8c25f81b 8from ..compat import (
0803753f 9 compat_etree_fromstring,
9eae41dd 10 compat_http_client,
9eae41dd 11 compat_urllib_error,
d7011316 12 compat_urllib_parse_unquote,
0803753f 13 compat_urllib_parse_unquote_plus,
8c25f81b
PH
14)
15from ..utils import (
9b9c5355 16 error_to_compat_str,
9eae41dd 17 ExtractorError,
a020a0dc 18 limit_length,
5c2266df 19 sanitized_Request,
2fc9f2b4 20 urlencode_postdata,
51a57515 21 get_element_by_id,
22 clean_html,
9eae41dd
PH
23)
24
25
26class FacebookIE(InfoExtractor):
9834872b 27 _VALID_URL = r'''(?x)
2e6e742c
S
28 (?:
29 https?://
30 (?:\w+\.)?facebook\.com/
31 (?:[^#]*?\#!/)?
32 (?:
33 (?:
34 video/video\.php|
35 photo\.php|
36 video\.php|
37 video/embed
38 )\?(?:.*?)(?:v|video_id)=|
39 [^/]+/videos/(?:[^/]+/)?
40 )|
41 facebook:
42 )
43 (?P<id>[0-9]+)
44 '''
67874aef
JMF
45 _LOGIN_URL = 'https://www.facebook.com/login.php?next=http%3A%2F%2Ffacebook.com%2Fhome.php&login_attempt=1'
46 _CHECKPOINT_URL = 'https://www.facebook.com/checkpoint/?next=http%3A%2F%2Ffacebook.com%2Fhome.php&_fb_noscript=1'
9eae41dd 47 _NETRC_MACHINE = 'facebook'
cb3bb2cf 48 IE_NAME = 'facebook'
0803753f
YCH
49
50 _CHROME_USER_AGENT = 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/48.0.2564.97 Safari/537.36'
51
60ac04e5 52 _TESTS = [{
50317dbb
PH
53 'url': 'https://www.facebook.com/video.php?v=637842556329505&fref=nf',
54 'md5': '6a40d33c0eccbb1af76cf0485a052659',
cb3bb2cf 55 'info_dict': {
50317dbb 56 'id': '637842556329505',
cb3bb2cf 57 'ext': 'mp4',
5e4f0619 58 'title': 're:Did you know Kei Nishikori is the first Asian man to ever reach a Grand Slam',
67b8a28a 59 'uploader': 'Tennis on Facebook',
6f5ac90c 60 }
a020a0dc
PH
61 }, {
62 'note': 'Video without discernible title',
63 'url': 'https://www.facebook.com/video.php?v=274175099429670',
64 'info_dict': {
65 'id': '274175099429670',
66 'ext': 'mp4',
67 'title': 'Facebook video #274175099429670',
67b8a28a 68 'uploader': 'Asif Nawab Butt',
db3ca364
YCH
69 },
70 'expected_warnings': [
71 'title'
72 ]
0803753f
YCH
73 }, {
74 'note': 'Video with DASH manifest',
75 'url': 'https://www.facebook.com/video.php?v=957955867617029',
248ae880 76 'md5': '54706e4db4f5ad58fbad82dde1f1213f',
0803753f
YCH
77 'info_dict': {
78 'id': '957955867617029',
79 'ext': 'mp4',
80 'title': 'When you post epic content on instagram.com/433 8 million followers, this is ...',
81 'uploader': 'Demy de Zeeuw',
82 },
60ac04e5
PH
83 }, {
84 'url': 'https://www.facebook.com/video.php?v=10204634152394104',
85 'only_matching': True,
c6256697
YCH
86 }, {
87 'url': 'https://www.facebook.com/amogood/videos/1618742068337349/?fref=nf',
88 'only_matching': True,
53faa3ca
YCH
89 }, {
90 'url': 'https://www.facebook.com/ChristyClarkForBC/videos/vb.22819070941/10153870694020942/?type=2&theater',
91 'only_matching': True,
2e6e742c
S
92 }, {
93 'url': 'facebook:544765982287235',
94 'only_matching': True,
60ac04e5 95 }]
9eae41dd 96
67874aef
JMF
97 def _login(self):
98 (useremail, password) = self._get_login_info()
9eae41dd
PH
99 if useremail is None:
100 return
101
5c2266df 102 login_page_req = sanitized_Request(self._LOGIN_URL)
c1f49e16 103 self._set_cookie('facebook.com', 'locale', 'en_US')
b74fa8cd 104 login_page = self._download_webpage(login_page_req, None,
9e1a5b84
JW
105 note='Downloading login page',
106 errnote='Unable to download login page')
b37b9450 107 lsd = self._search_regex(
d0ff8384 108 r'<input type="hidden" name="lsd" value="([^"]*)"',
b37b9450 109 login_page, 'lsd')
cb3bb2cf 110 lgnrnd = self._search_regex(r'name="lgnrnd" value="([^"]*?)"', login_page, 'lgnrnd')
67874aef 111
9eae41dd
PH
112 login_form = {
113 'email': useremail,
114 'pass': password,
67874aef
JMF
115 'lsd': lsd,
116 'lgnrnd': lgnrnd,
117 'next': 'http://facebook.com/home.php',
118 'default_persistent': '0',
119 'legacy_return': '1',
120 'timezone': '-60',
121 'trynum': '1',
b74e86f4 122 }
5c2266df 123 request = sanitized_Request(self._LOGIN_URL, urlencode_postdata(login_form))
67874aef 124 request.add_header('Content-Type', 'application/x-www-form-urlencoded')
9eae41dd 125 try:
b74fa8cd 126 login_results = self._download_webpage(request, None,
9e1a5b84 127 note='Logging in', errnote='unable to fetch login page')
9eae41dd 128 if re.search(r'<form(.*)name="login"(.*)</form>', login_results) is not None:
9f66931e
S
129 error = self._html_search_regex(
130 r'(?s)<div[^>]+class=(["\']).*?login_error_box.*?\1[^>]*><div[^>]*>.*?</div><div[^>]*>(?P<error>.+?)</div>',
131 login_results, 'login error', default=None, group='error')
132 if error:
133 raise ExtractorError('Unable to login: %s' % error, expected=True)
dfb1b146 134 self._downloader.report_warning('unable to log in: bad username/password, or exceeded login rate limit (~3/min). Check credentials or wait.')
9eae41dd 135 return
67874aef 136
c1f49e16
S
137 fb_dtsg = self._search_regex(
138 r'name="fb_dtsg" value="(.+?)"', login_results, 'fb_dtsg', default=None)
139 h = self._search_regex(
140 r'name="h"\s+(?:\w+="[^"]+"\s+)*?value="([^"]+)"', login_results, 'h', default=None)
141
142 if not fb_dtsg or not h:
143 return
144
67874aef 145 check_form = {
c1f49e16
S
146 'fb_dtsg': fb_dtsg,
147 'h': h,
67874aef 148 'name_action_selected': 'dont_save',
67874aef 149 }
5c2266df 150 check_req = sanitized_Request(self._CHECKPOINT_URL, urlencode_postdata(check_form))
67874aef 151 check_req.add_header('Content-Type', 'application/x-www-form-urlencoded')
b74fa8cd 152 check_response = self._download_webpage(check_req, None,
9e1a5b84 153 note='Confirming login')
67874aef 154 if re.search(r'id="checkpointSubmitButton"', check_response) is not None:
dfb1b146 155 self._downloader.report_warning('Unable to confirm login, you have to login in your browser and authorize the login.')
9eae41dd 156 except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
9b9c5355 157 self._downloader.report_warning('unable to log in: %s' % error_to_compat_str(err))
9eae41dd
PH
158 return
159
67874aef
JMF
160 def _real_initialize(self):
161 self._login()
162
9eae41dd 163 def _real_extract(self, url):
2fc9f2b4 164 video_id = self._match_id(url)
0803753f
YCH
165 req = sanitized_Request('https://www.facebook.com/video/video.php?v=%s' % video_id)
166 req.add_header('User-Agent', self._CHROME_USER_AGENT)
167 webpage = self._download_webpage(req, video_id)
9eae41dd 168
c1406299
YCH
169 video_data = None
170
9eae41dd
PH
171 BEFORE = '{swf.addParam(param[0], param[1]);});\n'
172 AFTER = '.forEach(function(variable) {swf.addVariable(variable[0], variable[1]);});'
173 m = re.search(re.escape(BEFORE) + '(.*?)' + re.escape(AFTER), webpage)
c1406299
YCH
174 if m:
175 data = dict(json.loads(m.group(1)))
176 params_raw = compat_urllib_parse_unquote(data['params'])
177 video_data = json.loads(params_raw)['video_data']
178
179 def video_data_list2dict(video_data):
180 ret = {}
181 for item in video_data:
182 format_id = item['stream_type']
183 ret.setdefault(format_id, []).append(item)
184 return ret
185
186 if not video_data:
187 server_js_data = self._parse_json(self._search_regex(
188 r'handleServerJS\(({.+})\);', webpage, 'server js data'), video_id)
cb64ccc7 189 for item in server_js_data.get('instances', []):
c1406299
YCH
190 if item[1][0] == 'VideoConfig':
191 video_data = video_data_list2dict(item[2][0]['videoData'])
192 break
193
194 if not video_data:
6f71ef58
JMF
195 m_msg = re.search(r'class="[^"]*uiInterstitialContent[^"]*"><div>(.*?)</div>', webpage)
196 if m_msg is not None:
749a4fd2 197 raise ExtractorError(
cb3bb2cf 198 'The video is not available, Facebook said: "%s"' % m_msg.group(1),
749a4fd2 199 expected=True)
6f71ef58 200 else:
cb3bb2cf 201 raise ExtractorError('Cannot parse data')
ffdf972b
JMF
202
203 formats = []
c1406299 204 for format_id, f in video_data.items():
44d6dd08
S
205 if not f or not isinstance(f, list):
206 continue
207 for quality in ('sd', 'hd'):
208 for src_type in ('src', 'src_no_ratelimit'):
209 src = f[0].get('%s_%s' % (quality, src_type))
210 if src:
211 formats.append({
212 'format_id': '%s_%s_%s' % (format_id, quality, src_type),
213 'url': src,
214 'preference': -10 if format_id == 'progressive' else 0,
215 })
0803753f
YCH
216 dash_manifest = f[0].get('dash_manifest')
217 if dash_manifest:
91cb6b50 218 formats.extend(self._parse_mpd_formats(
c11875b3 219 compat_etree_fromstring(compat_urllib_parse_unquote_plus(dash_manifest))))
ffdf972b
JMF
220 if not formats:
221 raise ExtractorError('Cannot find video formats')
9eae41dd 222
0803753f
YCH
223 self._sort_formats(formats)
224
81ec7c79 225 video_title = self._html_search_regex(
bf24c3d0 226 r'<h2\s+[^>]*class="uiHeaderTitle"[^>]*>([^<]*)</h2>', webpage, 'title',
db3ca364 227 default=None)
50317dbb
PH
228 if not video_title:
229 video_title = self._html_search_regex(
230 r'(?s)<span class="fbPhotosPhotoCaption".*?id="fbPhotoPageCaption"><span class="hasCaption">(.*?)</span>',
59ee8a86 231 webpage, 'alternative title', default=None)
a020a0dc 232 video_title = limit_length(video_title, 80)
50317dbb
PH
233 if not video_title:
234 video_title = 'Facebook video #%s' % video_id
51a57515 235 uploader = clean_html(get_element_by_id('fbPhotoPageAuthorName', webpage))
9eae41dd 236
9d9d70c4 237 return {
9eae41dd
PH
238 'id': video_id,
239 'title': video_title,
ffdf972b 240 'formats': formats,
51a57515 241 'uploader': uploader,
9eae41dd 242 }
de691a49
S
243
244
245class FacebookPostIE(InfoExtractor):
246 IE_NAME = 'facebook:post'
247 _VALID_URL = r'https?://(?:\w+\.)?facebook\.com/[^/]+/posts/(?P<id>\d+)'
248 _TEST = {
249 'url': 'https://www.facebook.com/maxlayn/posts/10153807558977570',
250 'md5': '037b1fa7f3c2d02b7a0d7bc16031ecc6',
251 'info_dict': {
252 'id': '544765982287235',
253 'ext': 'mp4',
254 'title': '"What are you doing running in the snow?"',
255 'uploader': 'FailArmy',
256 }
257 }
258
259 def _real_extract(self, url):
260 post_id = self._match_id(url)
261
262 webpage = self._download_webpage(url, post_id)
263
264 entries = [
265 self.url_result('facebook:%s' % video_id, FacebookIE.ie_key())
266 for video_id in self._parse_json(
267 self._search_regex(
268 r'(["\'])video_ids\1\s*:\s*(?P<ids>\[.+?\])',
269 webpage, 'video ids', group='ids'),
270 post_id)]
271
272 return self.playlist_result(entries, post_id)