2 from __future__
import unicode_literals
7 from .common
import InfoExtractor
9 compat_etree_fromstring
,
12 compat_urllib_parse_unquote
,
13 compat_urllib_parse_unquote_plus
,
29 class FacebookIE(InfoExtractor
):
33 (?:[\w-]+\.)?(?:facebook\.com|facebookcorewwwi\.onion)/
42 )\?(?:.*?)(?:v|video_id|story_fbid)=|
43 [^/]+/videos/(?:[^/]+/)?|
45 groups/[^/]+/permalink/
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'
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'
58 _VIDEO_PAGE_TEMPLATE
= 'https://www.facebook.com/video/video.php?v=%s'
61 'url': 'https://www.facebook.com/video.php?v=637842556329505&fref=nf',
62 'md5': '6a40d33c0eccbb1af76cf0485a052659',
64 'id': '637842556329505',
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,
72 'note': 'Video without discernible title',
73 'url': 'https://www.facebook.com/video.php?v=274175099429670',
75 'id': '274175099429670',
77 'title': 'Asif Nawab Butt posted a video to his Timeline.',
78 'uploader': 'Asif Nawab Butt',
79 'upload_date': '20140506',
80 'timestamp': 1399398998,
82 'expected_warnings': [
86 'note': 'Video with DASH manifest',
87 'url': 'https://www.facebook.com/video.php?v=957955867617029',
88 'md5': 'b2c28d528273b323abe5c6ab59f0f030',
90 'id': '957955867617029',
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,
98 'url': 'https://www.facebook.com/maxlayn/posts/10153807558977570',
99 'md5': '037b1fa7f3c2d02b7a0d7bc16031ecc6',
101 'id': '544765982287235',
103 'title': '"What are you doing running in the snow?"',
104 'uploader': 'FailArmy',
106 'skip': 'Video gone',
108 'url': 'https://m.facebook.com/story.php?story_fbid=1035862816472149&id=116132035111903',
109 'md5': '1deb90b6ac27f7efcf6d747c8a27f5e3',
111 'id': '1035862816472149',
113 'title': 'What the Flock Is Going On In New Zealand Credit: ViralHog',
114 'uploader': 'S. Saint',
116 'skip': 'Video gone',
118 'note': 'swf params escaped',
119 'url': 'https://www.facebook.com/barackobama/posts/10153664894881749',
120 'md5': '97ba073838964d12c70566e0085c2b91',
122 'id': '10153664894881749',
124 'title': 'Facebook video #10153664894881749',
127 # have 1080P, but only up to 720p in swf params
128 'url': 'https://www.facebook.com/cnn/videos/10155529876156509/',
129 'md5': '0d9813160b146b3bc8744e006027fcc6',
131 'id': '10155529876156509',
133 'title': 'Holocaust survivor becomes US citizen',
134 'timestamp': 1477818095,
135 'upload_date': '20161030',
139 # bigPipe.onPageletArrive ... onPageletArrive pagelet_group_mall
140 'url': 'https://www.facebook.com/yaroslav.korpan/videos/1417995061575415/',
142 'id': '1417995061575415',
144 'title': 'md5:a7b86ca673f51800cd54687b7f4012fe',
145 'timestamp': 1486648217,
146 'upload_date': '20170209',
147 'uploader': 'Yaroslav Korpan',
150 'skip_download': True,
153 'url': 'https://www.facebook.com/LaGuiaDelVaron/posts/1072691702860471',
155 'id': '1072691702860471',
157 'title': 'md5:ae2d22a93fbb12dad20dc393a869739d',
158 'timestamp': 1477305000,
159 'upload_date': '20161024',
160 'uploader': 'La Guía Del Varón',
163 'skip_download': True,
166 'url': 'https://www.facebook.com/groups/1024490957622648/permalink/1396382447100162/',
168 'id': '1396382447100162',
170 'title': 'md5:e2d2700afdf84e121f5d0f999bad13a3',
171 'timestamp': 1486035494,
172 'upload_date': '20170202',
173 'uploader': 'Elisabeth Ahtn',
176 'skip_download': True,
179 'url': 'https://www.facebook.com/video.php?v=10204634152394104',
180 'only_matching': True,
182 'url': 'https://www.facebook.com/amogood/videos/1618742068337349/?fref=nf',
183 'only_matching': True,
185 'url': 'https://www.facebook.com/ChristyClarkForBC/videos/vb.22819070941/10153870694020942/?type=2&theater',
186 'only_matching': True,
188 'url': 'facebook:544765982287235',
189 'only_matching': True,
191 'url': 'https://www.facebook.com/groups/164828000315060/permalink/764967300301124/',
192 'only_matching': True,
194 'url': 'https://zh-hk.facebook.com/peoplespower/videos/1135894589806027/',
195 'only_matching': True,
197 'url': 'https://www.facebookcorewwwi.onion/video.php?v=274175099429670',
198 'only_matching': True,
202 def _extract_url(webpage
):
204 r
'<iframe[^>]+?src=(["\'])(?P
<url
>https
://www\
.facebook\
.com
/video
/embed
.+?
)\
1', webpage)
206 return mobj.group('url
')
209 # see https://developers.facebook.com/docs/plugins/embedded-video-player
210 mobj = re.search(r'''(?x)<div[^>]+
211 class=(?P<q1>[\'"])[^\'"]*\bfb-(?:video|post)\b[^\'"]*(?P=q1)[^>]+
212 data-href=(?P<q2>[\'"])(?P<url>(?:https?:)?//(?:www\.)?facebook.com/.+?)(?P=q2)''', webpage)
214 return mobj.group('url
')
217 (useremail, password) = self._get_login_info()
218 if useremail is None:
221 login_page_req = sanitized_Request(self._LOGIN_URL)
222 self._set_cookie('facebook
.com
', 'locale
', 'en_US
')
223 login_page = self._download_webpage(login_page_req, None,
224 note='Downloading login page
',
225 errnote='Unable to download login page
')
226 lsd = self._search_regex(
227 r'<input type="hidden" name
="lsd" value
="([^"]*)"',
229 lgnrnd = self._search_regex(r'name="lgnrnd
" value="([^
"]*?)"', login_page, 'lgnrnd
')
236 'next
': 'http
://facebook
.com
/home
.php
',
237 'default_persistent
': '0',
238 'legacy_return
': '1',
242 request = sanitized_Request(self._LOGIN_URL, urlencode_postdata(login_form))
243 request.add_header('Content
-Type
', 'application
/x
-www
-form
-urlencoded
')
245 login_results = self._download_webpage(request, None,
246 note='Logging
in', errnote='unable to fetch login page
')
247 if re.search(r'<form(.*)name
="login"(.*)</form
>', login_results) is not None:
248 error = self._html_search_regex(
249 r'(?s
)<div
[^
>]+class=(["\']).*?login_error_box.*?\1[^>]*><div[^>]*>.*?</div><div[^>]*>(?P<error>.+?)</div>',
250 login_results, 'login error', default=None, group='error')
252 raise ExtractorError('Unable to login: %s' % error, expected=True)
253 self._downloader.report_warning('unable to log in: bad username/password, or exceeded login rate limit (~3/min). Check credentials or wait.')
256 fb_dtsg = self._search_regex(
257 r'name="fb_dtsg
" value="(.+?
)"', login_results, 'fb_dtsg', default=None)
258 h = self._search_regex(
259 r'name="h
"\s+(?:\w+="[^
"]+"\s
+)*?value
="([^"]+)"', login_results, 'h', default=None)
261 if not fb_dtsg or not h:
267 'name_action_selected': 'dont_save',
269 check_req = sanitized_Request(self._CHECKPOINT_URL, urlencode_postdata(check_form))
270 check_req.add_header('Content-Type', 'application/x-www-form-urlencoded')
271 check_response = self._download_webpage(check_req, None,
272 note='Confirming login')
273 if re.search(r'id="checkpointSubmitButton
"', check_response) is not None:
274 self._downloader.report_warning('Unable to confirm login, you have to login in your browser and authorize the login.')
275 except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
276 self._downloader.report_warning('unable to log in: %s' % error_to_compat_str(err))
279 def _real_initialize(self):
282 def _extract_from_url(self, url, video_id, fatal_if_no_video=True):
283 req = sanitized_Request(url)
284 req.add_header('User-Agent', self._CHROME_USER_AGENT)
285 webpage = self._download_webpage(req, video_id)
289 def extract_video_data(instances):
290 for item in instances:
291 if item[1][0] == 'VideoConfig':
292 video_item = item[2][0]
293 if video_item.get('video_id'):
294 return video_item['videoData']
296 server_js_data = self._parse_json(self._search_regex(
297 r'handleServerJS\(({.+})(?:\);|,")', webpage,
298 'server js data
', default='{}'), video_id, fatal=False)
301 video_data = extract_video_data(server_js_data.get('instances
', []))
304 server_js_data = self._parse_json(
306 r'bigPipe\
.onPageletArrive\
(({.+?
})\
)\s
*;\s
*}\s
*\
)\s
*,\s
*["\']onPageletArrive\s+(?:stream_pagelet|pagelet_group_mall|permalink_video_pagelet)',
307 webpage, 'js data', default='{}'),
308 video_id, transform_source=js_to_json, fatal=False)
310 video_data = extract_video_data(try_get(
311 server_js_data, lambda x: x['jsmods']['instances'],
315 if not fatal_if_no_video:
316 return webpage, False
317 m_msg = re.search(r'class="[^
"]*uiInterstitialContent[^"]*"><div>(.*?)</div>', webpage)
318 if m_msg is not None:
319 raise ExtractorError(
320 'The video is not available, Facebook said: "%s"' % m_msg.group(1),
322 elif '>You must log in to continue' in webpage:
323 self.raise_login_required()
325 raise ExtractorError('Cannot parse data')
329 format_id = f['stream_type']
330 if f and isinstance(f, dict):
332 if not f or not isinstance(f, list):
334 for quality in ('sd', 'hd'):
335 for src_type in ('src', 'src_no_ratelimit'):
336 src = f[0].get('%s_%s' % (quality, src_type))
338 preference = -10 if format_id == 'progressive' else 0
342 'format_id': '%s_%s_%s' % (format_id, quality, src_type),
344 'preference': preference,
346 dash_manifest = f[0].get('dash_manifest')
348 formats.extend(self._parse_mpd_formats(
349 compat_etree_fromstring(compat_urllib_parse_unquote_plus(dash_manifest))))
351 raise ExtractorError('Cannot find video formats')
353 self._sort_formats(formats)
355 video_title = self._html_search_regex(
356 r'<h2\s+[^>]*class="uiHeaderTitle
"[^>]*>([^<]*)</h2>', webpage, 'title',
359 video_title = self._html_search_regex(
360 r'(?s)<span class="fbPhotosPhotoCaption
".*?id="fbPhotoPageCaption
"><span class="hasCaption
">(.*?)</span>',
361 webpage, 'alternative title', default=None)
363 video_title = self._html_search_meta(
364 'description', webpage, 'title')
366 video_title = limit_length(video_title, 80)
368 video_title = 'Facebook video #%s' % video_id
369 uploader = clean_html(get_element_by_id(
370 'fbPhotoPageAuthorName', webpage)) or self._search_regex(
371 r'ownerName\s*:\s*"([^
"]+)"', webpage, 'uploader
', fatal=False)
372 timestamp = int_or_none(self._search_regex(
373 r'<abbr
[^
>]+data
-utime
=["\'](\d+)', webpage,
374 'timestamp', default=None))
378 'title': video_title,
380 'uploader': uploader,
381 'timestamp': timestamp,
384 return webpage, info_dict
386 def _real_extract(self, url):
387 video_id = self._match_id(url)
389 real_url = self._VIDEO_PAGE_TEMPLATE % video_id if url.startswith('facebook:') else url
390 webpage, info_dict = self._extract_from_url(real_url, video_id, fatal_if_no_video=False)
397 self.url_result('facebook:%s' % vid, FacebookIE.ie_key())
398 for vid in self._parse_json(
400 r'(["\'])video_ids\
1\s
*:\s
*(?P
<ids
>\
[.+?\
])',
401 webpage, 'video ids
', group='ids
'),
404 return self.playlist_result(entries, video_id)
406 _, info_dict = self._extract_from_url(
407 self._VIDEO_PAGE_TEMPLATE % video_id,
408 video_id, fatal_if_no_video=True)
412 class FacebookPluginsVideoIE(InfoExtractor):
413 _VALID_URL = r'https?
://(?
:[\w
-]+\
.)?facebook\
.com
/plugins
/video\
.php
\?.*?
\bhref
=(?P
<id>https
.+)'
416 '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',
417 'md5
': '5954e92cdfe51fe5782ae9bda7058a07
',
419 'id': '10154383743583686',
421 'title
': 'What to do during the haze?
',
422 'uploader
': 'Gov
.sg
',
423 'upload_date
': '20160826',
424 'timestamp
': 1472184808,
426 'add_ie
': [FacebookIE.ie_key()],
428 'url
': 'https
://www
.facebook
.com
/plugins
/video
.php?href
=https
%3A
%2F
%2Fwww
.facebook
.com
%2Fvideo
.php
%3Fv
%3D10204634152394104
',
429 'only_matching
': True,
431 'url
': 'https
://www
.facebook
.com
/plugins
/video
.php?href
=https
://www
.facebook
.com
/gov
.sg
/videos
/10154383743583686/&show_text
=0&width
=560',
432 'only_matching
': True,
435 def _real_extract(self, url):
436 return self.url_result(
437 compat_urllib_parse_unquote(self._match_id(url)),