]> jfr.im git - yt-dlp.git/blob - yt_dlp/extractor/facebook.py
[Facebook] Handle redirect URLs
[yt-dlp.git] / yt_dlp / extractor / facebook.py
1 # coding: utf-8
2 from __future__ import unicode_literals
3
4 import json
5 import re
6
7 from .common import InfoExtractor
8 from ..compat import (
9 compat_etree_fromstring,
10 compat_str,
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 float_or_none,
19 get_element_by_id,
20 int_or_none,
21 js_to_json,
22 limit_length,
23 merge_dicts,
24 network_exceptions,
25 parse_count,
26 parse_qs,
27 qualities,
28 sanitized_Request,
29 try_get,
30 url_or_none,
31 urlencode_postdata,
32 urljoin,
33 )
34
35
36 class FacebookIE(InfoExtractor):
37 _VALID_URL = r'''(?x)
38 (?:
39 https?://
40 (?:[\w-]+\.)?(?:facebook\.com|facebookwkhpilnemxj7asaniu7vnjjbiltxjqhye3mhbshg7kx5tfyd\.onion)/
41 (?:[^#]*?\#!/)?
42 (?:
43 (?:
44 video/video\.php|
45 photo\.php|
46 video\.php|
47 video/embed|
48 story\.php|
49 watch(?:/live)?/?
50 )\?(?:.*?)(?:v|video_id|story_fbid)=|
51 [^/]+/videos/(?:[^/]+/)?|
52 [^/]+/posts/|
53 groups/[^/]+/permalink/|
54 watchparty/
55 )|
56 facebook:
57 )
58 (?P<id>[0-9]+)
59 '''
60 _LOGIN_URL = 'https://www.facebook.com/login.php?next=http%3A%2F%2Ffacebook.com%2Fhome.php&login_attempt=1'
61 _CHECKPOINT_URL = 'https://www.facebook.com/checkpoint/?next=http%3A%2F%2Ffacebook.com%2Fhome.php&_fb_noscript=1'
62 _NETRC_MACHINE = 'facebook'
63 IE_NAME = 'facebook'
64
65 _VIDEO_PAGE_TEMPLATE = 'https://www.facebook.com/video/video.php?v=%s'
66 _VIDEO_PAGE_TAHOE_TEMPLATE = 'https://www.facebook.com/video/tahoe/async/%s/?chain=true&isvideo=true&payloadtype=primary'
67
68 _TESTS = [{
69 'url': 'https://www.facebook.com/video.php?v=637842556329505&fref=nf',
70 'md5': '6a40d33c0eccbb1af76cf0485a052659',
71 'info_dict': {
72 'id': '637842556329505',
73 'ext': 'mp4',
74 'title': 're:Did you know Kei Nishikori is the first Asian man to ever reach a Grand Slam',
75 'uploader': 'Tennis on Facebook',
76 'upload_date': '20140908',
77 'timestamp': 1410199200,
78 },
79 'skip': 'Requires logging in',
80 }, {
81 # data.video
82 'url': 'https://www.facebook.com/video.php?v=274175099429670',
83 'info_dict': {
84 'id': '274175099429670',
85 'ext': 'mp4',
86 'title': 'Asif Nawab Butt',
87 'description': 'Asif Nawab Butt',
88 'uploader': 'Asif Nawab Butt',
89 'upload_date': '20140506',
90 'timestamp': 1399398998,
91 'thumbnail': r're:^https?://.*',
92 },
93 'expected_warnings': [
94 'title'
95 ]
96 }, {
97 'note': 'Video with DASH manifest',
98 'url': 'https://www.facebook.com/video.php?v=957955867617029',
99 'md5': 'b2c28d528273b323abe5c6ab59f0f030',
100 'info_dict': {
101 'id': '957955867617029',
102 'ext': 'mp4',
103 'title': 'When you post epic content on instagram.com/433 8 million followers, this is ...',
104 'uploader': 'Demy de Zeeuw',
105 'upload_date': '20160110',
106 'timestamp': 1452431627,
107 },
108 'skip': 'Requires logging in',
109 }, {
110 'url': 'https://www.facebook.com/maxlayn/posts/10153807558977570',
111 'md5': '037b1fa7f3c2d02b7a0d7bc16031ecc6',
112 'info_dict': {
113 'id': '544765982287235',
114 'ext': 'mp4',
115 'title': '"What are you doing running in the snow?"',
116 'uploader': 'FailArmy',
117 },
118 'skip': 'Video gone',
119 }, {
120 'url': 'https://m.facebook.com/story.php?story_fbid=1035862816472149&id=116132035111903',
121 'md5': '1deb90b6ac27f7efcf6d747c8a27f5e3',
122 'info_dict': {
123 'id': '1035862816472149',
124 'ext': 'mp4',
125 'title': 'What the Flock Is Going On In New Zealand Credit: ViralHog',
126 'uploader': 'S. Saint',
127 },
128 'skip': 'Video gone',
129 }, {
130 'note': 'swf params escaped',
131 'url': 'https://www.facebook.com/barackobama/posts/10153664894881749',
132 'md5': '97ba073838964d12c70566e0085c2b91',
133 'info_dict': {
134 'id': '10153664894881749',
135 'ext': 'mp4',
136 'title': 'Average time to confirm recent Supreme Court nominees: 67 days Longest it\'s t...',
137 'thumbnail': r're:^https?://.*',
138 'timestamp': 1456259628,
139 'upload_date': '20160223',
140 'uploader': 'Barack Obama',
141 },
142 'skip': 'Gif on giphy.com gone',
143 }, {
144 # have 1080P, but only up to 720p in swf params
145 # data.video.story.attachments[].media
146 'url': 'https://www.facebook.com/cnn/videos/10155529876156509/',
147 'md5': '3f3798adb2b73423263e59376f1f5eb7',
148 'info_dict': {
149 'id': '10155529876156509',
150 'ext': 'mp4',
151 'title': 'Holocaust survivor becomes US citizen',
152 'description': 'She survived the holocaust — and years later, she’s getting her citizenship so she can vote for Hillary Clinton http://cnn.it/2eERh5f',
153 'timestamp': 1477818095,
154 'upload_date': '20161030',
155 'uploader': 'CNN',
156 'thumbnail': r're:^https?://.*',
157 'view_count': int,
158 },
159 }, {
160 # bigPipe.onPageletArrive ... onPageletArrive pagelet_group_mall
161 # data.node.comet_sections.content.story.attachments[].style_type_renderer.attachment.media
162 'url': 'https://www.facebook.com/yaroslav.korpan/videos/1417995061575415/',
163 'info_dict': {
164 'id': '1417995061575415',
165 'ext': 'mp4',
166 'title': 'Yaroslav Korpan - Довгоочікуване відео',
167 'description': 'Довгоочікуване відео',
168 'timestamp': 1486648771,
169 'upload_date': '20170209',
170 'uploader': 'Yaroslav Korpan',
171 'uploader_id': '100000948048708',
172 },
173 'params': {
174 'skip_download': True,
175 },
176 }, {
177 # FIXME
178 'url': 'https://www.facebook.com/LaGuiaDelVaron/posts/1072691702860471',
179 'info_dict': {
180 'id': '1072691702860471',
181 'ext': 'mp4',
182 'title': 'md5:ae2d22a93fbb12dad20dc393a869739d',
183 'timestamp': 1477305000,
184 'upload_date': '20161024',
185 'uploader': 'La Guía Del Varón',
186 'thumbnail': r're:^https?://.*',
187 },
188 'params': {
189 'skip_download': True,
190 },
191 }, {
192 # data.node.comet_sections.content.story.attachments[].style_type_renderer.attachment.media
193 'url': 'https://www.facebook.com/groups/1024490957622648/permalink/1396382447100162/',
194 'info_dict': {
195 'id': '202882990186699',
196 'ext': 'mp4',
197 'title': 'Elisabeth Ahtn - Hello? Yes your uber ride is here\n* Jukin...',
198 'description': 'Hello? Yes your uber ride is here\n* Jukin Media Verified *\nFind this video and others like it by visiting...',
199 'timestamp': 1486035513,
200 'upload_date': '20170202',
201 'uploader': 'Elisabeth Ahtn',
202 'uploader_id': '100013949973717',
203 },
204 'params': {
205 'skip_download': True,
206 },
207 }, {
208 'url': 'https://www.facebook.com/video.php?v=10204634152394104',
209 'only_matching': True,
210 }, {
211 'url': 'https://www.facebook.com/amogood/videos/1618742068337349/?fref=nf',
212 'only_matching': True,
213 }, {
214 # data.mediaset.currMedia.edges
215 'url': 'https://www.facebook.com/ChristyClarkForBC/videos/vb.22819070941/10153870694020942/?type=2&theater',
216 'only_matching': True,
217 }, {
218 # data.video.story.attachments[].media
219 'url': 'facebook:544765982287235',
220 'only_matching': True,
221 }, {
222 # data.node.comet_sections.content.story.attachments[].style_type_renderer.attachment.media
223 'url': 'https://www.facebook.com/groups/164828000315060/permalink/764967300301124/',
224 'only_matching': True,
225 }, {
226 # data.video.creation_story.attachments[].media
227 'url': 'https://zh-hk.facebook.com/peoplespower/videos/1135894589806027/',
228 'only_matching': True,
229 }, {
230 # data.video
231 'url': 'https://www.facebookwkhpilnemxj7asaniu7vnjjbiltxjqhye3mhbshg7kx5tfyd.onion/video.php?v=274175099429670',
232 'only_matching': True,
233 }, {
234 # no title
235 'url': 'https://www.facebook.com/onlycleverentertainment/videos/1947995502095005/',
236 'only_matching': True,
237 }, {
238 # data.video
239 'url': 'https://www.facebook.com/WatchESLOne/videos/359649331226507/',
240 'info_dict': {
241 'id': '359649331226507',
242 'ext': 'mp4',
243 'title': 'Fnatic vs. EG - Group A - Opening Match - ESL One Birmingham Day 1',
244 'description': '#ESLOne VoD - Birmingham Finals Day#1 Fnatic vs. @Evil Geniuses',
245 'timestamp': 1527084179,
246 'upload_date': '20180523',
247 'uploader': 'ESL One Dota 2',
248 'uploader_id': '234218833769558',
249 },
250 'params': {
251 'skip_download': True,
252 },
253 }, {
254 # data.node.comet_sections.content.story.attachments[].style_type_renderer.attachment.all_subattachments.nodes[].media
255 'url': 'https://www.facebook.com/100033620354545/videos/106560053808006/',
256 'info_dict': {
257 'id': '106560053808006',
258 },
259 'playlist_count': 2,
260 }, {
261 # data.video.story.attachments[].media
262 'url': 'https://www.facebook.com/watch/?v=647537299265662',
263 'only_matching': True,
264 }, {
265 # FIXME: https://github.com/yt-dlp/yt-dlp/issues/542
266 # data.node.comet_sections.content.story.attachments[].style_type_renderer.attachment.all_subattachments.nodes[].media
267 'url': 'https://www.facebook.com/PankajShahLondon/posts/10157667649866271',
268 'info_dict': {
269 'id': '10157667649866271',
270 },
271 'playlist_count': 3,
272 }, {
273 # data.nodes[].comet_sections.content.story.attachments[].style_type_renderer.attachment.media
274 'url': 'https://m.facebook.com/Alliance.Police.Department/posts/4048563708499330',
275 'info_dict': {
276 'id': '117576630041613',
277 'ext': 'mp4',
278 # TODO: title can be extracted from video page
279 'title': 'Facebook video #117576630041613',
280 'uploader_id': '189393014416438',
281 'upload_date': '20201123',
282 'timestamp': 1606162592,
283 },
284 'skip': 'Requires logging in',
285 }, {
286 # node.comet_sections.content.story.attached_story.attachments.style_type_renderer.attachment.media
287 'url': 'https://www.facebook.com/groups/ateistiskselskab/permalink/10154930137678856/',
288 'info_dict': {
289 'id': '211567722618337',
290 'ext': 'mp4',
291 'title': 'Facebook video #211567722618337',
292 'uploader_id': '127875227654254',
293 'upload_date': '20161122',
294 'timestamp': 1479793574,
295 },
296 'skip': 'No video',
297 }, {
298 # data.video.creation_story.attachments[].media
299 'url': 'https://www.facebook.com/watch/live/?v=1823658634322275',
300 'only_matching': True,
301 }, {
302 'url': 'https://www.facebook.com/watchparty/211641140192478',
303 'info_dict': {
304 'id': '211641140192478',
305 },
306 'playlist_count': 1,
307 'skip': 'Requires logging in',
308 }]
309 _SUPPORTED_PAGLETS_REGEX = r'(?:pagelet_group_mall|permalink_video_pagelet|hyperfeed_story_id_[0-9a-f]+)'
310 _api_config = {
311 'graphURI': '/api/graphql/'
312 }
313
314 @staticmethod
315 def _extract_urls(webpage):
316 urls = []
317 for mobj in re.finditer(
318 r'<iframe[^>]+?src=(["\'])(?P<url>https?://www\.facebook\.com/(?:video/embed|plugins/video\.php).+?)\1',
319 webpage):
320 urls.append(mobj.group('url'))
321 # Facebook API embed
322 # see https://developers.facebook.com/docs/plugins/embedded-video-player
323 for mobj in re.finditer(r'''(?x)<div[^>]+
324 class=(?P<q1>[\'"])[^\'"]*\bfb-(?:video|post)\b[^\'"]*(?P=q1)[^>]+
325 data-href=(?P<q2>[\'"])(?P<url>(?:https?:)?//(?:www\.)?facebook.com/.+?)(?P=q2)''', webpage):
326 urls.append(mobj.group('url'))
327 return urls
328
329 def _login(self):
330 useremail, password = self._get_login_info()
331 if useremail is None:
332 return
333
334 login_page_req = sanitized_Request(self._LOGIN_URL)
335 self._set_cookie('facebook.com', 'locale', 'en_US')
336 login_page = self._download_webpage(login_page_req, None,
337 note='Downloading login page',
338 errnote='Unable to download login page')
339 lsd = self._search_regex(
340 r'<input type="hidden" name="lsd" value="([^"]*)"',
341 login_page, 'lsd')
342 lgnrnd = self._search_regex(r'name="lgnrnd" value="([^"]*?)"', login_page, 'lgnrnd')
343
344 login_form = {
345 'email': useremail,
346 'pass': password,
347 'lsd': lsd,
348 'lgnrnd': lgnrnd,
349 'next': 'http://facebook.com/home.php',
350 'default_persistent': '0',
351 'legacy_return': '1',
352 'timezone': '-60',
353 'trynum': '1',
354 }
355 request = sanitized_Request(self._LOGIN_URL, urlencode_postdata(login_form))
356 request.add_header('Content-Type', 'application/x-www-form-urlencoded')
357 try:
358 login_results = self._download_webpage(request, None,
359 note='Logging in', errnote='unable to fetch login page')
360 if re.search(r'<form(.*)name="login"(.*)</form>', login_results) is not None:
361 error = self._html_search_regex(
362 r'(?s)<div[^>]+class=(["\']).*?login_error_box.*?\1[^>]*><div[^>]*>.*?</div><div[^>]*>(?P<error>.+?)</div>',
363 login_results, 'login error', default=None, group='error')
364 if error:
365 raise ExtractorError('Unable to login: %s' % error, expected=True)
366 self.report_warning('unable to log in: bad username/password, or exceeded login rate limit (~3/min). Check credentials or wait.')
367 return
368
369 fb_dtsg = self._search_regex(
370 r'name="fb_dtsg" value="(.+?)"', login_results, 'fb_dtsg', default=None)
371 h = self._search_regex(
372 r'name="h"\s+(?:\w+="[^"]+"\s+)*?value="([^"]+)"', login_results, 'h', default=None)
373
374 if not fb_dtsg or not h:
375 return
376
377 check_form = {
378 'fb_dtsg': fb_dtsg,
379 'h': h,
380 'name_action_selected': 'dont_save',
381 }
382 check_req = sanitized_Request(self._CHECKPOINT_URL, urlencode_postdata(check_form))
383 check_req.add_header('Content-Type', 'application/x-www-form-urlencoded')
384 check_response = self._download_webpage(check_req, None,
385 note='Confirming login')
386 if re.search(r'id="checkpointSubmitButton"', check_response) is not None:
387 self.report_warning('Unable to confirm login, you have to login in your browser and authorize the login.')
388 except network_exceptions as err:
389 self.report_warning('unable to log in: %s' % error_to_compat_str(err))
390 return
391
392 def _real_initialize(self):
393 self._login()
394
395 def _extract_from_url(self, url, video_id):
396 webpage = self._download_webpage(
397 url.replace('://m.facebook.com/', '://www.facebook.com/'), video_id)
398
399 def extract_metadata(webpage):
400 video_title = self._html_search_regex(
401 r'<h2\s+[^>]*class="uiHeaderTitle"[^>]*>([^<]*)</h2>', webpage,
402 'title', default=None)
403 if not video_title:
404 video_title = self._html_search_regex(
405 r'(?s)<span class="fbPhotosPhotoCaption".*?id="fbPhotoPageCaption"><span class="hasCaption">(.*?)</span>',
406 webpage, 'alternative title', default=None)
407 if not video_title:
408 video_title = self._html_search_meta(
409 ['og:title', 'twitter:title', 'description'],
410 webpage, 'title', default=None)
411 if video_title:
412 video_title = limit_length(video_title, 80)
413 else:
414 video_title = 'Facebook video #%s' % video_id
415 description = self._html_search_meta(
416 ['description', 'og:description', 'twitter:description'],
417 webpage, 'description', default=None)
418 uploader = clean_html(get_element_by_id(
419 'fbPhotoPageAuthorName', webpage)) or self._search_regex(
420 r'ownerName\s*:\s*"([^"]+)"', webpage, 'uploader',
421 default=None) or self._og_search_title(webpage, fatal=False)
422 timestamp = int_or_none(self._search_regex(
423 r'<abbr[^>]+data-utime=["\'](\d+)', webpage,
424 'timestamp', default=None))
425 thumbnail = self._html_search_meta(
426 ['og:image', 'twitter:image'], webpage, 'thumbnail', default=None)
427 # some webpages contain unretrievable thumbnail urls
428 # like https://lookaside.fbsbx.com/lookaside/crawler/media/?media_id=10155168902769113&get_thumbnail=1
429 # in https://www.facebook.com/yaroslav.korpan/videos/1417995061575415/
430 if thumbnail and not re.search(r'\.(?:jpg|png)', thumbnail):
431 thumbnail = None
432 view_count = parse_count(self._search_regex(
433 r'\bviewCount\s*:\s*["\']([\d,.]+)', webpage, 'view count',
434 default=None))
435 info_dict = {
436 'title': video_title,
437 'description': description,
438 'uploader': uploader,
439 'timestamp': timestamp,
440 'thumbnail': thumbnail,
441 'view_count': view_count,
442 }
443 info_json_ld = self._search_json_ld(webpage, video_id, default={})
444 if info_json_ld.get('title'):
445 info_json_ld['title'] = limit_length(
446 re.sub(r'\s*\|\s*Facebook$', '', info_json_ld['title']), 80)
447 return merge_dicts(info_json_ld, info_dict)
448
449 video_data = None
450
451 def extract_video_data(instances):
452 video_data = []
453 for item in instances:
454 if try_get(item, lambda x: x[1][0]) == 'VideoConfig':
455 video_item = item[2][0]
456 if video_item.get('video_id'):
457 video_data.append(video_item['videoData'])
458 return video_data
459
460 server_js_data = self._parse_json(self._search_regex(
461 [r'handleServerJS\(({.+})(?:\);|,")', r'\bs\.handle\(({.+?})\);'],
462 webpage, 'server js data', default='{}'), video_id, fatal=False)
463
464 if server_js_data:
465 video_data = extract_video_data(server_js_data.get('instances', []))
466
467 def extract_from_jsmods_instances(js_data):
468 if js_data:
469 return extract_video_data(try_get(
470 js_data, lambda x: x['jsmods']['instances'], list) or [])
471
472 def extract_dash_manifest(video, formats):
473 dash_manifest = video.get('dash_manifest')
474 if dash_manifest:
475 formats.extend(self._parse_mpd_formats(
476 compat_etree_fromstring(compat_urllib_parse_unquote_plus(dash_manifest))))
477
478 def process_formats(formats):
479 # Downloads with browser's User-Agent are rate limited. Working around
480 # with non-browser User-Agent.
481 for f in formats:
482 f.setdefault('http_headers', {})['User-Agent'] = 'facebookexternalhit/1.1'
483
484 self._sort_formats(formats, ('res', 'quality'))
485
486 def extract_relay_data(_filter):
487 return self._parse_json(self._search_regex(
488 r'handleWithCustomApplyEach\([^,]+,\s*({.*?%s.*?})\);' % _filter,
489 webpage, 'replay data', default='{}'), video_id, fatal=False) or {}
490
491 def extract_relay_prefetched_data(_filter):
492 replay_data = extract_relay_data(_filter)
493 for require in (replay_data.get('require') or []):
494 if require[0] == 'RelayPrefetchedStreamCache':
495 return try_get(require, lambda x: x[3][1]['__bbox']['result']['data'], dict) or {}
496
497 if not video_data:
498 server_js_data = self._parse_json(self._search_regex([
499 r'bigPipe\.onPageletArrive\(({.+?})\)\s*;\s*}\s*\)\s*,\s*["\']onPageletArrive\s+' + self._SUPPORTED_PAGLETS_REGEX,
500 r'bigPipe\.onPageletArrive\(({.*?id\s*:\s*"%s".*?})\);' % self._SUPPORTED_PAGLETS_REGEX
501 ], webpage, 'js data', default='{}'), video_id, js_to_json, False)
502 video_data = extract_from_jsmods_instances(server_js_data)
503
504 if not video_data:
505 data = extract_relay_prefetched_data(
506 r'"(?:dash_manifest|playable_url(?:_quality_hd)?)"\s*:\s*"[^"]+"')
507 if data:
508 entries = []
509
510 def parse_graphql_video(video):
511 formats = []
512 q = qualities(['sd', 'hd'])
513 for (suffix, format_id) in [('', 'sd'), ('_quality_hd', 'hd')]:
514 playable_url = video.get('playable_url' + suffix)
515 if not playable_url:
516 continue
517 formats.append({
518 'format_id': format_id,
519 'quality': q(format_id),
520 'url': playable_url,
521 })
522 extract_dash_manifest(video, formats)
523 process_formats(formats)
524 v_id = video.get('videoId') or video.get('id') or video_id
525 info = {
526 'id': v_id,
527 'formats': formats,
528 'thumbnail': try_get(video, lambda x: x['thumbnailImage']['uri']),
529 'uploader_id': try_get(video, lambda x: x['owner']['id']),
530 'timestamp': int_or_none(video.get('publish_time')),
531 'duration': float_or_none(video.get('playable_duration_in_ms'), 1000),
532 }
533 description = try_get(video, lambda x: x['savable_description']['text'])
534 title = video.get('name')
535 if title:
536 info.update({
537 'title': title,
538 'description': description,
539 })
540 else:
541 info['title'] = description or 'Facebook video #%s' % v_id
542 entries.append(info)
543
544 def parse_attachment(attachment, key='media'):
545 media = attachment.get(key) or {}
546 if media.get('__typename') == 'Video':
547 return parse_graphql_video(media)
548
549 nodes = data.get('nodes') or []
550 node = data.get('node') or {}
551 if not nodes and node:
552 nodes.append(node)
553 for node in nodes:
554 story = try_get(node, lambda x: x['comet_sections']['content']['story'], dict) or {}
555 attachments = try_get(story, [
556 lambda x: x['attached_story']['attachments'],
557 lambda x: x['attachments']
558 ], list) or []
559 for attachment in attachments:
560 attachment = try_get(attachment, lambda x: x['style_type_renderer']['attachment'], dict)
561 ns = try_get(attachment, lambda x: x['all_subattachments']['nodes'], list) or []
562 for n in ns:
563 parse_attachment(n)
564 parse_attachment(attachment)
565
566 edges = try_get(data, lambda x: x['mediaset']['currMedia']['edges'], list) or []
567 for edge in edges:
568 parse_attachment(edge, key='node')
569
570 video = data.get('video') or {}
571 if video:
572 attachments = try_get(video, [
573 lambda x: x['story']['attachments'],
574 lambda x: x['creation_story']['attachments']
575 ], list) or []
576 for attachment in attachments:
577 parse_attachment(attachment)
578 if not entries:
579 parse_graphql_video(video)
580
581 if len(entries) > 1:
582 return self.playlist_result(entries, video_id)
583
584 video_info = entries[0]
585 webpage_info = extract_metadata(webpage)
586 # honor precise duration in video info
587 if video_info.get('duration'):
588 webpage_info['duration'] = video_info['duration']
589 return merge_dicts(webpage_info, video_info)
590
591 if not video_data:
592 m_msg = re.search(r'class="[^"]*uiInterstitialContent[^"]*"><div>(.*?)</div>', webpage)
593 if m_msg is not None:
594 raise ExtractorError(
595 'The video is not available, Facebook said: "%s"' % m_msg.group(1),
596 expected=True)
597 elif any(p in webpage for p in (
598 '>You must log in to continue',
599 'id="login_form"',
600 'id="loginbutton"')):
601 self.raise_login_required()
602
603 if not video_data and '/watchparty/' in url:
604 post_data = {
605 'doc_id': 3731964053542869,
606 'variables': json.dumps({
607 'livingRoomID': video_id,
608 }),
609 }
610
611 prefetched_data = extract_relay_prefetched_data(r'"login_data"\s*:\s*{')
612 if prefetched_data:
613 lsd = try_get(prefetched_data, lambda x: x['login_data']['lsd'], dict)
614 if lsd:
615 post_data[lsd['name']] = lsd['value']
616
617 relay_data = extract_relay_data(r'\[\s*"RelayAPIConfigDefaults"\s*,')
618 for define in (relay_data.get('define') or []):
619 if define[0] == 'RelayAPIConfigDefaults':
620 self._api_config = define[2]
621
622 living_room = self._download_json(
623 urljoin(url, self._api_config['graphURI']), video_id,
624 data=urlencode_postdata(post_data))['data']['living_room']
625
626 entries = []
627 for edge in (try_get(living_room, lambda x: x['recap']['watched_content']['edges']) or []):
628 video = try_get(edge, lambda x: x['node']['video']) or {}
629 v_id = video.get('id')
630 if not v_id:
631 continue
632 v_id = compat_str(v_id)
633 entries.append(self.url_result(
634 self._VIDEO_PAGE_TEMPLATE % v_id,
635 self.ie_key(), v_id, video.get('name')))
636
637 return self.playlist_result(entries, video_id)
638
639 if not video_data:
640 # Video info not in first request, do a secondary request using
641 # tahoe player specific URL
642 tahoe_data = self._download_webpage(
643 self._VIDEO_PAGE_TAHOE_TEMPLATE % video_id, video_id,
644 data=urlencode_postdata({
645 '__a': 1,
646 '__pc': self._search_regex(
647 r'pkg_cohort["\']\s*:\s*["\'](.+?)["\']', webpage,
648 'pkg cohort', default='PHASED:DEFAULT'),
649 '__rev': self._search_regex(
650 r'client_revision["\']\s*:\s*(\d+),', webpage,
651 'client revision', default='3944515'),
652 'fb_dtsg': self._search_regex(
653 r'"DTSGInitialData"\s*,\s*\[\]\s*,\s*{\s*"token"\s*:\s*"([^"]+)"',
654 webpage, 'dtsg token', default=''),
655 }),
656 headers={
657 'Content-Type': 'application/x-www-form-urlencoded',
658 })
659 tahoe_js_data = self._parse_json(
660 self._search_regex(
661 r'for\s+\(\s*;\s*;\s*\)\s*;(.+)', tahoe_data,
662 'tahoe js data', default='{}'),
663 video_id, fatal=False)
664 video_data = extract_from_jsmods_instances(tahoe_js_data)
665
666 if not video_data:
667 raise ExtractorError('Cannot parse data')
668
669 if len(video_data) > 1:
670 entries = []
671 for v in video_data:
672 video_url = v[0].get('video_url')
673 if not video_url:
674 continue
675 entries.append(self.url_result(urljoin(
676 url, video_url), self.ie_key(), v[0].get('video_id')))
677 return self.playlist_result(entries, video_id)
678 video_data = video_data[0]
679
680 formats = []
681 subtitles = {}
682 for f in video_data:
683 format_id = f['stream_type']
684 if f and isinstance(f, dict):
685 f = [f]
686 if not f or not isinstance(f, list):
687 continue
688 for quality in ('sd', 'hd'):
689 for src_type in ('src', 'src_no_ratelimit'):
690 src = f[0].get('%s_%s' % (quality, src_type))
691 if src:
692 preference = -10 if format_id == 'progressive' else -1
693 if quality == 'hd':
694 preference += 5
695 formats.append({
696 'format_id': '%s_%s_%s' % (format_id, quality, src_type),
697 'url': src,
698 'quality': preference,
699 'height': 720 if quality == 'hd' else None
700 })
701 extract_dash_manifest(f[0], formats)
702 subtitles_src = f[0].get('subtitles_src')
703 if subtitles_src:
704 subtitles.setdefault('en', []).append({'url': subtitles_src})
705
706 process_formats(formats)
707
708 info_dict = {
709 'id': video_id,
710 'formats': formats,
711 'subtitles': subtitles,
712 }
713 info_dict.update(extract_metadata(webpage))
714
715 return info_dict
716
717 def _real_extract(self, url):
718 video_id = self._match_id(url)
719
720 real_url = self._VIDEO_PAGE_TEMPLATE % video_id if url.startswith('facebook:') else url
721 return self._extract_from_url(real_url, video_id)
722
723
724 class FacebookPluginsVideoIE(InfoExtractor):
725 _VALID_URL = r'https?://(?:[\w-]+\.)?facebook\.com/plugins/video\.php\?.*?\bhref=(?P<id>https.+)'
726
727 _TESTS = [{
728 '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',
729 'md5': '5954e92cdfe51fe5782ae9bda7058a07',
730 'info_dict': {
731 'id': '10154383743583686',
732 'ext': 'mp4',
733 'title': 'What to do during the haze?',
734 'uploader': 'Gov.sg',
735 'upload_date': '20160826',
736 'timestamp': 1472184808,
737 },
738 'add_ie': [FacebookIE.ie_key()],
739 }, {
740 'url': 'https://www.facebook.com/plugins/video.php?href=https%3A%2F%2Fwww.facebook.com%2Fvideo.php%3Fv%3D10204634152394104',
741 'only_matching': True,
742 }, {
743 'url': 'https://www.facebook.com/plugins/video.php?href=https://www.facebook.com/gov.sg/videos/10154383743583686/&show_text=0&width=560',
744 'only_matching': True,
745 }]
746
747 def _real_extract(self, url):
748 return self.url_result(
749 compat_urllib_parse_unquote(self._match_id(url)),
750 FacebookIE.ie_key())
751
752
753 class FacebookRedirectURLIE(InfoExtractor):
754 IE_DESC = False # Do not list
755 _VALID_URL = r'https?://(?:[\w-]+\.)?facebook\.com/flx/warn[/?]'
756 _TESTS = [{
757 'url': 'https://www.facebook.com/flx/warn/?h=TAQHsoToz&u=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DpO8h3EaFRdo&s=1',
758 'info_dict': {
759 'id': 'pO8h3EaFRdo',
760 'ext': 'mp4',
761 'title': 'Tripeo Boiler Room x Dekmantel Festival DJ Set',
762 'description': 'md5:2d713ccbb45b686a1888397b2c77ca6b',
763 'channel_id': 'UCGBpxWJr9FNOcFYA5GkKrMg',
764 'playable_in_embed': True,
765 'categories': ['Music'],
766 'channel': 'Boiler Room',
767 'uploader_id': 'brtvofficial',
768 'uploader': 'Boiler Room',
769 'tags': 'count:11',
770 'duration': 3332,
771 'live_status': 'not_live',
772 'thumbnail': 'https://i.ytimg.com/vi/pO8h3EaFRdo/maxresdefault.jpg',
773 'channel_url': 'https://www.youtube.com/channel/UCGBpxWJr9FNOcFYA5GkKrMg',
774 'availability': 'public',
775 'uploader_url': 'http://www.youtube.com/user/brtvofficial',
776 'upload_date': '20150917',
777 'age_limit': 0,
778 'view_count': int,
779 'like_count': int,
780 },
781 'add_ie': ['Youtube'],
782 'params': {'skip_download': 'Youtube'},
783 }]
784
785 def _real_extract(self, url):
786 redirect_url = url_or_none(parse_qs(url).get('u', [None])[-1])
787 if not redirect_url:
788 raise ExtractorError('Invalid facebook redirect URL', expected=True)
789 return self.url_result(redirect_url)