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