[facebook] Add support for DASH manifests
[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 ..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                             )\?(?:.*?)(?:v|video_id)=|
39                             [^/]+/videos/(?:[^/]+/)?
40                         )|
41                     facebook:
42                 )
43                 (?P<id>[0-9]+)
44                 '''
45     _LOGIN_URL = 'https://www.facebook.com/login.php?next=http%3A%2F%2Ffacebook.com%2Fhome.php&login_attempt=1'
46     _CHECKPOINT_URL = 'https://www.facebook.com/checkpoint/?next=http%3A%2F%2Ffacebook.com%2Fhome.php&_fb_noscript=1'
47     _NETRC_MACHINE = 'facebook'
48     IE_NAME = 'facebook'
49
50     _CHROME_USER_AGENT = 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/48.0.2564.97 Safari/537.36'
51
52     _TESTS = [{
53         'url': 'https://www.facebook.com/video.php?v=637842556329505&fref=nf',
54         'md5': '6a40d33c0eccbb1af76cf0485a052659',
55         'info_dict': {
56             'id': '637842556329505',
57             'ext': 'mp4',
58             'title': 're:Did you know Kei Nishikori is the first Asian man to ever reach a Grand Slam',
59             'uploader': 'Tennis on Facebook',
60         }
61     }, {
62         'note': 'Video without discernible title',
63         'url': 'https://www.facebook.com/video.php?v=274175099429670',
64         'info_dict': {
65             'id': '274175099429670',
66             'ext': 'mp4',
67             'title': 'Facebook video #274175099429670',
68             'uploader': 'Asif Nawab Butt',
69         },
70         'expected_warnings': [
71             'title'
72         ]
73     }, {
74         'note': 'Video with DASH manifest',
75         'url': 'https://www.facebook.com/video.php?v=957955867617029',
76         'info_dict': {
77             'id': '957955867617029',
78             'ext': 'mp4',
79             'title': 'When you post epic content on instagram.com/433 8 million followers, this is ...',
80             'uploader': 'Demy de Zeeuw',
81         },
82     }, {
83         'url': 'https://www.facebook.com/video.php?v=10204634152394104',
84         'only_matching': True,
85     }, {
86         'url': 'https://www.facebook.com/amogood/videos/1618742068337349/?fref=nf',
87         'only_matching': True,
88     }, {
89         'url': 'https://www.facebook.com/ChristyClarkForBC/videos/vb.22819070941/10153870694020942/?type=2&theater',
90         'only_matching': True,
91     }, {
92         'url': 'facebook:544765982287235',
93         'only_matching': True,
94     }]
95
96     def _login(self):
97         (useremail, password) = self._get_login_info()
98         if useremail is None:
99             return
100
101         login_page_req = sanitized_Request(self._LOGIN_URL)
102         self._set_cookie('facebook.com', 'locale', 'en_US')
103         login_page = self._download_webpage(login_page_req, None,
104                                             note='Downloading login page',
105                                             errnote='Unable to download login page')
106         lsd = self._search_regex(
107             r'<input type="hidden" name="lsd" value="([^"]*)"',
108             login_page, 'lsd')
109         lgnrnd = self._search_regex(r'name="lgnrnd" value="([^"]*?)"', login_page, 'lgnrnd')
110
111         login_form = {
112             'email': useremail,
113             'pass': password,
114             'lsd': lsd,
115             'lgnrnd': lgnrnd,
116             'next': 'http://facebook.com/home.php',
117             'default_persistent': '0',
118             'legacy_return': '1',
119             'timezone': '-60',
120             'trynum': '1',
121         }
122         request = sanitized_Request(self._LOGIN_URL, urlencode_postdata(login_form))
123         request.add_header('Content-Type', 'application/x-www-form-urlencoded')
124         try:
125             login_results = self._download_webpage(request, None,
126                                                    note='Logging in', errnote='unable to fetch login page')
127             if re.search(r'<form(.*)name="login"(.*)</form>', login_results) is not None:
128                 error = self._html_search_regex(
129                     r'(?s)<div[^>]+class=(["\']).*?login_error_box.*?\1[^>]*><div[^>]*>.*?</div><div[^>]*>(?P<error>.+?)</div>',
130                     login_results, 'login error', default=None, group='error')
131                 if error:
132                     raise ExtractorError('Unable to login: %s' % error, expected=True)
133                 self._downloader.report_warning('unable to log in: bad username/password, or exceeded login rate limit (~3/min). Check credentials or wait.')
134                 return
135
136             fb_dtsg = self._search_regex(
137                 r'name="fb_dtsg" value="(.+?)"', login_results, 'fb_dtsg', default=None)
138             h = self._search_regex(
139                 r'name="h"\s+(?:\w+="[^"]+"\s+)*?value="([^"]+)"', login_results, 'h', default=None)
140
141             if not fb_dtsg or not h:
142                 return
143
144             check_form = {
145                 'fb_dtsg': fb_dtsg,
146                 'h': h,
147                 'name_action_selected': 'dont_save',
148             }
149             check_req = sanitized_Request(self._CHECKPOINT_URL, urlencode_postdata(check_form))
150             check_req.add_header('Content-Type', 'application/x-www-form-urlencoded')
151             check_response = self._download_webpage(check_req, None,
152                                                     note='Confirming login')
153             if re.search(r'id="checkpointSubmitButton"', check_response) is not None:
154                 self._downloader.report_warning('Unable to confirm login, you have to login in your browser and authorize the login.')
155         except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
156             self._downloader.report_warning('unable to log in: %s' % error_to_compat_str(err))
157             return
158
159     def _real_initialize(self):
160         self._login()
161
162     def _real_extract(self, url):
163         video_id = self._match_id(url)
164         req = sanitized_Request('https://www.facebook.com/video/video.php?v=%s' % video_id)
165         req.add_header('User-Agent', self._CHROME_USER_AGENT)
166         webpage = self._download_webpage(req, video_id)
167
168         video_data = None
169
170         BEFORE = '{swf.addParam(param[0], param[1]);});\n'
171         AFTER = '.forEach(function(variable) {swf.addVariable(variable[0], variable[1]);});'
172         m = re.search(re.escape(BEFORE) + '(.*?)' + re.escape(AFTER), webpage)
173         if m:
174             data = dict(json.loads(m.group(1)))
175             params_raw = compat_urllib_parse_unquote(data['params'])
176             video_data = json.loads(params_raw)['video_data']
177
178         def video_data_list2dict(video_data):
179             ret = {}
180             for item in video_data:
181                 format_id = item['stream_type']
182                 ret.setdefault(format_id, []).append(item)
183             return ret
184
185         if not video_data:
186             server_js_data = self._parse_json(self._search_regex(
187                 r'handleServerJS\(({.+})\);', webpage, 'server js data'), video_id)
188             for item in server_js_data['instances']:
189                 if item[1][0] == 'VideoConfig':
190                     video_data = video_data_list2dict(item[2][0]['videoData'])
191                     break
192
193         if not video_data:
194             m_msg = re.search(r'class="[^"]*uiInterstitialContent[^"]*"><div>(.*?)</div>', webpage)
195             if m_msg is not None:
196                 raise ExtractorError(
197                     'The video is not available, Facebook said: "%s"' % m_msg.group(1),
198                     expected=True)
199             else:
200                 raise ExtractorError('Cannot parse data')
201
202         formats = []
203         for format_id, f in video_data.items():
204             if not f or not isinstance(f, list):
205                 continue
206             for quality in ('sd', 'hd'):
207                 for src_type in ('src', 'src_no_ratelimit'):
208                     src = f[0].get('%s_%s' % (quality, src_type))
209                     if src:
210                         formats.append({
211                             'format_id': '%s_%s_%s' % (format_id, quality, src_type),
212                             'url': src,
213                             'preference': -10 if format_id == 'progressive' else 0,
214                         })
215             dash_manifest = f[0].get('dash_manifest')
216             if dash_manifest:
217                 formats.extend(self._parse_dash_manifest(
218                     video_id, compat_etree_fromstring(compat_urllib_parse_unquote_plus(dash_manifest)),
219                     default_ns='urn:mpeg:dash:schema:mpd:2011'))
220         if not formats:
221             raise ExtractorError('Cannot find video formats')
222
223         self._sort_formats(formats)
224
225         video_title = self._html_search_regex(
226             r'<h2\s+[^>]*class="uiHeaderTitle"[^>]*>([^<]*)</h2>', webpage, 'title',
227             default=None)
228         if not video_title:
229             video_title = self._html_search_regex(
230                 r'(?s)<span class="fbPhotosPhotoCaption".*?id="fbPhotoPageCaption"><span class="hasCaption">(.*?)</span>',
231                 webpage, 'alternative title', default=None)
232             video_title = limit_length(video_title, 80)
233         if not video_title:
234             video_title = 'Facebook video #%s' % video_id
235         uploader = clean_html(get_element_by_id('fbPhotoPageAuthorName', webpage))
236
237         return {
238             'id': video_id,
239             'title': video_title,
240             'formats': formats,
241             'uploader': uploader,
242         }
243
244
245 class FacebookPostIE(InfoExtractor):
246     IE_NAME = 'facebook:post'
247     _VALID_URL = r'https?://(?:\w+\.)?facebook\.com/[^/]+/posts/(?P<id>\d+)'
248     _TEST = {
249         'url': 'https://www.facebook.com/maxlayn/posts/10153807558977570',
250         'md5': '037b1fa7f3c2d02b7a0d7bc16031ecc6',
251         'info_dict': {
252             'id': '544765982287235',
253             'ext': 'mp4',
254             'title': '"What are you doing running in the snow?"',
255             'uploader': 'FailArmy',
256         }
257     }
258
259     def _real_extract(self, url):
260         post_id = self._match_id(url)
261
262         webpage = self._download_webpage(url, post_id)
263
264         entries = [
265             self.url_result('facebook:%s' % video_id, FacebookIE.ie_key())
266             for video_id in self._parse_json(
267                 self._search_regex(
268                     r'(["\'])video_ids\1\s*:\s*(?P<ids>\[.+?\])',
269                     webpage, 'video ids', group='ids'),
270                 post_id)]
271
272         return self.playlist_result(entries, post_id)