]> jfr.im git - yt-dlp.git/blame - youtube_dl/extractor/facebook.py
Merge pull request #8061 from dstftw/introduce-chapter-and-series-fields
[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 (
9eae41dd 9 compat_http_client,
9eae41dd 10 compat_urllib_error,
d7011316 11 compat_urllib_parse_unquote,
8c25f81b
PH
12)
13from ..utils import (
9b9c5355 14 error_to_compat_str,
9eae41dd 15 ExtractorError,
a020a0dc 16 limit_length,
5c2266df 17 sanitized_Request,
2fc9f2b4 18 urlencode_postdata,
51a57515 19 get_element_by_id,
20 clean_html,
9eae41dd
PH
21)
22
23
24class FacebookIE(InfoExtractor):
9834872b 25 _VALID_URL = r'''(?x)
9d9d70c4 26 https?://(?:\w+\.)?facebook\.com/
a6da7b6b 27 (?:[^#]*?\#!/)?
c6256697
YCH
28 (?:
29 (?:video/video\.php|photo\.php|video\.php|video/embed)\?(?:.*?)
30 (?:v|video_id)=|
53faa3ca 31 [^/]+/videos/(?:[^/]+/)?
c6256697
YCH
32 )
33 (?P<id>[0-9]+)
9834872b 34 (?:.*)'''
67874aef
JMF
35 _LOGIN_URL = 'https://www.facebook.com/login.php?next=http%3A%2F%2Ffacebook.com%2Fhome.php&login_attempt=1'
36 _CHECKPOINT_URL = 'https://www.facebook.com/checkpoint/?next=http%3A%2F%2Ffacebook.com%2Fhome.php&_fb_noscript=1'
9eae41dd 37 _NETRC_MACHINE = 'facebook'
cb3bb2cf 38 IE_NAME = 'facebook'
60ac04e5 39 _TESTS = [{
50317dbb
PH
40 'url': 'https://www.facebook.com/video.php?v=637842556329505&fref=nf',
41 'md5': '6a40d33c0eccbb1af76cf0485a052659',
cb3bb2cf 42 'info_dict': {
50317dbb 43 'id': '637842556329505',
cb3bb2cf 44 'ext': 'mp4',
5e4f0619 45 'title': 're:Did you know Kei Nishikori is the first Asian man to ever reach a Grand Slam',
67b8a28a 46 'uploader': 'Tennis on Facebook',
6f5ac90c 47 }
a020a0dc
PH
48 }, {
49 'note': 'Video without discernible title',
50 'url': 'https://www.facebook.com/video.php?v=274175099429670',
51 'info_dict': {
52 'id': '274175099429670',
53 'ext': 'mp4',
54 'title': 'Facebook video #274175099429670',
67b8a28a 55 'uploader': 'Asif Nawab Butt',
db3ca364
YCH
56 },
57 'expected_warnings': [
58 'title'
59 ]
60ac04e5
PH
60 }, {
61 'url': 'https://www.facebook.com/video.php?v=10204634152394104',
62 'only_matching': True,
c6256697
YCH
63 }, {
64 'url': 'https://www.facebook.com/amogood/videos/1618742068337349/?fref=nf',
65 'only_matching': True,
53faa3ca
YCH
66 }, {
67 'url': 'https://www.facebook.com/ChristyClarkForBC/videos/vb.22819070941/10153870694020942/?type=2&theater',
68 'only_matching': True,
60ac04e5 69 }]
9eae41dd 70
67874aef
JMF
71 def _login(self):
72 (useremail, password) = self._get_login_info()
9eae41dd
PH
73 if useremail is None:
74 return
75
5c2266df 76 login_page_req = sanitized_Request(self._LOGIN_URL)
c1f49e16 77 self._set_cookie('facebook.com', 'locale', 'en_US')
b74fa8cd 78 login_page = self._download_webpage(login_page_req, None,
9e1a5b84
JW
79 note='Downloading login page',
80 errnote='Unable to download login page')
b37b9450 81 lsd = self._search_regex(
d0ff8384 82 r'<input type="hidden" name="lsd" value="([^"]*)"',
b37b9450 83 login_page, 'lsd')
cb3bb2cf 84 lgnrnd = self._search_regex(r'name="lgnrnd" value="([^"]*?)"', login_page, 'lgnrnd')
67874aef 85
9eae41dd
PH
86 login_form = {
87 'email': useremail,
88 'pass': password,
67874aef
JMF
89 'lsd': lsd,
90 'lgnrnd': lgnrnd,
91 'next': 'http://facebook.com/home.php',
92 'default_persistent': '0',
93 'legacy_return': '1',
94 'timezone': '-60',
95 'trynum': '1',
b74e86f4 96 }
5c2266df 97 request = sanitized_Request(self._LOGIN_URL, urlencode_postdata(login_form))
67874aef 98 request.add_header('Content-Type', 'application/x-www-form-urlencoded')
9eae41dd 99 try:
b74fa8cd 100 login_results = self._download_webpage(request, None,
9e1a5b84 101 note='Logging in', errnote='unable to fetch login page')
9eae41dd 102 if re.search(r'<form(.*)name="login"(.*)</form>', login_results) is not None:
9f66931e
S
103 error = self._html_search_regex(
104 r'(?s)<div[^>]+class=(["\']).*?login_error_box.*?\1[^>]*><div[^>]*>.*?</div><div[^>]*>(?P<error>.+?)</div>',
105 login_results, 'login error', default=None, group='error')
106 if error:
107 raise ExtractorError('Unable to login: %s' % error, expected=True)
cb3bb2cf 108 self._downloader.report_warning('unable to log in: bad username/password, or exceded login rate limit (~3/min). Check credentials or wait.')
9eae41dd 109 return
67874aef 110
c1f49e16
S
111 fb_dtsg = self._search_regex(
112 r'name="fb_dtsg" value="(.+?)"', login_results, 'fb_dtsg', default=None)
113 h = self._search_regex(
114 r'name="h"\s+(?:\w+="[^"]+"\s+)*?value="([^"]+)"', login_results, 'h', default=None)
115
116 if not fb_dtsg or not h:
117 return
118
67874aef 119 check_form = {
c1f49e16
S
120 'fb_dtsg': fb_dtsg,
121 'h': h,
67874aef 122 'name_action_selected': 'dont_save',
67874aef 123 }
5c2266df 124 check_req = sanitized_Request(self._CHECKPOINT_URL, urlencode_postdata(check_form))
67874aef 125 check_req.add_header('Content-Type', 'application/x-www-form-urlencoded')
b74fa8cd 126 check_response = self._download_webpage(check_req, None,
9e1a5b84 127 note='Confirming login')
67874aef 128 if re.search(r'id="checkpointSubmitButton"', check_response) is not None:
cb3bb2cf 129 self._downloader.report_warning('Unable to confirm login, you have to login in your brower and authorize the login.')
9eae41dd 130 except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
9b9c5355 131 self._downloader.report_warning('unable to log in: %s' % error_to_compat_str(err))
9eae41dd
PH
132 return
133
67874aef
JMF
134 def _real_initialize(self):
135 self._login()
136
9eae41dd 137 def _real_extract(self, url):
2fc9f2b4 138 video_id = self._match_id(url)
9eae41dd
PH
139 url = 'https://www.facebook.com/video/video.php?v=%s' % video_id
140 webpage = self._download_webpage(url, video_id)
141
142 BEFORE = '{swf.addParam(param[0], param[1]);});\n'
143 AFTER = '.forEach(function(variable) {swf.addVariable(variable[0], variable[1]);});'
144 m = re.search(re.escape(BEFORE) + '(.*?)' + re.escape(AFTER), webpage)
145 if not m:
6f71ef58
JMF
146 m_msg = re.search(r'class="[^"]*uiInterstitialContent[^"]*"><div>(.*?)</div>', webpage)
147 if m_msg is not None:
749a4fd2 148 raise ExtractorError(
cb3bb2cf 149 'The video is not available, Facebook said: "%s"' % m_msg.group(1),
749a4fd2 150 expected=True)
6f71ef58 151 else:
cb3bb2cf 152 raise ExtractorError('Cannot parse data')
9eae41dd 153 data = dict(json.loads(m.group(1)))
d7011316 154 params_raw = compat_urllib_parse_unquote(data['params'])
9eae41dd 155 params = json.loads(params_raw)
ffdf972b
JMF
156
157 formats = []
44d6dd08
S
158 for format_id, f in params['video_data'].items():
159 if not f or not isinstance(f, list):
160 continue
161 for quality in ('sd', 'hd'):
162 for src_type in ('src', 'src_no_ratelimit'):
163 src = f[0].get('%s_%s' % (quality, src_type))
164 if src:
165 formats.append({
166 'format_id': '%s_%s_%s' % (format_id, quality, src_type),
167 'url': src,
168 'preference': -10 if format_id == 'progressive' else 0,
169 })
ffdf972b
JMF
170 if not formats:
171 raise ExtractorError('Cannot find video formats')
9eae41dd 172
81ec7c79 173 video_title = self._html_search_regex(
bf24c3d0 174 r'<h2\s+[^>]*class="uiHeaderTitle"[^>]*>([^<]*)</h2>', webpage, 'title',
db3ca364 175 default=None)
50317dbb
PH
176 if not video_title:
177 video_title = self._html_search_regex(
178 r'(?s)<span class="fbPhotosPhotoCaption".*?id="fbPhotoPageCaption"><span class="hasCaption">(.*?)</span>',
59ee8a86 179 webpage, 'alternative title', default=None)
a020a0dc 180 video_title = limit_length(video_title, 80)
50317dbb
PH
181 if not video_title:
182 video_title = 'Facebook video #%s' % video_id
51a57515 183 uploader = clean_html(get_element_by_id('fbPhotoPageAuthorName', webpage))
9eae41dd 184
9d9d70c4 185 return {
9eae41dd
PH
186 'id': video_id,
187 'title': video_title,
ffdf972b 188 'formats': formats,
51a57515 189 'uploader': uploader,
9eae41dd 190 }