statusmanager.js 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612
  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.Files_External) {
  16. OCA.Files_External = {};
  17. }
  18. if (!OCA.Files_External.StatusManager) {
  19. OCA.Files_External.StatusManager = {};
  20. }
  21. OCA.Files_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.getRootPath() + '/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.Files_External.StatusManager.Utils.jqSelEscape(mountPoint));
  191. var route = OCA.Files_External.StatusManager.Utils.getIconRoute(trElement) + '-error';
  192. if (OCA.Files_External.StatusManager.Utils.isCorrectViewAndRootFolder()) {
  193. OCA.Files_External.StatusManager.Utils.showIconError(mountPoint, $.proxy(OCA.Files_External.StatusManager.manageMountPointError, OCA.Files_External.StatusManager), route);
  194. }
  195. return false;
  196. } else {
  197. if (OCA.Files_External.StatusManager.Utils.isCorrectViewAndRootFolder()) {
  198. OCA.Files_External.StatusManager.Utils.restoreFolder(mountPoint);
  199. OCA.Files_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.Files_External.StatusManager.Utils.jqSelEscape(value.mount_point) + '\"]'); //FileList.findFileEl(OCA.Files_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.Files_External.StatusManager.Utils.isCorrectViewAndRootFolder()) {
  222. // Put their custom icon
  223. OCA.Files_External.StatusManager.Utils.changeFolderIcon(elementList);
  224. // Save default view
  225. OCA.Files_External.StatusManager.Utils.storeDefaultFolderIconAndBgcolor(elementList);
  226. // Disable row until check status
  227. elementList.addClass('externalDisabledRow');
  228. OCA.Files_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.Files_External.StatusManager.RollingQueue(ajaxQueue, 4, function () {
  261. if (!self.notificationHasShown) {
  262. $.each(self.mountStatus, function (key, value) {
  263. if (value.status === 1) {
  264. self.notificationHasShown = true;
  265. }
  266. });
  267. }
  268. });
  269. rolQueue.runQueue();
  270. }
  271. });
  272. },
  273. /**
  274. * Function to process a mount point list in relation with their status (Async queue)
  275. * @param {object} mountListData
  276. * @param {boolean} recheck delete cached info and force api call to check mount point status
  277. */
  278. launchPartialConnectivityCheck: function (mountListData, recheck) {
  279. if (mountListData.length === 0) {
  280. return;
  281. }
  282. var self = this;
  283. var ajaxQueue = [];
  284. $.each(mountListData, function (key, value) {
  285. if (recheck && value.mount_point in self.mountStatus) {
  286. delete self.mountStatus[value.mount_point];
  287. }
  288. var queueElement = {
  289. funcName: $.proxy(self.getMountStatusForMount, self),
  290. funcArgs: [value,
  291. $.proxy(self.processMountStatusIndividual, self)]
  292. };
  293. ajaxQueue.push(queueElement);
  294. });
  295. new OCA.Files_External.StatusManager.RollingQueue(ajaxQueue, 4).runQueue();
  296. },
  297. /**
  298. * Function to relaunch some mount point status check
  299. * @param {string} mountListNames
  300. * @param {boolean} recheck delete cached info and force api call to check mount point status
  301. */
  302. recheckConnectivityForMount: function (mountListNames, recheck) {
  303. if (mountListNames.length === 0) {
  304. return;
  305. }
  306. var self = this;
  307. var mountListData = [];
  308. if (!self.mountStatus) {
  309. self.mountStatus = {};
  310. }
  311. $.each(mountListNames, function (key, value) {
  312. var mountData = self.getMountPointListElement(value);
  313. if (mountData) {
  314. mountListData.push(mountData);
  315. }
  316. });
  317. // for all mounts in the list, delete the cached status values
  318. if (recheck) {
  319. $.each(mountListData, function (key, value) {
  320. if (value.mount_point in self.mountStatus) {
  321. delete self.mountStatus[value.mount_point];
  322. }
  323. });
  324. }
  325. self.processMountList(mountListData);
  326. self.launchPartialConnectivityCheck(mountListData, recheck);
  327. },
  328. credentialsDialogTemplate:
  329. '<div id="files_external_div_form"><div>' +
  330. '<div>{{credentials_text}}</div>' +
  331. '<form>' +
  332. '<input type="text" name="username" placeholder="{{placeholder_username}}"/>' +
  333. '<input type="password" name="password" placeholder="{{placeholder_password}}"/>' +
  334. '</form>' +
  335. '</div></div>',
  336. /**
  337. * Function to display custom dialog to enter credentials
  338. * @param mountPoint
  339. * @param mountData
  340. */
  341. showCredentialsDialog: function (mountPoint, mountData) {
  342. var dialog = $(OCA.Files_External.Templates.credentialsDialog({
  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.show(t('files_external', 'Credentials saved'), {type: 'error'});
  368. dialog.ocdialog('close');
  369. /* Trigger status check again */
  370. OCA.Files_External.StatusManager.recheckConnectivityForMount([OC.basename(data.mountPoint)], true);
  371. },
  372. error: function () {
  373. $('.oc-dialog-close').show();
  374. OC.Notification.show(t('files_external', 'Credentials saving failed'), {type: 'error'});
  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.Files_External.StatusManager.Utils = {
  406. showIconError: function (folder, clickAction, errorImageUrl) {
  407. var imageUrl = "url(" + errorImageUrl + ")";
  408. var trFolder = $('#fileList tr[data-file=\"' + OCA.Files_External.StatusManager.Utils.jqSelEscape(folder) + '\"]'); //FileList.findFileEl(OCA.Files_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.Files_External.StatusManager.Utils.jqSelEscape(folder) + '\"]'); //FileList.findFileEl(OCA.Files_External.StatusManager.Utils.jqSelEscape(folder)); //$('#fileList tr[data-file=\"' + OCA.Files_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.filename 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. // can't use here FileList.findFileEl(OCA.Files_External.StatusManager.Utils.jqSelEscape(folder)); return incorrect instance of filelist
  446. trFolder = $('#fileList tr[data-file=\"' + OCA.Files_External.StatusManager.Utils.jqSelEscape(folder) + '\"]');
  447. }
  448. trFolder.removeClass('externalErroredRow').removeClass('externalDisabledRow');
  449. var tdChilds = trFolder.find("td.filename 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.Files_External.StatusManager.Utils.getIconRoute($(this));
  466. $(this).attr("data-icon", route);
  467. $(this).find('td.filename 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.filename div.thumbnail");
  471. var parentTr = file.parents('tr:first');
  472. route = OCA.Files_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. if (OCA.Theming) {
  483. var icon = OC.generateUrl('/apps/theming/img/core/filetypes/folder-external.svg?v=' + OCA.Theming.cacheBuster);
  484. } else {
  485. var icon = OC.imagePath('core', 'filetypes/folder-external');
  486. }
  487. var backend = null;
  488. if (tr instanceof $) {
  489. backend = tr.attr('data-external-backend');
  490. }
  491. switch (backend) {
  492. case 'windows_network_drive':
  493. icon = OC.imagePath('windows_network_drive', 'folder-windows');
  494. break;
  495. }
  496. return icon;
  497. },
  498. toggleLink: function (filename, active, action) {
  499. var link;
  500. if (filename instanceof $) {
  501. link = filename;
  502. } else {
  503. link = $("#fileList tr[data-file=\"" + this.jqSelEscape(filename) + "\"] > td.filename a.name");
  504. }
  505. if (active) {
  506. link.off('click.connectivity');
  507. OCA.Files.App.fileList.fileActions.display(link.parent(), true, OCA.Files.App.fileList);
  508. } else {
  509. link.find('.fileactions, .nametext .action').remove(); // from files/js/fileactions (display)
  510. link.off('click.connectivity');
  511. link.on('click.connectivity', function (e) {
  512. if (action && $.isFunction(action)) {
  513. action(filename);
  514. }
  515. e.preventDefault();
  516. return false;
  517. });
  518. }
  519. },
  520. isCorrectViewAndRootFolder: function () {
  521. // correct views = files & extstoragemounts
  522. if (OCA.Files.App.getActiveView() === 'files' || OCA.Files.App.getActiveView() === 'extstoragemounts') {
  523. return OCA.Files.App.getCurrentAppContainer().find('#dir').val() === '/';
  524. }
  525. return false;
  526. },
  527. /* escape a selector expression for jQuery */
  528. jqSelEscape: function (expression) {
  529. if (expression) {
  530. return expression.replace(/[!"#$%&'()*+,.\/:;<=>?@\[\\\]^`{|}~]/g, '\\$&');
  531. }
  532. return null;
  533. },
  534. /* Copied from http://stackoverflow.com/questions/2631001/javascript-test-for-existence-of-nested-object-key */
  535. checkNested: function (cobj /*, level1, level2, ... levelN*/) {
  536. var args = Array.prototype.slice.call(arguments),
  537. obj = args.shift();
  538. for (var i = 0; i < args.length; i++) {
  539. if (!obj || !obj.hasOwnProperty(args[i])) {
  540. return false;
  541. }
  542. obj = obj[args[i]];
  543. }
  544. return true;
  545. }
  546. };