1
0

statusmanager.js 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613
  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. authMechanism: response.authMechanism,
  85. canEdit: response.can_edit,
  86. };
  87. }
  88. afterCallback(mountData, self.mountStatus[mountData.mount_point]);
  89. },
  90. error: function (jqxhr, state, error) {
  91. var message;
  92. if (mountData.location === 3) {
  93. // In this case the error is because mount point use Login credentials and don't exist in the session
  94. message = t('files_external', 'Couldn\'t access. Please log out and in again to activate this mount point');
  95. } else {
  96. message = t('files_external', 'Couldn\'t get the information from the remote server: {code} {type}', {
  97. code: jqxhr.status,
  98. type: error
  99. });
  100. }
  101. self.mountStatus[mountData.mount_point] = {
  102. type: mountData.type,
  103. status: 1,
  104. location: mountData.location,
  105. error: message
  106. };
  107. afterCallback(mountData, self.mountStatus[mountData.mount_point]);
  108. }
  109. });
  110. }
  111. return defObj;
  112. },
  113. /**
  114. * Function to get external mount point list from the files_external API
  115. * @param {Function} afterCallback function to be executed
  116. */
  117. getMountPointList: function (afterCallback) {
  118. var self = this;
  119. if (typeof afterCallback !== 'function' || self.isGetMountPointListRunning) {
  120. return;
  121. }
  122. if (self.mountPointList) {
  123. afterCallback(self.mountPointList);
  124. } else {
  125. self.isGetMountPointListRunning = true;
  126. $.ajax({
  127. type: 'GET',
  128. url: OC.linkToOCS('apps/files_external/api/v1') + 'mounts?format=json',
  129. success: function (response) {
  130. self.mountPointList = [];
  131. _.each(response.ocs.data, function (mount) {
  132. var element = {};
  133. element.mount_point = mount.name;
  134. element.type = mount.scope;
  135. element.location = "";
  136. element.id = mount.id;
  137. element.backendText = mount.backend;
  138. element.backend = mount.class;
  139. self.mountPointList.push(element);
  140. });
  141. afterCallback(self.mountPointList);
  142. },
  143. error: function (jqxhr, state, error) {
  144. self.mountPointList = [];
  145. OC.Notification.show(t('files_external', 'Couldn\'t get the list of external mount points: {type}',
  146. {type: error}), {type: 'error'}
  147. );
  148. },
  149. complete: function () {
  150. self.isGetMountPointListRunning = false;
  151. }
  152. });
  153. }
  154. },
  155. /**
  156. * Function to manage action when a mountpoint status = 1 (Errored). Show a dialog to be redirected to settings page.
  157. * @param {string} name MountPoint Name
  158. */
  159. manageMountPointError: function (name) {
  160. this.getMountStatus($.proxy(function (allMountStatus) {
  161. if (allMountStatus.hasOwnProperty(name) && allMountStatus[name].status > 0 && allMountStatus[name].status < 7) {
  162. var mountData = allMountStatus[name];
  163. if (mountData.type === "system") {
  164. if (mountData.userProvided || mountData.authMechanism === 'password::global::user') {
  165. // personal mount whit credentials problems
  166. this.showCredentialsDialog(name, mountData);
  167. } else if (mountData.canEdit) {
  168. 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) {
  169. if (e === true) {
  170. OC.redirect(OC.generateUrl('/settings/admin/externalstorages'));
  171. }
  172. });
  173. } else {
  174. OC.dialogs.info(t('files_external', 'There was an error with message: ') + mountData.error + '. Please contact your system administrator.', t('files_external', 'External mount error'), () => {});
  175. }
  176. } else {
  177. 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) {
  178. if (e === true) {
  179. OC.redirect(OC.generateUrl('/settings/personal#' + t('files_external', 'external-storage')));
  180. }
  181. });
  182. }
  183. }
  184. }, this));
  185. },
  186. /**
  187. * Function to process a mount point in relation with their status, Called from Async Queue.
  188. * @param {object} mountData
  189. * @param {object} mountStatus
  190. */
  191. processMountStatusIndividual: function (mountData, mountStatus) {
  192. var mountPoint = mountData.mount_point;
  193. if (mountStatus.status > 0) {
  194. var trElement = FileList.findFileEl(OCA.Files_External.StatusManager.Utils.jqSelEscape(mountPoint));
  195. var route = OCA.Files_External.StatusManager.Utils.getIconRoute(trElement) + '-error';
  196. if (OCA.Files_External.StatusManager.Utils.isCorrectViewAndRootFolder()) {
  197. OCA.Files_External.StatusManager.Utils.showIconError(mountPoint, $.proxy(OCA.Files_External.StatusManager.manageMountPointError, OCA.Files_External.StatusManager), route);
  198. }
  199. return false;
  200. } else {
  201. if (OCA.Files_External.StatusManager.Utils.isCorrectViewAndRootFolder()) {
  202. OCA.Files_External.StatusManager.Utils.restoreFolder(mountPoint);
  203. OCA.Files_External.StatusManager.Utils.toggleLink(mountPoint, true, true);
  204. }
  205. return true;
  206. }
  207. },
  208. /**
  209. * Function to process a mount point in relation with their status
  210. * @param {object} mountData
  211. * @param {object} mountStatus
  212. */
  213. processMountList: function (mountList) {
  214. var elementList = null;
  215. $.each(mountList, function (name, value) {
  216. var trElement = $('.files-fileList tr[data-file=\"' + OCA.Files_External.StatusManager.Utils.jqSelEscape(value.mount_point) + '\"]'); //FileList.findFileEl(OCA.Files_External.StatusManager.Utils.jqSelEscape(value.mount_point));
  217. trElement.attr('data-external-backend', value.backend);
  218. if (elementList) {
  219. elementList = elementList.add(trElement);
  220. } else {
  221. elementList = trElement;
  222. }
  223. });
  224. if (elementList instanceof $) {
  225. if (OCA.Files_External.StatusManager.Utils.isCorrectViewAndRootFolder()) {
  226. // Put their custom icon
  227. OCA.Files_External.StatusManager.Utils.changeFolderIcon(elementList);
  228. // Save default view
  229. OCA.Files_External.StatusManager.Utils.storeDefaultFolderIconAndBgcolor(elementList);
  230. OCA.Files_External.StatusManager.Utils.toggleLink(elementList.find('a.name'), false, false);
  231. }
  232. }
  233. },
  234. /**
  235. * Function to process the whole mount point list in relation with their status (Async queue)
  236. */
  237. launchFullConnectivityCheckOneByOne: function () {
  238. var self = this;
  239. this.getMountPointList(function (list) {
  240. // check if we have a list first
  241. if (list === undefined && !self.emptyWarningShown) {
  242. self.emptyWarningShown = true;
  243. OC.Notification.show(t('files_external', 'Couldn\'t fetch list of Windows network drive mount points: Empty response from server'),
  244. {type: 'error'}
  245. );
  246. return;
  247. }
  248. if (list && list.length > 0) {
  249. self.processMountList(list);
  250. if (!self.mountStatus) {
  251. self.mountStatus = {};
  252. }
  253. var ajaxQueue = [];
  254. $.each(list, function (key, value) {
  255. var queueElement = {
  256. funcName: $.proxy(self.getMountStatusForMount, self),
  257. funcArgs: [value,
  258. $.proxy(self.processMountStatusIndividual, self)]
  259. };
  260. ajaxQueue.push(queueElement);
  261. });
  262. var rolQueue = new OCA.Files_External.StatusManager.RollingQueue(ajaxQueue, 4, function () {
  263. if (!self.notificationHasShown) {
  264. $.each(self.mountStatus, function (key, value) {
  265. if (value.status === 1) {
  266. self.notificationHasShown = true;
  267. }
  268. });
  269. }
  270. });
  271. rolQueue.runQueue();
  272. }
  273. });
  274. },
  275. /**
  276. * Function to process a mount point list in relation with their status (Async queue)
  277. * @param {object} mountListData
  278. * @param {boolean} recheck delete cached info and force api call to check mount point status
  279. */
  280. launchPartialConnectivityCheck: function (mountListData, recheck) {
  281. if (mountListData.length === 0) {
  282. return;
  283. }
  284. var self = this;
  285. var ajaxQueue = [];
  286. $.each(mountListData, function (key, value) {
  287. if (recheck && value.mount_point in self.mountStatus) {
  288. delete self.mountStatus[value.mount_point];
  289. }
  290. var queueElement = {
  291. funcName: $.proxy(self.getMountStatusForMount, self),
  292. funcArgs: [value,
  293. $.proxy(self.processMountStatusIndividual, self)]
  294. };
  295. ajaxQueue.push(queueElement);
  296. });
  297. new OCA.Files_External.StatusManager.RollingQueue(ajaxQueue, 4).runQueue();
  298. },
  299. /**
  300. * Function to relaunch some mount point status check
  301. * @param {string} mountListNames
  302. * @param {boolean} recheck delete cached info and force api call to check mount point status
  303. */
  304. recheckConnectivityForMount: function (mountListNames, recheck) {
  305. if (mountListNames.length === 0) {
  306. return;
  307. }
  308. var self = this;
  309. var mountListData = [];
  310. if (!self.mountStatus) {
  311. self.mountStatus = {};
  312. }
  313. $.each(mountListNames, function (key, value) {
  314. var mountData = self.getMountPointListElement(value);
  315. if (mountData) {
  316. mountListData.push(mountData);
  317. }
  318. });
  319. // for all mounts in the list, delete the cached status values
  320. if (recheck) {
  321. $.each(mountListData, function (key, value) {
  322. if (value.mount_point in self.mountStatus) {
  323. delete self.mountStatus[value.mount_point];
  324. }
  325. });
  326. }
  327. self.processMountList(mountListData);
  328. self.launchPartialConnectivityCheck(mountListData, recheck);
  329. },
  330. credentialsDialogTemplate:
  331. '<div id="files_external_div_form"><div>' +
  332. '<div>{{credentials_text}}</div>' +
  333. '<form>' +
  334. '<input type="text" name="username" placeholder="{{placeholder_username}}"/>' +
  335. '<input type="password" name="password" placeholder="{{placeholder_password}}"/>' +
  336. '</form>' +
  337. '</div></div>',
  338. /**
  339. * Function to display custom dialog to enter credentials
  340. * @param {any} mountPoint -
  341. * @param {any} mountData -
  342. */
  343. showCredentialsDialog: function (mountPoint, mountData) {
  344. var dialog = $(OCA.Files_External.Templates.credentialsDialog({
  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.show(t('files_external', 'Credentials saved'), {type: 'success'});
  370. dialog.ocdialog('close');
  371. /* Trigger status check again */
  372. OCA.Files_External.StatusManager.recheckConnectivityForMount([OC.basename(data.mountPoint)], true);
  373. },
  374. error: function () {
  375. $('.oc-dialog-close').show();
  376. OC.Notification.show(t('files_external', 'Credentials saving failed'), {type: 'error'});
  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.Files_External.StatusManager.Utils = {
  408. showIconError: function (folder, clickAction, errorImageUrl) {
  409. var imageUrl = "url(" + errorImageUrl + ")";
  410. var trFolder = $('.files-fileList tr[data-file=\"' + OCA.Files_External.StatusManager.Utils.jqSelEscape(folder) + '\"]'); //FileList.findFileEl(OCA.Files_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 = $('.files-fileList tr[data-file=\"' + OCA.Files_External.StatusManager.Utils.jqSelEscape(folder) + '\"]'); //FileList.findFileEl(OCA.Files_External.StatusManager.Utils.jqSelEscape(folder)); //$('.files-fileList tr[data-file=\"' + OCA.Files_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.filename 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.Files_External.StatusManager.Utils.jqSelEscape(folder)); return incorrect instance of filelist
  448. trFolder = $('.files-fileList tr[data-file=\"' + OCA.Files_External.StatusManager.Utils.jqSelEscape(folder) + '\"]');
  449. }
  450. var tdChilds = trFolder.find("td.filename div.thumbnail");
  451. tdChilds.each(function () {
  452. var thisElement = $(this);
  453. thisElement.css('background-image', thisElement.data('oldImage'));
  454. });
  455. },
  456. /**
  457. * @param folder string with the folder or jQuery element pointing to the first td element
  458. * of the tr matching the folder name
  459. */
  460. changeFolderIcon: function (filename) {
  461. var file;
  462. var route;
  463. if (filename instanceof $) {
  464. //trElementList
  465. $.each(filename, function (index) {
  466. route = OCA.Files_External.StatusManager.Utils.getIconRoute($(this));
  467. $(this).attr("data-icon", route);
  468. $(this).find('td.filename div.thumbnail').css('background-image', "url(" + route + ")").css('display', 'none').css('display', 'inline');
  469. });
  470. } else {
  471. file = $(".files-fileList tr[data-file=\"" + this.jqSelEscape(filename) + "\"] > td.filename div.thumbnail");
  472. var parentTr = file.parents('tr:first');
  473. route = OCA.Files_External.StatusManager.Utils.getIconRoute(parentTr);
  474. parentTr.attr("data-icon", route);
  475. file.css('background-image', "url(" + route + ")").css('display', 'none').css('display', 'inline');
  476. }
  477. },
  478. /**
  479. * @param backend string with the name of the external storage backend
  480. * of the tr matching the folder name
  481. */
  482. getIconRoute: function (tr) {
  483. if (OCA.Theming) {
  484. var icon = OC.generateUrl('/apps/theming/img/core/filetypes/folder-external.svg?v=' + OCA.Theming.cacheBuster);
  485. } else {
  486. var icon = OC.imagePath('core', 'filetypes/folder-external');
  487. }
  488. var backend = null;
  489. if (tr instanceof $) {
  490. backend = tr.attr('data-external-backend');
  491. }
  492. switch (backend) {
  493. case 'windows_network_drive':
  494. icon = OC.imagePath('windows_network_drive', 'folder-windows');
  495. break;
  496. }
  497. return icon;
  498. },
  499. toggleLink: function (filename, active, action) {
  500. var link;
  501. if (filename instanceof $) {
  502. link = filename;
  503. } else {
  504. link = $(".files-fileList tr[data-file=\"" + this.jqSelEscape(filename) + "\"] > td.filename a.name");
  505. }
  506. if (active) {
  507. link.off('click.connectivity');
  508. OCA.Files.App.fileList.fileActions.display(link.parent(), true, OCA.Files.App.fileList);
  509. } else {
  510. link.find('.fileactions, .nametext .action').remove(); // from files/js/fileactions (display)
  511. link.off('click.connectivity');
  512. link.on('click.connectivity', function (e) {
  513. if (action && $.isFunction(action)) {
  514. action(filename);
  515. }
  516. e.preventDefault();
  517. return false;
  518. });
  519. }
  520. },
  521. isCorrectViewAndRootFolder: function () {
  522. // correct views = files & extstoragemounts
  523. if (OCA.Files.App.getActiveView() === 'files' || OCA.Files.App.getActiveView() === 'extstoragemounts') {
  524. return OCA.Files.App.currentFileList.getCurrentDirectory() === '/';
  525. }
  526. return false;
  527. },
  528. /* escape a selector expression for jQuery */
  529. jqSelEscape: function (expression) {
  530. if (expression) {
  531. return expression.replace(/[!"#$%&'()*+,.\/:;<=>?@\[\\\]^`{|}~]/g, '\\$&');
  532. }
  533. return null;
  534. },
  535. /* Copied from http://stackoverflow.com/questions/2631001/javascript-test-for-existence-of-nested-object-key */
  536. checkNested: function (cobj /*, level1, level2, ... levelN*/) {
  537. var args = Array.prototype.slice.call(arguments),
  538. obj = args.shift();
  539. for (var i = 0; i < args.length; i++) {
  540. if (!obj || !obj.hasOwnProperty(args[i])) {
  541. return false;
  542. }
  543. obj = obj[args[i]];
  544. }
  545. return true;
  546. }
  547. };