app.js 26 KB

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