statusmanager.js 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620
  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 log out and in again 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.show(t('files_external', 'Couldn\'t get the list of external mount points: {type}',
  144. {type: error}), {type: 'error'}
  145. );
  146. },
  147. complete: function () {
  148. self.isGetMountPointListRunning = false;
  149. }
  150. });
  151. }
  152. },
  153. /**
  154. * Function to manage action when a mountpoint status = 1 (Errored). Show a dialog to be redirected to settings page.
  155. * @param {string} name MountPoint Name
  156. */
  157. manageMountPointError: function (name) {
  158. this.getMountStatus($.proxy(function (allMountStatus) {
  159. if (allMountStatus.hasOwnProperty(name) && allMountStatus[name].status > 0 && allMountStatus[name].status < 7) {
  160. var mountData = allMountStatus[name];
  161. if (mountData.type === "system") {
  162. if (mountData.userProvided) {
  163. // personal mount whit credentials problems
  164. this.showCredentialsDialog(name, mountData);
  165. } else {
  166. 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) {
  167. if (e === true) {
  168. OC.redirect(OC.generateUrl('/settings/admin/externalstorages'));
  169. }
  170. });
  171. }
  172. } else {
  173. 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) {
  174. if (e === true) {
  175. OC.redirect(OC.generateUrl('/settings/personal#' + t('files_external', 'external-storage')));
  176. }
  177. });
  178. }
  179. }
  180. }, this));
  181. },
  182. /**
  183. * Function to process a mount point in relation with their status, Called from Async Queue.
  184. * @param {object} mountData
  185. * @param {object} mountStatus
  186. */
  187. processMountStatusIndividual: function (mountData, mountStatus) {
  188. var mountPoint = mountData.mount_point;
  189. if (mountStatus.status > 0) {
  190. var trElement = FileList.findFileEl(OCA.External.StatusManager.Utils.jqSelEscape(mountPoint));
  191. var route = OCA.External.StatusManager.Utils.getIconRoute(trElement) + '-error';
  192. if (OCA.External.StatusManager.Utils.isCorrectViewAndRootFolder()) {
  193. OCA.External.StatusManager.Utils.showIconError(mountPoint, $.proxy(OCA.External.StatusManager.manageMountPointError, OCA.External.StatusManager), route);
  194. }
  195. return false;
  196. } else {
  197. if (OCA.External.StatusManager.Utils.isCorrectViewAndRootFolder()) {
  198. OCA.External.StatusManager.Utils.restoreFolder(mountPoint);
  199. OCA.External.StatusManager.Utils.toggleLink(mountPoint, true, true);
  200. }
  201. return true;
  202. }
  203. },
  204. /**
  205. * Function to process a mount point in relation with their status
  206. * @param {object} mountData
  207. * @param {object} mountStatus
  208. */
  209. processMountList: function (mountList) {
  210. var elementList = null;
  211. $.each(mountList, function (name, value) {
  212. var trElement = $('#fileList tr[data-file=\"' + OCA.External.StatusManager.Utils.jqSelEscape(value.mount_point) + '\"]'); //FileList.findFileEl(OCA.External.StatusManager.Utils.jqSelEscape(value.mount_point));
  213. trElement.attr('data-external-backend', value.backend);
  214. if (elementList) {
  215. elementList = elementList.add(trElement);
  216. } else {
  217. elementList = trElement;
  218. }
  219. });
  220. if (elementList instanceof $) {
  221. if (OCA.External.StatusManager.Utils.isCorrectViewAndRootFolder()) {
  222. // Put their custom icon
  223. OCA.External.StatusManager.Utils.changeFolderIcon(elementList);
  224. // Save default view
  225. OCA.External.StatusManager.Utils.storeDefaultFolderIconAndBgcolor(elementList);
  226. // Disable row until check status
  227. elementList.addClass('externalDisabledRow');
  228. OCA.External.StatusManager.Utils.toggleLink(elementList.find('a.name'), false, false);
  229. }
  230. }
  231. },
  232. /**
  233. * Function to process the whole mount point list in relation with their status (Async queue)
  234. */
  235. launchFullConnectivityCheckOneByOne: function () {
  236. var self = this;
  237. this.getMountPointList(function (list) {
  238. // check if we have a list first
  239. if (list === undefined && !self.emptyWarningShown) {
  240. self.emptyWarningShown = true;
  241. OC.Notification.show(t('files_external', 'Couldn\'t fetch list of Windows network drive mount points: Empty response from server'),
  242. {type: 'error'}
  243. );
  244. return;
  245. }
  246. if (list && list.length > 0) {
  247. self.processMountList(list);
  248. if (!self.mountStatus) {
  249. self.mountStatus = {};
  250. }
  251. var ajaxQueue = [];
  252. $.each(list, function (key, value) {
  253. var queueElement = {
  254. funcName: $.proxy(self.getMountStatusForMount, self),
  255. funcArgs: [value,
  256. $.proxy(self.processMountStatusIndividual, self)]
  257. };
  258. ajaxQueue.push(queueElement);
  259. });
  260. var rolQueue = new OCA.External.StatusManager.RollingQueue(ajaxQueue, 4, function () {
  261. if (!self.notificationHasShown) {
  262. var showNotification = false;
  263. $.each(self.mountStatus, function (key, value) {
  264. if (value.status === 1) {
  265. self.notificationHasShown = true;
  266. showNotification = true;
  267. }
  268. });
  269. if (showNotification) {
  270. OC.Notification.show(t('files_external', 'Some of the configured external mount points are not connected. Please click on the red row(s) for more information'),
  271. {type: 'error'}
  272. );
  273. }
  274. }
  275. });
  276. rolQueue.runQueue();
  277. }
  278. });
  279. },
  280. /**
  281. * Function to process a mount point list in relation with their status (Async queue)
  282. * @param {object} mountListData
  283. * @param {boolean} recheck delete cached info and force api call to check mount point status
  284. */
  285. launchPartialConnectivityCheck: function (mountListData, recheck) {
  286. if (mountListData.length === 0) {
  287. return;
  288. }
  289. var self = this;
  290. var ajaxQueue = [];
  291. $.each(mountListData, function (key, value) {
  292. if (recheck && value.mount_point in self.mountStatus) {
  293. delete self.mountStatus[value.mount_point];
  294. }
  295. var queueElement = {
  296. funcName: $.proxy(self.getMountStatusForMount, self),
  297. funcArgs: [value,
  298. $.proxy(self.processMountStatusIndividual, self)]
  299. };
  300. ajaxQueue.push(queueElement);
  301. });
  302. new OCA.External.StatusManager.RollingQueue(ajaxQueue, 4).runQueue();
  303. },
  304. /**
  305. * Function to relaunch some mount point status check
  306. * @param {string} mountListNames
  307. * @param {boolean} recheck delete cached info and force api call to check mount point status
  308. */
  309. recheckConnectivityForMount: function (mountListNames, recheck) {
  310. if (mountListNames.length === 0) {
  311. return;
  312. }
  313. var self = this;
  314. var mountListData = [];
  315. if (!self.mountStatus) {
  316. self.mountStatus = {};
  317. }
  318. $.each(mountListNames, function (key, value) {
  319. var mountData = self.getMountPointListElement(value);
  320. if (mountData) {
  321. mountListData.push(mountData);
  322. }
  323. });
  324. // for all mounts in the list, delete the cached status values
  325. if (recheck) {
  326. $.each(mountListData, function (key, value) {
  327. if (value.mount_point in self.mountStatus) {
  328. delete self.mountStatus[value.mount_point];
  329. }
  330. });
  331. }
  332. self.processMountList(mountListData);
  333. self.launchPartialConnectivityCheck(mountListData, recheck);
  334. },
  335. credentialsDialogTemplate:
  336. '<div id="files_external_div_form"><div>' +
  337. '<div>{{credentials_text}}</div>' +
  338. '<form>' +
  339. '<input type="text" name="username" placeholder="{{placeholder_username}}"/>' +
  340. '<input type="password" name="password" placeholder="{{placeholder_password}}"/>' +
  341. '</form>' +
  342. '</div></div>',
  343. /**
  344. * Function to display custom dialog to enter credentials
  345. * @param mountPoint
  346. * @param mountData
  347. */
  348. showCredentialsDialog: function (mountPoint, mountData) {
  349. var template = Handlebars.compile(OCA.External.StatusManager.credentialsDialogTemplate);
  350. var dialog = $(template({
  351. credentials_text: t('files_external', 'Please enter the credentials for the {mount} mount', {
  352. 'mount': mountPoint
  353. }),
  354. placeholder_username: t('files_external', 'Username'),
  355. placeholder_password: t('files_external', 'Password')
  356. }));
  357. $('body').append(dialog);
  358. var apply = function () {
  359. var username = dialog.find('[name=username]').val();
  360. var password = dialog.find('[name=password]').val();
  361. var endpoint = OC.generateUrl('apps/files_external/userglobalstorages/{id}', {
  362. id: mountData.id
  363. });
  364. $('.oc-dialog-close').hide();
  365. $.ajax({
  366. type: 'PUT',
  367. url: endpoint,
  368. data: {
  369. backendOptions: {
  370. user: username,
  371. password: password
  372. }
  373. },
  374. success: function (data) {
  375. OC.Notification.show(t('files_external', 'Credentials saved'), {type: 'error'});
  376. dialog.ocdialog('close');
  377. /* Trigger status check again */
  378. OCA.External.StatusManager.recheckConnectivityForMount([OC.basename(data.mountPoint)], true);
  379. },
  380. error: function () {
  381. $('.oc-dialog-close').show();
  382. OC.Notification.show(t('files_external', 'Credentials saving failed'), {type: 'error'});
  383. }
  384. });
  385. return false;
  386. };
  387. var ocdialogParams = {
  388. modal: true,
  389. title: t('files_external', 'Credentials required'),
  390. buttons: [{
  391. text: t('files_external', 'Save'),
  392. click: apply,
  393. closeOnEscape: true
  394. }],
  395. closeOnExcape: true
  396. };
  397. dialog.ocdialog(ocdialogParams)
  398. .bind('ocdialogclose', function () {
  399. dialog.ocdialog('destroy').remove();
  400. });
  401. dialog.find('form').on('submit', apply);
  402. dialog.find('form input:first').focus();
  403. dialog.find('form input').keyup(function (e) {
  404. if ((e.which && e.which === 13) || (e.keyCode && e.keyCode === 13)) {
  405. $(e.target).closest('form').submit();
  406. return false;
  407. } else {
  408. return true;
  409. }
  410. });
  411. }
  412. };
  413. OCA.External.StatusManager.Utils = {
  414. showIconError: function (folder, clickAction, errorImageUrl) {
  415. var imageUrl = "url(" + errorImageUrl + ")";
  416. var trFolder = $('#fileList tr[data-file=\"' + OCA.External.StatusManager.Utils.jqSelEscape(folder) + '\"]'); //FileList.findFileEl(OCA.External.StatusManager.Utils.jqSelEscape(folder));
  417. this.changeFolderIcon(folder, imageUrl);
  418. this.toggleLink(folder, false, clickAction);
  419. trFolder.addClass('externalErroredRow');
  420. },
  421. /**
  422. * @param folder string with the folder or jQuery element pointing to the tr element
  423. */
  424. storeDefaultFolderIconAndBgcolor: function (folder) {
  425. var trFolder;
  426. if (folder instanceof $) {
  427. trFolder = folder;
  428. } else {
  429. 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) + '\"]');
  430. }
  431. trFolder.each(function () {
  432. var thisElement = $(this);
  433. if (thisElement.data('oldbgcolor') === undefined) {
  434. thisElement.data('oldbgcolor', thisElement.css('background-color'));
  435. }
  436. });
  437. var icon = trFolder.find('td.filename div.thumbnail');
  438. icon.each(function () {
  439. var thisElement = $(this);
  440. if (thisElement.data('oldImage') === undefined) {
  441. thisElement.data('oldImage', thisElement.css('background-image'));
  442. }
  443. });
  444. },
  445. /**
  446. * @param folder string with the folder or jQuery element pointing to the tr element
  447. */
  448. restoreFolder: function (folder) {
  449. var trFolder;
  450. if (folder instanceof $) {
  451. trFolder = folder;
  452. } else {
  453. // can't use here FileList.findFileEl(OCA.External.StatusManager.Utils.jqSelEscape(folder)); return incorrect instance of filelist
  454. trFolder = $('#fileList tr[data-file=\"' + OCA.External.StatusManager.Utils.jqSelEscape(folder) + '\"]');
  455. }
  456. trFolder.removeClass('externalErroredRow').removeClass('externalDisabledRow');
  457. var tdChilds = trFolder.find("td.filename div.thumbnail");
  458. tdChilds.each(function () {
  459. var thisElement = $(this);
  460. thisElement.css('background-image', thisElement.data('oldImage'));
  461. });
  462. },
  463. /**
  464. * @param folder string with the folder or jQuery element pointing to the first td element
  465. * of the tr matching the folder name
  466. */
  467. changeFolderIcon: function (filename) {
  468. var file;
  469. var route;
  470. if (filename instanceof $) {
  471. //trElementList
  472. $.each(filename, function (index) {
  473. route = OCA.External.StatusManager.Utils.getIconRoute($(this));
  474. $(this).attr("data-icon", route);
  475. $(this).find('td.filename div.thumbnail').css('background-image', "url(" + route + ")").css('display', 'none').css('display', 'inline');
  476. });
  477. } else {
  478. file = $("#fileList tr[data-file=\"" + this.jqSelEscape(filename) + "\"] > td.filename div.thumbnail");
  479. var parentTr = file.parents('tr:first');
  480. route = OCA.External.StatusManager.Utils.getIconRoute(parentTr);
  481. parentTr.attr("data-icon", route);
  482. file.css('background-image', "url(" + route + ")").css('display', 'none').css('display', 'inline');
  483. }
  484. },
  485. /**
  486. * @param backend string with the name of the external storage backend
  487. * of the tr matching the folder name
  488. */
  489. getIconRoute: function (tr) {
  490. if (OCA.Theming) {
  491. var icon = OC.generateUrl('/apps/theming/img/core/filetypes/folder-external.svg?v=' + OCA.Theming.cacheBuster);
  492. } else {
  493. var icon = OC.imagePath('core', 'filetypes/folder-external');
  494. }
  495. var backend = null;
  496. if (tr instanceof $) {
  497. backend = tr.attr('data-external-backend');
  498. }
  499. switch (backend) {
  500. case 'windows_network_drive':
  501. icon = OC.imagePath('windows_network_drive', 'folder-windows');
  502. break;
  503. }
  504. return icon;
  505. },
  506. toggleLink: function (filename, active, action) {
  507. var link;
  508. if (filename instanceof $) {
  509. link = filename;
  510. } else {
  511. link = $("#fileList tr[data-file=\"" + this.jqSelEscape(filename) + "\"] > td.filename a.name");
  512. }
  513. if (active) {
  514. link.off('click.connectivity');
  515. OCA.Files.App.fileList.fileActions.display(link.parent(), true, OCA.Files.App.fileList);
  516. } else {
  517. link.find('.fileactions, .nametext .action').remove(); // from files/js/fileactions (display)
  518. link.off('click.connectivity');
  519. link.on('click.connectivity', function (e) {
  520. if (action && $.isFunction(action)) {
  521. action(filename);
  522. }
  523. e.preventDefault();
  524. return false;
  525. });
  526. }
  527. },
  528. isCorrectViewAndRootFolder: function () {
  529. // correct views = files & extstoragemounts
  530. if (OCA.Files.App.getActiveView() === 'files' || OCA.Files.App.getActiveView() === 'extstoragemounts') {
  531. return OCA.Files.App.getCurrentAppContainer().find('#dir').val() === '/';
  532. }
  533. return false;
  534. },
  535. /* escape a selector expression for jQuery */
  536. jqSelEscape: function (expression) {
  537. if (expression) {
  538. return expression.replace(/[!"#$%&'()*+,.\/:;<=>?@\[\\\]^`{|}~]/g, '\\$&');
  539. }
  540. return null;
  541. },
  542. /* Copied from http://stackoverflow.com/questions/2631001/javascript-test-for-existence-of-nested-object-key */
  543. checkNested: function (cobj /*, level1, level2, ... levelN*/) {
  544. var args = Array.prototype.slice.call(arguments),
  545. obj = args.shift();
  546. for (var i = 0; i < args.length; i++) {
  547. if (!obj || !obj.hasOwnProperty(args[i])) {
  548. return false;
  549. }
  550. obj = obj[args[i]];
  551. }
  552. return true;
  553. }
  554. };