app.js 18 KB

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