app.js 24 KB

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