]> jfr.im git - yt-dlp.git/blob - yt_dlp/extractor/facebook.py
5b34f3bff3f55c2d423ffb5b59c4f21769336648
[yt-dlp.git] / yt_dlp / extractor / facebook.py
1 import json
2 import re
3 import urllib.parse
4
5 from .common import InfoExtractor
6 from ..compat import (
7 compat_etree_fromstring,
8 compat_str,
9 compat_urllib_parse_unquote,
10 )
11 from ..utils import (
12 ExtractorError,
13 clean_html,
14 determine_ext,
15 error_to_compat_str,
16 float_or_none,
17 get_element_by_id,
18 get_first,
19 int_or_none,
20 js_to_json,
21 merge_dicts,
22 network_exceptions,
23 parse_count,
24 parse_qs,
25 qualities,
26 sanitized_Request,
27 traverse_obj,
28 try_get,
29 url_or_none,
30 urlencode_postdata,
31 urljoin,
32 variadic,
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': 'Ukrainian Scientists Worldwide | Довгоочікуване відео',
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': 'birb (O v O") | Hello? Yes your uber ride is here',
198 'description': 'Hello? Yes your uber ride is here * Jukin Media Verified * Find 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 _perform_login(self, username, password):
330 login_page_req = sanitized_Request(self._LOGIN_URL)
331 self._set_cookie('facebook.com', 'locale', 'en_US')
332 login_page = self._download_webpage(login_page_req, None,
333 note='Downloading login page',
334 errnote='Unable to download login page')
335 lsd = self._search_regex(
336 r'<input type="hidden" name="lsd" value="([^"]*)"',
337 login_page, 'lsd')
338 lgnrnd = self._search_regex(r'name="lgnrnd" value="([^"]*?)"', login_page, 'lgnrnd')
339
340 login_form = {
341 'email': username,
342 'pass': password,
343 'lsd': lsd,
344 'lgnrnd': lgnrnd,
345 'next': 'http://facebook.com/home.php',
346 'default_persistent': '0',
347 'legacy_return': '1',
348 'timezone': '-60',
349 'trynum': '1',
350 }
351 request = sanitized_Request(self._LOGIN_URL, urlencode_postdata(login_form))
352 request.add_header('Content-Type', 'application/x-www-form-urlencoded')
353 try:
354 login_results = self._download_webpage(request, None,
355 note='Logging in', errnote='unable to fetch login page')
356 if re.search(r'<form(.*)name="login"(.*)</form>', login_results) is not None:
357 error = self._html_search_regex(
358 r'(?s)<div[^>]+class=(["\']).*?login_error_box.*?\1[^>]*><div[^>]*>.*?</div><div[^>]*>(?P<error>.+?)</div>',
359 login_results, 'login error', default=None, group='error')
360 if error:
361 raise ExtractorError('Unable to login: %s' % error, expected=True)
362 self.report_warning('unable to log in: bad username/password, or exceeded login rate limit (~3/min). Check credentials or wait.')
363 return
364
365 fb_dtsg = self._search_regex(
366 r'name="fb_dtsg" value="(.+?)"', login_results, 'fb_dtsg', default=None)
367 h = self._search_regex(
368 r'name="h"\s+(?:\w+="[^"]+"\s+)*?value="([^"]+)"', login_results, 'h', default=None)
369
370 if not fb_dtsg or not h:
371 return
372
373 check_form = {
374 'fb_dtsg': fb_dtsg,
375 'h': h,
376 'name_action_selected': 'dont_save',
377 }
378 check_req = sanitized_Request(self._CHECKPOINT_URL, urlencode_postdata(check_form))
379 check_req.add_header('Content-Type', 'application/x-www-form-urlencoded')
380 check_response = self._download_webpage(check_req, None,
381 note='Confirming login')
382 if re.search(r'id="checkpointSubmitButton"', check_response) is not None:
383 self.report_warning('Unable to confirm login, you have to login in your browser and authorize the login.')
384 except network_exceptions as err:
385 self.report_warning('unable to log in: %s' % error_to_compat_str(err))
386 return
387
388 def _extract_from_url(self, url, video_id):
389 webpage = self._download_webpage(
390 url.replace('://m.facebook.com/', '://www.facebook.com/'), video_id)
391
392 def extract_metadata(webpage):
393 post_data = [self._parse_json(j, video_id, fatal=False) for j in re.findall(
394 r'handleWithCustomApplyEach\(\s*ScheduledApplyEach\s*,\s*(\{.+?\})\s*\);', webpage)]
395 post = traverse_obj(post_data, (
396 ..., 'require', ..., ..., ..., '__bbox', 'result', 'data'), expected_type=dict) or []
397 media = traverse_obj(post, (..., 'attachments', ..., lambda k, v: (
398 k == 'media' and str(v['id']) == video_id and v['__typename'] == 'Video')), expected_type=dict)
399 title = get_first(media, ('title', 'text'))
400 description = get_first(media, ('creation_story', 'comet_sections', 'message', 'story', 'message', 'text'))
401 uploader_data = get_first(media, 'owner') or get_first(post, ('node', 'actors', ...)) or {}
402
403 page_title = title or self._html_search_regex((
404 r'<h2\s+[^>]*class="uiHeaderTitle"[^>]*>(?P<content>[^<]*)</h2>',
405 r'(?s)<span class="fbPhotosPhotoCaption".*?id="fbPhotoPageCaption"><span class="hasCaption">(?P<content>.*?)</span>',
406 self._meta_regex('og:title'), self._meta_regex('twitter:title'), r'<title>(?P<content>.+?)</title>'
407 ), webpage, 'title', default=None, group='content')
408 description = description or self._html_search_meta(
409 ['description', 'og:description', 'twitter:description'],
410 webpage, 'description', default=None)
411 uploader = uploader_data.get('name') or (
412 clean_html(get_element_by_id('fbPhotoPageAuthorName', webpage))
413 or self._search_regex(
414 (r'ownerName\s*:\s*"([^"]+)"', *self._og_regexes('title')), webpage, 'uploader', fatal=False))
415
416 timestamp = int_or_none(self._search_regex(
417 r'<abbr[^>]+data-utime=["\'](\d+)', webpage,
418 'timestamp', default=None))
419 thumbnail = self._html_search_meta(
420 ['og:image', 'twitter:image'], webpage, 'thumbnail', default=None)
421 # some webpages contain unretrievable thumbnail urls
422 # like https://lookaside.fbsbx.com/lookaside/crawler/media/?media_id=10155168902769113&get_thumbnail=1
423 # in https://www.facebook.com/yaroslav.korpan/videos/1417995061575415/
424 if thumbnail and not re.search(r'\.(?:jpg|png)', thumbnail):
425 thumbnail = None
426 view_count = parse_count(self._search_regex(
427 r'\bviewCount\s*:\s*["\']([\d,.]+)', webpage, 'view count',
428 default=None))
429 info_dict = {
430 'description': description,
431 'uploader': uploader,
432 'uploader_id': uploader_data.get('id'),
433 'timestamp': timestamp,
434 'thumbnail': thumbnail,
435 'view_count': view_count,
436 }
437
438 info_json_ld = self._search_json_ld(webpage, video_id, default={})
439 info_json_ld['title'] = (re.sub(r'\s*\|\s*Facebook$', '', title or info_json_ld.get('title') or page_title or '')
440 or (description or '').replace('\n', ' ') or f'Facebook video #{video_id}')
441 return merge_dicts(info_json_ld, info_dict)
442
443 video_data = None
444
445 def extract_video_data(instances):
446 video_data = []
447 for item in instances:
448 if try_get(item, lambda x: x[1][0]) == 'VideoConfig':
449 video_item = item[2][0]
450 if video_item.get('video_id'):
451 video_data.append(video_item['videoData'])
452 return video_data
453
454 server_js_data = self._parse_json(self._search_regex(
455 [r'handleServerJS\(({.+})(?:\);|,")', r'\bs\.handle\(({.+?})\);'],
456 webpage, 'server js data', default='{}'), video_id, fatal=False)
457
458 if server_js_data:
459 video_data = extract_video_data(server_js_data.get('instances', []))
460
461 def extract_from_jsmods_instances(js_data):
462 if js_data:
463 return extract_video_data(try_get(
464 js_data, lambda x: x['jsmods']['instances'], list) or [])
465
466 def extract_dash_manifest(video, formats):
467 dash_manifest = video.get('dash_manifest')
468 if dash_manifest:
469 formats.extend(self._parse_mpd_formats(
470 compat_etree_fromstring(urllib.parse.unquote_plus(dash_manifest))))
471
472 def process_formats(formats):
473 # Downloads with browser's User-Agent are rate limited. Working around
474 # with non-browser User-Agent.
475 for f in formats:
476 f.setdefault('http_headers', {})['User-Agent'] = 'facebookexternalhit/1.1'
477
478 self._sort_formats(formats, ('res', 'quality'))
479
480 def extract_relay_data(_filter):
481 return self._parse_json(self._search_regex(
482 r'handleWithCustomApplyEach\([^,]+,\s*({.*?%s.*?})\);' % _filter,
483 webpage, 'replay data', default='{}'), video_id, fatal=False) or {}
484
485 def extract_relay_prefetched_data(_filter):
486 replay_data = extract_relay_data(_filter)
487 for require in (replay_data.get('require') or []):
488 if require[0] == 'RelayPrefetchedStreamCache':
489 return try_get(require, lambda x: x[3][1]['__bbox']['result']['data'], dict) or {}
490
491 if not video_data:
492 server_js_data = self._parse_json(self._search_regex([
493 r'bigPipe\.onPageletArrive\(({.+?})\)\s*;\s*}\s*\)\s*,\s*["\']onPageletArrive\s+' + self._SUPPORTED_PAGLETS_REGEX,
494 r'bigPipe\.onPageletArrive\(({.*?id\s*:\s*"%s".*?})\);' % self._SUPPORTED_PAGLETS_REGEX
495 ], webpage, 'js data', default='{}'), video_id, js_to_json, False)
496 video_data = extract_from_jsmods_instances(server_js_data)
497
498 if not video_data:
499 data = extract_relay_prefetched_data(
500 r'"(?:dash_manifest|playable_url(?:_quality_hd)?)"\s*:\s*"[^"]+"')
501 if data:
502 entries = []
503
504 def parse_graphql_video(video):
505 formats = []
506 q = qualities(['sd', 'hd'])
507 for key, format_id in (('playable_url', 'sd'), ('playable_url_quality_hd', 'hd'),
508 ('playable_url_dash', '')):
509 playable_url = video.get(key)
510 if not playable_url:
511 continue
512 if determine_ext(playable_url) == 'mpd':
513 formats.extend(self._extract_mpd_formats(playable_url, video_id))
514 else:
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': traverse_obj(
527 video, ('thumbnailImage', 'uri'), ('preferred_thumbnail', 'image', 'uri')),
528 'uploader_id': try_get(video, lambda x: x['owner']['id']),
529 'timestamp': int_or_none(video.get('publish_time')),
530 'duration': float_or_none(video.get('playable_duration_in_ms'), 1000),
531 }
532 description = try_get(video, lambda x: x['savable_description']['text'])
533 title = video.get('name')
534 if title:
535 info.update({
536 'title': title,
537 'description': description,
538 })
539 else:
540 info['title'] = description or 'Facebook video #%s' % v_id
541 entries.append(info)
542
543 def parse_attachment(attachment, key='media'):
544 media = attachment.get(key) or {}
545 if media.get('__typename') == 'Video':
546 return parse_graphql_video(media)
547
548 nodes = variadic(traverse_obj(data, 'nodes', 'node') or [])
549 attachments = traverse_obj(nodes, (
550 ..., 'comet_sections', 'content', 'story', (None, 'attached_story'), 'attachments',
551 ..., ('styles', 'style_type_renderer'), 'attachment'), expected_type=dict) or []
552 for attachment in attachments:
553 ns = try_get(attachment, lambda x: x['all_subattachments']['nodes'], list) or []
554 for n in ns:
555 parse_attachment(n)
556 parse_attachment(attachment)
557
558 edges = try_get(data, lambda x: x['mediaset']['currMedia']['edges'], list) or []
559 for edge in edges:
560 parse_attachment(edge, key='node')
561
562 video = data.get('video') or {}
563 if video:
564 attachments = try_get(video, [
565 lambda x: x['story']['attachments'],
566 lambda x: x['creation_story']['attachments']
567 ], list) or []
568 for attachment in attachments:
569 parse_attachment(attachment)
570 if not entries:
571 parse_graphql_video(video)
572
573 if len(entries) > 1:
574 return self.playlist_result(entries, video_id)
575
576 video_info = entries[0]
577 webpage_info = extract_metadata(webpage)
578 # honor precise duration in video info
579 if video_info.get('duration'):
580 webpage_info['duration'] = video_info['duration']
581 return merge_dicts(webpage_info, video_info)
582
583 if not video_data:
584 m_msg = re.search(r'class="[^"]*uiInterstitialContent[^"]*"><div>(.*?)</div>', webpage)
585 if m_msg is not None:
586 raise ExtractorError(
587 'The video is not available, Facebook said: "%s"' % m_msg.group(1),
588 expected=True)
589 elif any(p in webpage for p in (
590 '>You must log in to continue',
591 'id="login_form"',
592 'id="loginbutton"')):
593 self.raise_login_required()
594
595 if not video_data and '/watchparty/' in url:
596 post_data = {
597 'doc_id': 3731964053542869,
598 'variables': json.dumps({
599 'livingRoomID': video_id,
600 }),
601 }
602
603 prefetched_data = extract_relay_prefetched_data(r'"login_data"\s*:\s*{')
604 if prefetched_data:
605 lsd = try_get(prefetched_data, lambda x: x['login_data']['lsd'], dict)
606 if lsd:
607 post_data[lsd['name']] = lsd['value']
608
609 relay_data = extract_relay_data(r'\[\s*"RelayAPIConfigDefaults"\s*,')
610 for define in (relay_data.get('define') or []):
611 if define[0] == 'RelayAPIConfigDefaults':
612 self._api_config = define[2]
613
614 living_room = self._download_json(
615 urljoin(url, self._api_config['graphURI']), video_id,
616 data=urlencode_postdata(post_data))['data']['living_room']
617
618 entries = []
619 for edge in (try_get(living_room, lambda x: x['recap']['watched_content']['edges']) or []):
620 video = try_get(edge, lambda x: x['node']['video']) or {}
621 v_id = video.get('id')
622 if not v_id:
623 continue
624 v_id = compat_str(v_id)
625 entries.append(self.url_result(
626 self._VIDEO_PAGE_TEMPLATE % v_id,
627 self.ie_key(), v_id, video.get('name')))
628
629 return self.playlist_result(entries, video_id)
630
631 if not video_data:
632 # Video info not in first request, do a secondary request using
633 # tahoe player specific URL
634 tahoe_data = self._download_webpage(
635 self._VIDEO_PAGE_TAHOE_TEMPLATE % video_id, video_id,
636 data=urlencode_postdata({
637 '__a': 1,
638 '__pc': self._search_regex(
639 r'pkg_cohort["\']\s*:\s*["\'](.+?)["\']', webpage,
640 'pkg cohort', default='PHASED:DEFAULT'),
641 '__rev': self._search_regex(
642 r'client_revision["\']\s*:\s*(\d+),', webpage,
643 'client revision', default='3944515'),
644 'fb_dtsg': self._search_regex(
645 r'"DTSGInitialData"\s*,\s*\[\]\s*,\s*{\s*"token"\s*:\s*"([^"]+)"',
646 webpage, 'dtsg token', default=''),
647 }),
648 headers={
649 'Content-Type': 'application/x-www-form-urlencoded',
650 })
651 tahoe_js_data = self._parse_json(
652 self._search_regex(
653 r'for\s+\(\s*;\s*;\s*\)\s*;(.+)', tahoe_data,
654 'tahoe js data', default='{}'),
655 video_id, fatal=False)
656 video_data = extract_from_jsmods_instances(tahoe_js_data)
657
658 if not video_data:
659 raise ExtractorError('Cannot parse data')
660
661 if len(video_data) > 1:
662 entries = []
663 for v in video_data:
664 video_url = v[0].get('video_url')
665 if not video_url:
666 continue
667 entries.append(self.url_result(urljoin(
668 url, video_url), self.ie_key(), v[0].get('video_id')))
669 return self.playlist_result(entries, video_id)
670 video_data = video_data[0]
671
672 formats = []
673 subtitles = {}
674 for f in video_data:
675 format_id = f['stream_type']
676 if f and isinstance(f, dict):
677 f = [f]
678 if not f or not isinstance(f, list):
679 continue
680 for quality in ('sd', 'hd'):
681 for src_type in ('src', 'src_no_ratelimit'):
682 src = f[0].get('%s_%s' % (quality, src_type))
683 if src:
684 preference = -10 if format_id == 'progressive' else -1
685 if quality == 'hd':
686 preference += 5
687 formats.append({
688 'format_id': '%s_%s_%s' % (format_id, quality, src_type),
689 'url': src,
690 'quality': preference,
691 'height': 720 if quality == 'hd' else None
692 })
693 extract_dash_manifest(f[0], formats)
694 subtitles_src = f[0].get('subtitles_src')
695 if subtitles_src:
696 subtitles.setdefault('en', []).append({'url': subtitles_src})
697
698 process_formats(formats)
699
700 info_dict = {
701 'id': video_id,
702 'formats': formats,
703 'subtitles': subtitles,
704 }
705 info_dict.update(extract_metadata(webpage))
706
707 return info_dict
708
709 def _real_extract(self, url):
710 video_id = self._match_id(url)
711
712 real_url = self._VIDEO_PAGE_TEMPLATE % video_id if url.startswith('facebook:') else url
713 return self._extract_from_url(real_url, video_id)
714
715
716 class FacebookPluginsVideoIE(InfoExtractor):
717 _VALID_URL = r'https?://(?:[\w-]+\.)?facebook\.com/plugins/video\.php\?.*?\bhref=(?P<id>https.+)'
718
719 _TESTS = [{
720 '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',
721 'md5': '5954e92cdfe51fe5782ae9bda7058a07',
722 'info_dict': {
723 'id': '10154383743583686',
724 'ext': 'mp4',
725 # TODO: Fix title, uploader
726 'title': 'What to do during the haze?',
727 'uploader': 'Gov.sg',
728 'upload_date': '20160826',
729 'timestamp': 1472184808,
730 },
731 'add_ie': [FacebookIE.ie_key()],
732 }, {
733 'url': 'https://www.facebook.com/plugins/video.php?href=https%3A%2F%2Fwww.facebook.com%2Fvideo.php%3Fv%3D10204634152394104',
734 'only_matching': True,
735 }, {
736 'url': 'https://www.facebook.com/plugins/video.php?href=https://www.facebook.com/gov.sg/videos/10154383743583686/&show_text=0&width=560',
737 'only_matching': True,
738 }]
739
740 def _real_extract(self, url):
741 return self.url_result(
742 compat_urllib_parse_unquote(self._match_id(url)),
743 FacebookIE.ie_key())
744
745
746 class FacebookRedirectURLIE(InfoExtractor):
747 IE_DESC = False # Do not list
748 _VALID_URL = r'https?://(?:[\w-]+\.)?facebook\.com/flx/warn[/?]'
749 _TESTS = [{
750 'url': 'https://www.facebook.com/flx/warn/?h=TAQHsoToz&u=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DpO8h3EaFRdo&s=1',
751 'info_dict': {
752 'id': 'pO8h3EaFRdo',
753 'ext': 'mp4',
754 'title': 'Tripeo Boiler Room x Dekmantel Festival DJ Set',
755 'description': 'md5:2d713ccbb45b686a1888397b2c77ca6b',
756 'channel_id': 'UCGBpxWJr9FNOcFYA5GkKrMg',
757 'playable_in_embed': True,
758 'categories': ['Music'],
759 'channel': 'Boiler Room',
760 'uploader_id': 'brtvofficial',
761 'uploader': 'Boiler Room',
762 'tags': 'count:11',
763 'duration': 3332,
764 'live_status': 'not_live',
765 'thumbnail': 'https://i.ytimg.com/vi/pO8h3EaFRdo/maxresdefault.jpg',
766 'channel_url': 'https://www.youtube.com/channel/UCGBpxWJr9FNOcFYA5GkKrMg',
767 'availability': 'public',
768 'uploader_url': 'http://www.youtube.com/user/brtvofficial',
769 'upload_date': '20150917',
770 'age_limit': 0,
771 'view_count': int,
772 'like_count': int,
773 },
774 'add_ie': ['Youtube'],
775 'params': {'skip_download': 'Youtube'},
776 }]
777
778 def _real_extract(self, url):
779 redirect_url = url_or_none(parse_qs(url).get('u', [None])[-1])
780 if not redirect_url:
781 raise ExtractorError('Invalid facebook redirect URL', expected=True)
782 return self.url_result(redirect_url)