app.js 18 KB

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