2 from __future__
import unicode_literals
7 from .common
import InfoExtractor
9 compat_etree_fromstring
,
11 compat_urllib_parse_unquote
,
12 compat_urllib_parse_unquote_plus
,
33 class FacebookIE(InfoExtractor
):
37 (?:[\w-]+\.)?(?:facebook\.com|facebookcorewwwi\.onion)/
47 )\?(?:.*?)(?:v|video_id|story_fbid)=|
48 [^/]+/videos/(?:[^/]+/)?|
50 groups/[^/]+/permalink/|
57 _LOGIN_URL
= 'https://www.facebook.com/login.php?next=http%3A%2F%2Ffacebook.com%2Fhome.php&login_attempt=1'
58 _CHECKPOINT_URL
= 'https://www.facebook.com/checkpoint/?next=http%3A%2F%2Ffacebook.com%2Fhome.php&_fb_noscript=1'
59 _NETRC_MACHINE
= 'facebook'
62 _VIDEO_PAGE_TEMPLATE
= 'https://www.facebook.com/video/video.php?v=%s'
63 _VIDEO_PAGE_TAHOE_TEMPLATE
= 'https://www.facebook.com/video/tahoe/async/%s/?chain=true&isvideo=true&payloadtype=primary'
66 'url': 'https://www.facebook.com/video.php?v=637842556329505&fref=nf',
67 'md5': '6a40d33c0eccbb1af76cf0485a052659',
69 'id': '637842556329505',
71 'title': 're:Did you know Kei Nishikori is the first Asian man to ever reach a Grand Slam',
72 'uploader': 'Tennis on Facebook',
73 'upload_date': '20140908',
74 'timestamp': 1410199200,
76 'skip': 'Requires logging in',
79 'url': 'https://www.facebook.com/video.php?v=274175099429670',
81 'id': '274175099429670',
83 'title': 're:^Asif Nawab Butt posted a video',
84 'uploader': 'Asif Nawab Butt',
85 'upload_date': '20140506',
86 'timestamp': 1399398998,
87 'thumbnail': r
're:^https?://.*',
89 'expected_warnings': [
93 'note': 'Video with DASH manifest',
94 'url': 'https://www.facebook.com/video.php?v=957955867617029',
95 'md5': 'b2c28d528273b323abe5c6ab59f0f030',
97 'id': '957955867617029',
99 'title': 'When you post epic content on instagram.com/433 8 million followers, this is ...',
100 'uploader': 'Demy de Zeeuw',
101 'upload_date': '20160110',
102 'timestamp': 1452431627,
104 'skip': 'Requires logging in',
106 'url': 'https://www.facebook.com/maxlayn/posts/10153807558977570',
107 'md5': '037b1fa7f3c2d02b7a0d7bc16031ecc6',
109 'id': '544765982287235',
111 'title': '"What are you doing running in the snow?"',
112 'uploader': 'FailArmy',
114 'skip': 'Video gone',
116 'url': 'https://m.facebook.com/story.php?story_fbid=1035862816472149&id=116132035111903',
117 'md5': '1deb90b6ac27f7efcf6d747c8a27f5e3',
119 'id': '1035862816472149',
121 'title': 'What the Flock Is Going On In New Zealand Credit: ViralHog',
122 'uploader': 'S. Saint',
124 'skip': 'Video gone',
126 'note': 'swf params escaped',
127 'url': 'https://www.facebook.com/barackobama/posts/10153664894881749',
128 'md5': '97ba073838964d12c70566e0085c2b91',
130 'id': '10153664894881749',
132 'title': 'Average time to confirm recent Supreme Court nominees: 67 days Longest it\'s t...',
133 'thumbnail': r
're:^https?://.*',
134 'timestamp': 1456259628,
135 'upload_date': '20160223',
136 'uploader': 'Barack Obama',
139 # have 1080P, but only up to 720p in swf params
140 # data.video.story.attachments[].media
141 'url': 'https://www.facebook.com/cnn/videos/10155529876156509/',
142 'md5': '9571fae53d4165bbbadb17a94651dcdc',
144 'id': '10155529876156509',
146 'title': 'She survived the holocaust — and years later, she’s getting her citizenship s...',
147 'timestamp': 1477818095,
148 'upload_date': '20161030',
150 'thumbnail': r
're:^https?://.*',
154 # bigPipe.onPageletArrive ... onPageletArrive pagelet_group_mall
155 # data.node.comet_sections.content.story.attachments[].style_type_renderer.attachment.media
156 'url': 'https://www.facebook.com/yaroslav.korpan/videos/1417995061575415/',
158 'id': '1417995061575415',
160 'title': 'md5:1db063d6a8c13faa8da727817339c857',
161 'timestamp': 1486648217,
162 'upload_date': '20170209',
163 'uploader': 'Yaroslav Korpan',
166 'skip_download': True,
169 'url': 'https://www.facebook.com/LaGuiaDelVaron/posts/1072691702860471',
171 'id': '1072691702860471',
173 'title': 'md5:ae2d22a93fbb12dad20dc393a869739d',
174 'timestamp': 1477305000,
175 'upload_date': '20161024',
176 'uploader': 'La Guía Del Varón',
177 'thumbnail': r
're:^https?://.*',
180 'skip_download': True,
183 # data.node.comet_sections.content.story.attachments[].style_type_renderer.attachment.media
184 'url': 'https://www.facebook.com/groups/1024490957622648/permalink/1396382447100162/',
186 'id': '1396382447100162',
188 'title': 'md5:19a428bbde91364e3de815383b54a235',
189 'timestamp': 1486035494,
190 'upload_date': '20170202',
191 'uploader': 'Elisabeth Ahtn',
194 'skip_download': True,
197 'url': 'https://www.facebook.com/video.php?v=10204634152394104',
198 'only_matching': True,
200 'url': 'https://www.facebook.com/amogood/videos/1618742068337349/?fref=nf',
201 'only_matching': True,
203 # data.mediaset.currMedia.edges
204 'url': 'https://www.facebook.com/ChristyClarkForBC/videos/vb.22819070941/10153870694020942/?type=2&theater',
205 'only_matching': True,
207 # data.video.story.attachments[].media
208 'url': 'facebook:544765982287235',
209 'only_matching': True,
211 # data.node.comet_sections.content.story.attachments[].style_type_renderer.attachment.media
212 'url': 'https://www.facebook.com/groups/164828000315060/permalink/764967300301124/',
213 'only_matching': True,
215 # data.video.creation_story.attachments[].media
216 'url': 'https://zh-hk.facebook.com/peoplespower/videos/1135894589806027/',
217 'only_matching': True,
220 'url': 'https://www.facebookcorewwwi.onion/video.php?v=274175099429670',
221 'only_matching': True,
224 'url': 'https://www.facebook.com/onlycleverentertainment/videos/1947995502095005/',
225 'only_matching': True,
228 'url': 'https://www.facebook.com/WatchESLOne/videos/359649331226507/',
230 'id': '359649331226507',
232 'title': '#ESLOne VoD - Birmingham Finals Day#1 Fnatic vs. @Evil Geniuses',
233 'uploader': 'ESL One Dota 2',
236 'skip_download': True,
239 # data.node.comet_sections.content.story.attachments[].style_type_renderer.attachment.all_subattachments.nodes[].media
240 'url': 'https://www.facebook.com/100033620354545/videos/106560053808006/',
242 'id': '106560053808006',
246 # data.video.story.attachments[].media
247 'url': 'https://www.facebook.com/watch/?v=647537299265662',
248 'only_matching': True,
250 # data.node.comet_sections.content.story.attachments[].style_type_renderer.attachment.all_subattachments.nodes[].media
251 'url': 'https://www.facebook.com/PankajShahLondon/posts/10157667649866271',
253 'id': '10157667649866271',
257 # data.nodes[].comet_sections.content.story.attachments[].style_type_renderer.attachment.media
258 'url': 'https://m.facebook.com/Alliance.Police.Department/posts/4048563708499330',
260 'id': '117576630041613',
262 # TODO: title can be extracted from video page
263 'title': 'Facebook video #117576630041613',
264 'uploader_id': '189393014416438',
265 'upload_date': '20201123',
266 'timestamp': 1606162592,
268 'skip': 'Requires logging in',
270 # node.comet_sections.content.story.attached_story.attachments.style_type_renderer.attachment.media
271 'url': 'https://www.facebook.com/groups/ateistiskselskab/permalink/10154930137678856/',
273 'id': '211567722618337',
275 'title': 'Facebook video #211567722618337',
276 'uploader_id': '127875227654254',
277 'upload_date': '20161122',
278 'timestamp': 1479793574,
281 # data.video.creation_story.attachments[].media
282 'url': 'https://www.facebook.com/watch/live/?v=1823658634322275',
283 'only_matching': True,
285 'url': 'https://www.facebook.com/watchparty/211641140192478',
287 'id': '211641140192478',
290 'skip': 'Requires logging in',
292 _SUPPORTED_PAGLETS_REGEX
= r
'(?:pagelet_group_mall|permalink_video_pagelet|hyperfeed_story_id_[0-9a-f]+)'
294 'graphURI': '/api/graphql/'
298 def _extract_urls(webpage
):
300 for mobj
in re
.finditer(
301 r
'<iframe[^>]+?src=(["\'])(?P
<url
>https?
://www\
.facebook\
.com
/(?
:video
/embed|plugins
/video\
.php
).+?
)\
1',
303 urls.append(mobj.group('url
'))
305 # see https://developers.facebook.com/docs/plugins/embedded-video-player
306 for mobj in re.finditer(r'''(?x)<div[^>]+
307 class=(?P<q1>[\'"])[^\'"]*\bfb-(?:video|post)\b[^\'"]*(?P=q1)[^>]+
308 data-href=(?P<q2>[\'"])(?P<url>(?:https?:)?//(?:www\.)?facebook.com/.+?)(?P=q2)''', webpage):
309 urls.append(mobj.group('url
'))
313 useremail, password = self._get_login_info()
314 if useremail is None:
317 login_page_req = sanitized_Request(self._LOGIN_URL)
318 self._set_cookie('facebook
.com
', 'locale
', 'en_US
')
319 login_page = self._download_webpage(login_page_req, None,
320 note='Downloading login page
',
321 errnote='Unable to download login page
')
322 lsd = self._search_regex(
323 r'<input type="hidden" name
="lsd" value
="([^"]*)"',
325 lgnrnd = self._search_regex(r'name="lgnrnd
" value="([^
"]*?)"', login_page, 'lgnrnd
')
332 'next
': 'http
://facebook
.com
/home
.php
',
333 'default_persistent
': '0',
334 'legacy_return
': '1',
338 request = sanitized_Request(self._LOGIN_URL, urlencode_postdata(login_form))
339 request.add_header('Content
-Type
', 'application
/x
-www
-form
-urlencoded
')
341 login_results = self._download_webpage(request, None,
342 note='Logging
in', errnote='unable to fetch login page
')
343 if re.search(r'<form(.*)name
="login"(.*)</form
>', login_results) is not None:
344 error = self._html_search_regex(
345 r'(?s
)<div
[^
>]+class=(["\']).*?login_error_box.*?\1[^>]*><div[^>]*>.*?</div><div[^>]*>(?P<error>.+?)</div>',
346 login_results, 'login error', default=None, group='error')
348 raise ExtractorError('Unable to login: %s' % error, expected=True)
349 self.report_warning('unable to log in: bad username/password, or exceeded login rate limit (~3/min). Check credentials or wait.')
352 fb_dtsg = self._search_regex(
353 r'name="fb_dtsg
" value="(.+?
)"', login_results, 'fb_dtsg', default=None)
354 h = self._search_regex(
355 r'name="h
"\s+(?:\w+="[^
"]+"\s
+)*?value
="([^"]+)"', login_results, 'h', default=None)
357 if not fb_dtsg or not h:
363 'name_action_selected': 'dont_save',
365 check_req = sanitized_Request(self._CHECKPOINT_URL, urlencode_postdata(check_form))
366 check_req.add_header('Content-Type', 'application/x-www-form-urlencoded')
367 check_response = self._download_webpage(check_req, None,
368 note='Confirming login')
369 if re.search(r'id="checkpointSubmitButton
"', check_response) is not None:
370 self.report_warning('Unable to confirm login, you have to login in your browser and authorize the login.')
371 except network_exceptions as err:
372 self.report_warning('unable to log in: %s' % error_to_compat_str(err))
375 def _real_initialize(self):
378 def _extract_from_url(self, url, video_id):
379 webpage = self._download_webpage(
380 url.replace('://m.facebook.com/', '://www.facebook.com/'), video_id)
384 def extract_video_data(instances):
386 for item in instances:
387 if try_get(item, lambda x: x[1][0]) == 'VideoConfig':
388 video_item = item[2][0]
389 if video_item.get('video_id'):
390 video_data.append(video_item['videoData'])
393 server_js_data = self._parse_json(self._search_regex(
394 [r'handleServerJS\(({.+})(?:\);|,")', r'\bs\
.handle\
(({.+?}
)\
);'],
395 webpage, 'server js data
', default='{}'), video_id, fatal=False)
398 video_data = extract_video_data(server_js_data.get('instances
', []))
400 def extract_from_jsmods_instances(js_data):
402 return extract_video_data(try_get(
403 js_data, lambda x: x['jsmods
']['instances
'], list) or [])
405 def extract_dash_manifest(video, formats):
406 dash_manifest = video.get('dash_manifest
')
408 formats.extend(self._parse_mpd_formats(
409 compat_etree_fromstring(compat_urllib_parse_unquote_plus(dash_manifest))))
411 def process_formats(formats):
412 # Downloads with browser's User
-Agent are rate limited
. Working around
413 # with non-browser User-Agent.
415 f
.setdefault('http_headers', {})['User-Agent'] = 'facebookexternalhit/1.1'
417 self
._sort
_formats
(formats
)
419 def extract_relay_data(_filter
):
420 return self
._parse
_json
(self
._search
_regex
(
421 r
'handleWithCustomApplyEach\([^,]+,\s*({.*?%s.*?})\);' % _filter
,
422 webpage
, 'replay data', default
='{}'), video_id, fatal=False) or {}
424 def extract_relay_prefetched_data(_filter):
425 replay_data = extract_relay_data(_filter)
426 for require in (replay_data.get('require
') or []):
427 if require[0] == 'RelayPrefetchedStreamCache
':
428 return try_get(require, lambda x: x[3][1]['__bbox
']['result
']['data
'], dict) or {}
431 server_js_data = self._parse_json(self._search_regex([
432 r'bigPipe\
.onPageletArrive\
(({.+?}
)\
)\s
*;\s
*}\s
*\
)\s
*,\s
*["\']onPageletArrive\s+' + self._SUPPORTED_PAGLETS_REGEX,
433 r'bigPipe\.onPageletArrive\(({.*?id\s*:\s*"%s".*?})\);' % self._SUPPORTED_PAGLETS_REGEX
434 ], webpage, 'js data', default='{}'), video_id, js_to_json, False)
435 video_data = extract_from_jsmods_instances(server_js_data)
438 data = extract_relay_prefetched_data(
439 r'"(?
:dash_manifest|
playable_url(?
:_quality_hd
)?
)"\s*:\s*"[^
"]+"')
443 def parse_graphql_video(video):
445 q = qualities(['sd
', 'hd
'])
446 for (suffix, format_id) in [('', 'sd
'), ('_quality_hd
', 'hd
')]:
447 playable_url = video.get('playable_url
' + suffix)
451 'format_id
': format_id,
452 'quality
': q(format_id),
455 extract_dash_manifest(video, formats)
456 process_formats(formats)
457 v_id = video.get('videoId
') or video.get('id') or video_id
461 'thumbnail
': try_get(video, lambda x: x['thumbnailImage
']['uri
']),
462 'uploader_id
': try_get(video, lambda x: x['owner
']['id']),
463 'timestamp
': int_or_none(video.get('publish_time
')),
464 'duration
': float_or_none(video.get('playable_duration_in_ms
'), 1000),
466 description = try_get(video, lambda x: x['savable_description
']['text
'])
467 title = video.get('name
')
471 'description
': description,
474 info['title
'] = description or 'Facebook video
#%s' % v_id
477 def parse_attachment(attachment
, key
='media'):
478 media
= attachment
.get(key
) or {}
479 if media
.get('__typename') == 'Video':
480 return parse_graphql_video(media
)
482 nodes
= data
.get('nodes') or []
483 node
= data
.get('node') or {}
484 if not nodes
and node
:
487 story
= try_get(node
, lambda x
: x
['comet_sections']['content']['story'], dict) or {}
488 attachments
= try_get(story
, [
489 lambda x
: x
['attached_story']['attachments'],
490 lambda x
: x
['attachments']
492 for attachment
in attachments
:
493 attachment
= try_get(attachment
, lambda x
: x
['style_type_renderer']['attachment'], dict)
494 ns
= try_get(attachment
, lambda x
: x
['all_subattachments']['nodes'], list) or []
497 parse_attachment(attachment
)
499 edges
= try_get(data
, lambda x
: x
['mediaset']['currMedia']['edges'], list) or []
501 parse_attachment(edge
, key
='node')
503 video
= data
.get('video') or {}
505 attachments
= try_get(video
, [
506 lambda x
: x
['story']['attachments'],
507 lambda x
: x
['creation_story']['attachments']
509 for attachment
in attachments
:
510 parse_attachment(attachment
)
512 parse_graphql_video(video
)
514 return self
.playlist_result(entries
, video_id
)
517 m_msg
= re
.search(r
'class="[^"]*uiInterstitialContent[^"]*"><div>(.*?)</div>', webpage
)
518 if m_msg
is not None:
519 raise ExtractorError(
520 'The video is not available, Facebook said: "%s"' % m_msg
.group(1),
522 elif any(p
in webpage
for p
in (
523 '>You must log in to continue',
525 'id="loginbutton"')):
526 self
.raise_login_required()
528 if not video_data
and '/watchparty/' in url
:
530 'doc_id': 3731964053542869,
531 'variables': json
.dumps({
532 'livingRoomID': video_id
,
536 prefetched_data
= extract_relay_prefetched_data(r
'"login_data"\s*:\s*{')
538 lsd
= try_get(prefetched_data
, lambda x
: x
['login_data']['lsd'], dict)
540 post_data
[lsd
['name']] = lsd
['value']
542 relay_data
= extract_relay_data(r
'\[\s*"RelayAPIConfigDefaults"\s*,')
543 for define
in (relay_data
.get('define') or []):
544 if define
[0] == 'RelayAPIConfigDefaults':
545 self
._api
_config
= define
[2]
547 living_room
= self
._download
_json
(
548 urljoin(url
, self
._api
_config
['graphURI']), video_id
,
549 data
=urlencode_postdata(post_data
))['data']['living_room']
552 for edge
in (try_get(living_room
, lambda x
: x
['recap']['watched_content']['edges']) or []):
553 video
= try_get(edge
, lambda x
: x
['node']['video']) or {}
554 v_id
= video
.get('id')
557 v_id
= compat_str(v_id
)
558 entries
.append(self
.url_result(
559 self
._VIDEO
_PAGE
_TEMPLATE
% v_id
,
560 self
.ie_key(), v_id
, video
.get('name')))
562 return self
.playlist_result(entries
, video_id
)
565 # Video info not in first request, do a secondary request using
566 # tahoe player specific URL
567 tahoe_data
= self
._download
_webpage
(
568 self
._VIDEO
_PAGE
_TAHOE
_TEMPLATE
% video_id
, video_id
,
569 data
=urlencode_postdata({
571 '__pc': self
._search
_regex
(
572 r
'pkg_cohort["\']\s
*:\s
*["\'](.+?)["\']', webpage,
573 'pkg cohort
', default='PHASED
:DEFAULT
'),
574 '__rev
': self._search_regex(
575 r'client_revision
["\']\s*:\s*(\d+),', webpage,
576 'client revision', default='3944515'),
577 'fb_dtsg': self._search_regex(
578 r'"DTSGInitialData
"\s*,\s*\[\]\s*,\s*{\s*"token
"\s*:\s*"([^
"]+)"',
579 webpage, 'dtsg token
', default=''),
582 'Content
-Type
': 'application
/x
-www
-form
-urlencoded
',
584 tahoe_js_data = self._parse_json(
586 r'for\s
+\
(\s
*;\s
*;\s
*\
)\s
*;(.+)', tahoe_data,
587 'tahoe js data
', default='{}'),
588 video_id, fatal=False)
589 video_data = extract_from_jsmods_instances(tahoe_js_data)
592 raise ExtractorError('Cannot parse data
')
594 if len(video_data) > 1:
597 video_url = v[0].get('video_url
')
600 entries.append(self.url_result(urljoin(
601 url, video_url), self.ie_key(), v[0].get('video_id
')))
602 return self.playlist_result(entries, video_id)
603 video_data = video_data[0]
608 format_id = f['stream_type
']
609 if f and isinstance(f, dict):
611 if not f or not isinstance(f, list):
613 for quality in ('sd
', 'hd
'):
614 for src_type in ('src
', 'src_no_ratelimit
'):
615 src = f[0].get('%s_%s' % (quality, src_type))
617 preference = -10 if format_id == 'progressive
' else 0
621 'format_id
': '%s_%s_%s' % (format_id, quality, src_type),
623 'quality
': preference,
625 extract_dash_manifest(f[0], formats)
626 subtitles_src = f[0].get('subtitles_src
')
628 subtitles.setdefault('en
', []).append({'url': subtitles_src})
630 process_formats(formats)
632 description = self._html_search_meta('description
', webpage, default=None)
633 video_title = self._html_search_regex(
634 (r'<h2\s
+[^
>]*class="uiHeaderTitle"[^
>]*>([^
<]*)</h2
>',
635 r'(?s
)<span
class="fbPhotosPhotoCaption".*?
id="fbPhotoPageCaption"><span
class="hasCaption">(.*?
)</span
>'),
636 webpage, 'title
', default=None) or self._og_search_title(webpage, default=None) or description
638 video_title = limit_length(video_title, 80)
640 video_title = 'Facebook video
#%s' % video_id
641 uploader
= clean_html(get_element_by_id(
642 'fbPhotoPageAuthorName', webpage
)) or self
._search
_regex
(
643 r
'ownerName\s*:\s*"([^"]+)"', webpage
, 'uploader',
644 default
=None) or self
._og
_search
_title
(webpage
, fatal
=False)
645 timestamp
= int_or_none(self
._search
_regex
(
646 r
'<abbr[^>]+data-utime=["\'](\d
+)', webpage,
647 'timestamp
', default=None))
648 thumbnail = self._html_search_meta(['og
:image
', 'twitter
:image
'], webpage)
650 view_count = parse_count(self._search_regex(
651 r'\bviewCount\s
*:\s
*["\']([\d,.]+)', webpage, 'view count',
656 'title': video_title,
658 'uploader': uploader,
659 'timestamp': timestamp,
660 'description': description,
661 'thumbnail': thumbnail,
662 'view_count': view_count,
663 'subtitles': subtitles,
668 def _real_extract(self, url):
669 video_id = self._match_id(url)
671 real_url = self._VIDEO_PAGE_TEMPLATE % video_id if url.startswith('facebook:') else url
672 return self._extract_from_url(real_url, video_id)
675 class FacebookPluginsVideoIE(InfoExtractor):
676 _VALID_URL = r'https?://(?:[\w-]+\.)?facebook\.com/plugins/video\.php\?.*?\bhref=(?P<id>https.+)'
679 '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',
680 'md5': '5954e92cdfe51fe5782ae9bda7058a07',
682 'id': '10154383743583686',
684 'title': 'What to do during the haze?',
685 'uploader': 'Gov.sg',
686 'upload_date': '20160826',
687 'timestamp': 1472184808,
689 'add_ie': [FacebookIE.ie_key()],
691 'url': 'https://www.facebook.com/plugins/video.php?href=https%3A%2F%2Fwww.facebook.com%2Fvideo.php%3Fv%3D10204634152394104',
692 'only_matching': True,
694 'url': 'https://www.facebook.com/plugins/video.php?href=https://www.facebook.com/gov.sg/videos/10154383743583686/&show_text=0&width=560',
695 'only_matching': True,
698 def _real_extract(self, url):
699 return self.url_result(
700 compat_urllib_parse_unquote(self._match_id(url)),