app.js 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645
  1. /*jslint browser: true, continue: true, plusplus: true */
  2. /*global $: false, angular: false */
  3. 'use strict';
  4. var syncthing = angular.module('syncthing', []);
  5. var urlbase = 'rest';
  6. syncthing.controller('SyncthingCtrl', function ($scope, $http) {
  7. var prevDate = 0;
  8. var getOK = true;
  9. var restarting = false;
  10. $scope.connections = {};
  11. $scope.config = {};
  12. $scope.myID = '';
  13. $scope.nodes = [];
  14. $scope.configInSync = true;
  15. $scope.errors = [];
  16. $scope.seenError = '';
  17. $scope.model = {};
  18. $scope.repos = {};
  19. // Strings before bools look better
  20. $scope.settings = [
  21. {id: 'ListenStr', descr: 'Sync Protocol Listen Addresses', type: 'text', restart: true},
  22. {id: 'MaxSendKbps', descr: 'Outgoing Rate Limit (KiB/s)', type: 'number', restart: true},
  23. {id: 'RescanIntervalS', descr: 'Rescan Interval (s)', type: 'number', restart: true},
  24. {id: 'ReconnectIntervalS', descr: 'Reconnect Interval (s)', type: 'number', restart: true},
  25. {id: 'ParallelRequests', descr: 'Max Outstanding Requests', type: 'number', restart: true},
  26. {id: 'MaxChangeKbps', descr: 'Max File Change Rate (KiB/s)', type: 'number', restart: true},
  27. {id: 'GlobalAnnEnabled', descr: 'Global Announce', type: 'bool', restart: true},
  28. {id: 'LocalAnnEnabled', descr: 'Local Announce', type: 'bool', restart: true},
  29. {id: 'StartBrowser', descr: 'Start Browser', type: 'bool'},
  30. {id: 'UPnPEnabled', descr: 'Enable UPnP', type: 'bool'},
  31. ];
  32. $scope.guiSettings = [
  33. {id: 'Address', descr: 'GUI Listen Addresses', type: 'text', restart: true},
  34. {id: 'User', descr: 'GUI Authentication User', type: 'text', restart: true},
  35. {id: 'Password', descr: 'GUI Authentication Password', type: 'password', restart: true},
  36. {id: 'UseTLS', descr: 'Use HTTPS for GUI', type: 'bool', restart: true},
  37. ];
  38. function getSucceeded() {
  39. if (!getOK) {
  40. $scope.init();
  41. $('#networkError').modal('hide');
  42. getOK = true;
  43. }
  44. if (restarting) {
  45. $scope.init();
  46. $('#restarting').modal('hide');
  47. restarting = false;
  48. }
  49. }
  50. function getFailed() {
  51. if (restarting) {
  52. return;
  53. }
  54. if (getOK) {
  55. $('#networkError').modal({backdrop: 'static', keyboard: false});
  56. getOK = false;
  57. }
  58. }
  59. $scope.refresh = function () {
  60. $http.get(urlbase + '/system').success(function (data) {
  61. getSucceeded();
  62. $scope.system = data;
  63. }).error(function () {
  64. getFailed();
  65. });
  66. Object.keys($scope.repos).forEach(function (id) {
  67. $http.get(urlbase + '/model?repo=' + encodeURIComponent(id)).success(function (data) {
  68. $scope.model[id] = data;
  69. });
  70. });
  71. $http.get(urlbase + '/connections').success(function (data) {
  72. var now = Date.now(),
  73. td = (now - prevDate) / 1000,
  74. id;
  75. prevDate = now;
  76. $scope.inbps = 0;
  77. $scope.outbps = 0;
  78. for (id in data) {
  79. if (!data.hasOwnProperty(id)) {
  80. continue;
  81. }
  82. try {
  83. data[id].inbps = Math.max(0, 8 * (data[id].InBytesTotal - $scope.connections[id].InBytesTotal) / td);
  84. data[id].outbps = Math.max(0, 8 * (data[id].OutBytesTotal - $scope.connections[id].OutBytesTotal) / td);
  85. } catch (e) {
  86. data[id].inbps = 0;
  87. data[id].outbps = 0;
  88. }
  89. $scope.inbps += data[id].inbps;
  90. $scope.outbps += data[id].outbps;
  91. }
  92. $scope.connections = data;
  93. });
  94. $http.get(urlbase + '/errors').success(function (data) {
  95. $scope.errors = data;
  96. });
  97. };
  98. $scope.repoStatus = function (repo) {
  99. if (typeof $scope.model[repo] === 'undefined') {
  100. return 'Unknown';
  101. }
  102. if ($scope.model[repo].invalid !== '') {
  103. return 'Stopped';
  104. }
  105. var state = '' + $scope.model[repo].state;
  106. state = state[0].toUpperCase() + state.substr(1);
  107. if (state == "Syncing" || state == "Idle") {
  108. state += " (" + $scope.syncPercentage(repo) + "%)";
  109. }
  110. return state;
  111. }
  112. $scope.repoClass = function (repo) {
  113. if (typeof $scope.model[repo] === 'undefined') {
  114. return 'info';
  115. }
  116. if ($scope.model[repo].invalid !== '') {
  117. return 'danger';
  118. }
  119. var state = '' + $scope.model[repo].state;
  120. if (state == 'idle') {
  121. return 'success';
  122. }
  123. if (state == 'syncing') {
  124. return 'primary';
  125. }
  126. return 'info';
  127. }
  128. $scope.syncPercentage = function (repo) {
  129. if (typeof $scope.model[repo] === 'undefined') {
  130. return 100;
  131. }
  132. if ($scope.model[repo].globalBytes === 0) {
  133. return 100;
  134. }
  135. var pct = 100 * $scope.model[repo].inSyncBytes / $scope.model[repo].globalBytes;
  136. return Math.floor(pct);
  137. };
  138. $scope.nodeStatus = function (nodeCfg) {
  139. var conn = $scope.connections[nodeCfg.NodeID];
  140. if (conn) {
  141. if (conn.Completion === 100) {
  142. return 'In Sync';
  143. } else {
  144. return 'Syncing (' + conn.Completion + '%)';
  145. }
  146. }
  147. return 'Disconnected';
  148. };
  149. $scope.nodeIcon = function (nodeCfg) {
  150. var conn = $scope.connections[nodeCfg.NodeID];
  151. if (conn) {
  152. if (conn.Completion === 100) {
  153. return 'ok';
  154. } else {
  155. return 'refresh';
  156. }
  157. }
  158. return 'minus';
  159. };
  160. $scope.nodeClass = function (nodeCfg) {
  161. var conn = $scope.connections[nodeCfg.NodeID];
  162. if (conn) {
  163. if (conn.Completion === 100) {
  164. return 'success';
  165. } else {
  166. return 'primary';
  167. }
  168. }
  169. return 'info';
  170. };
  171. $scope.nodeAddr = function (nodeCfg) {
  172. var conn = $scope.connections[nodeCfg.NodeID];
  173. if (conn) {
  174. return conn.Address;
  175. }
  176. return '?';
  177. };
  178. $scope.nodeCompletion = function (nodeCfg) {
  179. var conn = $scope.connections[nodeCfg.NodeID];
  180. if (conn) {
  181. return conn.Completion + '%';
  182. }
  183. return '';
  184. };
  185. $scope.nodeVer = function (nodeCfg) {
  186. if (nodeCfg.NodeID === $scope.myID) {
  187. return $scope.version;
  188. }
  189. var conn = $scope.connections[nodeCfg.NodeID];
  190. if (conn) {
  191. return conn.ClientVersion;
  192. }
  193. return '?';
  194. };
  195. $scope.findNode = function (nodeID) {
  196. var matches = $scope.nodes.filter(function (n) { return n.NodeID == nodeID; });
  197. if (matches.length != 1) {
  198. return undefined;
  199. }
  200. return matches[0];
  201. };
  202. $scope.nodeName = function (nodeCfg) {
  203. if (typeof nodeCfg === 'undefined') {
  204. return "";
  205. }
  206. if (nodeCfg.Name) {
  207. return nodeCfg.Name;
  208. }
  209. return nodeCfg.NodeID.substr(0, 6);
  210. };
  211. $scope.thisNodeName = function () {
  212. var node = $scope.thisNode();
  213. if (typeof node === 'undefined') {
  214. return "(unknown node)";
  215. }
  216. if (node.Name) {
  217. return node.Name;
  218. }
  219. return node.NodeID.substr(0, 6);
  220. };
  221. $scope.editSettings = function () {
  222. $('#settings').modal({backdrop: 'static', keyboard: true});
  223. }
  224. $scope.saveSettings = function () {
  225. $scope.configInSync = false;
  226. $scope.config.Options.ListenAddress = $scope.config.Options.ListenStr.split(',').map(function (x) { return x.trim(); });
  227. $http.post(urlbase + '/config', JSON.stringify($scope.config), {headers: {'Content-Type': 'application/json'}});
  228. $('#settings').modal("hide");
  229. };
  230. $scope.restart = function () {
  231. restarting = true;
  232. $('#restarting').modal({backdrop: 'static', keyboard: false});
  233. $http.post(urlbase + '/restart');
  234. $scope.configInSync = true;
  235. };
  236. $scope.shutdown = function () {
  237. restarting = true;
  238. $http.post(urlbase + '/shutdown').success(function () {
  239. $('#shutdown').modal({backdrop: 'static', keyboard: false});
  240. });
  241. $scope.configInSync = true;
  242. };
  243. $scope.editNode = function (nodeCfg) {
  244. $scope.currentNode = $.extend({}, nodeCfg);
  245. $scope.editingExisting = true;
  246. $scope.editingSelf = (nodeCfg.NodeID == $scope.myID);
  247. $scope.currentNode.AddressesStr = nodeCfg.Addresses.join(', ');
  248. $scope.nodeEditor.$setPristine();
  249. $('#editNode').modal({backdrop: 'static', keyboard: true});
  250. };
  251. $scope.idNode = function () {
  252. $('#idqr').modal('show');
  253. };
  254. $scope.addNode = function () {
  255. $scope.currentNode = {AddressesStr: 'dynamic'};
  256. $scope.editingExisting = false;
  257. $scope.editingSelf = false;
  258. $scope.nodeEditor.$setPristine();
  259. $('#editNode').modal({backdrop: 'static', keyboard: true});
  260. };
  261. $scope.deleteNode = function () {
  262. $('#editNode').modal('hide');
  263. if (!$scope.editingExisting) {
  264. return;
  265. }
  266. $scope.nodes = $scope.nodes.filter(function (n) {
  267. return n.NodeID !== $scope.currentNode.NodeID;
  268. });
  269. $scope.config.Nodes = $scope.nodes;
  270. for (var id in $scope.repos) {
  271. $scope.repos[id].Nodes = $scope.repos[id].Nodes.filter(function (n) {
  272. return n.NodeID !== $scope.currentNode.NodeID;
  273. });
  274. }
  275. $scope.configInSync = false;
  276. $http.post(urlbase + '/config', JSON.stringify($scope.config), {headers: {'Content-Type': 'application/json'}});
  277. };
  278. $scope.saveNode = function () {
  279. var nodeCfg, done, i;
  280. $scope.configInSync = false;
  281. $('#editNode').modal('hide');
  282. nodeCfg = $scope.currentNode;
  283. nodeCfg.NodeID = nodeCfg.NodeID.replace(/ /g, '').replace(/-/g, '').trim();
  284. nodeCfg.Addresses = nodeCfg.AddressesStr.split(',').map(function (x) { return x.trim(); });
  285. done = false;
  286. for (i = 0; i < $scope.nodes.length; i++) {
  287. if ($scope.nodes[i].NodeID === nodeCfg.NodeID) {
  288. $scope.nodes[i] = nodeCfg;
  289. done = true;
  290. break;
  291. }
  292. }
  293. if (!done) {
  294. $scope.nodes.push(nodeCfg);
  295. }
  296. $scope.nodes.sort(nodeCompare);
  297. $scope.config.Nodes = $scope.nodes;
  298. $http.post(urlbase + '/config', JSON.stringify($scope.config), {headers: {'Content-Type': 'application/json'}});
  299. };
  300. $scope.otherNodes = function () {
  301. return $scope.nodes.filter(function (n){
  302. return n.NodeID !== $scope.myID;
  303. });
  304. };
  305. $scope.thisNode = function () {
  306. var i, n;
  307. for (i = 0; i < $scope.nodes.length; i++) {
  308. n = $scope.nodes[i];
  309. if (n.NodeID === $scope.myID) {
  310. return n;
  311. }
  312. }
  313. };
  314. $scope.allNodes = function () {
  315. var nodes = $scope.otherNodes();
  316. nodes.push($scope.thisNode());
  317. return nodes;
  318. };
  319. $scope.errorList = function () {
  320. return $scope.errors.filter(function (e) {
  321. return e.Time > $scope.seenError;
  322. });
  323. };
  324. $scope.clearErrors = function () {
  325. $scope.seenError = $scope.errors[$scope.errors.length - 1].Time;
  326. $http.post(urlbase + '/error/clear');
  327. };
  328. $scope.friendlyNodes = function (str) {
  329. for (var i = 0; i < $scope.nodes.length; i++) {
  330. var cfg = $scope.nodes[i];
  331. str = str.replace(cfg.NodeID, $scope.nodeName(cfg));
  332. }
  333. return str;
  334. };
  335. $scope.repoList = function () {
  336. return repoList($scope.repos);
  337. }
  338. $scope.editRepo = function (nodeCfg) {
  339. $scope.currentRepo = $.extend({selectedNodes: {}}, nodeCfg);
  340. $scope.currentRepo.Nodes.forEach(function (n) {
  341. $scope.currentRepo.selectedNodes[n.NodeID] = true;
  342. });
  343. $scope.editingExisting = true;
  344. $scope.repoEditor.$setPristine();
  345. $('#editRepo').modal({backdrop: 'static', keyboard: true});
  346. };
  347. $scope.addRepo = function () {
  348. $scope.currentRepo = {selectedNodes: {}};
  349. $scope.editingExisting = false;
  350. $scope.repoEditor.$setPristine();
  351. $('#editRepo').modal({backdrop: 'static', keyboard: true});
  352. };
  353. $scope.saveRepo = function () {
  354. var repoCfg, done, i;
  355. $scope.configInSync = false;
  356. $('#editRepo').modal('hide');
  357. repoCfg = $scope.currentRepo;
  358. repoCfg.Nodes = [];
  359. repoCfg.selectedNodes[$scope.myID] = true;
  360. for (var nodeID in repoCfg.selectedNodes) {
  361. if (repoCfg.selectedNodes[nodeID] === true) {
  362. repoCfg.Nodes.push({NodeID: nodeID});
  363. }
  364. }
  365. delete repoCfg.selectedNodes;
  366. $scope.repos[repoCfg.ID] = repoCfg;
  367. $scope.config.Repositories = repoList($scope.repos);
  368. $http.post(urlbase + '/config', JSON.stringify($scope.config), {headers: {'Content-Type': 'application/json'}});
  369. };
  370. $scope.deleteRepo = function () {
  371. $('#editRepo').modal('hide');
  372. if (!$scope.editingExisting) {
  373. return;
  374. }
  375. delete $scope.repos[$scope.currentRepo.ID];
  376. $scope.config.Repositories = repoList($scope.repos);
  377. $scope.configInSync = false;
  378. $http.post(urlbase + '/config', JSON.stringify($scope.config), {headers: {'Content-Type': 'application/json'}});
  379. };
  380. $scope.init = function() {
  381. $http.get(urlbase + '/version').success(function (data) {
  382. $scope.version = data;
  383. });
  384. $http.get(urlbase + '/system').success(function (data) {
  385. $scope.system = data;
  386. $scope.myID = data.myID;
  387. });
  388. $http.get(urlbase + '/config').success(function (data) {
  389. $scope.config = data;
  390. $scope.config.Options.ListenStr = $scope.config.Options.ListenAddress.join(', ');
  391. $scope.nodes = $scope.config.Nodes;
  392. $scope.nodes.sort(nodeCompare);
  393. $scope.repos = repoMap($scope.config.Repositories);
  394. $scope.refresh();
  395. });
  396. $http.get(urlbase + '/config/sync').success(function (data) {
  397. $scope.configInSync = data.configInSync;
  398. });
  399. };
  400. $scope.init();
  401. setInterval($scope.refresh, 10000);
  402. });
  403. function nodeCompare(a, b) {
  404. if (typeof a.Name !== 'undefined' && typeof b.Name !== 'undefined') {
  405. if (a.Name < b.Name)
  406. return -1;
  407. return a.Name > b.Name;
  408. }
  409. if (a.NodeID < b.NodeID) {
  410. return -1;
  411. }
  412. return a.NodeID > b.NodeID;
  413. }
  414. function repoCompare(a, b) {
  415. if (a.Directory < b.Directory) {
  416. return -1;
  417. }
  418. return a.Directory > b.Directory;
  419. }
  420. function repoMap(l) {
  421. var m = {};
  422. l.forEach(function (r) {
  423. m[r.ID] = r;
  424. });
  425. return m;
  426. }
  427. function repoList(m) {
  428. var l = [];
  429. for (var id in m) {
  430. l.push(m[id])
  431. }
  432. l.sort(repoCompare);
  433. return l;
  434. }
  435. function decimals(val, num) {
  436. var digits, decs;
  437. if (val === 0) {
  438. return 0;
  439. }
  440. digits = Math.floor(Math.log(Math.abs(val)) / Math.log(10));
  441. decs = Math.max(0, num - digits);
  442. return decs;
  443. }
  444. syncthing.filter('natural', function () {
  445. return function (input, valid) {
  446. return input.toFixed(decimals(input, valid));
  447. };
  448. });
  449. syncthing.filter('binary', function () {
  450. return function (input) {
  451. if (input === undefined) {
  452. return '0 ';
  453. }
  454. if (input > 1024 * 1024 * 1024) {
  455. input /= 1024 * 1024 * 1024;
  456. return input.toFixed(decimals(input, 2)) + ' Gi';
  457. }
  458. if (input > 1024 * 1024) {
  459. input /= 1024 * 1024;
  460. return input.toFixed(decimals(input, 2)) + ' Mi';
  461. }
  462. if (input > 1024) {
  463. input /= 1024;
  464. return input.toFixed(decimals(input, 2)) + ' Ki';
  465. }
  466. return Math.round(input) + ' ';
  467. };
  468. });
  469. syncthing.filter('metric', function () {
  470. return function (input) {
  471. if (input === undefined) {
  472. return '0 ';
  473. }
  474. if (input > 1000 * 1000 * 1000) {
  475. input /= 1000 * 1000 * 1000;
  476. return input.toFixed(decimals(input, 2)) + ' G';
  477. }
  478. if (input > 1000 * 1000) {
  479. input /= 1000 * 1000;
  480. return input.toFixed(decimals(input, 2)) + ' M';
  481. }
  482. if (input > 1000) {
  483. input /= 1000;
  484. return input.toFixed(decimals(input, 2)) + ' k';
  485. }
  486. return Math.round(input) + ' ';
  487. };
  488. });
  489. syncthing.filter('short', function () {
  490. return function (input) {
  491. return input.substr(0, 6);
  492. };
  493. });
  494. syncthing.filter('alwaysNumber', function () {
  495. return function (input) {
  496. if (input === undefined) {
  497. return 0;
  498. }
  499. return input;
  500. };
  501. });
  502. syncthing.filter('chunkID', function () {
  503. return function (input) {
  504. if (input === undefined)
  505. return "";
  506. var parts = input.match(/.{1,6}/g);
  507. if (!parts)
  508. return "";
  509. return parts.join('-');
  510. }
  511. });
  512. syncthing.filter('shortPath', function () {
  513. return function (input) {
  514. if (input === undefined)
  515. return "";
  516. var parts = input.split(/[\/\\]/);
  517. if (!parts || parts.length <= 3) {
  518. return input;
  519. }
  520. return ".../" + parts.slice(parts.length-2).join("/");
  521. }
  522. });
  523. syncthing.directive('optionEditor', function () {
  524. return {
  525. restrict: 'C',
  526. replace: true,
  527. transclude: true,
  528. scope: {
  529. setting: '=setting',
  530. },
  531. template: '<input type="text" ng-model="config.Options[setting.id]"></input>',
  532. };
  533. });
  534. syncthing.directive('uniqueRepo', function() {
  535. return {
  536. require: 'ngModel',
  537. link: function(scope, elm, attrs, ctrl) {
  538. ctrl.$parsers.unshift(function(viewValue) {
  539. if (scope.editingExisting) {
  540. // we shouldn't validate
  541. ctrl.$setValidity('uniqueRepo', true);
  542. } else if (scope.repos[viewValue]) {
  543. // the repo exists already
  544. ctrl.$setValidity('uniqueRepo', false);
  545. } else {
  546. // the repo is unique
  547. ctrl.$setValidity('uniqueRepo', true);
  548. }
  549. return viewValue;
  550. });
  551. }
  552. };
  553. });