statusmanager.js 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601
  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. }
  261. });
  262. },
  263. /**
  264. * Function to process a mount point list in relation with their status (Async queue)
  265. * @param {object} mountListData
  266. * @param {boolean} recheck delete cached info and force api call to check mount point status
  267. */
  268. launchPartialConnectivityCheck: function (mountListData, recheck) {
  269. if (mountListData.length === 0) {
  270. return;
  271. }
  272. var self = this;
  273. var ajaxQueue = [];
  274. $.each(mountListData, function (key, value) {
  275. if (recheck && value.mount_point in self.mountStatus) {
  276. delete self.mountStatus[value.mount_point];
  277. }
  278. var queueElement = {
  279. funcName: $.proxy(self.getMountStatusForMount, self),
  280. funcArgs: [value,
  281. $.proxy(self.processMountStatusIndividual, self)]
  282. };
  283. ajaxQueue.push(queueElement);
  284. });
  285. new OCA.Files_External.StatusManager.RollingQueue(ajaxQueue, 4).runQueue();
  286. },
  287. /**
  288. * Function to relaunch some mount point status check
  289. * @param {string} mountListNames
  290. * @param {boolean} recheck delete cached info and force api call to check mount point status
  291. */
  292. recheckConnectivityForMount: function (mountListNames, recheck) {
  293. if (mountListNames.length === 0) {
  294. return;
  295. }
  296. var self = this;
  297. var mountListData = [];
  298. if (!self.mountStatus) {
  299. self.mountStatus = {};
  300. }
  301. $.each(mountListNames, function (key, value) {
  302. var mountData = self.getMountPointListElement(value);
  303. if (mountData) {
  304. mountListData.push(mountData);
  305. }
  306. });
  307. // for all mounts in the list, delete the cached status values
  308. if (recheck) {
  309. $.each(mountListData, function (key, value) {
  310. if (value.mount_point in self.mountStatus) {
  311. delete self.mountStatus[value.mount_point];
  312. }
  313. });
  314. }
  315. self.processMountList(mountListData);
  316. self.launchPartialConnectivityCheck(mountListData, recheck);
  317. },
  318. credentialsDialogTemplate:
  319. '<div id="files_external_div_form"><div>' +
  320. '<div>{{credentials_text}}</div>' +
  321. '<form>' +
  322. '<input type="text" name="username" placeholder="{{placeholder_username}}"/>' +
  323. '<input type="password" name="password" placeholder="{{placeholder_password}}"/>' +
  324. '</form>' +
  325. '</div></div>',
  326. /**
  327. * Function to display custom dialog to enter credentials
  328. * @param mountPoint
  329. * @param mountData
  330. */
  331. showCredentialsDialog: function (mountPoint, mountData) {
  332. var dialog = $(OCA.Files_External.Templates.credentialsDialog({
  333. credentials_text: t('files_external', 'Please enter the credentials for the {mount} mount', {
  334. 'mount': mountPoint
  335. }),
  336. placeholder_username: t('files_external', 'Username'),
  337. placeholder_password: t('files_external', 'Password')
  338. }));
  339. $('body').append(dialog);
  340. var apply = function () {
  341. var username = dialog.find('[name=username]').val();
  342. var password = dialog.find('[name=password]').val();
  343. var endpoint = OC.generateUrl('apps/files_external/userglobalstorages/{id}', {
  344. id: mountData.id
  345. });
  346. $('.oc-dialog-close').hide();
  347. $.ajax({
  348. type: 'PUT',
  349. url: endpoint,
  350. data: {
  351. backendOptions: {
  352. user: username,
  353. password: password
  354. }
  355. },
  356. success: function (data) {
  357. OC.Notification.show(t('files_external', 'Credentials saved'), {type: 'error'});
  358. dialog.ocdialog('close');
  359. /* Trigger status check again */
  360. OCA.Files_External.StatusManager.recheckConnectivityForMount([OC.basename(data.mountPoint)], true);
  361. },
  362. error: function () {
  363. $('.oc-dialog-close').show();
  364. OC.Notification.show(t('files_external', 'Credentials saving failed'), {type: 'error'});
  365. }
  366. });
  367. return false;
  368. };
  369. var ocdialogParams = {
  370. modal: true,
  371. title: t('files_external', 'Credentials required'),
  372. buttons: [{
  373. text: t('files_external', 'Save'),
  374. click: apply,
  375. closeOnEscape: true
  376. }],
  377. closeOnExcape: true
  378. };
  379. dialog.ocdialog(ocdialogParams)
  380. .bind('ocdialogclose', function () {
  381. dialog.ocdialog('destroy').remove();
  382. });
  383. dialog.find('form').on('submit', apply);
  384. dialog.find('form input:first').focus();
  385. dialog.find('form input').keyup(function (e) {
  386. if ((e.which && e.which === 13) || (e.keyCode && e.keyCode === 13)) {
  387. $(e.target).closest('form').submit();
  388. return false;
  389. } else {
  390. return true;
  391. }
  392. });
  393. }
  394. };
  395. OCA.Files_External.StatusManager.Utils = {
  396. showIconError: function (folder, clickAction, errorImageUrl) {
  397. var imageUrl = "url(" + errorImageUrl + ")";
  398. var trFolder = $('#fileList tr[data-file=\"' + OCA.Files_External.StatusManager.Utils.jqSelEscape(folder) + '\"]'); //FileList.findFileEl(OCA.Files_External.StatusManager.Utils.jqSelEscape(folder));
  399. this.changeFolderIcon(folder, imageUrl);
  400. this.toggleLink(folder, false, clickAction);
  401. trFolder.addClass('externalErroredRow');
  402. },
  403. /**
  404. * @param folder string with the folder or jQuery element pointing to the tr element
  405. */
  406. storeDefaultFolderIconAndBgcolor: function (folder) {
  407. var trFolder;
  408. if (folder instanceof $) {
  409. trFolder = folder;
  410. } else {
  411. 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) + '\"]');
  412. }
  413. trFolder.each(function () {
  414. var thisElement = $(this);
  415. if (thisElement.data('oldbgcolor') === undefined) {
  416. thisElement.data('oldbgcolor', thisElement.css('background-color'));
  417. }
  418. });
  419. var icon = trFolder.find('td.filename div.thumbnail');
  420. icon.each(function () {
  421. var thisElement = $(this);
  422. if (thisElement.data('oldImage') === undefined) {
  423. thisElement.data('oldImage', thisElement.css('background-image'));
  424. }
  425. });
  426. },
  427. /**
  428. * @param folder string with the folder or jQuery element pointing to the tr element
  429. */
  430. restoreFolder: function (folder) {
  431. var trFolder;
  432. if (folder instanceof $) {
  433. trFolder = folder;
  434. } else {
  435. // can't use here FileList.findFileEl(OCA.Files_External.StatusManager.Utils.jqSelEscape(folder)); return incorrect instance of filelist
  436. trFolder = $('#fileList tr[data-file=\"' + OCA.Files_External.StatusManager.Utils.jqSelEscape(folder) + '\"]');
  437. }
  438. trFolder.removeClass('externalErroredRow').removeClass('externalDisabledRow');
  439. var tdChilds = trFolder.find("td.filename div.thumbnail");
  440. tdChilds.each(function () {
  441. var thisElement = $(this);
  442. thisElement.css('background-image', thisElement.data('oldImage'));
  443. });
  444. },
  445. /**
  446. * @param folder string with the folder or jQuery element pointing to the first td element
  447. * of the tr matching the folder name
  448. */
  449. changeFolderIcon: function (filename) {
  450. var file;
  451. var route;
  452. if (filename instanceof $) {
  453. //trElementList
  454. $.each(filename, function (index) {
  455. route = OCA.Files_External.StatusManager.Utils.getIconRoute($(this));
  456. $(this).attr("data-icon", route);
  457. $(this).find('td.filename div.thumbnail').css('background-image', "url(" + route + ")").css('display', 'none').css('display', 'inline');
  458. });
  459. } else {
  460. file = $("#fileList tr[data-file=\"" + this.jqSelEscape(filename) + "\"] > td.filename div.thumbnail");
  461. var parentTr = file.parents('tr:first');
  462. route = OCA.Files_External.StatusManager.Utils.getIconRoute(parentTr);
  463. parentTr.attr("data-icon", route);
  464. file.css('background-image', "url(" + route + ")").css('display', 'none').css('display', 'inline');
  465. }
  466. },
  467. /**
  468. * @param backend string with the name of the external storage backend
  469. * of the tr matching the folder name
  470. */
  471. getIconRoute: function (tr) {
  472. if (OCA.Theming) {
  473. var icon = OC.generateUrl('/apps/theming/img/core/filetypes/folder-external.svg?v=' + OCA.Theming.cacheBuster);
  474. } else {
  475. var icon = OC.imagePath('core', 'filetypes/folder-external');
  476. }
  477. var backend = null;
  478. if (tr instanceof $) {
  479. backend = tr.attr('data-external-backend');
  480. }
  481. switch (backend) {
  482. case 'windows_network_drive':
  483. icon = OC.imagePath('windows_network_drive', 'folder-windows');
  484. break;
  485. }
  486. return icon;
  487. },
  488. toggleLink: function (filename, active, action) {
  489. var link;
  490. if (filename instanceof $) {
  491. link = filename;
  492. } else {
  493. link = $("#fileList tr[data-file=\"" + this.jqSelEscape(filename) + "\"] > td.filename a.name");
  494. }
  495. if (active) {
  496. link.off('click.connectivity');
  497. OCA.Files.App.fileList.fileActions.display(link.parent(), true, OCA.Files.App.fileList);
  498. } else {
  499. link.find('.fileactions, .nametext .action').remove(); // from files/js/fileactions (display)
  500. link.off('click.connectivity');
  501. link.on('click.connectivity', function (e) {
  502. if (action && $.isFunction(action)) {
  503. action(filename);
  504. }
  505. e.preventDefault();
  506. return false;
  507. });
  508. }
  509. },
  510. isCorrectViewAndRootFolder: function () {
  511. // correct views = files & extstoragemounts
  512. if (OCA.Files.App.getActiveView() === 'files' || OCA.Files.App.getActiveView() === 'extstoragemounts') {
  513. return OCA.Files.App.getCurrentAppContainer().find('#dir').val() === '/';
  514. }
  515. return false;
  516. },
  517. /* escape a selector expression for jQuery */
  518. jqSelEscape: function (expression) {
  519. if (expression) {
  520. return expression.replace(/[!"#$%&'()*+,.\/:;<=>?@\[\\\]^`{|}~]/g, '\\$&');
  521. }
  522. return null;
  523. },
  524. /* Copied from http://stackoverflow.com/questions/2631001/javascript-test-for-existence-of-nested-object-key */
  525. checkNested: function (cobj /*, level1, level2, ... levelN*/) {
  526. var args = Array.prototype.slice.call(arguments),
  527. obj = args.shift();
  528. for (var i = 0; i < args.length; i++) {
  529. if (!obj || !obj.hasOwnProperty(args[i])) {
  530. return false;
  531. }
  532. obj = obj[args[i]];
  533. }
  534. return true;
  535. }
  536. };