]>
Commit | Line | Data |
---|---|---|
624c4b92 | 1 | # coding: utf-8 |
cb3bb2cf PH |
2 | from __future__ import unicode_literals |
3 | ||
29f7c58a | 4 | import json |
9eae41dd | 5 | import re |
9eae41dd PH |
6 | |
7 | from .common import InfoExtractor | |
8c25f81b | 8 | from ..compat import ( |
0803753f | 9 | compat_etree_fromstring, |
29f7c58a | 10 | compat_str, |
d7011316 | 11 | compat_urllib_parse_unquote, |
0803753f | 12 | compat_urllib_parse_unquote_plus, |
8c25f81b PH |
13 | ) |
14 | from ..utils import ( | |
b83ef507 | 15 | clean_html, |
9b9c5355 | 16 | error_to_compat_str, |
9eae41dd | 17 | ExtractorError, |
29f7c58a | 18 | float_or_none, |
b83ef507 | 19 | get_element_by_id, |
196c6ba0 | 20 | int_or_none, |
b83ef507 | 21 | js_to_json, |
a020a0dc | 22 | limit_length, |
a181cd0c | 23 | merge_dicts, |
3158150c | 24 | network_exceptions, |
11330f51 | 25 | parse_count, |
29f7c58a | 26 | qualities, |
5c2266df | 27 | sanitized_Request, |
b83ef507 | 28 | try_get, |
2fc9f2b4 | 29 | urlencode_postdata, |
29f7c58a | 30 | urljoin, |
9eae41dd PH |
31 | ) |
32 | ||
33 | ||
34 | class FacebookIE(InfoExtractor): | |
9834872b | 35 | _VALID_URL = r'''(?x) |
2e6e742c S |
36 | (?: |
37 | https?:// | |
61bfacb2 | 38 | (?:[\w-]+\.)?(?:facebook\.com|facebookwkhpilnemxj7asaniu7vnjjbiltxjqhye3mhbshg7kx5tfyd\.onion)/ |
2e6e742c S |
39 | (?:[^#]*?\#!/)? |
40 | (?: | |
41 | (?: | |
42 | video/video\.php| | |
43 | photo\.php| | |
44 | video\.php| | |
efbeddea | 45 | video/embed| |
29f7c58a | 46 | story\.php| |
47 | watch(?:/live)?/? | |
efbeddea | 48 | )\?(?:.*?)(?:v|video_id|story_fbid)=| |
9c7b509b | 49 | [^/]+/videos/(?:[^/]+/)?| |
e738e433 | 50 | [^/]+/posts/| |
29f7c58a | 51 | groups/[^/]+/permalink/| |
52 | watchparty/ | |
2e6e742c S |
53 | )| |
54 | facebook: | |
55 | ) | |
56 | (?P<id>[0-9]+) | |
57 | ''' | |
67874aef JMF |
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' | |
9eae41dd | 60 | _NETRC_MACHINE = 'facebook' |
cb3bb2cf | 61 | IE_NAME = 'facebook' |
0803753f | 62 | |
9c7b509b | 63 | _VIDEO_PAGE_TEMPLATE = 'https://www.facebook.com/video/video.php?v=%s' |
0df514f0 | 64 | _VIDEO_PAGE_TAHOE_TEMPLATE = 'https://www.facebook.com/video/tahoe/async/%s/?chain=true&isvideo=true&payloadtype=primary' |
9c7b509b | 65 | |
60ac04e5 | 66 | _TESTS = [{ |
50317dbb PH |
67 | 'url': 'https://www.facebook.com/video.php?v=637842556329505&fref=nf', |
68 | 'md5': '6a40d33c0eccbb1af76cf0485a052659', | |
cb3bb2cf | 69 | 'info_dict': { |
50317dbb | 70 | 'id': '637842556329505', |
cb3bb2cf | 71 | 'ext': 'mp4', |
5e4f0619 | 72 | 'title': 're:Did you know Kei Nishikori is the first Asian man to ever reach a Grand Slam', |
67b8a28a | 73 | 'uploader': 'Tennis on Facebook', |
196c6ba0 S |
74 | 'upload_date': '20140908', |
75 | 'timestamp': 1410199200, | |
01c742ec YCH |
76 | }, |
77 | 'skip': 'Requires logging in', | |
a020a0dc | 78 | }, { |
29f7c58a | 79 | # data.video |
a020a0dc PH |
80 | 'url': 'https://www.facebook.com/video.php?v=274175099429670', |
81 | 'info_dict': { | |
82 | 'id': '274175099429670', | |
83 | 'ext': 'mp4', | |
a181cd0c | 84 | 'title': 'Asif Nawab Butt', |
85 | 'description': 'Asif Nawab Butt', | |
67b8a28a | 86 | 'uploader': 'Asif Nawab Butt', |
196c6ba0 S |
87 | 'upload_date': '20140506', |
88 | 'timestamp': 1399398998, | |
01c742ec | 89 | 'thumbnail': r're:^https?://.*', |
db3ca364 YCH |
90 | }, |
91 | 'expected_warnings': [ | |
92 | 'title' | |
93 | ] | |
0803753f YCH |
94 | }, { |
95 | 'note': 'Video with DASH manifest', | |
96 | 'url': 'https://www.facebook.com/video.php?v=957955867617029', | |
196c6ba0 | 97 | 'md5': 'b2c28d528273b323abe5c6ab59f0f030', |
0803753f YCH |
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', | |
196c6ba0 S |
103 | 'upload_date': '20160110', |
104 | 'timestamp': 1452431627, | |
0803753f | 105 | }, |
01c742ec | 106 | 'skip': 'Requires logging in', |
9c7b509b YCH |
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', | |
d9ee2e5c YCH |
115 | }, |
116 | 'skip': 'Video gone', | |
98801241 YCH |
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 | }, | |
d9ee2e5c | 126 | 'skip': 'Video gone', |
5080cbf9 YCH |
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', | |
01c742ec YCH |
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', | |
5080cbf9 | 139 | }, |
a181cd0c | 140 | 'skip': 'Gif on giphy.com gone', |
d9ee2e5c YCH |
141 | }, { |
142 | # have 1080P, but only up to 720p in swf params | |
29f7c58a | 143 | # data.video.story.attachments[].media |
d9ee2e5c | 144 | 'url': 'https://www.facebook.com/cnn/videos/10155529876156509/', |
a181cd0c | 145 | 'md5': '3f3798adb2b73423263e59376f1f5eb7', |
d9ee2e5c YCH |
146 | 'info_dict': { |
147 | 'id': '10155529876156509', | |
148 | 'ext': 'mp4', | |
a181cd0c | 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', | |
d9ee2e5c YCH |
151 | 'timestamp': 1477818095, |
152 | 'upload_date': '20161030', | |
153 | 'uploader': 'CNN', | |
01c742ec | 154 | 'thumbnail': r're:^https?://.*', |
11330f51 | 155 | 'view_count': int, |
d9ee2e5c | 156 | }, |
78ef214d S |
157 | }, { |
158 | # bigPipe.onPageletArrive ... onPageletArrive pagelet_group_mall | |
29f7c58a | 159 | # data.node.comet_sections.content.story.attachments[].style_type_renderer.attachment.media |
78ef214d S |
160 | 'url': 'https://www.facebook.com/yaroslav.korpan/videos/1417995061575415/', |
161 | 'info_dict': { | |
162 | 'id': '1417995061575415', | |
163 | 'ext': 'mp4', | |
a181cd0c | 164 | 'title': 'Yaroslav Korpan - Довгоочікуване відео', |
165 | 'description': 'Довгоочікуване відео', | |
166 | 'timestamp': 1486648771, | |
78ef214d S |
167 | 'upload_date': '20170209', |
168 | 'uploader': 'Yaroslav Korpan', | |
a181cd0c | 169 | 'uploader_id': '100000948048708', |
78ef214d S |
170 | }, |
171 | 'params': { | |
172 | 'skip_download': True, | |
173 | }, | |
71cdd756 | 174 | }, { |
a181cd0c | 175 | # FIXME |
71cdd756 S |
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', | |
01c742ec | 184 | 'thumbnail': r're:^https?://.*', |
71cdd756 S |
185 | }, |
186 | 'params': { | |
187 | 'skip_download': True, | |
188 | }, | |
189 | }, { | |
29f7c58a | 190 | # data.node.comet_sections.content.story.attachments[].style_type_renderer.attachment.media |
71cdd756 S |
191 | 'url': 'https://www.facebook.com/groups/1024490957622648/permalink/1396382447100162/', |
192 | 'info_dict': { | |
a181cd0c | 193 | 'id': '202882990186699', |
71cdd756 | 194 | 'ext': 'mp4', |
a181cd0c | 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, | |
71cdd756 S |
198 | 'upload_date': '20170202', |
199 | 'uploader': 'Elisabeth Ahtn', | |
a181cd0c | 200 | 'uploader_id': '100013949973717', |
71cdd756 S |
201 | }, |
202 | 'params': { | |
203 | 'skip_download': True, | |
204 | }, | |
60ac04e5 PH |
205 | }, { |
206 | 'url': 'https://www.facebook.com/video.php?v=10204634152394104', | |
207 | 'only_matching': True, | |
c6256697 YCH |
208 | }, { |
209 | 'url': 'https://www.facebook.com/amogood/videos/1618742068337349/?fref=nf', | |
210 | 'only_matching': True, | |
53faa3ca | 211 | }, { |
29f7c58a | 212 | # data.mediaset.currMedia.edges |
53faa3ca YCH |
213 | 'url': 'https://www.facebook.com/ChristyClarkForBC/videos/vb.22819070941/10153870694020942/?type=2&theater', |
214 | 'only_matching': True, | |
2e6e742c | 215 | }, { |
29f7c58a | 216 | # data.video.story.attachments[].media |
2e6e742c S |
217 | 'url': 'facebook:544765982287235', |
218 | 'only_matching': True, | |
e738e433 | 219 | }, { |
29f7c58a | 220 | # data.node.comet_sections.content.story.attachments[].style_type_renderer.attachment.media |
e738e433 YCH |
221 | 'url': 'https://www.facebook.com/groups/164828000315060/permalink/764967300301124/', |
222 | 'only_matching': True, | |
b4a131e1 | 223 | }, { |
29f7c58a | 224 | # data.video.creation_story.attachments[].media |
b4a131e1 S |
225 | 'url': 'https://zh-hk.facebook.com/peoplespower/videos/1135894589806027/', |
226 | 'only_matching': True, | |
30918999 | 227 | }, { |
29f7c58a | 228 | # data.video |
61bfacb2 | 229 | 'url': 'https://www.facebookwkhpilnemxj7asaniu7vnjjbiltxjqhye3mhbshg7kx5tfyd.onion/video.php?v=274175099429670', |
30918999 | 230 | 'only_matching': True, |
66bf351f S |
231 | }, { |
232 | # no title | |
233 | 'url': 'https://www.facebook.com/onlycleverentertainment/videos/1947995502095005/', | |
234 | 'only_matching': True, | |
9d082e7c | 235 | }, { |
29f7c58a | 236 | # data.video |
9d082e7c NR |
237 | 'url': 'https://www.facebook.com/WatchESLOne/videos/359649331226507/', |
238 | 'info_dict': { | |
239 | 'id': '359649331226507', | |
240 | 'ext': 'mp4', | |
a181cd0c | 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', | |
9d082e7c | 245 | 'uploader': 'ESL One Dota 2', |
a181cd0c | 246 | 'uploader_id': '234218833769558', |
9d082e7c NR |
247 | }, |
248 | 'params': { | |
249 | 'skip_download': True, | |
250 | }, | |
29f7c58a | 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 | }, { | |
a181cd0c | 263 | # FIXME: https://github.com/yt-dlp/yt-dlp/issues/542 |
29f7c58a | 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 | }, | |
a181cd0c | 294 | 'skip': 'No video', |
29f7c58a | 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', | |
60ac04e5 | 306 | }] |
29f7c58a | 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 | } | |
9eae41dd | 311 | |
fd6ca382 | 312 | @staticmethod |
0646e34c S |
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')) | |
fd6ca382 YCH |
319 | # Facebook API embed |
320 | # see https://developers.facebook.com/docs/plugins/embedded-video-player | |
0646e34c | 321 | for mobj in re.finditer(r'''(?x)<div[^>]+ |
369bb062 | 322 | class=(?P<q1>[\'"])[^\'"]*\bfb-(?:video|post)\b[^\'"]*(?P=q1)[^>]+ |
0646e34c S |
323 | data-href=(?P<q2>[\'"])(?P<url>(?:https?:)?//(?:www\.)?facebook.com/.+?)(?P=q2)''', webpage): |
324 | urls.append(mobj.group('url')) | |
325 | return urls | |
fd6ca382 | 326 | |
67874aef | 327 | def _login(self): |
68217024 | 328 | useremail, password = self._get_login_info() |
9eae41dd PH |
329 | if useremail is None: |
330 | return | |
331 | ||
5c2266df | 332 | login_page_req = sanitized_Request(self._LOGIN_URL) |
c1f49e16 | 333 | self._set_cookie('facebook.com', 'locale', 'en_US') |
b74fa8cd | 334 | login_page = self._download_webpage(login_page_req, None, |
9e1a5b84 JW |
335 | note='Downloading login page', |
336 | errnote='Unable to download login page') | |
b37b9450 | 337 | lsd = self._search_regex( |
d0ff8384 | 338 | r'<input type="hidden" name="lsd" value="([^"]*)"', |
b37b9450 | 339 | login_page, 'lsd') |
cb3bb2cf | 340 | lgnrnd = self._search_regex(r'name="lgnrnd" value="([^"]*?)"', login_page, 'lgnrnd') |
67874aef | 341 | |
9eae41dd PH |
342 | login_form = { |
343 | 'email': useremail, | |
344 | 'pass': password, | |
67874aef JMF |
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', | |
b74e86f4 | 352 | } |
5c2266df | 353 | request = sanitized_Request(self._LOGIN_URL, urlencode_postdata(login_form)) |
67874aef | 354 | request.add_header('Content-Type', 'application/x-www-form-urlencoded') |
9eae41dd | 355 | try: |
b74fa8cd | 356 | login_results = self._download_webpage(request, None, |
9e1a5b84 | 357 | note='Logging in', errnote='unable to fetch login page') |
9eae41dd | 358 | if re.search(r'<form(.*)name="login"(.*)</form>', login_results) is not None: |
9f66931e S |
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) | |
6a39ee13 | 364 | self.report_warning('unable to log in: bad username/password, or exceeded login rate limit (~3/min). Check credentials or wait.') |
9eae41dd | 365 | return |
67874aef | 366 | |
c1f49e16 S |
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 | ||
67874aef | 375 | check_form = { |
c1f49e16 S |
376 | 'fb_dtsg': fb_dtsg, |
377 | 'h': h, | |
67874aef | 378 | 'name_action_selected': 'dont_save', |
67874aef | 379 | } |
5c2266df | 380 | check_req = sanitized_Request(self._CHECKPOINT_URL, urlencode_postdata(check_form)) |
67874aef | 381 | check_req.add_header('Content-Type', 'application/x-www-form-urlencoded') |
b74fa8cd | 382 | check_response = self._download_webpage(check_req, None, |
9e1a5b84 | 383 | note='Confirming login') |
67874aef | 384 | if re.search(r'id="checkpointSubmitButton"', check_response) is not None: |
6a39ee13 | 385 | self.report_warning('Unable to confirm login, you have to login in your browser and authorize the login.') |
3158150c | 386 | except network_exceptions as err: |
6a39ee13 | 387 | self.report_warning('unable to log in: %s' % error_to_compat_str(err)) |
9eae41dd PH |
388 | return |
389 | ||
67874aef JMF |
390 | def _real_initialize(self): |
391 | self._login() | |
392 | ||
29f7c58a | 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) | |
9eae41dd | 396 | |
a181cd0c | 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 | ||
c1406299 YCH |
447 | video_data = None |
448 | ||
b83ef507 | 449 | def extract_video_data(instances): |
29f7c58a | 450 | video_data = [] |
b83ef507 | 451 | for item in instances: |
29f7c58a | 452 | if try_get(item, lambda x: x[1][0]) == 'VideoConfig': |
b83ef507 | 453 | video_item = item[2][0] |
71cdd756 | 454 | if video_item.get('video_id'): |
29f7c58a | 455 | video_data.append(video_item['videoData']) |
456 | return video_data | |
b83ef507 | 457 | |
d9ee2e5c | 458 | server_js_data = self._parse_json(self._search_regex( |
29f7c58a | 459 | [r'handleServerJS\(({.+})(?:\);|,")', r'\bs\.handle\(({.+?})\);'], |
460 | webpage, 'server js data', default='{}'), video_id, fatal=False) | |
b83ef507 S |
461 | |
462 | if server_js_data: | |
463 | video_data = extract_video_data(server_js_data.get('instances', [])) | |
464 | ||
9b89daef S |
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 | ||
29f7c58a | 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 | ||
8a2d9923 | 482 | self._sort_formats(formats, ('res', 'quality')) |
29f7c58a | 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 | ||
b83ef507 | 495 | if not video_data: |
29f7c58a | 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) | |
9b89daef | 500 | video_data = extract_from_jsmods_instances(server_js_data) |
c1406299 | 501 | |
9d082e7c | 502 | if not video_data: |
29f7c58a | 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 | ||
a181cd0c | 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) | |
29f7c58a | 588 | |
589 | if not video_data: | |
9b89daef S |
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) | |
46358f64 | 595 | elif any(p in webpage for p in ( |
596 | '>You must log in to continue', | |
597 | 'id="login_form"', | |
598 | 'id="loginbutton"')): | |
9b89daef S |
599 | self.raise_login_required() |
600 | ||
29f7c58a | 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: | |
9b89daef S |
638 | # Video info not in first request, do a secondary request using |
639 | # tahoe player specific URL | |
9d082e7c NR |
640 | tahoe_data = self._download_webpage( |
641 | self._VIDEO_PAGE_TAHOE_TEMPLATE % video_id, video_id, | |
642 | data=urlencode_postdata({ | |
9d082e7c | 643 | '__a': 1, |
9b89daef S |
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'), | |
631f93ee RA |
650 | 'fb_dtsg': self._search_regex( |
651 | r'"DTSGInitialData"\s*,\s*\[\]\s*,\s*{\s*"token"\s*:\s*"([^"]+)"', | |
652 | webpage, 'dtsg token', default=''), | |
9d082e7c NR |
653 | }), |
654 | headers={ | |
655 | 'Content-Type': 'application/x-www-form-urlencoded', | |
656 | }) | |
9b89daef S |
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) | |
9d082e7c | 663 | |
c1406299 | 664 | if not video_data: |
9b89daef | 665 | raise ExtractorError('Cannot parse data') |
ffdf972b | 666 | |
29f7c58a | 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 | ||
ffdf972b | 678 | formats = [] |
29f7c58a | 679 | subtitles = {} |
d9ee2e5c YCH |
680 | for f in video_data: |
681 | format_id = f['stream_type'] | |
ca74c90b SC |
682 | if f and isinstance(f, dict): |
683 | f = [f] | |
44d6dd08 S |
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: | |
8a2d9923 | 690 | preference = -10 if format_id == 'progressive' else -1 |
c24883a1 YCH |
691 | if quality == 'hd': |
692 | preference += 5 | |
44d6dd08 S |
693 | formats.append({ |
694 | 'format_id': '%s_%s_%s' % (format_id, quality, src_type), | |
695 | 'url': src, | |
f983b875 | 696 | 'quality': preference, |
8a2d9923 | 697 | 'height': 720 if quality == 'hd' else None |
44d6dd08 | 698 | }) |
29f7c58a | 699 | extract_dash_manifest(f[0], formats) |
07154c79 RA |
700 | subtitles_src = f[0].get('subtitles_src') |
701 | if subtitles_src: | |
702 | subtitles.setdefault('en', []).append({'url': subtitles_src}) | |
9eae41dd | 703 | |
29f7c58a | 704 | process_formats(formats) |
0803753f | 705 | |
9c7b509b | 706 | info_dict = { |
9eae41dd | 707 | 'id': video_id, |
ffdf972b | 708 | 'formats': formats, |
07154c79 | 709 | 'subtitles': subtitles, |
9eae41dd | 710 | } |
a181cd0c | 711 | info_dict.update(extract_metadata(webpage)) |
de691a49 | 712 | |
29f7c58a | 713 | return info_dict |
de691a49 S |
714 | |
715 | def _real_extract(self, url): | |
9c7b509b YCH |
716 | video_id = self._match_id(url) |
717 | ||
718 | real_url = self._VIDEO_PAGE_TEMPLATE % video_id if url.startswith('facebook:') else url | |
29f7c58a | 719 | return self._extract_from_url(real_url, video_id) |
349fc5c7 S |
720 | |
721 | ||
722 | class FacebookPluginsVideoIE(InfoExtractor): | |
723 | _VALID_URL = r'https?://(?:[\w-]+\.)?facebook\.com/plugins/video\.php\?.*?\bhref=(?P<id>https.+)' | |
724 | ||
725 | _TESTS = [{ | |
726 | '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', | |
727 | 'md5': '5954e92cdfe51fe5782ae9bda7058a07', | |
728 | 'info_dict': { | |
729 | 'id': '10154383743583686', | |
730 | 'ext': 'mp4', | |
731 | 'title': 'What to do during the haze?', | |
732 | 'uploader': 'Gov.sg', | |
733 | 'upload_date': '20160826', | |
734 | 'timestamp': 1472184808, | |
735 | }, | |
736 | 'add_ie': [FacebookIE.ie_key()], | |
737 | }, { | |
738 | 'url': 'https://www.facebook.com/plugins/video.php?href=https%3A%2F%2Fwww.facebook.com%2Fvideo.php%3Fv%3D10204634152394104', | |
739 | 'only_matching': True, | |
740 | }, { | |
741 | 'url': 'https://www.facebook.com/plugins/video.php?href=https://www.facebook.com/gov.sg/videos/10154383743583686/&show_text=0&width=560', | |
742 | 'only_matching': True, | |
743 | }] | |
744 | ||
745 | def _real_extract(self, url): | |
746 | return self.url_result( | |
747 | compat_urllib_parse_unquote(self._match_id(url)), | |
748 | FacebookIE.ie_key()) |