statusmanager.js 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610
  1. /**
  2. * ownCloud
  3. *
  4. * @author Juan Pablo Villafañez Ramos <jvillafanez@owncloud.com>
  5. * @author Jesus Macias Portela <jesus@owncloud.com>
  6. * @copyright (C) 2014 ownCloud, Inc.
  7. *
  8. * This file is licensed under the Affero General Public License version 3
  9. * or later.
  10. *
  11. * See the COPYING-README file.
  12. *
  13. */
  14. if (!OCA.External) {
  15. OCA.External = {};
  16. }
  17. if (!OCA.External.StatusManager) {
  18. OCA.External.StatusManager = {};
  19. }
  20. OCA.External.StatusManager = {
  21. mountStatus: null,
  22. mountPointList: null,
  23. /**
  24. * Function
  25. * @param {callback} afterCallback
  26. */
  27. getMountStatus: function (afterCallback) {
  28. var self = this;
  29. if (typeof afterCallback !== 'function' || self.isGetMountStatusRunning) {
  30. return;
  31. }
  32. if (self.mountStatus) {
  33. afterCallback(self.mountStatus);
  34. }
  35. },
  36. /**
  37. * Function Check mount point status from cache
  38. * @param {string} mount_point
  39. */
  40. getMountPointListElement: function (mount_point) {
  41. var element;
  42. $.each(this.mountPointList, function (key, value) {
  43. if (value.mount_point === mount_point) {
  44. element = value;
  45. return false;
  46. }
  47. });
  48. return element;
  49. },
  50. /**
  51. * Function Check mount point status from cache
  52. * @param {string} mount_point
  53. * @param {string} mount_point
  54. */
  55. getMountStatusForMount: function (mountData, afterCallback) {
  56. var self = this;
  57. if (typeof afterCallback !== 'function' || self.isGetMountStatusRunning) {
  58. return $.Deferred().resolve();
  59. }
  60. var defObj;
  61. if (self.mountStatus[mountData.mount_point]) {
  62. defObj = $.Deferred();
  63. afterCallback(mountData, self.mountStatus[mountData.mount_point]);
  64. defObj.resolve(); // not really useful, but it'll keep the same behaviour
  65. } else {
  66. defObj = $.ajax({
  67. type: 'GET',
  68. url: OC.webroot + '/index.php/apps/files_external/' + ((mountData.type === 'personal') ? 'userstorages' : 'userglobalstorages') + '/' + mountData.id,
  69. success: function (response) {
  70. if (response && response.status === 0) {
  71. self.mountStatus[mountData.mount_point] = response;
  72. } else {
  73. var statusCode = response.status ? response.status : 1;
  74. var statusMessage = response.statusMessage ? response.statusMessage : t('files_external', 'Empty response from the server')
  75. // failure response with error message
  76. self.mountStatus[mountData.mount_point] = {
  77. type: mountData.type,
  78. status: statusCode,
  79. id: mountData.id,
  80. error: statusMessage,
  81. userProvided: response.userProvided
  82. };
  83. }
  84. afterCallback(mountData, self.mountStatus[mountData.mount_point]);
  85. },
  86. error: function (jqxhr, state, error) {
  87. var message;
  88. if (mountData.location === 3) {
  89. // In this case the error is because mount point use Login credentials and don't exist in the session
  90. message = t('files_external', 'Couldn\'t access. Please logout and login to activate this mount point');
  91. } else {
  92. message = t('files_external', 'Couldn\'t get the information from the ownCloud server: {code} {type}', {
  93. code: jqxhr.status,
  94. type: error
  95. });
  96. }
  97. self.mountStatus[mountData.mount_point] = {
  98. type: mountData.type,
  99. status: 1,
  100. location: mountData.location,
  101. error: message
  102. };
  103. afterCallback(mountData, self.mountStatus[mountData.mount_point]);
  104. }
  105. });
  106. }
  107. return defObj;
  108. },
  109. /**
  110. * Function to get external mount point list from the files_external API
  111. * @param {function} afterCallback function to be executed
  112. */
  113. getMountPointList: function (afterCallback) {
  114. var self = this;
  115. if (typeof afterCallback !== 'function' || self.isGetMountPointListRunning) {
  116. return;
  117. }
  118. if (self.mountPointList) {
  119. afterCallback(self.mountPointList);
  120. } else {
  121. self.isGetMountPointListRunning = true;
  122. $.ajax({
  123. type: 'GET',
  124. url: OC.linkToOCS('apps/files_external/api/v1') + 'mounts?format=json',
  125. success: function (response) {
  126. self.mountPointList = [];
  127. _.each(response.ocs.data, function (mount) {
  128. var element = {};
  129. element.mount_point = mount.name;
  130. element.type = mount.scope;
  131. element.location = "";
  132. element.id = mount.id;
  133. element.backendText = mount.backend;
  134. element.backend = mount.class;
  135. self.mountPointList.push(element);
  136. });
  137. afterCallback(self.mountPointList);
  138. },
  139. error: function (jqxhr, state, error) {
  140. self.mountPointList = [];
  141. OC.Notification.showTemporary(t('files_external', 'Couldn\'t get the list of external mount points: {type}', {type: error}));
  142. },
  143. complete: function () {
  144. self.isGetMountPointListRunning = false;
  145. }
  146. });
  147. }
  148. },
  149. /**
  150. * Function to manage action when a mountpoint status = 1 (Errored). Show a dialog to be redirected to settings page.
  151. * @param {string} name MountPoint Name
  152. */
  153. manageMountPointError: function (name) {
  154. this.getMountStatus($.proxy(function (allMountStatus) {
  155. if (allMountStatus.hasOwnProperty(name) && allMountStatus[name].status > 0 && allMountStatus[name].status < 7) {
  156. var mountData = allMountStatus[name];
  157. if (mountData.type === "system") {
  158. if (mountData.userProvided) {
  159. // personal mount whit credentials problems
  160. this.showCredentialsDialog(name, mountData);
  161. } else {
  162. OC.dialogs.confirm(t('files_external', 'There was an error with message: ') + mountData.error + '. Do you want to review mount point config in admin settings page?', t('files_external', 'External mount error'), function (e) {
  163. if (e === true) {
  164. OC.redirect(OC.generateUrl('/settings/admin#files_external'));
  165. }
  166. });
  167. }
  168. } else {
  169. OC.dialogs.confirm(t('files_external', 'There was an error with message: ') + mountData.error + '. Do you want to review mount point config in personal settings page?', t('files_external', 'External mount error'), function (e) {
  170. if (e === true) {
  171. OC.redirect(OC.generateUrl('/settings/personal#' + t('files_external', 'external-storage')));
  172. }
  173. });
  174. }
  175. }
  176. }, this));
  177. },
  178. /**
  179. * Function to process a mount point in relation with their status, Called from Async Queue.
  180. * @param {object} mountData
  181. * @param {object} mountStatus
  182. */
  183. processMountStatusIndividual: function (mountData, mountStatus) {
  184. var mountPoint = mountData.mount_point;
  185. if (mountStatus.status > 0) {
  186. var trElement = FileList.findFileEl(OCA.External.StatusManager.Utils.jqSelEscape(mountPoint));
  187. var route = OCA.External.StatusManager.Utils.getIconRoute(trElement) + '-error';
  188. if (OCA.External.StatusManager.Utils.isCorrectViewAndRootFolder()) {
  189. OCA.External.StatusManager.Utils.showIconError(mountPoint, $.proxy(OCA.External.StatusManager.manageMountPointError, OCA.External.StatusManager), route);
  190. }
  191. return false;
  192. } else {
  193. if (OCA.External.StatusManager.Utils.isCorrectViewAndRootFolder()) {
  194. OCA.External.StatusManager.Utils.restoreFolder(mountPoint);
  195. OCA.External.StatusManager.Utils.toggleLink(mountPoint, true, true);
  196. }
  197. return true;
  198. }
  199. },
  200. /**
  201. * Function to process a mount point in relation with their status
  202. * @param {object} mountData
  203. * @param {object} mountStatus
  204. */
  205. processMountList: function (mountList) {
  206. var elementList = null;
  207. $.each(mountList, function (name, value) {
  208. var trElement = $('#fileList tr[data-file=\"' + OCA.External.StatusManager.Utils.jqSelEscape(value.mount_point) + '\"]'); //FileList.findFileEl(OCA.External.StatusManager.Utils.jqSelEscape(value.mount_point));
  209. trElement.attr('data-external-backend', value.backend);
  210. if (elementList) {
  211. elementList = elementList.add(trElement);
  212. } else {
  213. elementList = trElement;
  214. }
  215. });
  216. if (elementList instanceof $) {
  217. if (OCA.External.StatusManager.Utils.isCorrectViewAndRootFolder()) {
  218. // Put their custom icon
  219. OCA.External.StatusManager.Utils.changeFolderIcon(elementList);
  220. // Save default view
  221. OCA.External.StatusManager.Utils.storeDefaultFolderIconAndBgcolor(elementList);
  222. // Disable row until check status
  223. elementList.addClass('externalDisabledRow');
  224. OCA.External.StatusManager.Utils.toggleLink(elementList.find('a.name'), false, false);
  225. }
  226. }
  227. },
  228. /**
  229. * Function to process the whole mount point list in relation with their status (Async queue)
  230. */
  231. launchFullConnectivityCheckOneByOne: function () {
  232. var self = this;
  233. this.getMountPointList(function (list) {
  234. // check if we have a list first
  235. if (list === undefined && !self.emptyWarningShown) {
  236. self.emptyWarningShown = true;
  237. OC.Notification.showTemporary(t('files_external', 'Couldn\'t get the list of Windows network drive mount points: empty response from the server'));
  238. return;
  239. }
  240. if (list && list.length > 0) {
  241. self.processMountList(list);
  242. if (!self.mountStatus) {
  243. self.mountStatus = {};
  244. }
  245. var ajaxQueue = [];
  246. $.each(list, function (key, value) {
  247. var queueElement = {
  248. funcName: $.proxy(self.getMountStatusForMount, self),
  249. funcArgs: [value,
  250. $.proxy(self.processMountStatusIndividual, self)]
  251. };
  252. ajaxQueue.push(queueElement);
  253. });
  254. var rolQueue = new OCA.External.StatusManager.RollingQueue(ajaxQueue, 4, function () {
  255. if (!self.notificationHasShown) {
  256. var showNotification = false;
  257. $.each(self.mountStatus, function (key, value) {
  258. if (value.status === 1) {
  259. self.notificationHasShown = true;
  260. showNotification = true;
  261. }
  262. });
  263. if (showNotification) {
  264. OC.Notification.showTemporary(t('files_external', 'Some of the configured external mount points are not connected. Please click on the red row(s) for more information'));
  265. }
  266. }
  267. });
  268. rolQueue.runQueue();
  269. }
  270. });
  271. },
  272. /**
  273. * Function to process a mount point list in relation with their status (Async queue)
  274. * @param {object} mountListData
  275. * @param {boolean} recheck delete cached info and force api call to check mount point status
  276. */
  277. launchPartialConnectivityCheck: function (mountListData, recheck) {
  278. if (mountListData.length === 0) {
  279. return;
  280. }
  281. var self = this;
  282. var ajaxQueue = [];
  283. $.each(mountListData, function (key, value) {
  284. if (recheck && value.mount_point in self.mountStatus) {
  285. delete self.mountStatus[value.mount_point];
  286. }
  287. var queueElement = {
  288. funcName: $.proxy(self.getMountStatusForMount, self),
  289. funcArgs: [value,
  290. $.proxy(self.processMountStatusIndividual, self)]
  291. };
  292. ajaxQueue.push(queueElement);
  293. });
  294. new OCA.External.StatusManager.RollingQueue(ajaxQueue, 4).runQueue();
  295. },
  296. /**
  297. * Function to relaunch some mount point status check
  298. * @param {string} mountListNames
  299. * @param {boolean} recheck delete cached info and force api call to check mount point status
  300. */
  301. recheckConnectivityForMount: function (mountListNames, recheck) {
  302. if (mountListNames.length === 0) {
  303. return;
  304. }
  305. var self = this;
  306. var mountListData = [];
  307. if (!self.mountStatus) {
  308. self.mountStatus = {};
  309. }
  310. $.each(mountListNames, function (key, value) {
  311. var mountData = self.getMountPointListElement(value);
  312. if (mountData) {
  313. mountListData.push(mountData);
  314. }
  315. });
  316. // for all mounts in the list, delete the cached status values
  317. if (recheck) {
  318. $.each(mountListData, function (key, value) {
  319. if (value.mount_point in self.mountStatus) {
  320. delete self.mountStatus[value.mount_point];
  321. }
  322. });
  323. }
  324. self.processMountList(mountListData);
  325. self.launchPartialConnectivityCheck(mountListData, recheck);
  326. },
  327. credentialsDialogTemplate:
  328. '<div id="files_external_div_form"><div>' +
  329. '<div>{{credentials_text}}</div>' +
  330. '<form>' +
  331. '<input type="text" name="username" placeholder="{{placeholder_username}}"/>' +
  332. '<input type="password" name="password" placeholder="{{placeholder_password}}"/>' +
  333. '</form>' +
  334. '</div></div>',
  335. /**
  336. * Function to display custom dialog to enter credentials
  337. * @param mountPoint
  338. * @param mountData
  339. */
  340. showCredentialsDialog: function (mountPoint, mountData) {
  341. var template = Handlebars.compile(OCA.External.StatusManager.credentialsDialogTemplate);
  342. var dialog = $(template({
  343. credentials_text: t('files_external', 'Please enter the credentials for the {mount} mount', {
  344. 'mount': mountPoint
  345. }),
  346. placeholder_username: t('files_external', 'Username'),
  347. placeholder_password: t('files_external', 'Password')
  348. }));
  349. $('body').append(dialog);
  350. var apply = function () {
  351. var username = dialog.find('[name=username]').val();
  352. var password = dialog.find('[name=password]').val();
  353. var endpoint = OC.generateUrl('apps/files_external/userglobalstorages/{id}', {
  354. id: mountData.id
  355. });
  356. $('.oc-dialog-close').hide();
  357. $.ajax({
  358. type: 'PUT',
  359. url: endpoint,
  360. data: {
  361. backendOptions: {
  362. user: username,
  363. password: password
  364. }
  365. },
  366. success: function (data) {
  367. OC.Notification.showTemporary(t('files_external', 'Credentials saved'));
  368. dialog.ocdialog('close');
  369. /* Trigger status check again */
  370. OCA.External.StatusManager.recheckConnectivityForMount([OC.basename(data.mountPoint)], true);
  371. },
  372. error: function () {
  373. $('.oc-dialog-close').show();
  374. OC.Notification.showTemporary(t('files_external', 'Credentials saving failed'));
  375. }
  376. });
  377. return false;
  378. };
  379. var ocdialogParams = {
  380. modal: true,
  381. title: t('files_external', 'Credentials required'),
  382. buttons: [{
  383. text: t('files_external', 'Save'),
  384. click: apply,
  385. closeOnEscape: true
  386. }],
  387. closeOnExcape: true
  388. };
  389. dialog.ocdialog(ocdialogParams)
  390. .bind('ocdialogclose', function () {
  391. dialog.ocdialog('destroy').remove();
  392. });
  393. dialog.find('form').on('submit', apply);
  394. dialog.find('form input:first').focus();
  395. dialog.find('form input').keyup(function (e) {
  396. if ((e.which && e.which === 13) || (e.keyCode && e.keyCode === 13)) {
  397. $(e.target).closest('form').submit();
  398. return false;
  399. } else {
  400. return true;
  401. }
  402. });
  403. }
  404. };
  405. OCA.External.StatusManager.Utils = {
  406. showIconError: function (folder, clickAction, errorImageUrl) {
  407. var imageUrl = "url(" + errorImageUrl + ")";
  408. var trFolder = $('#fileList tr[data-file=\"' + OCA.External.StatusManager.Utils.jqSelEscape(folder) + '\"]'); //FileList.findFileEl(OCA.External.StatusManager.Utils.jqSelEscape(folder));
  409. this.changeFolderIcon(folder, imageUrl);
  410. this.toggleLink(folder, false, clickAction);
  411. trFolder.addClass('externalErroredRow');
  412. },
  413. /**
  414. * @param folder string with the folder or jQuery element pointing to the tr element
  415. */
  416. storeDefaultFolderIconAndBgcolor: function (folder) {
  417. var trFolder;
  418. if (folder instanceof $) {
  419. trFolder = folder;
  420. } else {
  421. trFolder = $('#fileList tr[data-file=\"' + OCA.External.StatusManager.Utils.jqSelEscape(folder) + '\"]'); //FileList.findFileEl(OCA.External.StatusManager.Utils.jqSelEscape(folder)); //$('#fileList tr[data-file=\"' + OCA.External.StatusManager.Utils.jqSelEscape(folder) + '\"]');
  422. }
  423. trFolder.each(function () {
  424. var thisElement = $(this);
  425. if (thisElement.data('oldbgcolor') === undefined) {
  426. thisElement.data('oldbgcolor', thisElement.css('background-color'));
  427. }
  428. });
  429. var icon = trFolder.find('td:first-child div.thumbnail');
  430. icon.each(function () {
  431. var thisElement = $(this);
  432. if (thisElement.data('oldImage') === undefined) {
  433. thisElement.data('oldImage', thisElement.css('background-image'));
  434. }
  435. });
  436. },
  437. /**
  438. * @param folder string with the folder or jQuery element pointing to the tr element
  439. */
  440. restoreFolder: function (folder) {
  441. var trFolder;
  442. if (folder instanceof $) {
  443. trFolder = folder;
  444. } else {
  445. // cant use here FileList.findFileEl(OCA.External.StatusManager.Utils.jqSelEscape(folder)); return incorrect instance of filelist
  446. trFolder = $('#fileList tr[data-file=\"' + OCA.External.StatusManager.Utils.jqSelEscape(folder) + '\"]');
  447. }
  448. trFolder.removeClass('externalErroredRow').removeClass('externalDisabledRow');
  449. tdChilds = trFolder.find("td:first-child div.thumbnail");
  450. tdChilds.each(function () {
  451. var thisElement = $(this);
  452. thisElement.css('background-image', thisElement.data('oldImage'));
  453. });
  454. },
  455. /**
  456. * @param folder string with the folder or jQuery element pointing to the first td element
  457. * of the tr matching the folder name
  458. */
  459. changeFolderIcon: function (filename) {
  460. var file;
  461. var route;
  462. if (filename instanceof $) {
  463. //trElementList
  464. $.each(filename, function (index) {
  465. route = OCA.External.StatusManager.Utils.getIconRoute($(this));
  466. $(this).attr("data-icon", route);
  467. $(this).find('td:first-child div.thumbnail').css('background-image', "url(" + route + ")").css('display', 'none').css('display', 'inline');
  468. });
  469. } else {
  470. file = $("#fileList tr[data-file=\"" + this.jqSelEscape(filename) + "\"] > td:first-child div.thumbnail");
  471. parentTr = file.parents('tr:first');
  472. route = OCA.External.StatusManager.Utils.getIconRoute(parentTr);
  473. parentTr.attr("data-icon", route);
  474. file.css('background-image', "url(" + route + ")").css('display', 'none').css('display', 'inline');
  475. }
  476. },
  477. /**
  478. * @param backend string with the name of the external storage backend
  479. * of the tr matching the folder name
  480. */
  481. getIconRoute: function (tr) {
  482. var icon = OC.imagePath('core', 'filetypes/folder-external');
  483. var backend = null;
  484. if (tr instanceof $) {
  485. backend = tr.attr('data-external-backend');
  486. }
  487. switch (backend) {
  488. case 'windows_network_drive':
  489. icon = OC.imagePath('windows_network_drive', 'folder-windows');
  490. break;
  491. case 'sharepoint':
  492. icon = OC.imagePath('sharepoint', 'folder-sharepoint');
  493. break;
  494. }
  495. return icon;
  496. },
  497. toggleLink: function (filename, active, action) {
  498. var link;
  499. if (filename instanceof $) {
  500. link = filename;
  501. } else {
  502. link = $("#fileList tr[data-file=\"" + this.jqSelEscape(filename) + "\"] > td:first-child a.name");
  503. }
  504. if (active) {
  505. link.off('click.connectivity');
  506. OCA.Files.App.fileList.fileActions.display(link.parent(), true, OCA.Files.App.fileList);
  507. } else {
  508. link.find('.fileactions, .nametext .action').remove(); // from files/js/fileactions (display)
  509. link.off('click.connectivity');
  510. link.on('click.connectivity', function (e) {
  511. if (action && $.isFunction(action)) {
  512. action(filename);
  513. }
  514. e.preventDefault();
  515. return false;
  516. });
  517. }
  518. },
  519. isCorrectViewAndRootFolder: function () {
  520. // correct views = files & extstoragemounts
  521. if (OCA.Files.App.getActiveView() === 'files' || OCA.Files.App.getActiveView() === 'extstoragemounts') {
  522. return OCA.Files.App.getCurrentAppContainer().find('#dir').val() === '/';
  523. }
  524. return false;
  525. },
  526. /* escape a selector expression for jQuery */
  527. jqSelEscape: function (expression) {
  528. if (expression) {
  529. return expression.replace(/[!"#$%&'()*+,.\/:;<=>?@\[\\\]^`{|}~]/g, '\\$&');
  530. }
  531. return null;
  532. },
  533. /* Copied from http://stackoverflow.com/questions/2631001/javascript-test-for-existence-of-nested-object-key */
  534. checkNested: function (cobj /*, level1, level2, ... levelN*/) {
  535. var args = Array.prototype.slice.call(arguments),
  536. obj = args.shift();
  537. for (var i = 0; i < args.length; i++) {
  538. if (!obj || !obj.hasOwnProperty(args[i])) {
  539. return false;
  540. }
  541. obj = obj[args[i]];
  542. }
  543. return true;
  544. }
  545. };