]> gitweb @ CieloNegro.org - youtube-dl.git/blob - youtube_dl/extractor/facebook.py
[facebook] Relax _VALID_URL (Closes #10151)
[youtube-dl.git] / 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_etree_fromstring,
10     compat_http_client,
11     compat_urllib_error,
12     compat_urllib_parse_unquote,
13     compat_urllib_parse_unquote_plus,
14 )
15 from ..utils import (
16     error_to_compat_str,
17     ExtractorError,
18     limit_length,
19     sanitized_Request,
20     urlencode_postdata,
21     get_element_by_id,
22     clean_html,
23 )
24
25
26 class FacebookIE(InfoExtractor):
27     _VALID_URL = r'''(?x)
28                 (?:
29                     https?://
30                         (?:[\w-]+\.)?facebook\.com/
31                         (?:[^#]*?\#!/)?
32                         (?:
33                             (?:
34                                 video/video\.php|
35                                 photo\.php|
36                                 video\.php|
37                                 video/embed|
38                                 story\.php
39                             )\?(?:.*?)(?:v|video_id|story_fbid)=|
40                             [^/]+/videos/(?:[^/]+/)?|
41                             [^/]+/posts/|
42                             groups/[^/]+/permalink/
43                         )|
44                     facebook:
45                 )
46                 (?P<id>[0-9]+)
47                 '''
48     _LOGIN_URL = 'https://www.facebook.com/login.php?next=http%3A%2F%2Ffacebook.com%2Fhome.php&login_attempt=1'
49     _CHECKPOINT_URL = 'https://www.facebook.com/checkpoint/?next=http%3A%2F%2Ffacebook.com%2Fhome.php&_fb_noscript=1'
50     _NETRC_MACHINE = 'facebook'
51     IE_NAME = 'facebook'
52
53     _CHROME_USER_AGENT = 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/48.0.2564.97 Safari/537.36'
54
55     _VIDEO_PAGE_TEMPLATE = 'https://www.facebook.com/video/video.php?v=%s'
56
57     _TESTS = [{
58         'url': 'https://www.facebook.com/video.php?v=637842556329505&fref=nf',
59         'md5': '6a40d33c0eccbb1af76cf0485a052659',
60         'info_dict': {
61             'id': '637842556329505',
62             'ext': 'mp4',
63             'title': 're:Did you know Kei Nishikori is the first Asian man to ever reach a Grand Slam',
64             'uploader': 'Tennis on Facebook',
65         }
66     }, {
67         'note': 'Video without discernible title',
68         'url': 'https://www.facebook.com/video.php?v=274175099429670',
69         'info_dict': {
70             'id': '274175099429670',
71             'ext': 'mp4',
72             'title': 'Facebook video #274175099429670',
73             'uploader': 'Asif Nawab Butt',
74         },
75         'expected_warnings': [
76             'title'
77         ]
78     }, {
79         'note': 'Video with DASH manifest',
80         'url': 'https://www.facebook.com/video.php?v=957955867617029',
81         'md5': '54706e4db4f5ad58fbad82dde1f1213f',
82         'info_dict': {
83             'id': '957955867617029',
84             'ext': 'mp4',
85             'title': 'When you post epic content on instagram.com/433 8 million followers, this is ...',
86             'uploader': 'Demy de Zeeuw',
87         },
88     }, {
89         'url': 'https://www.facebook.com/maxlayn/posts/10153807558977570',
90         'md5': '037b1fa7f3c2d02b7a0d7bc16031ecc6',
91         'info_dict': {
92             'id': '544765982287235',
93             'ext': 'mp4',
94             'title': '"What are you doing running in the snow?"',
95             'uploader': 'FailArmy',
96         }
97     }, {
98         'url': 'https://m.facebook.com/story.php?story_fbid=1035862816472149&id=116132035111903',
99         'md5': '1deb90b6ac27f7efcf6d747c8a27f5e3',
100         'info_dict': {
101             'id': '1035862816472149',
102             'ext': 'mp4',
103             'title': 'What the Flock Is Going On In New Zealand  Credit: ViralHog',
104             'uploader': 'S. Saint',
105         },
106     }, {
107         'note': 'swf params escaped',
108         'url': 'https://www.facebook.com/barackobama/posts/10153664894881749',
109         'md5': '97ba073838964d12c70566e0085c2b91',
110         'info_dict': {
111             'id': '10153664894881749',
112             'ext': 'mp4',
113             'title': 'Facebook video #10153664894881749',
114         },
115     }, {
116         'url': 'https://www.facebook.com/video.php?v=10204634152394104',
117         'only_matching': True,
118     }, {
119         'url': 'https://www.facebook.com/amogood/videos/1618742068337349/?fref=nf',
120         'only_matching': True,
121     }, {
122         'url': 'https://www.facebook.com/ChristyClarkForBC/videos/vb.22819070941/10153870694020942/?type=2&theater',
123         'only_matching': True,
124     }, {
125         'url': 'facebook:544765982287235',
126         'only_matching': True,
127     }, {
128         'url': 'https://www.facebook.com/groups/164828000315060/permalink/764967300301124/',
129         'only_matching': True,
130     }, {
131         'url': 'https://zh-hk.facebook.com/peoplespower/videos/1135894589806027/',
132         'only_matching': True,
133     }]
134
135     @staticmethod
136     def _extract_url(webpage):
137         mobj = re.search(
138             r'<iframe[^>]+?src=(["\'])(?P<url>https://www\.facebook\.com/video/embed.+?)\1', webpage)
139         if mobj is not None:
140             return mobj.group('url')
141
142         # Facebook API embed
143         # see https://developers.facebook.com/docs/plugins/embedded-video-player
144         mobj = re.search(r'''(?x)<div[^>]+
145                 class=(?P<q1>[\'"])[^\'"]*\bfb-(?:video|post)\b[^\'"]*(?P=q1)[^>]+
146                 data-href=(?P<q2>[\'"])(?P<url>(?:https?:)?//(?:www\.)?facebook.com/.+?)(?P=q2)''', webpage)
147         if mobj is not None:
148             return mobj.group('url')
149
150     def _login(self):
151         (useremail, password) = self._get_login_info()
152         if useremail is None:
153             return
154
155         login_page_req = sanitized_Request(self._LOGIN_URL)
156         self._set_cookie('facebook.com', 'locale', 'en_US')
157         login_page = self._download_webpage(login_page_req, None,
158                                             note='Downloading login page',
159                                             errnote='Unable to download login page')
160         lsd = self._search_regex(
161             r'<input type="hidden" name="lsd" value="([^"]*)"',
162             login_page, 'lsd')
163         lgnrnd = self._search_regex(r'name="lgnrnd" value="([^"]*?)"', login_page, 'lgnrnd')
164
165         login_form = {
166             'email': useremail,
167             'pass': password,
168             'lsd': lsd,
169             'lgnrnd': lgnrnd,
170             'next': 'http://facebook.com/home.php',
171             'default_persistent': '0',
172             'legacy_return': '1',
173             'timezone': '-60',
174             'trynum': '1',
175         }
176         request = sanitized_Request(self._LOGIN_URL, urlencode_postdata(login_form))
177         request.add_header('Content-Type', 'application/x-www-form-urlencoded')
178         try:
179             login_results = self._download_webpage(request, None,
180                                                    note='Logging in', errnote='unable to fetch login page')
181             if re.search(r'<form(.*)name="login"(.*)</form>', login_results) is not None:
182                 error = self._html_search_regex(
183                     r'(?s)<div[^>]+class=(["\']).*?login_error_box.*?\1[^>]*><div[^>]*>.*?</div><div[^>]*>(?P<error>.+?)</div>',
184                     login_results, 'login error', default=None, group='error')
185                 if error:
186                     raise ExtractorError('Unable to login: %s' % error, expected=True)
187                 self._downloader.report_warning('unable to log in: bad username/password, or exceeded login rate limit (~3/min). Check credentials or wait.')
188                 return
189
190             fb_dtsg = self._search_regex(
191                 r'name="fb_dtsg" value="(.+?)"', login_results, 'fb_dtsg', default=None)
192             h = self._search_regex(
193                 r'name="h"\s+(?:\w+="[^"]+"\s+)*?value="([^"]+)"', login_results, 'h', default=None)
194
195             if not fb_dtsg or not h:
196                 return
197
198             check_form = {
199                 'fb_dtsg': fb_dtsg,
200                 'h': h,
201                 'name_action_selected': 'dont_save',
202             }
203             check_req = sanitized_Request(self._CHECKPOINT_URL, urlencode_postdata(check_form))
204             check_req.add_header('Content-Type', 'application/x-www-form-urlencoded')
205             check_response = self._download_webpage(check_req, None,
206                                                     note='Confirming login')
207             if re.search(r'id="checkpointSubmitButton"', check_response) is not None:
208                 self._downloader.report_warning('Unable to confirm login, you have to login in your browser and authorize the login.')
209         except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
210             self._downloader.report_warning('unable to log in: %s' % error_to_compat_str(err))
211             return
212
213     def _real_initialize(self):
214         self._login()
215
216     def _extract_from_url(self, url, video_id, fatal_if_no_video=True):
217         req = sanitized_Request(url)
218         req.add_header('User-Agent', self._CHROME_USER_AGENT)
219         webpage = self._download_webpage(req, video_id)
220
221         video_data = None
222
223         BEFORE = '{swf.addParam(param[0], param[1]);});'
224         AFTER = '.forEach(function(variable) {swf.addVariable(variable[0], variable[1]);});'
225         PATTERN = re.escape(BEFORE) + '(?:\n|\\\\n)(.*?)' + re.escape(AFTER)
226
227         for m in re.findall(PATTERN, webpage):
228             swf_params = m.replace('\\\\', '\\').replace('\\"', '"')
229             data = dict(json.loads(swf_params))
230             params_raw = compat_urllib_parse_unquote(data['params'])
231             video_data_candidate = json.loads(params_raw)['video_data']
232             for _, f in video_data_candidate.items():
233                 if not f:
234                     continue
235                 if isinstance(f, dict):
236                     f = [f]
237                 if not isinstance(f, list):
238                     continue
239                 if f[0].get('video_id') == video_id:
240                     video_data = video_data_candidate
241                     break
242             if video_data:
243                 break
244
245         def video_data_list2dict(video_data):
246             ret = {}
247             for item in video_data:
248                 format_id = item['stream_type']
249                 ret.setdefault(format_id, []).append(item)
250             return ret
251
252         if not video_data:
253             server_js_data = self._parse_json(self._search_regex(
254                 r'handleServerJS\(({.+})\);', webpage, 'server js data', default='{}'), video_id)
255             for item in server_js_data.get('instances', []):
256                 if item[1][0] == 'VideoConfig':
257                     video_data = video_data_list2dict(item[2][0]['videoData'])
258                     break
259
260         if not video_data:
261             if not fatal_if_no_video:
262                 return webpage, False
263             m_msg = re.search(r'class="[^"]*uiInterstitialContent[^"]*"><div>(.*?)</div>', webpage)
264             if m_msg is not None:
265                 raise ExtractorError(
266                     'The video is not available, Facebook said: "%s"' % m_msg.group(1),
267                     expected=True)
268             else:
269                 raise ExtractorError('Cannot parse data')
270
271         formats = []
272         for format_id, f in video_data.items():
273             if f and isinstance(f, dict):
274                 f = [f]
275             if not f or not isinstance(f, list):
276                 continue
277             for quality in ('sd', 'hd'):
278                 for src_type in ('src', 'src_no_ratelimit'):
279                     src = f[0].get('%s_%s' % (quality, src_type))
280                     if src:
281                         preference = -10 if format_id == 'progressive' else 0
282                         if quality == 'hd':
283                             preference += 5
284                         formats.append({
285                             'format_id': '%s_%s_%s' % (format_id, quality, src_type),
286                             'url': src,
287                             'preference': preference,
288                         })
289             dash_manifest = f[0].get('dash_manifest')
290             if dash_manifest:
291                 formats.extend(self._parse_mpd_formats(
292                     compat_etree_fromstring(compat_urllib_parse_unquote_plus(dash_manifest))))
293         if not formats:
294             raise ExtractorError('Cannot find video formats')
295
296         self._sort_formats(formats)
297
298         video_title = self._html_search_regex(
299             r'<h2\s+[^>]*class="uiHeaderTitle"[^>]*>([^<]*)</h2>', webpage, 'title',
300             default=None)
301         if not video_title:
302             video_title = self._html_search_regex(
303                 r'(?s)<span class="fbPhotosPhotoCaption".*?id="fbPhotoPageCaption"><span class="hasCaption">(.*?)</span>',
304                 webpage, 'alternative title', default=None)
305             video_title = limit_length(video_title, 80)
306         if not video_title:
307             video_title = 'Facebook video #%s' % video_id
308         uploader = clean_html(get_element_by_id('fbPhotoPageAuthorName', webpage))
309
310         info_dict = {
311             'id': video_id,
312             'title': video_title,
313             'formats': formats,
314             'uploader': uploader,
315         }
316
317         return webpage, info_dict
318
319     def _real_extract(self, url):
320         video_id = self._match_id(url)
321
322         real_url = self._VIDEO_PAGE_TEMPLATE % video_id if url.startswith('facebook:') else url
323         webpage, info_dict = self._extract_from_url(real_url, video_id, fatal_if_no_video=False)
324
325         if info_dict:
326             return info_dict
327
328         if '/posts/' in url:
329             entries = [
330                 self.url_result('facebook:%s' % vid, FacebookIE.ie_key())
331                 for vid in self._parse_json(
332                     self._search_regex(
333                         r'(["\'])video_ids\1\s*:\s*(?P<ids>\[.+?\])',
334                         webpage, 'video ids', group='ids'),
335                     video_id)]
336
337             return self.playlist_result(entries, video_id)
338         else:
339             _, info_dict = self._extract_from_url(
340                 self._VIDEO_PAGE_TEMPLATE % video_id,
341                 video_id, fatal_if_no_video=True)
342             return info_dict