[facebook] Match video.php URLs
[youtube-dl] / 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 ..utils import (
9     compat_http_client,
10     compat_str,
11     compat_urllib_error,
12     compat_urllib_parse,
13     compat_urllib_request,
14     urlencode_postdata,
15
16     ExtractorError,
17 )
18
19
20 class FacebookIE(InfoExtractor):
21     _VALID_URL = r'''(?x)
22         https?://(?:\w+\.)?facebook\.com/
23         (?:[^#]*?\#!/)?
24         (?:video/video\.php|photo\.php|video\.php|video/embed)\?(?:.*?)
25         (?:v|video_id)=(?P<id>[0-9]+)
26         (?:.*)'''
27     _LOGIN_URL = 'https://www.facebook.com/login.php?next=http%3A%2F%2Ffacebook.com%2Fhome.php&login_attempt=1'
28     _CHECKPOINT_URL = 'https://www.facebook.com/checkpoint/?next=http%3A%2F%2Ffacebook.com%2Fhome.php&_fb_noscript=1'
29     _NETRC_MACHINE = 'facebook'
30     IE_NAME = 'facebook'
31     _TESTS = [{
32         'url': 'https://www.facebook.com/photo.php?v=120708114770723',
33         'md5': '48975a41ccc4b7a581abd68651c1a5a8',
34         'info_dict': {
35             'id': '120708114770723',
36             'ext': 'mp4',
37             'duration': 279,
38             'title': 'PEOPLE ARE AWESOME 2013',
39         }
40     }, {
41         'url': 'https://www.facebook.com/video.php?v=10204634152394104',
42         'only_matching': True,
43     }]
44
45     def _login(self):
46         (useremail, password) = self._get_login_info()
47         if useremail is None:
48             return
49
50         login_page_req = compat_urllib_request.Request(self._LOGIN_URL)
51         login_page_req.add_header('Cookie', 'locale=en_US')
52         login_page = self._download_webpage(login_page_req, None,
53             note='Downloading login page',
54             errnote='Unable to download login page')
55         lsd = self._search_regex(
56             r'<input type="hidden" name="lsd" value="([^"]*)"',
57             login_page, 'lsd')
58         lgnrnd = self._search_regex(r'name="lgnrnd" value="([^"]*?)"', login_page, 'lgnrnd')
59
60         login_form = {
61             'email': useremail,
62             'pass': password,
63             'lsd': lsd,
64             'lgnrnd': lgnrnd,
65             'next': 'http://facebook.com/home.php',
66             'default_persistent': '0',
67             'legacy_return': '1',
68             'timezone': '-60',
69             'trynum': '1',
70             }
71         request = compat_urllib_request.Request(self._LOGIN_URL, urlencode_postdata(login_form))
72         request.add_header('Content-Type', 'application/x-www-form-urlencoded')
73         try:
74             login_results = self._download_webpage(request, None,
75                 note='Logging in', errnote='unable to fetch login page')
76             if re.search(r'<form(.*)name="login"(.*)</form>', login_results) is not None:
77                 self._downloader.report_warning('unable to log in: bad username/password, or exceded login rate limit (~3/min). Check credentials or wait.')
78                 return
79
80             check_form = {
81                 'fb_dtsg': self._search_regex(r'name="fb_dtsg" value="(.+?)"', login_results, 'fb_dtsg'),
82                 'h': self._search_regex(r'name="h" value="(\w*?)"', login_results, 'h'),
83                 'name_action_selected': 'dont_save',
84             }
85             check_req = compat_urllib_request.Request(self._CHECKPOINT_URL, urlencode_postdata(check_form))
86             check_req.add_header('Content-Type', 'application/x-www-form-urlencoded')
87             check_response = self._download_webpage(check_req, None,
88                 note='Confirming login')
89             if re.search(r'id="checkpointSubmitButton"', check_response) is not None:
90                 self._downloader.report_warning('Unable to confirm login, you have to login in your brower and authorize the login.')
91         except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
92             self._downloader.report_warning('unable to log in: %s' % compat_str(err))
93             return
94
95     def _real_initialize(self):
96         self._login()
97
98     def _real_extract(self, url):
99         mobj = re.match(self._VALID_URL, url)
100         video_id = mobj.group('id')
101
102         url = 'https://www.facebook.com/video/video.php?v=%s' % video_id
103         webpage = self._download_webpage(url, video_id)
104
105         BEFORE = '{swf.addParam(param[0], param[1]);});\n'
106         AFTER = '.forEach(function(variable) {swf.addVariable(variable[0], variable[1]);});'
107         m = re.search(re.escape(BEFORE) + '(.*?)' + re.escape(AFTER), webpage)
108         if not m:
109             m_msg = re.search(r'class="[^"]*uiInterstitialContent[^"]*"><div>(.*?)</div>', webpage)
110             if m_msg is not None:
111                 raise ExtractorError(
112                     'The video is not available, Facebook said: "%s"' % m_msg.group(1),
113                     expected=True)
114             else:
115                 raise ExtractorError('Cannot parse data')
116         data = dict(json.loads(m.group(1)))
117         params_raw = compat_urllib_parse.unquote(data['params'])
118         params = json.loads(params_raw)
119         video_data = params['video_data'][0]
120         video_url = video_data.get('hd_src')
121         if not video_url:
122             video_url = video_data['sd_src']
123         if not video_url:
124             raise ExtractorError('Cannot find video URL')
125
126         video_title = self._html_search_regex(
127             r'<h2 class="uiHeaderTitle">([^<]*)</h2>', webpage, 'title')
128
129         return {
130             'id': video_id,
131             'title': video_title,
132             'url': video_url,
133             'duration': int(video_data['video_duration']),
134             'thumbnail': video_data['thumbnail_src'],
135         }