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