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