settings.js 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395
  1. /*
  2. * Copyright (c) 2014
  3. *
  4. * This file is licensed under the Affero General Public License version 3
  5. * or later.
  6. *
  7. * See the COPYING-README file.
  8. *
  9. */
  10. (function(){
  11. /**
  12. * Returns the selection of applicable users in the given configuration row
  13. *
  14. * @param $row configuration row
  15. * @return array array of user names
  16. */
  17. function getSelection($row) {
  18. var values = $row.find('.applicableUsers').select2('val');
  19. if (!values || values.length === 0) {
  20. values = [];
  21. }
  22. return values;
  23. }
  24. function highlightBorder($element, highlight) {
  25. $element.toggleClass('warning-input', highlight);
  26. return highlight;
  27. }
  28. function isInputValid($input) {
  29. var optional = $input.hasClass('optional');
  30. switch ($input.attr('type')) {
  31. case 'text':
  32. case 'password':
  33. if ($input.val() === '' && !optional) {
  34. return false;
  35. }
  36. break;
  37. }
  38. return true;
  39. }
  40. function highlightInput($input) {
  41. switch ($input.attr('type')) {
  42. case 'text':
  43. case 'password':
  44. return highlightBorder($input, !isInputValid($input));
  45. }
  46. }
  47. /**
  48. * Initialize select2 plugin on the given elements
  49. *
  50. * @param {Array<Object>} array of jQuery elements
  51. * @param {int} userListLimit page size for result list
  52. */
  53. function addSelect2 ($elements, userListLimit) {
  54. if (!$elements.length) {
  55. return;
  56. }
  57. $elements.select2({
  58. placeholder: t('files_external', 'All users. Type to select user or group.'),
  59. allowClear: true,
  60. multiple: true,
  61. toggleSelect: true,
  62. dropdownCssClass: 'files-external-select2',
  63. //minimumInputLength: 1,
  64. ajax: {
  65. url: OC.generateUrl('apps/files_external/applicable'),
  66. dataType: 'json',
  67. quietMillis: 100,
  68. data: function (term, page) { // page is the one-based page number tracked by Select2
  69. return {
  70. pattern: term, //search term
  71. limit: userListLimit, // page size
  72. offset: userListLimit*(page-1) // page number starts with 0
  73. };
  74. },
  75. results: function (data) {
  76. if (data.status === 'success') {
  77. var results = [];
  78. var userCount = 0; // users is an object
  79. // add groups
  80. $.each(data.groups, function(i, group) {
  81. results.push({name:group+'(group)', displayname:group, type:'group' });
  82. });
  83. // add users
  84. $.each(data.users, function(id, user) {
  85. userCount++;
  86. results.push({name:id, displayname:user, type:'user' });
  87. });
  88. var more = (userCount >= userListLimit) || (data.groups.length >= userListLimit);
  89. return {results: results, more: more};
  90. } else {
  91. //FIXME add error handling
  92. }
  93. }
  94. },
  95. initSelection: function(element, callback) {
  96. var users = {};
  97. users['users'] = [];
  98. var toSplit = element.val().split(",");
  99. for (var i = 0; i < toSplit.length; i++) {
  100. users['users'].push(toSplit[i]);
  101. }
  102. $.ajax(OC.generateUrl('displaynames'), {
  103. type: 'POST',
  104. contentType: 'application/json',
  105. data: JSON.stringify(users),
  106. dataType: 'json'
  107. }).done(function(data) {
  108. var results = [];
  109. if (data.status === 'success') {
  110. $.each(data.users, function(user, displayname) {
  111. if (displayname !== false) {
  112. results.push({name:user, displayname:displayname, type:'user'});
  113. }
  114. });
  115. callback(results);
  116. } else {
  117. //FIXME add error handling
  118. }
  119. });
  120. },
  121. id: function(element) {
  122. return element.name;
  123. },
  124. formatResult: function (element) {
  125. var $result = $('<span><div class="avatardiv"/><span>'+escapeHTML(element.displayname)+'</span></span>');
  126. var $div = $result.find('.avatardiv')
  127. .attr('data-type', element.type)
  128. .attr('data-name', element.name)
  129. .attr('data-displayname', element.displayname);
  130. if (element.type === 'group') {
  131. var url = OC.imagePath('core','actions/group');
  132. $div.html('<img width="32" height="32" src="'+url+'">');
  133. }
  134. return $result.get(0).outerHTML;
  135. },
  136. formatSelection: function (element) {
  137. if (element.type === 'group') {
  138. return '<span title="'+escapeHTML(element.name)+'" class="group">'+escapeHTML(element.displayname+' '+t('files_external', '(group)'))+'</span>';
  139. } else {
  140. return '<span title="'+escapeHTML(element.name)+'" class="user">'+escapeHTML(element.displayname)+'</span>';
  141. }
  142. },
  143. escapeMarkup: function (m) { return m; } // we escape the markup in formatResult and formatSelection
  144. }).on('select2-loaded', function() {
  145. $.each($('.avatardiv'), function(i, div) {
  146. var $div = $(div);
  147. if ($div.data('type') === 'user') {
  148. $div.avatar($div.data('name'),32);
  149. }
  150. });
  151. });
  152. }
  153. /**
  154. * @class OCA.Files_External.Settings.StorageConfig
  155. *
  156. * @classdesc External storage config
  157. */
  158. var StorageConfig = function(id) {
  159. this.id = id;
  160. this.backendOptions = {};
  161. };
  162. // Keep this in sync with \OC_Mount_Config::STATUS_*
  163. StorageConfig.Status = {
  164. IN_PROGRESS: -1,
  165. SUCCESS: 0,
  166. ERROR: 1,
  167. INDETERMINATE: 2
  168. };
  169. StorageConfig.Visibility = {
  170. NONE: 0,
  171. PERSONAL: 1,
  172. ADMIN: 2,
  173. DEFAULT: 3
  174. };
  175. /**
  176. * @memberof OCA.Files_External.Settings
  177. */
  178. StorageConfig.prototype = {
  179. _url: null,
  180. /**
  181. * Storage id
  182. *
  183. * @type int
  184. */
  185. id: null,
  186. /**
  187. * Mount point
  188. *
  189. * @type string
  190. */
  191. mountPoint: '',
  192. /**
  193. * Backend
  194. *
  195. * @type string
  196. */
  197. backend: null,
  198. /**
  199. * Authentication mechanism
  200. *
  201. * @type string
  202. */
  203. authMechanism: null,
  204. /**
  205. * Backend-specific configuration
  206. *
  207. * @type Object.<string,object>
  208. */
  209. backendOptions: null,
  210. /**
  211. * Mount-specific options
  212. *
  213. * @type Object.<string,object>
  214. */
  215. mountOptions: null,
  216. /**
  217. * Creates or saves the storage.
  218. *
  219. * @param {Function} [options.success] success callback, receives result as argument
  220. * @param {Function} [options.error] error callback
  221. */
  222. save: function(options) {
  223. var self = this;
  224. var url = OC.generateUrl(this._url);
  225. var method = 'POST';
  226. if (_.isNumber(this.id)) {
  227. method = 'PUT';
  228. url = OC.generateUrl(this._url + '/{id}', {id: this.id});
  229. }
  230. $.ajax({
  231. type: method,
  232. url: url,
  233. contentType: 'application/json',
  234. data: JSON.stringify(this.getData()),
  235. success: function(result) {
  236. self.id = result.id;
  237. if (_.isFunction(options.success)) {
  238. options.success(result);
  239. }
  240. },
  241. error: options.error
  242. });
  243. },
  244. /**
  245. * Returns the data from this object
  246. *
  247. * @return {Array} JSON array of the data
  248. */
  249. getData: function() {
  250. var data = {
  251. mountPoint: this.mountPoint,
  252. backend: this.backend,
  253. authMechanism: this.authMechanism,
  254. backendOptions: this.backendOptions,
  255. testOnly: true
  256. };
  257. if (this.id) {
  258. data.id = this.id;
  259. }
  260. if (this.mountOptions) {
  261. data.mountOptions = this.mountOptions;
  262. }
  263. return data;
  264. },
  265. /**
  266. * Recheck the storage
  267. *
  268. * @param {Function} [options.success] success callback, receives result as argument
  269. * @param {Function} [options.error] error callback
  270. */
  271. recheck: function(options) {
  272. if (!_.isNumber(this.id)) {
  273. if (_.isFunction(options.error)) {
  274. options.error();
  275. }
  276. return;
  277. }
  278. $.ajax({
  279. type: 'GET',
  280. url: OC.generateUrl(this._url + '/{id}', {id: this.id}),
  281. data: {'testOnly': true},
  282. success: options.success,
  283. error: options.error
  284. });
  285. },
  286. /**
  287. * Deletes the storage
  288. *
  289. * @param {Function} [options.success] success callback
  290. * @param {Function} [options.error] error callback
  291. */
  292. destroy: function(options) {
  293. if (!_.isNumber(this.id)) {
  294. // the storage hasn't even been created => success
  295. if (_.isFunction(options.success)) {
  296. options.success();
  297. }
  298. return;
  299. }
  300. $.ajax({
  301. type: 'DELETE',
  302. url: OC.generateUrl(this._url + '/{id}', {id: this.id}),
  303. success: options.success,
  304. error: options.error
  305. });
  306. },
  307. /**
  308. * Validate this model
  309. *
  310. * @return {boolean} false if errors exist, true otherwise
  311. */
  312. validate: function() {
  313. if (this.mountPoint === '') {
  314. return false;
  315. }
  316. if (!this.backend) {
  317. return false;
  318. }
  319. if (this.errors) {
  320. return false;
  321. }
  322. return true;
  323. }
  324. };
  325. /**
  326. * @class OCA.Files_External.Settings.GlobalStorageConfig
  327. * @augments OCA.Files_External.Settings.StorageConfig
  328. *
  329. * @classdesc Global external storage config
  330. */
  331. var GlobalStorageConfig = function(id) {
  332. this.id = id;
  333. this.applicableUsers = [];
  334. this.applicableGroups = [];
  335. };
  336. /**
  337. * @memberOf OCA.Files_External.Settings
  338. */
  339. GlobalStorageConfig.prototype = _.extend({}, StorageConfig.prototype,
  340. /** @lends OCA.Files_External.Settings.GlobalStorageConfig.prototype */ {
  341. _url: 'apps/files_external/globalstorages',
  342. /**
  343. * Applicable users
  344. *
  345. * @type Array.<string>
  346. */
  347. applicableUsers: null,
  348. /**
  349. * Applicable groups
  350. *
  351. * @type Array.<string>
  352. */
  353. applicableGroups: null,
  354. /**
  355. * Storage priority
  356. *
  357. * @type int
  358. */
  359. priority: null,
  360. /**
  361. * Returns the data from this object
  362. *
  363. * @return {Array} JSON array of the data
  364. */
  365. getData: function() {
  366. var data = StorageConfig.prototype.getData.apply(this, arguments);
  367. return _.extend(data, {
  368. applicableUsers: this.applicableUsers,
  369. applicableGroups: this.applicableGroups,
  370. priority: this.priority,
  371. });
  372. }
  373. });
  374. /**
  375. * @class OCA.Files_External.Settings.UserStorageConfig
  376. * @augments OCA.Files_External.Settings.StorageConfig
  377. *
  378. * @classdesc User external storage config
  379. */
  380. var UserStorageConfig = function(id) {
  381. this.id = id;
  382. };
  383. UserStorageConfig.prototype = _.extend({}, StorageConfig.prototype,
  384. /** @lends OCA.Files_External.Settings.UserStorageConfig.prototype */ {
  385. _url: 'apps/files_external/userstorages'
  386. });
  387. /**
  388. * @class OCA.Files_External.Settings.UserGlobalStorageConfig
  389. * @augments OCA.Files_External.Settings.StorageConfig
  390. *
  391. * @classdesc User external storage config
  392. */
  393. var UserGlobalStorageConfig = function (id) {
  394. this.id = id;
  395. };
  396. UserGlobalStorageConfig.prototype = _.extend({}, StorageConfig.prototype,
  397. /** @lends OCA.Files_External.Settings.UserStorageConfig.prototype */ {
  398. _url: 'apps/files_external/userglobalstorages'
  399. });
  400. /**
  401. * @class OCA.Files_External.Settings.MountOptionsDropdown
  402. *
  403. * @classdesc Dropdown for mount options
  404. *
  405. * @param {Object} $container container DOM object
  406. */
  407. var MountOptionsDropdown = function() {
  408. };
  409. /**
  410. * @memberof OCA.Files_External.Settings
  411. */
  412. MountOptionsDropdown.prototype = {
  413. /**
  414. * Dropdown element
  415. *
  416. * @var Object
  417. */
  418. $el: null,
  419. /**
  420. * Show dropdown
  421. *
  422. * @param {Object} $container container
  423. * @param {Object} mountOptions mount options
  424. * @param {Array} visibleOptions enabled mount options
  425. */
  426. show: function($container, mountOptions, visibleOptions) {
  427. if (MountOptionsDropdown._last) {
  428. MountOptionsDropdown._last.hide();
  429. }
  430. var $el = $(OCA.Files_External.Templates.mountOptionsDropDown({
  431. mountOptionsEncodingLabel: t('files_external', 'Compatibility with Mac NFD encoding (slow)'),
  432. mountOptionsEncryptLabel: t('files_external', 'Enable encryption'),
  433. mountOptionsPreviewsLabel: t('files_external', 'Enable previews'),
  434. mountOptionsSharingLabel: t('files_external', 'Enable sharing'),
  435. mountOptionsFilesystemCheckLabel: t('files_external', 'Check for changes'),
  436. mountOptionsFilesystemCheckOnce: t('files_external', 'Never'),
  437. mountOptionsFilesystemCheckDA: t('files_external', 'Once every direct access'),
  438. mountOptionsReadOnlyLabel: t('files_external', 'Read only'),
  439. deleteLabel: t('files_external', 'Delete')
  440. }));
  441. this.$el = $el;
  442. this.setOptions(mountOptions, visibleOptions);
  443. this.$el.appendTo($container);
  444. MountOptionsDropdown._last = this;
  445. this.$el.trigger('show');
  446. },
  447. hide: function() {
  448. if (this.$el) {
  449. this.$el.trigger('hide');
  450. this.$el.remove();
  451. this.$el = null;
  452. MountOptionsDropdown._last = null;
  453. }
  454. },
  455. /**
  456. * Returns the mount options from the dropdown controls
  457. *
  458. * @return {Object} options mount options
  459. */
  460. getOptions: function() {
  461. var options = {};
  462. this.$el.find('input, select').each(function() {
  463. var $this = $(this);
  464. var key = $this.attr('name');
  465. var value = null;
  466. if ($this.attr('type') === 'checkbox') {
  467. value = $this.prop('checked');
  468. } else {
  469. value = $this.val();
  470. }
  471. if ($this.attr('data-type') === 'int') {
  472. value = parseInt(value, 10);
  473. }
  474. options[key] = value;
  475. });
  476. return options;
  477. },
  478. /**
  479. * Sets the mount options to the dropdown controls
  480. *
  481. * @param {Object} options mount options
  482. * @param {Array} visibleOptions enabled mount options
  483. */
  484. setOptions: function(options, visibleOptions) {
  485. var $el = this.$el;
  486. _.each(options, function(value, key) {
  487. var $optionEl = $el.find('input, select').filterAttr('name', key);
  488. if ($optionEl.attr('type') === 'checkbox') {
  489. if (_.isString(value)) {
  490. value = (value === 'true');
  491. }
  492. $optionEl.prop('checked', !!value);
  493. } else {
  494. $optionEl.val(value);
  495. }
  496. });
  497. $el.find('.optionRow').each(function(i, row){
  498. var $row = $(row);
  499. var optionId = $row.find('input, select').attr('name');
  500. if (visibleOptions.indexOf(optionId) === -1 && !$row.hasClass('persistent')) {
  501. $row.hide();
  502. } else {
  503. $row.show();
  504. }
  505. });
  506. }
  507. };
  508. /**
  509. * @class OCA.Files_External.Settings.MountConfigListView
  510. *
  511. * @classdesc Mount configuration list view
  512. *
  513. * @param {Object} $el DOM object containing the list
  514. * @param {Object} [options]
  515. * @param {int} [options.userListLimit] page size in applicable users dropdown
  516. */
  517. var MountConfigListView = function($el, options) {
  518. this.initialize($el, options);
  519. };
  520. MountConfigListView.ParameterFlags = {
  521. OPTIONAL: 1,
  522. USER_PROVIDED: 2
  523. };
  524. MountConfigListView.ParameterTypes = {
  525. TEXT: 0,
  526. BOOLEAN: 1,
  527. PASSWORD: 2,
  528. HIDDEN: 3
  529. };
  530. /**
  531. * @memberOf OCA.Files_External.Settings
  532. */
  533. MountConfigListView.prototype = _.extend({
  534. /**
  535. * jQuery element containing the config list
  536. *
  537. * @type Object
  538. */
  539. $el: null,
  540. /**
  541. * Storage config class
  542. *
  543. * @type Class
  544. */
  545. _storageConfigClass: null,
  546. /**
  547. * Flag whether the list is about user storage configs (true)
  548. * or global storage configs (false)
  549. *
  550. * @type bool
  551. */
  552. _isPersonal: false,
  553. /**
  554. * Page size in applicable users dropdown
  555. *
  556. * @type int
  557. */
  558. _userListLimit: 30,
  559. /**
  560. * List of supported backends
  561. *
  562. * @type Object.<string,Object>
  563. */
  564. _allBackends: null,
  565. /**
  566. * List of all supported authentication mechanisms
  567. *
  568. * @type Object.<string,Object>
  569. */
  570. _allAuthMechanisms: null,
  571. _encryptionEnabled: false,
  572. /**
  573. * @param {Object} $el DOM object containing the list
  574. * @param {Object} [options]
  575. * @param {int} [options.userListLimit] page size in applicable users dropdown
  576. */
  577. initialize: function($el, options) {
  578. var self = this;
  579. this.$el = $el;
  580. this._isPersonal = ($el.data('admin') !== true);
  581. if (this._isPersonal) {
  582. this._storageConfigClass = OCA.Files_External.Settings.UserStorageConfig;
  583. } else {
  584. this._storageConfigClass = OCA.Files_External.Settings.GlobalStorageConfig;
  585. }
  586. if (options && !_.isUndefined(options.userListLimit)) {
  587. this._userListLimit = options.userListLimit;
  588. }
  589. this._encryptionEnabled = options.encryptionEnabled;
  590. // read the backend config that was carefully crammed
  591. // into the data-configurations attribute of the select
  592. this._allBackends = this.$el.find('.selectBackend').data('configurations');
  593. this._allAuthMechanisms = this.$el.find('#addMountPoint .authentication').data('mechanisms');
  594. this._initEvents();
  595. },
  596. /**
  597. * Custom JS event handlers
  598. * Trigger callback for all existing configurations
  599. */
  600. whenSelectBackend: function(callback) {
  601. this.$el.find('tbody tr:not(#addMountPoint)').each(function(i, tr) {
  602. var backend = $(tr).find('.backend').data('identifier');
  603. callback($(tr), backend);
  604. });
  605. this.on('selectBackend', callback);
  606. },
  607. whenSelectAuthMechanism: function(callback) {
  608. var self = this;
  609. this.$el.find('tbody tr:not(#addMountPoint)').each(function(i, tr) {
  610. var authMechanism = $(tr).find('.selectAuthMechanism').val();
  611. callback($(tr), authMechanism, self._allAuthMechanisms[authMechanism]['scheme']);
  612. });
  613. this.on('selectAuthMechanism', callback);
  614. },
  615. /**
  616. * Initialize DOM event handlers
  617. */
  618. _initEvents: function() {
  619. var self = this;
  620. var onChangeHandler = _.bind(this._onChange, this);
  621. //this.$el.on('input', 'td input', onChangeHandler);
  622. this.$el.on('keyup', 'td input', onChangeHandler);
  623. this.$el.on('paste', 'td input', onChangeHandler);
  624. this.$el.on('change', 'td input:checkbox', onChangeHandler);
  625. this.$el.on('change', '.applicable', onChangeHandler);
  626. this.$el.on('click', '.status>span', function() {
  627. self.recheckStorageConfig($(this).closest('tr'));
  628. });
  629. this.$el.on('click', 'td.mountOptionsToggle .icon-delete', function() {
  630. self.deleteStorageConfig($(this).closest('tr'));
  631. });
  632. this.$el.on('click', 'td.save>.icon-checkmark', function () {
  633. self.saveStorageConfig($(this).closest('tr'));
  634. });
  635. this.$el.on('click', 'td.mountOptionsToggle>.icon-more', function() {
  636. self._showMountOptionsDropdown($(this).closest('tr'));
  637. });
  638. this.$el.on('change', '.selectBackend', _.bind(this._onSelectBackend, this));
  639. this.$el.on('change', '.selectAuthMechanism', _.bind(this._onSelectAuthMechanism, this));
  640. },
  641. _onChange: function(event) {
  642. var self = this;
  643. var $target = $(event.target);
  644. if ($target.closest('.dropdown').length) {
  645. // ignore dropdown events
  646. return;
  647. }
  648. highlightInput($target);
  649. var $tr = $target.closest('tr');
  650. this.updateStatus($tr, null);
  651. },
  652. _onSelectBackend: function(event) {
  653. var $target = $(event.target);
  654. var $tr = $target.closest('tr');
  655. var storageConfig = new this._storageConfigClass();
  656. storageConfig.mountPoint = $tr.find('.mountPoint input').val();
  657. storageConfig.backend = $target.val();
  658. $tr.find('.mountPoint input').val('');
  659. var onCompletion = jQuery.Deferred();
  660. $tr = this.newStorage(storageConfig, onCompletion);
  661. onCompletion.resolve();
  662. $tr.find('td.configuration').children().not('[type=hidden]').first().focus();
  663. this.saveStorageConfig($tr);
  664. },
  665. _onSelectAuthMechanism: function(event) {
  666. var $target = $(event.target);
  667. var $tr = $target.closest('tr');
  668. var authMechanism = $target.val();
  669. var onCompletion = jQuery.Deferred();
  670. this.configureAuthMechanism($tr, authMechanism, onCompletion);
  671. onCompletion.resolve();
  672. this.saveStorageConfig($tr);
  673. },
  674. /**
  675. * Configure the storage config with a new authentication mechanism
  676. *
  677. * @param {jQuery} $tr config row
  678. * @param {string} authMechanism
  679. * @param {jQuery.Deferred} onCompletion
  680. */
  681. configureAuthMechanism: function($tr, authMechanism, onCompletion) {
  682. var authMechanismConfiguration = this._allAuthMechanisms[authMechanism];
  683. var $td = $tr.find('td.configuration');
  684. $td.find('.auth-param').remove();
  685. $.each(authMechanismConfiguration['configuration'], _.partial(
  686. this.writeParameterInput, $td, _, _, ['auth-param']
  687. ).bind(this));
  688. this.trigger('selectAuthMechanism',
  689. $tr, authMechanism, authMechanismConfiguration['scheme'], onCompletion
  690. );
  691. },
  692. /**
  693. * Create a config row for a new storage
  694. *
  695. * @param {StorageConfig} storageConfig storage config to pull values from
  696. * @param {jQuery.Deferred} onCompletion
  697. * @return {jQuery} created row
  698. */
  699. newStorage: function(storageConfig, onCompletion) {
  700. var mountPoint = storageConfig.mountPoint;
  701. var backend = this._allBackends[storageConfig.backend];
  702. if (!backend) {
  703. backend = {
  704. name: 'Unknown: ' + storageConfig.backend,
  705. invalid: true
  706. };
  707. }
  708. // FIXME: Replace with a proper Handlebar template
  709. var $tr = this.$el.find('tr#addMountPoint');
  710. this.$el.find('tbody').append($tr.clone());
  711. $tr.data('storageConfig', storageConfig);
  712. $tr.show();
  713. $tr.find('td.mountOptionsToggle, td.save, td.remove').removeClass('hidden');
  714. $tr.find('td').last().removeAttr('style');
  715. $tr.removeAttr('id');
  716. $tr.find('select#selectBackend');
  717. addSelect2($tr.find('.applicableUsers'), this._userListLimit);
  718. if (storageConfig.id) {
  719. $tr.data('id', storageConfig.id);
  720. }
  721. $tr.find('.backend').text(backend.name);
  722. if (mountPoint === '') {
  723. mountPoint = this._suggestMountPoint(backend.name);
  724. }
  725. $tr.find('.mountPoint input').val(mountPoint);
  726. $tr.addClass(backend.identifier);
  727. $tr.find('.backend').data('identifier', backend.identifier);
  728. if (backend.invalid) {
  729. $tr.find('[name=mountPoint]').prop('disabled', true);
  730. $tr.find('.applicable,.mountOptionsToggle').empty();
  731. this.updateStatus($tr, false, 'Unknown backend: ' + backend.name);
  732. return $tr;
  733. }
  734. var selectAuthMechanism = $('<select class="selectAuthMechanism"></select>');
  735. var neededVisibility = (this._isPersonal) ? StorageConfig.Visibility.PERSONAL : StorageConfig.Visibility.ADMIN;
  736. $.each(this._allAuthMechanisms, function(authIdentifier, authMechanism) {
  737. if (backend.authSchemes[authMechanism.scheme] && (authMechanism.visibility & neededVisibility)) {
  738. selectAuthMechanism.append(
  739. $('<option value="'+authMechanism.identifier+'" data-scheme="'+authMechanism.scheme+'">'+authMechanism.name+'</option>')
  740. );
  741. }
  742. });
  743. if (storageConfig.authMechanism) {
  744. selectAuthMechanism.val(storageConfig.authMechanism);
  745. } else {
  746. storageConfig.authMechanism = selectAuthMechanism.val();
  747. }
  748. $tr.find('td.authentication').append(selectAuthMechanism);
  749. var $td = $tr.find('td.configuration');
  750. $.each(backend.configuration, _.partial(this.writeParameterInput, $td).bind(this));
  751. this.trigger('selectBackend', $tr, backend.identifier, onCompletion);
  752. this.configureAuthMechanism($tr, storageConfig.authMechanism, onCompletion);
  753. if (storageConfig.backendOptions) {
  754. $td.find('input, select').each(function() {
  755. var input = $(this);
  756. var val = storageConfig.backendOptions[input.data('parameter')];
  757. if (val !== undefined) {
  758. if(input.is('input:checkbox')) {
  759. input.prop('checked', val);
  760. }
  761. input.val(storageConfig.backendOptions[input.data('parameter')]);
  762. highlightInput(input);
  763. }
  764. });
  765. }
  766. var applicable = [];
  767. if (storageConfig.applicableUsers) {
  768. applicable = applicable.concat(storageConfig.applicableUsers);
  769. }
  770. if (storageConfig.applicableGroups) {
  771. applicable = applicable.concat(
  772. _.map(storageConfig.applicableGroups, function(group) {
  773. return group+'(group)';
  774. })
  775. );
  776. }
  777. $tr.find('.applicableUsers').val(applicable).trigger('change');
  778. var priorityEl = $('<input type="hidden" class="priority" value="' + backend.priority + '" />');
  779. $tr.append(priorityEl);
  780. if (storageConfig.mountOptions) {
  781. $tr.find('input.mountOptions').val(JSON.stringify(storageConfig.mountOptions));
  782. } else {
  783. // FIXME default backend mount options
  784. $tr.find('input.mountOptions').val(JSON.stringify({
  785. 'encrypt': true,
  786. 'previews': true,
  787. 'enable_sharing': false,
  788. 'filesystem_check_changes': 1,
  789. 'encoding_compatibility': false,
  790. 'readonly': false,
  791. }));
  792. }
  793. return $tr;
  794. },
  795. /**
  796. * Load storages into config rows
  797. */
  798. loadStorages: function() {
  799. var self = this;
  800. if (this._isPersonal) {
  801. // load userglobal storages
  802. $.ajax({
  803. type: 'GET',
  804. url: OC.generateUrl('apps/files_external/userglobalstorages'),
  805. data: {'testOnly' : true},
  806. contentType: 'application/json',
  807. success: function(result) {
  808. var onCompletion = jQuery.Deferred();
  809. $.each(result, function(i, storageParams) {
  810. var storageConfig;
  811. var isUserGlobal = storageParams.type === 'system' && self._isPersonal;
  812. storageParams.mountPoint = storageParams.mountPoint.substr(1); // trim leading slash
  813. if (isUserGlobal) {
  814. storageConfig = new UserGlobalStorageConfig();
  815. } else {
  816. storageConfig = new self._storageConfigClass();
  817. }
  818. _.extend(storageConfig, storageParams);
  819. var $tr = self.newStorage(storageConfig, onCompletion);
  820. // userglobal storages must be at the top of the list
  821. $tr.detach();
  822. self.$el.prepend($tr);
  823. var $authentication = $tr.find('.authentication');
  824. $authentication.text($authentication.find('select option:selected').text());
  825. // disable any other inputs
  826. $tr.find('.mountOptionsToggle, .remove').empty();
  827. $tr.find('input:not(.user_provided), select:not(.user_provided)').attr('disabled', 'disabled');
  828. if (isUserGlobal) {
  829. $tr.find('.configuration').find(':not(.user_provided)').remove();
  830. } else {
  831. // userglobal storages do not expose configuration data
  832. $tr.find('.configuration').text(t('files_external', 'Admin defined'));
  833. }
  834. });
  835. var mainForm = $('#files_external');
  836. if (result.length === 0 && mainForm.attr('data-can-create') === 'false') {
  837. mainForm.hide();
  838. $('a[href="#external-storage"]').parent().hide();
  839. $('#emptycontent').show();
  840. }
  841. onCompletion.resolve();
  842. }
  843. });
  844. }
  845. var url = this._storageConfigClass.prototype._url;
  846. $.ajax({
  847. type: 'GET',
  848. url: OC.generateUrl(url),
  849. contentType: 'application/json',
  850. success: function(result) {
  851. var onCompletion = jQuery.Deferred();
  852. $.each(result, function(i, storageParams) {
  853. storageParams.mountPoint = (storageParams.mountPoint === '/')? '/' : storageParams.mountPoint.substr(1); // trim leading slash
  854. var storageConfig = new self._storageConfigClass();
  855. _.extend(storageConfig, storageParams);
  856. var $tr = self.newStorage(storageConfig, onCompletion);
  857. self.recheckStorageConfig($tr);
  858. });
  859. onCompletion.resolve();
  860. }
  861. });
  862. },
  863. /**
  864. * @param {jQuery} $td
  865. * @param {string} parameter
  866. * @param {string} placeholder
  867. * @param {Array} classes
  868. * @return {jQuery} newly created input
  869. */
  870. writeParameterInput: function($td, parameter, placeholder, classes) {
  871. var hasFlag = function(flag) {
  872. return (placeholder.flags & flag) === flag;
  873. };
  874. classes = $.isArray(classes) ? classes : [];
  875. classes.push('added');
  876. if (hasFlag(MountConfigListView.ParameterFlags.OPTIONAL)) {
  877. classes.push('optional');
  878. }
  879. if (hasFlag(MountConfigListView.ParameterFlags.USER_PROVIDED)) {
  880. if (this._isPersonal) {
  881. classes.push('user_provided');
  882. } else {
  883. return;
  884. }
  885. }
  886. var newElement;
  887. var trimmedPlaceholder = placeholder.value;
  888. if (placeholder.type === MountConfigListView.ParameterTypes.PASSWORD) {
  889. newElement = $('<input type="password" class="'+classes.join(' ')+'" data-parameter="'+parameter+'" placeholder="'+ trimmedPlaceholder+'" />');
  890. } else if (placeholder.type === MountConfigListView.ParameterTypes.BOOLEAN) {
  891. var checkboxId = _.uniqueId('checkbox_');
  892. newElement = $('<div><label><input type="checkbox" id="'+checkboxId+'" class="'+classes.join(' ')+'" data-parameter="'+parameter+'" />'+ trimmedPlaceholder+'</label></div>');
  893. } else if (placeholder.type === MountConfigListView.ParameterTypes.HIDDEN) {
  894. newElement = $('<input type="hidden" class="'+classes.join(' ')+'" data-parameter="'+parameter+'" />');
  895. } else {
  896. newElement = $('<input type="text" class="'+classes.join(' ')+'" data-parameter="'+parameter+'" placeholder="'+ trimmedPlaceholder+'" />');
  897. }
  898. highlightInput(newElement);
  899. $td.append(newElement);
  900. return newElement;
  901. },
  902. /**
  903. * Gets the storage model from the given row
  904. *
  905. * @param $tr row element
  906. * @return {OCA.Files_External.StorageConfig} storage model instance
  907. */
  908. getStorageConfig: function($tr) {
  909. var storageId = $tr.data('id');
  910. if (!storageId) {
  911. // new entry
  912. storageId = null;
  913. }
  914. var storage = $tr.data('storageConfig');
  915. if (!storage) {
  916. storage = new this._storageConfigClass(storageId);
  917. }
  918. storage.errors = null;
  919. storage.mountPoint = $tr.find('.mountPoint input').val();
  920. storage.backend = $tr.find('.backend').data('identifier');
  921. storage.authMechanism = $tr.find('.selectAuthMechanism').val();
  922. var classOptions = {};
  923. var configuration = $tr.find('.configuration input');
  924. var missingOptions = [];
  925. $.each(configuration, function(index, input) {
  926. var $input = $(input);
  927. var parameter = $input.data('parameter');
  928. if ($input.attr('type') === 'button') {
  929. return;
  930. }
  931. if (!isInputValid($input) && !$input.hasClass('optional')) {
  932. missingOptions.push(parameter);
  933. return;
  934. }
  935. if ($(input).is(':checkbox')) {
  936. if ($(input).is(':checked')) {
  937. classOptions[parameter] = true;
  938. } else {
  939. classOptions[parameter] = false;
  940. }
  941. } else {
  942. classOptions[parameter] = $(input).val();
  943. }
  944. });
  945. storage.backendOptions = classOptions;
  946. if (missingOptions.length) {
  947. storage.errors = {
  948. backendOptions: missingOptions
  949. };
  950. }
  951. // gather selected users and groups
  952. if (!this._isPersonal) {
  953. var groups = [];
  954. var users = [];
  955. var multiselect = getSelection($tr);
  956. $.each(multiselect, function(index, value) {
  957. var pos = (value.indexOf)?value.indexOf('(group)'): -1;
  958. if (pos !== -1) {
  959. groups.push(value.substr(0, pos));
  960. } else {
  961. users.push(value);
  962. }
  963. });
  964. // FIXME: this should be done in the multiselect change event instead
  965. $tr.find('.applicable')
  966. .data('applicable-groups', groups)
  967. .data('applicable-users', users);
  968. storage.applicableUsers = users;
  969. storage.applicableGroups = groups;
  970. storage.priority = parseInt($tr.find('input.priority').val() || '100', 10);
  971. }
  972. var mountOptions = $tr.find('input.mountOptions').val();
  973. if (mountOptions) {
  974. storage.mountOptions = JSON.parse(mountOptions);
  975. }
  976. return storage;
  977. },
  978. /**
  979. * Deletes the storage from the given tr
  980. *
  981. * @param $tr storage row
  982. * @param Function callback callback to call after save
  983. */
  984. deleteStorageConfig: function($tr) {
  985. var self = this;
  986. var configId = $tr.data('id');
  987. if (!_.isNumber(configId)) {
  988. // deleting unsaved storage
  989. $tr.remove();
  990. return;
  991. }
  992. var storage = new this._storageConfigClass(configId);
  993. OC.dialogs.confirm(t('files_external', 'Are you sure you want to delete this external storage?', {
  994. storage: this.mountPoint
  995. }), t('files_external', 'Delete storage?'), function(confirm) {
  996. if (confirm) {
  997. self.updateStatus($tr, StorageConfig.Status.IN_PROGRESS);
  998. storage.destroy({
  999. success: function () {
  1000. $tr.remove();
  1001. },
  1002. error: function () {
  1003. self.updateStatus($tr, StorageConfig.Status.ERROR);
  1004. }
  1005. });
  1006. }
  1007. });
  1008. },
  1009. /**
  1010. * Saves the storage from the given tr
  1011. *
  1012. * @param $tr storage row
  1013. * @param Function callback callback to call after save
  1014. * @param concurrentTimer only update if the timer matches this
  1015. */
  1016. saveStorageConfig:function($tr, callback, concurrentTimer) {
  1017. var self = this;
  1018. var storage = this.getStorageConfig($tr);
  1019. if (!storage || !storage.validate()) {
  1020. return false;
  1021. }
  1022. this.updateStatus($tr, StorageConfig.Status.IN_PROGRESS);
  1023. storage.save({
  1024. success: function(result) {
  1025. if (concurrentTimer === undefined
  1026. || $tr.data('save-timer') === concurrentTimer
  1027. ) {
  1028. self.updateStatus($tr, result.status);
  1029. $tr.data('id', result.id);
  1030. if (_.isFunction(callback)) {
  1031. callback(storage);
  1032. }
  1033. }
  1034. },
  1035. error: function() {
  1036. if (concurrentTimer === undefined
  1037. || $tr.data('save-timer') === concurrentTimer
  1038. ) {
  1039. self.updateStatus($tr, StorageConfig.Status.ERROR);
  1040. }
  1041. }
  1042. });
  1043. },
  1044. /**
  1045. * Recheck storage availability
  1046. *
  1047. * @param {jQuery} $tr storage row
  1048. * @return {boolean} success
  1049. */
  1050. recheckStorageConfig: function($tr) {
  1051. var self = this;
  1052. var storage = this.getStorageConfig($tr);
  1053. if (!storage.validate()) {
  1054. return false;
  1055. }
  1056. this.updateStatus($tr, StorageConfig.Status.IN_PROGRESS);
  1057. storage.recheck({
  1058. success: function(result) {
  1059. self.updateStatus($tr, result.status, result.statusMessage);
  1060. },
  1061. error: function() {
  1062. self.updateStatus($tr, StorageConfig.Status.ERROR);
  1063. }
  1064. });
  1065. },
  1066. /**
  1067. * Update status display
  1068. *
  1069. * @param {jQuery} $tr
  1070. * @param {int} status
  1071. * @param {string} message
  1072. */
  1073. updateStatus: function($tr, status, message) {
  1074. var $statusSpan = $tr.find('.status span');
  1075. switch (status) {
  1076. case null:
  1077. // remove status
  1078. break;
  1079. case StorageConfig.Status.IN_PROGRESS:
  1080. $statusSpan.attr('class', 'icon-loading-small');
  1081. break;
  1082. case StorageConfig.Status.SUCCESS:
  1083. $statusSpan.attr('class', 'success icon-checkmark-white');
  1084. break;
  1085. case StorageConfig.Status.INDETERMINATE:
  1086. $statusSpan.attr('class', 'indeterminate icon-info-white');
  1087. break;
  1088. default:
  1089. $statusSpan.attr('class', 'error icon-error-white');
  1090. }
  1091. if (typeof message === 'string') {
  1092. $statusSpan.attr('title', message);
  1093. $statusSpan.tooltip();
  1094. } else {
  1095. $statusSpan.tooltip('destroy');
  1096. }
  1097. },
  1098. /**
  1099. * Suggest mount point name that doesn't conflict with the existing names in the list
  1100. *
  1101. * @param {string} defaultMountPoint default name
  1102. */
  1103. _suggestMountPoint: function(defaultMountPoint) {
  1104. var $el = this.$el;
  1105. var pos = defaultMountPoint.indexOf('/');
  1106. if (pos !== -1) {
  1107. defaultMountPoint = defaultMountPoint.substring(0, pos);
  1108. }
  1109. defaultMountPoint = defaultMountPoint.replace(/\s+/g, '');
  1110. var i = 1;
  1111. var append = '';
  1112. var match = true;
  1113. while (match && i < 20) {
  1114. match = false;
  1115. $el.find('tbody td.mountPoint input').each(function(index, mountPoint) {
  1116. if ($(mountPoint).val() === defaultMountPoint+append) {
  1117. match = true;
  1118. return false;
  1119. }
  1120. });
  1121. if (match) {
  1122. append = i;
  1123. i++;
  1124. } else {
  1125. break;
  1126. }
  1127. }
  1128. return defaultMountPoint + append;
  1129. },
  1130. /**
  1131. * Toggles the mount options dropdown
  1132. *
  1133. * @param {Object} $tr configuration row
  1134. */
  1135. _showMountOptionsDropdown: function($tr) {
  1136. var self = this;
  1137. var storage = this.getStorageConfig($tr);
  1138. var $toggle = $tr.find('.mountOptionsToggle');
  1139. var dropDown = new MountOptionsDropdown();
  1140. var visibleOptions = [
  1141. 'previews',
  1142. 'filesystem_check_changes',
  1143. 'enable_sharing',
  1144. 'encoding_compatibility',
  1145. 'readonly',
  1146. 'delete'
  1147. ];
  1148. if (this._encryptionEnabled) {
  1149. visibleOptions.push('encrypt');
  1150. }
  1151. dropDown.show($toggle, storage.mountOptions || [], visibleOptions);
  1152. $('body').on('mouseup.mountOptionsDropdown', function(event) {
  1153. var $target = $(event.target);
  1154. if ($target.closest('.popovermenu').length) {
  1155. return;
  1156. }
  1157. dropDown.hide();
  1158. });
  1159. dropDown.$el.on('hide', function() {
  1160. var mountOptions = dropDown.getOptions();
  1161. $('body').off('mouseup.mountOptionsDropdown');
  1162. $tr.find('input.mountOptions').val(JSON.stringify(mountOptions));
  1163. self.saveStorageConfig($tr);
  1164. });
  1165. }
  1166. }, OC.Backbone.Events);
  1167. $(document).ready(function() {
  1168. var enabled = $('#files_external').attr('data-encryption-enabled');
  1169. var encryptionEnabled = (enabled ==='true')? true: false;
  1170. var mountConfigListView = new MountConfigListView($('#externalStorage'), {
  1171. encryptionEnabled: encryptionEnabled
  1172. });
  1173. mountConfigListView.loadStorages();
  1174. // TODO: move this into its own View class
  1175. var $allowUserMounting = $('#allowUserMounting');
  1176. $allowUserMounting.bind('change', function() {
  1177. OC.msg.startSaving('#userMountingMsg');
  1178. if (this.checked) {
  1179. OCP.AppConfig.setValue('files_external', 'allow_user_mounting', 'yes');
  1180. $('input[name="allowUserMountingBackends\\[\\]"]').prop('checked', true);
  1181. $('#userMountingBackends').removeClass('hidden');
  1182. $('input[name="allowUserMountingBackends\\[\\]"]').eq(0).trigger('change');
  1183. } else {
  1184. OCP.AppConfig.setValue('files_external', 'allow_user_mounting', 'no');
  1185. $('#userMountingBackends').addClass('hidden');
  1186. }
  1187. OC.msg.finishedSaving('#userMountingMsg', {status: 'success', data: {message: t('files_external', 'Saved')}});
  1188. });
  1189. $('input[name="allowUserMountingBackends\\[\\]"]').bind('change', function() {
  1190. OC.msg.startSaving('#userMountingMsg');
  1191. var userMountingBackends = $('input[name="allowUserMountingBackends\\[\\]"]:checked').map(function(){
  1192. return $(this).val();
  1193. }).get();
  1194. var deprecatedBackends = $('input[name="allowUserMountingBackends\\[\\]"][data-deprecate-to]').map(function(){
  1195. if ($.inArray($(this).data('deprecate-to'), userMountingBackends) !== -1) {
  1196. return $(this).val();
  1197. }
  1198. return null;
  1199. }).get();
  1200. userMountingBackends = userMountingBackends.concat(deprecatedBackends);
  1201. OCP.AppConfig.setValue('files_external', 'user_mounting_backends', userMountingBackends.join());
  1202. OC.msg.finishedSaving('#userMountingMsg', {status: 'success', data: {message: t('files_external', 'Saved')}});
  1203. // disable allowUserMounting
  1204. if(userMountingBackends.length === 0) {
  1205. $allowUserMounting.prop('checked', false);
  1206. $allowUserMounting.trigger('change');
  1207. }
  1208. });
  1209. $('#global_credentials').on('submit', function() {
  1210. var $form = $(this);
  1211. var uid = $form.find('[name=uid]').val();
  1212. var user = $form.find('[name=username]').val();
  1213. var password = $form.find('[name=password]').val();
  1214. var $submit = $form.find('[type=submit]');
  1215. $submit.val(t('files_external', 'Saving...'));
  1216. $.ajax({
  1217. type: 'POST',
  1218. contentType: 'application/json',
  1219. data: JSON.stringify({
  1220. uid: uid,
  1221. user: user,
  1222. password: password
  1223. }),
  1224. url: OC.generateUrl('apps/files_external/globalcredentials'),
  1225. dataType: 'json',
  1226. success: function() {
  1227. $submit.val(t('files_external', 'Saved'));
  1228. setTimeout(function(){
  1229. $submit.val(t('files_external', 'Save'));
  1230. }, 2500);
  1231. }
  1232. });
  1233. return false;
  1234. });
  1235. // global instance
  1236. OCA.Files_External.Settings.mountConfig = mountConfigListView;
  1237. /**
  1238. * Legacy
  1239. *
  1240. * @namespace
  1241. * @deprecated use OCA.Files_External.Settings.mountConfig instead
  1242. */
  1243. OC.MountConfig = {
  1244. saveStorage: _.bind(mountConfigListView.saveStorageConfig, mountConfigListView)
  1245. };
  1246. });
  1247. // export
  1248. OCA.Files_External = OCA.Files_External || {};
  1249. /**
  1250. * @namespace
  1251. */
  1252. OCA.Files_External.Settings = OCA.Files_External.Settings || {};
  1253. OCA.Files_External.Settings.GlobalStorageConfig = GlobalStorageConfig;
  1254. OCA.Files_External.Settings.UserStorageConfig = UserStorageConfig;
  1255. OCA.Files_External.Settings.MountConfigListView = MountConfigListView;
  1256. })();