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