app.js 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884
  1. // Copyright (C) 2014 Jakob Borg and Contributors (see the CONTRIBUTORS file).
  2. // All rights reserved. Use of this source code is governed by an MIT-style
  3. // license that can be found in the LICENSE file.
  4. /*jslint browser: true, continue: true, plusplus: true */
  5. /*global $: false, angular: false */
  6. 'use strict';
  7. var syncthing = angular.module('syncthing', ['pascalprecht.translate']);
  8. var urlbase = 'rest';
  9. var validLangs = ['de', 'en', 'es', 'fr', 'pt', 'sv'];
  10. syncthing.config(function ($httpProvider, $translateProvider) {
  11. $httpProvider.defaults.xsrfHeaderName = 'X-CSRF-Token';
  12. $httpProvider.defaults.xsrfCookieName = 'CSRF-Token';
  13. $translateProvider.useStaticFilesLoader({
  14. prefix: 'lang-',
  15. suffix: '.json'
  16. });
  17. });
  18. syncthing.controller('SyncthingCtrl', function ($scope, $http, $translate, $location) {
  19. var prevDate = 0;
  20. var getOK = true;
  21. var restarting = false;
  22. $scope.connections = {};
  23. $scope.config = {};
  24. $scope.myID = '';
  25. $scope.nodes = [];
  26. $scope.configInSync = true;
  27. $scope.protocolChanged = false;
  28. $scope.errors = [];
  29. $scope.seenError = '';
  30. $scope.model = {};
  31. $scope.repos = {};
  32. $scope.reportData = {};
  33. $scope.reportPreview = false;
  34. $scope.upgradeInfo = {};
  35. $http.get(urlbase+"/lang").success(function (langs) {
  36. var lang;
  37. for (var i = 0; i < langs.length; i++) {
  38. lang = langs[i];
  39. if (validLangs.indexOf(lang) >= 0) {
  40. $translate.use(lang);
  41. break;
  42. }
  43. }
  44. })
  45. $scope.$on("$locationChangeSuccess", function () {
  46. var lang = $location.search().lang;
  47. if (lang) {
  48. $translate.use(lang);
  49. }
  50. });
  51. $scope.needActions = {
  52. 'rm': 'Del',
  53. 'rmdir': 'Del (dir)',
  54. 'sync': 'Sync',
  55. 'touch': 'Update',
  56. }
  57. $scope.needIcons = {
  58. 'rm': 'remove',
  59. 'rmdir': 'remove',
  60. 'sync': 'download',
  61. 'touch': 'asterisk',
  62. }
  63. function getSucceeded() {
  64. if (!getOK) {
  65. $scope.init();
  66. $('#networkError').modal('hide');
  67. getOK = true;
  68. }
  69. if (restarting) {
  70. $scope.init();
  71. $('#restarting').modal('hide');
  72. $('#shutdown').modal('hide');
  73. restarting = false;
  74. }
  75. }
  76. function getFailed() {
  77. if (restarting) {
  78. return;
  79. }
  80. if (getOK) {
  81. $('#networkError').modal({backdrop: 'static', keyboard: false});
  82. getOK = false;
  83. }
  84. }
  85. $scope.refresh = function () {
  86. $http.get(urlbase + '/system').success(function (data) {
  87. getSucceeded();
  88. $scope.system = data;
  89. }).error(function () {
  90. getFailed();
  91. });
  92. Object.keys($scope.repos).forEach(function (id) {
  93. if (typeof $scope.model[id] === 'undefined') {
  94. // Never fetched before
  95. $http.get(urlbase + '/model?repo=' + encodeURIComponent(id)).success(function (data) {
  96. $scope.model[id] = data;
  97. });
  98. } else {
  99. $http.get(urlbase + '/model/version?repo=' + encodeURIComponent(id)).success(function (data) {
  100. if (data.version > $scope.model[id].version) {
  101. $http.get(urlbase + '/model?repo=' + encodeURIComponent(id)).success(function (data) {
  102. $scope.model[id] = data;
  103. });
  104. }
  105. });
  106. }
  107. });
  108. $http.get(urlbase + '/connections').success(function (data) {
  109. var now = Date.now(),
  110. td = (now - prevDate) / 1000,
  111. id;
  112. prevDate = now;
  113. for (id in data) {
  114. if (!data.hasOwnProperty(id)) {
  115. continue;
  116. }
  117. try {
  118. data[id].inbps = Math.max(0, 8 * (data[id].InBytesTotal - $scope.connections[id].InBytesTotal) / td);
  119. data[id].outbps = Math.max(0, 8 * (data[id].OutBytesTotal - $scope.connections[id].OutBytesTotal) / td);
  120. } catch (e) {
  121. data[id].inbps = 0;
  122. data[id].outbps = 0;
  123. }
  124. }
  125. $scope.connections = data;
  126. });
  127. $http.get(urlbase + '/errors').success(function (data) {
  128. $scope.errors = data;
  129. });
  130. };
  131. $scope.repoStatus = function (repo) {
  132. if (typeof $scope.model[repo] === 'undefined') {
  133. return 'unknown';
  134. }
  135. if ($scope.model[repo].invalid !== '') {
  136. return 'stopped';
  137. }
  138. return '' + $scope.model[repo].state;
  139. };
  140. $scope.repoClass = function (repo) {
  141. if (typeof $scope.model[repo] === 'undefined') {
  142. return 'info';
  143. }
  144. if ($scope.model[repo].invalid !== '') {
  145. return 'danger';
  146. }
  147. var state = '' + $scope.model[repo].state;
  148. if (state == 'idle') {
  149. return 'success';
  150. }
  151. if (state == 'syncing') {
  152. return 'primary';
  153. }
  154. return 'info';
  155. };
  156. $scope.syncPercentage = function (repo) {
  157. if (typeof $scope.model[repo] === 'undefined') {
  158. return 100;
  159. }
  160. if ($scope.model[repo].globalBytes === 0) {
  161. return 100;
  162. }
  163. var pct = 100 * $scope.model[repo].inSyncBytes / $scope.model[repo].globalBytes;
  164. return Math.floor(pct);
  165. };
  166. $scope.nodeIcon = function (nodeCfg) {
  167. var conn = $scope.connections[nodeCfg.NodeID];
  168. if (conn) {
  169. if (conn.Completion === 100) {
  170. return 'ok';
  171. } else {
  172. return 'refresh';
  173. }
  174. }
  175. return 'minus';
  176. };
  177. $scope.nodeClass = function (nodeCfg) {
  178. var conn = $scope.connections[nodeCfg.NodeID];
  179. if (conn) {
  180. if (conn.Completion === 100) {
  181. return 'success';
  182. } else {
  183. return 'primary';
  184. }
  185. }
  186. return 'info';
  187. };
  188. $scope.nodeAddr = function (nodeCfg) {
  189. var conn = $scope.connections[nodeCfg.NodeID];
  190. if (conn) {
  191. return conn.Address;
  192. }
  193. return '?';
  194. };
  195. $scope.nodeCompletion = function (nodeCfg) {
  196. var conn = $scope.connections[nodeCfg.NodeID];
  197. if (conn) {
  198. return conn.Completion + '%';
  199. }
  200. return '';
  201. };
  202. $scope.nodeVer = function (nodeCfg) {
  203. if (nodeCfg.NodeID === $scope.myID) {
  204. return $scope.version;
  205. }
  206. var conn = $scope.connections[nodeCfg.NodeID];
  207. if (conn) {
  208. return conn.ClientVersion;
  209. }
  210. return '?';
  211. };
  212. $scope.findNode = function (nodeID) {
  213. var matches = $scope.nodes.filter(function (n) { return n.NodeID == nodeID; });
  214. if (matches.length != 1) {
  215. return undefined;
  216. }
  217. return matches[0];
  218. };
  219. $scope.nodeName = function (nodeCfg) {
  220. if (typeof nodeCfg === 'undefined') {
  221. return "";
  222. }
  223. if (nodeCfg.Name) {
  224. return nodeCfg.Name;
  225. }
  226. return nodeCfg.NodeID.substr(0, 6);
  227. };
  228. $scope.thisNodeName = function () {
  229. var node = $scope.thisNode();
  230. if (typeof node === 'undefined') {
  231. return "(unknown node)";
  232. }
  233. if (node.Name) {
  234. return node.Name;
  235. }
  236. return node.NodeID.substr(0, 6);
  237. };
  238. $scope.editSettings = function () {
  239. // Make a working copy
  240. $scope.tmpOptions = angular.copy($scope.config.Options);
  241. $scope.tmpOptions.UREnabled = ($scope.tmpOptions.URAccepted > 0);
  242. $scope.tmpGUI = angular.copy($scope.config.GUI);
  243. $('#settings').modal({backdrop: 'static', keyboard: true});
  244. };
  245. $scope.saveConfig = function() {
  246. var cfg = JSON.stringify($scope.config);
  247. var opts = {headers: {'Content-Type': 'application/json'}};
  248. $http.post(urlbase + '/config', cfg, opts).success(function () {
  249. $http.get(urlbase + '/config/sync').success(function (data) {
  250. $scope.configInSync = data.configInSync;
  251. });
  252. });
  253. };
  254. $scope.saveSettings = function () {
  255. // Make sure something changed
  256. var changed = !angular.equals($scope.config.Options, $scope.tmpOptions) ||
  257. !angular.equals($scope.config.GUI, $scope.tmpGUI);
  258. if (changed) {
  259. // Check if usage reporting has been enabled or disabled
  260. if ($scope.tmpOptions.UREnabled && $scope.tmpOptions.URAccepted <= 0) {
  261. $scope.tmpOptions.URAccepted = 1000;
  262. } else if (!$scope.tmpOptions.UREnabled && $scope.tmpOptions.URAccepted > 0){
  263. $scope.tmpOptions.URAccepted = -1;
  264. }
  265. // Check if protocol will need to be changed on restart
  266. if($scope.config.GUI.UseTLS !== $scope.tmpGUI.UseTLS){
  267. $scope.protocolChanged = true;
  268. }
  269. // Apply new settings locally
  270. $scope.config.Options = angular.copy($scope.tmpOptions);
  271. $scope.config.GUI = angular.copy($scope.tmpGUI);
  272. $scope.config.Options.ListenAddress = $scope.config.Options.ListenStr.split(',').map(function (x) { return x.trim(); });
  273. $scope.saveConfig();
  274. }
  275. $('#settings').modal("hide");
  276. };
  277. $scope.restart = function () {
  278. restarting = true;
  279. $scope.restartingTitle = "Restarting"
  280. $scope.restartingBody = "Syncthing is restarting."
  281. $('#restarting').modal({backdrop: 'static', keyboard: false});
  282. $http.post(urlbase + '/restart');
  283. $scope.configInSync = true;
  284. // Switch webpage protocol if needed
  285. if($scope.protocolChanged){
  286. var protocol = 'http';
  287. if($scope.config.GUI.UseTLS){
  288. protocol = 'https';
  289. }
  290. setTimeout(function(){
  291. window.location.protocol = protocol;
  292. }, 1000);
  293. $scope.protocolChanged = false;
  294. }
  295. };
  296. $scope.upgrade = function () {
  297. $scope.restartingTitle = "Upgrading"
  298. $scope.restartingBody = "Syncthing is upgrading."
  299. $('#restarting').modal({backdrop: 'static', keyboard: false});
  300. $http.post(urlbase + '/upgrade').success(function () {
  301. restarting = true;
  302. $scope.restartingBody = "Syncthing is restarting into the new version."
  303. }).error(function () {
  304. $('#restarting').modal('hide');
  305. });
  306. };
  307. $scope.shutdown = function () {
  308. restarting = true;
  309. $http.post(urlbase + '/shutdown').success(function () {
  310. $('#shutdown').modal({backdrop: 'static', keyboard: false});
  311. });
  312. $scope.configInSync = true;
  313. };
  314. $scope.editNode = function (nodeCfg) {
  315. $scope.currentNode = $.extend({}, nodeCfg);
  316. $scope.editingExisting = true;
  317. $scope.editingSelf = (nodeCfg.NodeID == $scope.myID);
  318. $scope.currentNode.AddressesStr = nodeCfg.Addresses.join(', ');
  319. $scope.nodeEditor.$setPristine();
  320. $('#editNode').modal({backdrop: 'static', keyboard: true});
  321. };
  322. $scope.idNode = function () {
  323. $('#idqr').modal('show');
  324. };
  325. $scope.addNode = function () {
  326. $scope.currentNode = {AddressesStr: 'dynamic', Compression: true};
  327. $scope.editingExisting = false;
  328. $scope.editingSelf = false;
  329. $scope.nodeEditor.$setPristine();
  330. $('#editNode').modal({backdrop: 'static', keyboard: true});
  331. };
  332. $scope.deleteNode = function () {
  333. $('#editNode').modal('hide');
  334. if (!$scope.editingExisting) {
  335. return;
  336. }
  337. $scope.nodes = $scope.nodes.filter(function (n) {
  338. return n.NodeID !== $scope.currentNode.NodeID;
  339. });
  340. $scope.config.Nodes = $scope.nodes;
  341. for (var id in $scope.repos) {
  342. $scope.repos[id].Nodes = $scope.repos[id].Nodes.filter(function (n) {
  343. return n.NodeID !== $scope.currentNode.NodeID;
  344. });
  345. }
  346. $scope.saveConfig();
  347. };
  348. $scope.saveNode = function () {
  349. var nodeCfg, done, i;
  350. $('#editNode').modal('hide');
  351. nodeCfg = $scope.currentNode;
  352. nodeCfg.Addresses = nodeCfg.AddressesStr.split(',').map(function (x) { return x.trim(); });
  353. done = false;
  354. for (i = 0; i < $scope.nodes.length; i++) {
  355. if ($scope.nodes[i].NodeID === nodeCfg.NodeID) {
  356. $scope.nodes[i] = nodeCfg;
  357. done = true;
  358. break;
  359. }
  360. }
  361. if (!done) {
  362. $scope.nodes.push(nodeCfg);
  363. }
  364. $scope.nodes.sort(nodeCompare);
  365. $scope.config.Nodes = $scope.nodes;
  366. $scope.saveConfig();
  367. };
  368. $scope.otherNodes = function () {
  369. return $scope.nodes.filter(function (n){
  370. return n.NodeID !== $scope.myID;
  371. });
  372. };
  373. $scope.thisNode = function () {
  374. var i, n;
  375. for (i = 0; i < $scope.nodes.length; i++) {
  376. n = $scope.nodes[i];
  377. if (n.NodeID === $scope.myID) {
  378. return n;
  379. }
  380. }
  381. };
  382. $scope.allNodes = function () {
  383. var nodes = $scope.otherNodes();
  384. nodes.push($scope.thisNode());
  385. return nodes;
  386. };
  387. $scope.errorList = function () {
  388. return $scope.errors.filter(function (e) {
  389. return e.Time > $scope.seenError;
  390. });
  391. };
  392. $scope.clearErrors = function () {
  393. $scope.seenError = $scope.errors[$scope.errors.length - 1].Time;
  394. $http.post(urlbase + '/error/clear');
  395. };
  396. $scope.friendlyNodes = function (str) {
  397. for (var i = 0; i < $scope.nodes.length; i++) {
  398. var cfg = $scope.nodes[i];
  399. str = str.replace(cfg.NodeID, $scope.nodeName(cfg));
  400. }
  401. return str;
  402. };
  403. $scope.repoList = function () {
  404. return repoList($scope.repos);
  405. };
  406. $scope.editRepo = function (nodeCfg) {
  407. $scope.currentRepo = angular.copy(nodeCfg);
  408. $scope.currentRepo.selectedNodes = {};
  409. $scope.currentRepo.Nodes.forEach(function (n) {
  410. $scope.currentRepo.selectedNodes[n.NodeID] = true;
  411. });
  412. if ($scope.currentRepo.Versioning && $scope.currentRepo.Versioning.Type === "simple") {
  413. $scope.currentRepo.simpleFileVersioning = true;
  414. $scope.currentRepo.simpleKeep = +$scope.currentRepo.Versioning.Params.keep;
  415. }
  416. $scope.currentRepo.simpleKeep = $scope.currentRepo.simpleKeep || 5;
  417. $scope.editingExisting = true;
  418. $scope.repoEditor.$setPristine();
  419. $('#editRepo').modal({backdrop: 'static', keyboard: true});
  420. };
  421. $scope.addRepo = function () {
  422. $scope.currentRepo = {selectedNodes: {}};
  423. $scope.editingExisting = false;
  424. $scope.repoEditor.$setPristine();
  425. $('#editRepo').modal({backdrop: 'static', keyboard: true});
  426. };
  427. $scope.saveRepo = function () {
  428. var repoCfg, done, i;
  429. $('#editRepo').modal('hide');
  430. repoCfg = $scope.currentRepo;
  431. repoCfg.Nodes = [];
  432. repoCfg.selectedNodes[$scope.myID] = true;
  433. for (var nodeID in repoCfg.selectedNodes) {
  434. if (repoCfg.selectedNodes[nodeID] === true) {
  435. repoCfg.Nodes.push({NodeID: nodeID});
  436. }
  437. }
  438. delete repoCfg.selectedNodes;
  439. if (repoCfg.simpleFileVersioning) {
  440. repoCfg.Versioning = {
  441. 'Type': 'simple',
  442. 'Params': {
  443. 'keep': '' + repoCfg.simpleKeep,
  444. }
  445. };
  446. delete repoCfg.simpleFileVersioning;
  447. delete repoCfg.simpleKeep;
  448. } else {
  449. delete repoCfg.Versioning;
  450. }
  451. $scope.repos[repoCfg.ID] = repoCfg;
  452. $scope.config.Repositories = repoList($scope.repos);
  453. $scope.saveConfig();
  454. };
  455. $scope.sharesRepo = function(repoCfg) {
  456. var names = [];
  457. repoCfg.Nodes.forEach(function (node) {
  458. names.push($scope.nodeName($scope.findNode(node.NodeID)));
  459. });
  460. names.sort();
  461. return names.join(", ");
  462. };
  463. $scope.deleteRepo = function () {
  464. $('#editRepo').modal('hide');
  465. if (!$scope.editingExisting) {
  466. return;
  467. }
  468. delete $scope.repos[$scope.currentRepo.ID];
  469. $scope.config.Repositories = repoList($scope.repos);
  470. $scope.saveConfig();
  471. };
  472. $scope.setAPIKey = function (cfg) {
  473. cfg.APIKey = randomString(30, 32);
  474. };
  475. $scope.init = function() {
  476. $http.get(urlbase + '/version').success(function (data) {
  477. $scope.version = data;
  478. });
  479. $http.get(urlbase + '/system').success(function (data) {
  480. $scope.system = data;
  481. $scope.myID = data.myID;
  482. });
  483. $http.get(urlbase + '/config').success(function (data) {
  484. $scope.config = data;
  485. $scope.config.Options.ListenStr = $scope.config.Options.ListenAddress.join(', ');
  486. $scope.nodes = $scope.config.Nodes;
  487. $scope.nodes.sort(nodeCompare);
  488. $scope.repos = repoMap($scope.config.Repositories);
  489. $scope.refresh();
  490. if ($scope.config.Options.URAccepted == 0) {
  491. // If usage reporting has been neither accepted nor declined,
  492. // we want to ask the user to make a choice. But we don't want
  493. // to bug them during initial setup, so we set a cookie with
  494. // the time of the first visit. When that cookie is present
  495. // and the time is more than four hours ago, we ask the
  496. // question.
  497. var firstVisit = document.cookie.replace(/(?:(?:^|.*;\s*)firstVisit\s*\=\s*([^;]*).*$)|^.*$/, "$1");
  498. if (!firstVisit) {
  499. document.cookie = "firstVisit=" + Date.now() + ";max-age=" + 30*24*3600;
  500. } else {
  501. if (+firstVisit < Date.now() - 4*3600*1000){
  502. $('#ur').modal({backdrop: 'static', keyboard: false});
  503. }
  504. }
  505. }
  506. });
  507. $http.get(urlbase + '/config/sync').success(function (data) {
  508. $scope.configInSync = data.configInSync;
  509. });
  510. $http.get(urlbase + '/report').success(function (data) {
  511. $scope.reportData = data;
  512. });
  513. $http.get(urlbase + '/upgrade').success(function (data) {
  514. $scope.upgradeInfo = data;
  515. }).error(function () {
  516. $scope.upgradeInfo = {};
  517. });
  518. };
  519. $scope.acceptUR = function () {
  520. $scope.config.Options.URAccepted = 1000; // Larger than the largest existing report version
  521. $scope.saveConfig();
  522. $('#ur').modal('hide');
  523. };
  524. $scope.declineUR = function () {
  525. $scope.config.Options.URAccepted = -1;
  526. $scope.saveConfig();
  527. $('#ur').modal('hide');
  528. };
  529. $scope.showNeed = function (repo) {
  530. $scope.neededLoaded = false;
  531. $('#needed').modal({backdrop: 'static', keyboard: true});
  532. $http.get(urlbase + "/need?repo=" + encodeURIComponent(repo)).success(function (data) {
  533. $scope.needed = data;
  534. $scope.neededLoaded = true;
  535. });
  536. };
  537. $scope.needAction = function (file) {
  538. var fDelete = 4096;
  539. var fDirectory = 16384;
  540. if ((file.Flags & (fDelete+fDirectory)) === fDelete+fDirectory) {
  541. return 'rmdir';
  542. } else if ((file.Flags & fDelete) === fDelete) {
  543. return 'rm';
  544. } else if ((file.Flags & fDirectory) === fDirectory) {
  545. return 'touch';
  546. } else {
  547. return 'sync';
  548. }
  549. };
  550. $scope.override = function (repo) {
  551. $http.post(urlbase + "/model/override?repo=" + encodeURIComponent(repo)).success(function () {
  552. $scope.refresh();
  553. });
  554. };
  555. $scope.about = function () {
  556. $('#about').modal('show');
  557. };
  558. $scope.init();
  559. setInterval($scope.refresh, 10000);
  560. });
  561. function nodeCompare(a, b) {
  562. if (typeof a.Name !== 'undefined' && typeof b.Name !== 'undefined') {
  563. if (a.Name < b.Name)
  564. return -1;
  565. return a.Name > b.Name;
  566. }
  567. if (a.NodeID < b.NodeID) {
  568. return -1;
  569. }
  570. return a.NodeID > b.NodeID;
  571. }
  572. function repoCompare(a, b) {
  573. if (a.Directory < b.Directory) {
  574. return -1;
  575. }
  576. return a.Directory > b.Directory;
  577. }
  578. function repoMap(l) {
  579. var m = {};
  580. l.forEach(function (r) {
  581. m[r.ID] = r;
  582. });
  583. return m;
  584. }
  585. function repoList(m) {
  586. var l = [];
  587. for (var id in m) {
  588. l.push(m[id]);
  589. }
  590. l.sort(repoCompare);
  591. return l;
  592. }
  593. function decimals(val, num) {
  594. var digits, decs;
  595. if (val === 0) {
  596. return 0;
  597. }
  598. digits = Math.floor(Math.log(Math.abs(val)) / Math.log(10));
  599. decs = Math.max(0, num - digits);
  600. return decs;
  601. }
  602. function randomString(len, bits)
  603. {
  604. bits = bits || 36;
  605. var outStr = "", newStr;
  606. while (outStr.length < len)
  607. {
  608. newStr = Math.random().toString(bits).slice(2);
  609. outStr += newStr.slice(0, Math.min(newStr.length, (len - outStr.length)));
  610. }
  611. return outStr.toLowerCase();
  612. }
  613. syncthing.filter('natural', function () {
  614. return function (input, valid) {
  615. return input.toFixed(decimals(input, valid));
  616. };
  617. });
  618. syncthing.filter('binary', function () {
  619. return function (input) {
  620. if (input === undefined) {
  621. return '0 ';
  622. }
  623. if (input > 1024 * 1024 * 1024) {
  624. input /= 1024 * 1024 * 1024;
  625. return input.toFixed(decimals(input, 2)) + ' Gi';
  626. }
  627. if (input > 1024 * 1024) {
  628. input /= 1024 * 1024;
  629. return input.toFixed(decimals(input, 2)) + ' Mi';
  630. }
  631. if (input > 1024) {
  632. input /= 1024;
  633. return input.toFixed(decimals(input, 2)) + ' Ki';
  634. }
  635. return Math.round(input) + ' ';
  636. };
  637. });
  638. syncthing.filter('metric', function () {
  639. return function (input) {
  640. if (input === undefined) {
  641. return '0 ';
  642. }
  643. if (input > 1000 * 1000 * 1000) {
  644. input /= 1000 * 1000 * 1000;
  645. return input.toFixed(decimals(input, 2)) + ' G';
  646. }
  647. if (input > 1000 * 1000) {
  648. input /= 1000 * 1000;
  649. return input.toFixed(decimals(input, 2)) + ' M';
  650. }
  651. if (input > 1000) {
  652. input /= 1000;
  653. return input.toFixed(decimals(input, 2)) + ' k';
  654. }
  655. return Math.round(input) + ' ';
  656. };
  657. });
  658. syncthing.filter('short', function () {
  659. return function (input) {
  660. return input.substr(0, 6);
  661. };
  662. });
  663. syncthing.filter('alwaysNumber', function () {
  664. return function (input) {
  665. if (input === undefined) {
  666. return 0;
  667. }
  668. return input;
  669. };
  670. });
  671. syncthing.filter('shortPath', function () {
  672. return function (input) {
  673. if (input === undefined)
  674. return "";
  675. var parts = input.split(/[\/\\]/);
  676. if (!parts || parts.length <= 3) {
  677. return input;
  678. }
  679. return ".../" + parts.slice(parts.length-2).join("/");
  680. };
  681. });
  682. syncthing.filter('basename', function () {
  683. return function (input) {
  684. if (input === undefined)
  685. return "";
  686. var parts = input.split(/[\/\\]/);
  687. if (!parts || parts.length < 1) {
  688. return input;
  689. }
  690. return parts[parts.length-1];
  691. };
  692. });
  693. syncthing.filter('clean', function () {
  694. return function (input) {
  695. return encodeURIComponent(input).replace(/%/g, '');
  696. };
  697. });
  698. syncthing.directive('optionEditor', function () {
  699. return {
  700. restrict: 'C',
  701. replace: true,
  702. transclude: true,
  703. scope: {
  704. setting: '=setting',
  705. },
  706. template: '<input type="text" ng-model="config.Options[setting.id]"></input>',
  707. };
  708. });
  709. syncthing.directive('uniqueRepo', function() {
  710. return {
  711. require: 'ngModel',
  712. link: function(scope, elm, attrs, ctrl) {
  713. ctrl.$parsers.unshift(function(viewValue) {
  714. if (scope.editingExisting) {
  715. // we shouldn't validate
  716. ctrl.$setValidity('uniqueRepo', true);
  717. } else if (scope.repos[viewValue]) {
  718. // the repo exists already
  719. ctrl.$setValidity('uniqueRepo', false);
  720. } else {
  721. // the repo is unique
  722. ctrl.$setValidity('uniqueRepo', true);
  723. }
  724. return viewValue;
  725. });
  726. }
  727. };
  728. });
  729. syncthing.directive('validNodeid', function($http) {
  730. return {
  731. require: 'ngModel',
  732. link: function(scope, elm, attrs, ctrl) {
  733. ctrl.$parsers.unshift(function(viewValue) {
  734. if (scope.editingExisting) {
  735. // we shouldn't validate
  736. ctrl.$setValidity('validNodeid', true);
  737. } else {
  738. $http.get(urlbase + '/nodeid?id='+viewValue).success(function (resp) {
  739. if (resp.error) {
  740. ctrl.$setValidity('validNodeid', false);
  741. } else {
  742. scope.currentNode.NodeID = resp.id;
  743. ctrl.$setValidity('validNodeid', true);
  744. }
  745. });
  746. }
  747. return viewValue;
  748. });
  749. }
  750. };
  751. });
  752. syncthing.directive('modal', function () {
  753. return {
  754. restrict: 'E',
  755. templateUrl: 'modal.html',
  756. replace: true,
  757. transclude: true,
  758. scope: {
  759. title: '@',
  760. status: '@',
  761. icon: '@',
  762. close: '@',
  763. large: '@',
  764. },
  765. }
  766. });