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