statusmanager.js 19 KB

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