Merge pull request #14225 from Tithen-Firion/openload-phantomjs-method
[youtube-dl] / youtube_dl / extractor / facebook.py
1 # coding: utf-8
2 from __future__ import unicode_literals
3
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     clean_html,
17     error_to_compat_str,
18     ExtractorError,
19     get_element_by_id,
20     int_or_none,
21     js_to_json,
22     limit_length,
23     sanitized_Request,
24     try_get,
25     urlencode_postdata,
26 )
27
28
29 class FacebookIE(InfoExtractor):
30     _VALID_URL = r'''(?x)
31                 (?:
32                     https?://
33                         (?:[\w-]+\.)?(?:facebook\.com|facebookcorewwwi\.onion)/
34                         (?:[^#]*?\#!/)?
35                         (?:
36                             (?:
37                                 video/video\.php|
38                                 photo\.php|
39                                 video\.php|
40                                 video/embed|
41                                 story\.php
42                             )\?(?:.*?)(?:v|video_id|story_fbid)=|
43                             [^/]+/videos/(?:[^/]+/)?|
44                             [^/]+/posts/|
45                             groups/[^/]+/permalink/
46                         )|
47                     facebook:
48                 )
49                 (?P<id>[0-9]+)
50                 '''
51     _LOGIN_URL = 'https://www.facebook.com/login.php?next=http%3A%2F%2Ffacebook.com%2Fhome.php&login_attempt=1'
52     _CHECKPOINT_URL = 'https://www.facebook.com/checkpoint/?next=http%3A%2F%2Ffacebook.com%2Fhome.php&_fb_noscript=1'
53     _NETRC_MACHINE = 'facebook'
54     IE_NAME = 'facebook'
55
56     _CHROME_USER_AGENT = 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/48.0.2564.97 Safari/537.36'
57
58     _VIDEO_PAGE_TEMPLATE = 'https://www.facebook.com/video/video.php?v=%s'
59
60     _TESTS = [{
61         'url': 'https://www.facebook.com/video.php?v=637842556329505&fref=nf',
62         'md5': '6a40d33c0eccbb1af76cf0485a052659',
63         'info_dict': {
64             'id': '637842556329505',
65             'ext': 'mp4',
66             'title': 're:Did you know Kei Nishikori is the first Asian man to ever reach a Grand Slam',
67             'uploader': 'Tennis on Facebook',
68             'upload_date': '20140908',
69             'timestamp': 1410199200,
70         }
71     }, {
72         'note': 'Video without discernible title',
73         'url': 'https://www.facebook.com/video.php?v=274175099429670',
74         'info_dict': {
75             'id': '274175099429670',
76             'ext': 'mp4',
77             'title': 'Asif Nawab Butt posted a video to his Timeline.',
78             'uploader': 'Asif Nawab Butt',
79             'upload_date': '20140506',
80             'timestamp': 1399398998,
81         },
82         'expected_warnings': [
83             'title'
84         ]
85     }, {
86         'note': 'Video with DASH manifest',
87         'url': 'https://www.facebook.com/video.php?v=957955867617029',
88         'md5': 'b2c28d528273b323abe5c6ab59f0f030',
89         'info_dict': {
90             'id': '957955867617029',
91             'ext': 'mp4',
92             'title': 'When you post epic content on instagram.com/433 8 million followers, this is ...',
93             'uploader': 'Demy de Zeeuw',
94             'upload_date': '20160110',
95             'timestamp': 1452431627,
96         },
97     }, {
98         'url': 'https://www.facebook.com/maxlayn/posts/10153807558977570',
99         'md5': '037b1fa7f3c2d02b7a0d7bc16031ecc6',
100         'info_dict': {
101             'id': '544765982287235',
102             'ext': 'mp4',
103             'title': '"What are you doing running in the snow?"',
104             'uploader': 'FailArmy',
105         },
106         'skip': 'Video gone',
107     }, {
108         'url': 'https://m.facebook.com/story.php?story_fbid=1035862816472149&id=116132035111903',
109         'md5': '1deb90b6ac27f7efcf6d747c8a27f5e3',
110         'info_dict': {
111             'id': '1035862816472149',
112             'ext': 'mp4',
113             'title': 'What the Flock Is Going On In New Zealand  Credit: ViralHog',
114             'uploader': 'S. Saint',
115         },
116         'skip': 'Video gone',
117     }, {
118         'note': 'swf params escaped',
119         'url': 'https://www.facebook.com/barackobama/posts/10153664894881749',
120         'md5': '97ba073838964d12c70566e0085c2b91',
121         'info_dict': {
122             'id': '10153664894881749',
123             'ext': 'mp4',
124             'title': 'Facebook video #10153664894881749',
125         },
126     }, {
127         # have 1080P, but only up to 720p in swf params
128         'url': 'https://www.facebook.com/cnn/videos/10155529876156509/',
129         'md5': '0d9813160b146b3bc8744e006027fcc6',
130         'info_dict': {
131             'id': '10155529876156509',
132             'ext': 'mp4',
133             'title': 'Holocaust survivor becomes US citizen',
134             'timestamp': 1477818095,
135             'upload_date': '20161030',
136             'uploader': 'CNN',
137         },
138     }, {
139         # bigPipe.onPageletArrive ... onPageletArrive pagelet_group_mall
140         'url': 'https://www.facebook.com/yaroslav.korpan/videos/1417995061575415/',
141         'info_dict': {
142             'id': '1417995061575415',
143             'ext': 'mp4',
144             'title': 'md5:a7b86ca673f51800cd54687b7f4012fe',
145             'timestamp': 1486648217,
146             'upload_date': '20170209',
147             'uploader': 'Yaroslav Korpan',
148         },
149         'params': {
150             'skip_download': True,
151         },
152     }, {
153         'url': 'https://www.facebook.com/LaGuiaDelVaron/posts/1072691702860471',
154         'info_dict': {
155             'id': '1072691702860471',
156             'ext': 'mp4',
157             'title': 'md5:ae2d22a93fbb12dad20dc393a869739d',
158             'timestamp': 1477305000,
159             'upload_date': '20161024',
160             'uploader': 'La Guía Del Varón',
161         },
162         'params': {
163             'skip_download': True,
164         },
165     }, {
166         'url': 'https://www.facebook.com/groups/1024490957622648/permalink/1396382447100162/',
167         'info_dict': {
168             'id': '1396382447100162',
169             'ext': 'mp4',
170             'title': 'md5:e2d2700afdf84e121f5d0f999bad13a3',
171             'timestamp': 1486035494,
172             'upload_date': '20170202',
173             'uploader': 'Elisabeth Ahtn',
174         },
175         'params': {
176             'skip_download': True,
177         },
178     }, {
179         'url': 'https://www.facebook.com/video.php?v=10204634152394104',
180         'only_matching': True,
181     }, {
182         'url': 'https://www.facebook.com/amogood/videos/1618742068337349/?fref=nf',
183         'only_matching': True,
184     }, {
185         'url': 'https://www.facebook.com/ChristyClarkForBC/videos/vb.22819070941/10153870694020942/?type=2&theater',
186         'only_matching': True,
187     }, {
188         'url': 'facebook:544765982287235',
189         'only_matching': True,
190     }, {
191         'url': 'https://www.facebook.com/groups/164828000315060/permalink/764967300301124/',
192         'only_matching': True,
193     }, {
194         'url': 'https://zh-hk.facebook.com/peoplespower/videos/1135894589806027/',
195         'only_matching': True,
196     }, {
197         'url': 'https://www.facebookcorewwwi.onion/video.php?v=274175099429670',
198         'only_matching': True,
199     }, {
200         # no title
201         'url': 'https://www.facebook.com/onlycleverentertainment/videos/1947995502095005/',
202         'only_matching': True,
203     }]
204
205     @staticmethod
206     def _extract_urls(webpage):
207         urls = []
208         for mobj in re.finditer(
209                 r'<iframe[^>]+?src=(["\'])(?P<url>https?://www\.facebook\.com/(?:video/embed|plugins/video\.php).+?)\1',
210                 webpage):
211             urls.append(mobj.group('url'))
212         # Facebook API embed
213         # see https://developers.facebook.com/docs/plugins/embedded-video-player
214         for mobj in re.finditer(r'''(?x)<div[^>]+
215                 class=(?P<q1>[\'"])[^\'"]*\bfb-(?:video|post)\b[^\'"]*(?P=q1)[^>]+
216                 data-href=(?P<q2>[\'"])(?P<url>(?:https?:)?//(?:www\.)?facebook.com/.+?)(?P=q2)''', webpage):
217             urls.append(mobj.group('url'))
218         return urls
219
220     def _login(self):
221         (useremail, password) = self._get_login_info()
222         if useremail is None:
223             return
224
225         login_page_req = sanitized_Request(self._LOGIN_URL)
226         self._set_cookie('facebook.com', 'locale', 'en_US')
227         login_page = self._download_webpage(login_page_req, None,
228                                             note='Downloading login page',
229                                             errnote='Unable to download login page')
230         lsd = self._search_regex(
231             r'<input type="hidden" name="lsd" value="([^"]*)"',
232             login_page, 'lsd')
233         lgnrnd = self._search_regex(r'name="lgnrnd" value="([^"]*?)"', login_page, 'lgnrnd')
234
235         login_form = {
236             'email': useremail,
237             'pass': password,
238             'lsd': lsd,
239             'lgnrnd': lgnrnd,
240             'next': 'http://facebook.com/home.php',
241             'default_persistent': '0',
242             'legacy_return': '1',
243             'timezone': '-60',
244             'trynum': '1',
245         }
246         request = sanitized_Request(self._LOGIN_URL, urlencode_postdata(login_form))
247         request.add_header('Content-Type', 'application/x-www-form-urlencoded')
248         try:
249             login_results = self._download_webpage(request, None,
250                                                    note='Logging in', errnote='unable to fetch login page')
251             if re.search(r'<form(.*)name="login"(.*)</form>', login_results) is not None:
252                 error = self._html_search_regex(
253                     r'(?s)<div[^>]+class=(["\']).*?login_error_box.*?\1[^>]*><div[^>]*>.*?</div><div[^>]*>(?P<error>.+?)</div>',
254                     login_results, 'login error', default=None, group='error')
255                 if error:
256                     raise ExtractorError('Unable to login: %s' % error, expected=True)
257                 self._downloader.report_warning('unable to log in: bad username/password, or exceeded login rate limit (~3/min). Check credentials or wait.')
258                 return
259
260             fb_dtsg = self._search_regex(
261                 r'name="fb_dtsg" value="(.+?)"', login_results, 'fb_dtsg', default=None)
262             h = self._search_regex(
263                 r'name="h"\s+(?:\w+="[^"]+"\s+)*?value="([^"]+)"', login_results, 'h', default=None)
264
265             if not fb_dtsg or not h:
266                 return
267
268             check_form = {
269                 'fb_dtsg': fb_dtsg,
270                 'h': h,
271                 'name_action_selected': 'dont_save',
272             }
273             check_req = sanitized_Request(self._CHECKPOINT_URL, urlencode_postdata(check_form))
274             check_req.add_header('Content-Type', 'application/x-www-form-urlencoded')
275             check_response = self._download_webpage(check_req, None,
276                                                     note='Confirming login')
277             if re.search(r'id="checkpointSubmitButton"', check_response) is not None:
278                 self._downloader.report_warning('Unable to confirm login, you have to login in your browser and authorize the login.')
279         except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
280             self._downloader.report_warning('unable to log in: %s' % error_to_compat_str(err))
281             return
282
283     def _real_initialize(self):
284         self._login()
285
286     def _extract_from_url(self, url, video_id, fatal_if_no_video=True):
287         req = sanitized_Request(url)
288         req.add_header('User-Agent', self._CHROME_USER_AGENT)
289         webpage = self._download_webpage(req, video_id)
290
291         video_data = None
292
293         def extract_video_data(instances):
294             for item in instances:
295                 if item[1][0] == 'VideoConfig':
296                     video_item = item[2][0]
297                     if video_item.get('video_id'):
298                         return video_item['videoData']
299
300         server_js_data = self._parse_json(self._search_regex(
301             r'handleServerJS\(({.+})(?:\);|,")', webpage,
302             'server js data', default='{}'), video_id, fatal=False)
303
304         if server_js_data:
305             video_data = extract_video_data(server_js_data.get('instances', []))
306
307         if not video_data:
308             server_js_data = self._parse_json(
309                 self._search_regex(
310                     r'bigPipe\.onPageletArrive\(({.+?})\)\s*;\s*}\s*\)\s*,\s*["\']onPageletArrive\s+(?:stream_pagelet|pagelet_group_mall|permalink_video_pagelet)',
311                     webpage, 'js data', default='{}'),
312                 video_id, transform_source=js_to_json, fatal=False)
313             if server_js_data:
314                 video_data = extract_video_data(try_get(
315                     server_js_data, lambda x: x['jsmods']['instances'],
316                     list) or [])
317
318         if not video_data:
319             if not fatal_if_no_video:
320                 return webpage, False
321             m_msg = re.search(r'class="[^"]*uiInterstitialContent[^"]*"><div>(.*?)</div>', webpage)
322             if m_msg is not None:
323                 raise ExtractorError(
324                     'The video is not available, Facebook said: "%s"' % m_msg.group(1),
325                     expected=True)
326             elif '>You must log in to continue' in webpage:
327                 self.raise_login_required()
328             else:
329                 raise ExtractorError('Cannot parse data')
330
331         formats = []
332         for f in video_data:
333             format_id = f['stream_type']
334             if f and isinstance(f, dict):
335                 f = [f]
336             if not f or not isinstance(f, list):
337                 continue
338             for quality in ('sd', 'hd'):
339                 for src_type in ('src', 'src_no_ratelimit'):
340                     src = f[0].get('%s_%s' % (quality, src_type))
341                     if src:
342                         preference = -10 if format_id == 'progressive' else 0
343                         if quality == 'hd':
344                             preference += 5
345                         formats.append({
346                             'format_id': '%s_%s_%s' % (format_id, quality, src_type),
347                             'url': src,
348                             'preference': preference,
349                         })
350             dash_manifest = f[0].get('dash_manifest')
351             if dash_manifest:
352                 formats.extend(self._parse_mpd_formats(
353                     compat_etree_fromstring(compat_urllib_parse_unquote_plus(dash_manifest))))
354         if not formats:
355             raise ExtractorError('Cannot find video formats')
356
357         self._sort_formats(formats)
358
359         video_title = self._html_search_regex(
360             r'<h2\s+[^>]*class="uiHeaderTitle"[^>]*>([^<]*)</h2>', webpage,
361             'title', default=None)
362         if not video_title:
363             video_title = self._html_search_regex(
364                 r'(?s)<span class="fbPhotosPhotoCaption".*?id="fbPhotoPageCaption"><span class="hasCaption">(.*?)</span>',
365                 webpage, 'alternative title', default=None)
366         if not video_title:
367             video_title = self._html_search_meta(
368                 'description', webpage, 'title', default=None)
369         if video_title:
370             video_title = limit_length(video_title, 80)
371         else:
372             video_title = 'Facebook video #%s' % video_id
373         uploader = clean_html(get_element_by_id(
374             'fbPhotoPageAuthorName', webpage)) or self._search_regex(
375             r'ownerName\s*:\s*"([^"]+)"', webpage, 'uploader', fatal=False)
376         timestamp = int_or_none(self._search_regex(
377             r'<abbr[^>]+data-utime=["\'](\d+)', webpage,
378             'timestamp', default=None))
379
380         info_dict = {
381             'id': video_id,
382             'title': video_title,
383             'formats': formats,
384             'uploader': uploader,
385             'timestamp': timestamp,
386         }
387
388         return webpage, info_dict
389
390     def _real_extract(self, url):
391         video_id = self._match_id(url)
392
393         real_url = self._VIDEO_PAGE_TEMPLATE % video_id if url.startswith('facebook:') else url
394         webpage, info_dict = self._extract_from_url(real_url, video_id, fatal_if_no_video=False)
395
396         if info_dict:
397             return info_dict
398
399         if '/posts/' in url:
400             entries = [
401                 self.url_result('facebook:%s' % vid, FacebookIE.ie_key())
402                 for vid in self._parse_json(
403                     self._search_regex(
404                         r'(["\'])video_ids\1\s*:\s*(?P<ids>\[.+?\])',
405                         webpage, 'video ids', group='ids'),
406                     video_id)]
407
408             return self.playlist_result(entries, video_id)
409         else:
410             _, info_dict = self._extract_from_url(
411                 self._VIDEO_PAGE_TEMPLATE % video_id,
412                 video_id, fatal_if_no_video=True)
413             return info_dict
414
415
416 class FacebookPluginsVideoIE(InfoExtractor):
417     _VALID_URL = r'https?://(?:[\w-]+\.)?facebook\.com/plugins/video\.php\?.*?\bhref=(?P<id>https.+)'
418
419     _TESTS = [{
420         'url': 'https://www.facebook.com/plugins/video.php?href=https%3A%2F%2Fwww.facebook.com%2Fgov.sg%2Fvideos%2F10154383743583686%2F&show_text=0&width=560',
421         'md5': '5954e92cdfe51fe5782ae9bda7058a07',
422         'info_dict': {
423             'id': '10154383743583686',
424             'ext': 'mp4',
425             'title': 'What to do during the haze?',
426             'uploader': 'Gov.sg',
427             'upload_date': '20160826',
428             'timestamp': 1472184808,
429         },
430         'add_ie': [FacebookIE.ie_key()],
431     }, {
432         'url': 'https://www.facebook.com/plugins/video.php?href=https%3A%2F%2Fwww.facebook.com%2Fvideo.php%3Fv%3D10204634152394104',
433         'only_matching': True,
434     }, {
435         'url': 'https://www.facebook.com/plugins/video.php?href=https://www.facebook.com/gov.sg/videos/10154383743583686/&show_text=0&width=560',
436         'only_matching': True,
437     }]
438
439     def _real_extract(self, url):
440         return self.url_result(
441             compat_urllib_parse_unquote(self._match_id(url)),
442             FacebookIE.ie_key())