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