logo

youtube-dl

[mirror] Download/Watch videos from video hostersgit clone https://hacktivis.me/git/mirror/youtube-dl.git

facebook.py (30183B)


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