app.js 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071
  1. // Copyright (C) 2014 Jakob Borg and Contributors (see the CONTRIBUTORS file).
  2. // All rights reserved. Use of this source code is governed by an MIT-style
  3. // license that can be 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', ['pascalprecht.translate']);
  8. var urlbase = 'rest';
  9. syncthing.config(function ($httpProvider, $translateProvider) {
  10. $httpProvider.defaults.xsrfHeaderName = 'X-CSRF-Token';
  11. $httpProvider.defaults.xsrfCookieName = 'CSRF-Token';
  12. $translateProvider.useStaticFilesLoader({
  13. prefix: 'lang-',
  14. suffix: '.json'
  15. });
  16. });
  17. syncthing.controller('EventCtrl', function ($scope, $http) {
  18. $scope.lastEvent = null;
  19. var online = false;
  20. var lastID = 0;
  21. var successFn = function (data) {
  22. if (!online) {
  23. $scope.$emit('UIOnline');
  24. online = true;
  25. }
  26. if (lastID > 0) {
  27. data.forEach(function (event) {
  28. console.log("event", event.id, event.type, event.data);
  29. $scope.$emit(event.type, event);
  30. });
  31. };
  32. $scope.lastEvent = data[data.length - 1];
  33. lastID = $scope.lastEvent.id;
  34. setTimeout(function () {
  35. $http.get(urlbase + '/events?since=' + lastID)
  36. .success(successFn)
  37. .error(errorFn);
  38. }, 500);
  39. };
  40. var errorFn = function (data) {
  41. if (online) {
  42. $scope.$emit('UIOffline');
  43. online = false;
  44. }
  45. setTimeout(function () {
  46. $http.get(urlbase + '/events?limit=1')
  47. .success(successFn)
  48. .error(errorFn);
  49. }, 1000);
  50. };
  51. $http.get(urlbase + '/events?limit=1')
  52. .success(successFn)
  53. .error(errorFn);
  54. });
  55. syncthing.controller('SyncthingCtrl', function ($scope, $http, $translate, $location) {
  56. var prevDate = 0;
  57. var getOK = true;
  58. var restarting = false;
  59. $scope.completion = {};
  60. $scope.config = {};
  61. $scope.configInSync = true;
  62. $scope.connections = {};
  63. $scope.errors = [];
  64. $scope.model = {};
  65. $scope.myID = '';
  66. $scope.nodes = [];
  67. $scope.protocolChanged = false;
  68. $scope.reportData = {};
  69. $scope.reportPreview = false;
  70. $scope.repos = {};
  71. $scope.seenError = '';
  72. $scope.upgradeInfo = {};
  73. $http.get(urlbase+"/lang").success(function (langs) {
  74. var lang;
  75. for (var i = 0; i < langs.length; i++) {
  76. lang = langs[i];
  77. if (validLangs.indexOf(lang) >= 0) {
  78. $translate.use(lang);
  79. break;
  80. }
  81. }
  82. })
  83. $scope.$on("$locationChangeSuccess", function () {
  84. var lang = $location.search().lang;
  85. if (lang) {
  86. $translate.use(lang);
  87. }
  88. });
  89. $scope.needActions = {
  90. 'rm': 'Del',
  91. 'rmdir': 'Del (dir)',
  92. 'sync': 'Sync',
  93. 'touch': 'Update',
  94. }
  95. $scope.needIcons = {
  96. 'rm': 'remove',
  97. 'rmdir': 'remove',
  98. 'sync': 'download',
  99. 'touch': 'asterisk',
  100. }
  101. $scope.$on('UIOnline', function (event, arg) {
  102. console.log('UIOnline');
  103. $scope.init();
  104. restarting = false;
  105. $('#networkError').modal('hide');
  106. $('#restarting').modal('hide');
  107. $('#shutdown').modal('hide');
  108. });
  109. $scope.$on('UIOffline', function (event, arg) {
  110. console.log('UIOffline');
  111. if (!restarting) {
  112. $('#networkError').modal({backdrop: 'static', keyboard: false});
  113. }
  114. });
  115. $scope.$on('StateChanged', function (event, arg) {
  116. var data = arg.data;
  117. if ($scope.model[data.repo]) {
  118. $scope.model[data.repo].state = data.to;
  119. }
  120. });
  121. $scope.$on('LocalIndexUpdated', function (event, arg) {
  122. var data = arg.data;
  123. refreshRepo(data.repo);
  124. // Update completion status for all nodes that we share this repo with.
  125. $scope.repos[data.repo].Nodes.forEach(function (nodeCfg) {
  126. refreshCompletion(nodeCfg.NodeID, data.repo);
  127. });
  128. });
  129. $scope.$on('RemoteIndexUpdated', function (event, arg) {
  130. var data = arg.data;
  131. refreshRepo(data.repo);
  132. refreshCompletion(data.node, data.repo);
  133. });
  134. $scope.$on('NodeDisconnected', function (event, arg) {
  135. delete $scope.connections[arg.data.id];
  136. });
  137. $scope.$on('NodeConnected', function (event, arg) {
  138. if (!$scope.connections[arg.data.id]) {
  139. $scope.connections[arg.data.id] = {
  140. inbps: 0,
  141. outbps: 0,
  142. InBytesTotal: 0,
  143. OutBytesTotal: 0,
  144. Address: arg.data.addr,
  145. };
  146. $scope.completion[arg.data.id] = {
  147. _total: 100,
  148. };
  149. }
  150. });
  151. $scope.$on('ConfigLoaded', function (event) {
  152. if ($scope.config.Options.URAccepted == 0) {
  153. // If usage reporting has been neither accepted nor declined,
  154. // we want to ask the user to make a choice. But we don't want
  155. // to bug them during initial setup, so we set a cookie with
  156. // the time of the first visit. When that cookie is present
  157. // and the time is more than four hours ago, we ask the
  158. // question.
  159. var firstVisit = document.cookie.replace(/(?:(?:^|.*;\s*)firstVisit\s*\=\s*([^;]*).*$)|^.*$/, "$1");
  160. if (!firstVisit) {
  161. document.cookie = "firstVisit=" + Date.now() + ";max-age=" + 30*24*3600;
  162. } else {
  163. if (+firstVisit < Date.now() - 4*3600*1000){
  164. $('#ur').modal({backdrop: 'static', keyboard: false});
  165. }
  166. }
  167. }
  168. })
  169. var debouncedFuncs = {};
  170. function refreshRepo(repo) {
  171. var key = "refreshRepo" + repo;
  172. if (!debouncedFuncs[key]) {
  173. debouncedFuncs[key] = debounce(function () {
  174. $http.get(urlbase + '/model?repo=' + encodeURIComponent(repo)).success(function (data) {
  175. $scope.model[repo] = data;
  176. console.log("refreshRepo", repo, data);
  177. });
  178. }, 1000, true);
  179. }
  180. debouncedFuncs[key]();
  181. }
  182. function refreshSystem() {
  183. $http.get(urlbase + '/system').success(function (data) {
  184. $scope.myID = data.myID;
  185. $scope.system = data;
  186. console.log("refreshSystem", data);
  187. });
  188. }
  189. function refreshCompletion(node, repo) {
  190. if (node === $scope.myID) {
  191. return
  192. }
  193. var key = "refreshCompletion" + node + repo;
  194. if (!debouncedFuncs[key]) {
  195. debouncedFuncs[key] = debounce(function () {
  196. $http.get(urlbase + '/completion?node=' + node + '&repo=' + encodeURIComponent(repo)).success(function (data) {
  197. if (!$scope.completion[node]) {
  198. $scope.completion[node] = {};
  199. }
  200. $scope.completion[node][repo] = data.completion;
  201. var tot = 0, cnt = 0;
  202. for (var cmp in $scope.completion[node]) {
  203. if (cmp === "_total") {
  204. continue;
  205. }
  206. tot += $scope.completion[node][cmp];
  207. cnt += 1;
  208. }
  209. $scope.completion[node]._total = tot / cnt;
  210. console.log("refreshCompletion", node, repo, $scope.completion[node]);
  211. });
  212. }, 1000, true);
  213. }
  214. debouncedFuncs[key]();
  215. }
  216. function refreshConnectionStats() {
  217. $http.get(urlbase + '/connections').success(function (data) {
  218. var now = Date.now(),
  219. td = (now - prevDate) / 1000,
  220. id;
  221. prevDate = now;
  222. for (id in data) {
  223. if (!data.hasOwnProperty(id)) {
  224. continue;
  225. }
  226. try {
  227. data[id].inbps = Math.max(0, 8 * (data[id].InBytesTotal - $scope.connections[id].InBytesTotal) / td);
  228. data[id].outbps = Math.max(0, 8 * (data[id].OutBytesTotal - $scope.connections[id].OutBytesTotal) / td);
  229. } catch (e) {
  230. data[id].inbps = 0;
  231. data[id].outbps = 0;
  232. }
  233. }
  234. $scope.connections = data;
  235. console.log("refreshConnections", data);
  236. });
  237. }
  238. function refreshErrors() {
  239. $http.get(urlbase + '/errors').success(function (data) {
  240. $scope.errors = data;
  241. console.log("refreshErrors", data);
  242. });
  243. }
  244. function refreshConfig() {
  245. $http.get(urlbase + '/config').success(function (data) {
  246. var hasConfig = !isEmptyObject($scope.config);
  247. $scope.config = data;
  248. $scope.config.Options.ListenStr = $scope.config.Options.ListenAddress.join(', ');
  249. $scope.nodes = $scope.config.Nodes;
  250. $scope.nodes.forEach(function (nodeCfg) {
  251. $scope.completion[nodeCfg.NodeID] = {
  252. _total: 100,
  253. };
  254. });
  255. $scope.nodes.sort(nodeCompare);
  256. $scope.repos = repoMap($scope.config.Repositories);
  257. Object.keys($scope.repos).forEach(function (repo) {
  258. refreshRepo(repo);
  259. $scope.repos[repo].Nodes.forEach(function (nodeCfg) {
  260. refreshCompletion(nodeCfg.NodeID, repo);
  261. });
  262. });
  263. if (!hasConfig) {
  264. $scope.$emit('ConfigLoaded');
  265. }
  266. console.log("refreshConfig", data);
  267. });
  268. $http.get(urlbase + '/config/sync').success(function (data) {
  269. $scope.configInSync = data.configInSync;
  270. });
  271. }
  272. $scope.init = function() {
  273. refreshSystem();
  274. refreshConfig();
  275. refreshConnectionStats();
  276. $http.get(urlbase + '/version').success(function (data) {
  277. $scope.version = data;
  278. });
  279. $http.get(urlbase + '/report').success(function (data) {
  280. $scope.reportData = data;
  281. });
  282. $http.get(urlbase + '/upgrade').success(function (data) {
  283. $scope.upgradeInfo = data;
  284. }).error(function () {
  285. $scope.upgradeInfo = {};
  286. });
  287. };
  288. $scope.refresh = function () {
  289. refreshSystem();
  290. refreshConnectionStats();
  291. refreshErrors();
  292. };
  293. $scope.repoStatus = function (repo) {
  294. if (typeof $scope.model[repo] === 'undefined') {
  295. return 'unknown';
  296. }
  297. if ($scope.model[repo].invalid !== '') {
  298. return 'stopped';
  299. }
  300. return '' + $scope.model[repo].state;
  301. };
  302. $scope.repoClass = function (repo) {
  303. if (typeof $scope.model[repo] === 'undefined') {
  304. return 'info';
  305. }
  306. if ($scope.model[repo].invalid !== '') {
  307. return 'danger';
  308. }
  309. var state = '' + $scope.model[repo].state;
  310. if (state == 'idle') {
  311. return 'success';
  312. }
  313. if (state == 'syncing') {
  314. return 'primary';
  315. }
  316. if (state == 'scanning') {
  317. return 'primary';
  318. }
  319. return 'info';
  320. };
  321. $scope.syncPercentage = function (repo) {
  322. if (typeof $scope.model[repo] === 'undefined') {
  323. return 100;
  324. }
  325. if ($scope.model[repo].globalBytes === 0) {
  326. return 100;
  327. }
  328. var pct = 100 * $scope.model[repo].inSyncBytes / $scope.model[repo].globalBytes;
  329. return Math.floor(pct);
  330. };
  331. $scope.nodeIcon = function (nodeCfg) {
  332. if ($scope.connections[nodeCfg.NodeID]) {
  333. if ($scope.completion[nodeCfg.NodeID] && $scope.completion[nodeCfg.NodeID]._total === 100) {
  334. return 'ok';
  335. } else {
  336. return 'refresh';
  337. }
  338. }
  339. return 'minus';
  340. };
  341. $scope.nodeClass = function (nodeCfg) {
  342. if ($scope.connections[nodeCfg.NodeID]) {
  343. if ($scope.completion[nodeCfg.NodeID] && $scope.completion[nodeCfg.NodeID]._total === 100) {
  344. return 'success';
  345. } else {
  346. return 'primary';
  347. }
  348. }
  349. return 'info';
  350. };
  351. $scope.nodeAddr = function (nodeCfg) {
  352. var conn = $scope.connections[nodeCfg.NodeID];
  353. if (conn) {
  354. return conn.Address;
  355. }
  356. return '?';
  357. };
  358. $scope.nodeCompletion = function (nodeCfg) {
  359. var conn = $scope.connections[nodeCfg.NodeID];
  360. if (conn) {
  361. return conn.Completion + '%';
  362. }
  363. return '';
  364. };
  365. $scope.nodeVer = function (nodeCfg) {
  366. if (nodeCfg.NodeID === $scope.myID) {
  367. return $scope.version;
  368. }
  369. var conn = $scope.connections[nodeCfg.NodeID];
  370. if (conn) {
  371. return conn.ClientVersion;
  372. }
  373. return '?';
  374. };
  375. $scope.findNode = function (nodeID) {
  376. var matches = $scope.nodes.filter(function (n) { return n.NodeID == nodeID; });
  377. if (matches.length != 1) {
  378. return undefined;
  379. }
  380. return matches[0];
  381. };
  382. $scope.nodeName = function (nodeCfg) {
  383. if (typeof nodeCfg === 'undefined') {
  384. return "";
  385. }
  386. if (nodeCfg.Name) {
  387. return nodeCfg.Name;
  388. }
  389. return nodeCfg.NodeID.substr(0, 6);
  390. };
  391. $scope.thisNodeName = function () {
  392. var node = $scope.thisNode();
  393. if (typeof node === 'undefined') {
  394. return "(unknown node)";
  395. }
  396. if (node.Name) {
  397. return node.Name;
  398. }
  399. return node.NodeID.substr(0, 6);
  400. };
  401. $scope.editSettings = function () {
  402. // Make a working copy
  403. $scope.tmpOptions = angular.copy($scope.config.Options);
  404. $scope.tmpOptions.UREnabled = ($scope.tmpOptions.URAccepted > 0);
  405. $scope.tmpGUI = angular.copy($scope.config.GUI);
  406. $('#settings').modal({backdrop: 'static', keyboard: true});
  407. };
  408. $scope.saveConfig = function() {
  409. var cfg = JSON.stringify($scope.config);
  410. var opts = {headers: {'Content-Type': 'application/json'}};
  411. $http.post(urlbase + '/config', cfg, opts).success(function () {
  412. $http.get(urlbase + '/config/sync').success(function (data) {
  413. $scope.configInSync = data.configInSync;
  414. });
  415. });
  416. };
  417. $scope.saveSettings = function () {
  418. // Make sure something changed
  419. var changed = !angular.equals($scope.config.Options, $scope.tmpOptions) ||
  420. !angular.equals($scope.config.GUI, $scope.tmpGUI);
  421. if (changed) {
  422. // Check if usage reporting has been enabled or disabled
  423. if ($scope.tmpOptions.UREnabled && $scope.tmpOptions.URAccepted <= 0) {
  424. $scope.tmpOptions.URAccepted = 1000;
  425. } else if (!$scope.tmpOptions.UREnabled && $scope.tmpOptions.URAccepted > 0){
  426. $scope.tmpOptions.URAccepted = -1;
  427. }
  428. // Check if protocol will need to be changed on restart
  429. if($scope.config.GUI.UseTLS !== $scope.tmpGUI.UseTLS){
  430. $scope.protocolChanged = true;
  431. }
  432. // Apply new settings locally
  433. $scope.config.Options = angular.copy($scope.tmpOptions);
  434. $scope.config.GUI = angular.copy($scope.tmpGUI);
  435. $scope.config.Options.ListenAddress = $scope.config.Options.ListenStr.split(',').map(function (x) { return x.trim(); });
  436. $scope.saveConfig();
  437. }
  438. $('#settings').modal("hide");
  439. };
  440. $scope.restart = function () {
  441. restarting = true;
  442. $('#restarting').modal({backdrop: 'static', keyboard: false});
  443. $http.post(urlbase + '/restart');
  444. $scope.configInSync = true;
  445. // Switch webpage protocol if needed
  446. if($scope.protocolChanged){
  447. var protocol = 'http';
  448. if($scope.config.GUI.UseTLS){
  449. protocol = 'https';
  450. }
  451. setTimeout(function(){
  452. window.location.protocol = protocol;
  453. }, 1000);
  454. $scope.protocolChanged = false;
  455. }
  456. };
  457. $scope.upgrade = function () {
  458. restarting = true;
  459. $('#upgrading').modal({backdrop: 'static', keyboard: false});
  460. $http.post(urlbase + '/upgrade').success(function () {
  461. $('#restarting').modal({backdrop: 'static', keyboard: false});
  462. $('#upgrading').modal('hide');
  463. }).error(function () {
  464. $('#upgrading').modal('hide');
  465. });
  466. };
  467. $scope.shutdown = function () {
  468. restarting = true;
  469. $http.post(urlbase + '/shutdown').success(function () {
  470. $('#shutdown').modal({backdrop: 'static', keyboard: false});
  471. });
  472. $scope.configInSync = true;
  473. };
  474. $scope.editNode = function (nodeCfg) {
  475. $scope.currentNode = $.extend({}, nodeCfg);
  476. $scope.editingExisting = true;
  477. $scope.editingSelf = (nodeCfg.NodeID == $scope.myID);
  478. $scope.currentNode.AddressesStr = nodeCfg.Addresses.join(', ');
  479. $scope.nodeEditor.$setPristine();
  480. $('#editNode').modal({backdrop: 'static', keyboard: true});
  481. };
  482. $scope.idNode = function () {
  483. $('#idqr').modal('show');
  484. };
  485. $scope.addNode = function () {
  486. $scope.currentNode = {AddressesStr: 'dynamic', Compression: true};
  487. $scope.editingExisting = false;
  488. $scope.editingSelf = false;
  489. $scope.nodeEditor.$setPristine();
  490. $('#editNode').modal({backdrop: 'static', keyboard: true});
  491. };
  492. $scope.deleteNode = function () {
  493. $('#editNode').modal('hide');
  494. if (!$scope.editingExisting) {
  495. return;
  496. }
  497. $scope.nodes = $scope.nodes.filter(function (n) {
  498. return n.NodeID !== $scope.currentNode.NodeID;
  499. });
  500. $scope.config.Nodes = $scope.nodes;
  501. for (var id in $scope.repos) {
  502. $scope.repos[id].Nodes = $scope.repos[id].Nodes.filter(function (n) {
  503. return n.NodeID !== $scope.currentNode.NodeID;
  504. });
  505. }
  506. $scope.saveConfig();
  507. };
  508. $scope.saveNode = function () {
  509. var nodeCfg, done, i;
  510. $('#editNode').modal('hide');
  511. nodeCfg = $scope.currentNode;
  512. nodeCfg.Addresses = nodeCfg.AddressesStr.split(',').map(function (x) { return x.trim(); });
  513. done = false;
  514. for (i = 0; i < $scope.nodes.length; i++) {
  515. if ($scope.nodes[i].NodeID === nodeCfg.NodeID) {
  516. $scope.nodes[i] = nodeCfg;
  517. done = true;
  518. break;
  519. }
  520. }
  521. if (!done) {
  522. $scope.nodes.push(nodeCfg);
  523. }
  524. $scope.nodes.sort(nodeCompare);
  525. $scope.config.Nodes = $scope.nodes;
  526. $scope.saveConfig();
  527. };
  528. $scope.otherNodes = function () {
  529. return $scope.nodes.filter(function (n){
  530. return n.NodeID !== $scope.myID;
  531. });
  532. };
  533. $scope.thisNode = function () {
  534. var i, n;
  535. for (i = 0; i < $scope.nodes.length; i++) {
  536. n = $scope.nodes[i];
  537. if (n.NodeID === $scope.myID) {
  538. return n;
  539. }
  540. }
  541. };
  542. $scope.allNodes = function () {
  543. var nodes = $scope.otherNodes();
  544. nodes.push($scope.thisNode());
  545. return nodes;
  546. };
  547. $scope.errorList = function () {
  548. return $scope.errors.filter(function (e) {
  549. return e.Time > $scope.seenError;
  550. });
  551. };
  552. $scope.clearErrors = function () {
  553. $scope.seenError = $scope.errors[$scope.errors.length - 1].Time;
  554. $http.post(urlbase + '/error/clear');
  555. };
  556. $scope.friendlyNodes = function (str) {
  557. for (var i = 0; i < $scope.nodes.length; i++) {
  558. var cfg = $scope.nodes[i];
  559. str = str.replace(cfg.NodeID, $scope.nodeName(cfg));
  560. }
  561. return str;
  562. };
  563. $scope.repoList = function () {
  564. return repoList($scope.repos);
  565. };
  566. $scope.editRepo = function (nodeCfg) {
  567. $scope.currentRepo = angular.copy(nodeCfg);
  568. $scope.currentRepo.selectedNodes = {};
  569. $scope.currentRepo.Nodes.forEach(function (n) {
  570. $scope.currentRepo.selectedNodes[n.NodeID] = true;
  571. });
  572. if ($scope.currentRepo.Versioning && $scope.currentRepo.Versioning.Type === "simple") {
  573. $scope.currentRepo.simpleFileVersioning = true;
  574. $scope.currentRepo.simpleKeep = +$scope.currentRepo.Versioning.Params.keep;
  575. }
  576. $scope.currentRepo.simpleKeep = $scope.currentRepo.simpleKeep || 5;
  577. $scope.editingExisting = true;
  578. $scope.repoEditor.$setPristine();
  579. $('#editRepo').modal({backdrop: 'static', keyboard: true});
  580. };
  581. $scope.addRepo = function () {
  582. $scope.currentRepo = {selectedNodes: {}};
  583. $scope.editingExisting = false;
  584. $scope.repoEditor.$setPristine();
  585. $('#editRepo').modal({backdrop: 'static', keyboard: true});
  586. };
  587. $scope.saveRepo = function () {
  588. var repoCfg, done, i;
  589. $('#editRepo').modal('hide');
  590. repoCfg = $scope.currentRepo;
  591. repoCfg.Nodes = [];
  592. repoCfg.selectedNodes[$scope.myID] = true;
  593. for (var nodeID in repoCfg.selectedNodes) {
  594. if (repoCfg.selectedNodes[nodeID] === true) {
  595. repoCfg.Nodes.push({NodeID: nodeID});
  596. }
  597. }
  598. delete repoCfg.selectedNodes;
  599. if (repoCfg.simpleFileVersioning) {
  600. repoCfg.Versioning = {
  601. 'Type': 'simple',
  602. 'Params': {
  603. 'keep': '' + repoCfg.simpleKeep,
  604. }
  605. };
  606. delete repoCfg.simpleFileVersioning;
  607. delete repoCfg.simpleKeep;
  608. } else {
  609. delete repoCfg.Versioning;
  610. }
  611. $scope.repos[repoCfg.ID] = repoCfg;
  612. $scope.config.Repositories = repoList($scope.repos);
  613. $scope.saveConfig();
  614. };
  615. $scope.sharesRepo = function(repoCfg) {
  616. var names = [];
  617. repoCfg.Nodes.forEach(function (node) {
  618. names.push($scope.nodeName($scope.findNode(node.NodeID)));
  619. });
  620. names.sort();
  621. return names.join(", ");
  622. };
  623. $scope.deleteRepo = function () {
  624. $('#editRepo').modal('hide');
  625. if (!$scope.editingExisting) {
  626. return;
  627. }
  628. delete $scope.repos[$scope.currentRepo.ID];
  629. $scope.config.Repositories = repoList($scope.repos);
  630. $scope.saveConfig();
  631. };
  632. $scope.setAPIKey = function (cfg) {
  633. cfg.APIKey = randomString(30, 32);
  634. };
  635. $scope.acceptUR = function () {
  636. $scope.config.Options.URAccepted = 1000; // Larger than the largest existing report version
  637. $scope.saveConfig();
  638. $('#ur').modal('hide');
  639. };
  640. $scope.declineUR = function () {
  641. $scope.config.Options.URAccepted = -1;
  642. $scope.saveConfig();
  643. $('#ur').modal('hide');
  644. };
  645. $scope.showNeed = function (repo) {
  646. $scope.neededLoaded = false;
  647. $('#needed').modal({backdrop: 'static', keyboard: true});
  648. $http.get(urlbase + "/need?repo=" + encodeURIComponent(repo)).success(function (data) {
  649. $scope.needed = data;
  650. $scope.neededLoaded = true;
  651. });
  652. };
  653. $scope.needAction = function (file) {
  654. var fDelete = 4096;
  655. var fDirectory = 16384;
  656. if ((file.Flags & (fDelete+fDirectory)) === fDelete+fDirectory) {
  657. return 'rmdir';
  658. } else if ((file.Flags & fDelete) === fDelete) {
  659. return 'rm';
  660. } else if ((file.Flags & fDirectory) === fDirectory) {
  661. return 'touch';
  662. } else {
  663. return 'sync';
  664. }
  665. };
  666. $scope.override = function (repo) {
  667. $http.post(urlbase + "/model/override?repo=" + encodeURIComponent(repo)).success(function () {
  668. $scope.refresh();
  669. });
  670. };
  671. $scope.about = function () {
  672. $('#about').modal('show');
  673. };
  674. $scope.showReportPreview = function () {
  675. $scope.reportPreview = true;
  676. };
  677. $scope.init();
  678. setInterval($scope.refresh, 10000);
  679. });
  680. function nodeCompare(a, b) {
  681. if (typeof a.Name !== 'undefined' && typeof b.Name !== 'undefined') {
  682. if (a.Name < b.Name)
  683. return -1;
  684. return a.Name > b.Name;
  685. }
  686. if (a.NodeID < b.NodeID) {
  687. return -1;
  688. }
  689. return a.NodeID > b.NodeID;
  690. }
  691. function repoCompare(a, b) {
  692. if (a.Directory < b.Directory) {
  693. return -1;
  694. }
  695. return a.Directory > b.Directory;
  696. }
  697. function repoMap(l) {
  698. var m = {};
  699. l.forEach(function (r) {
  700. m[r.ID] = r;
  701. });
  702. return m;
  703. }
  704. function repoList(m) {
  705. var l = [];
  706. for (var id in m) {
  707. l.push(m[id]);
  708. }
  709. l.sort(repoCompare);
  710. return l;
  711. }
  712. function decimals(val, num) {
  713. var digits, decs;
  714. if (val === 0) {
  715. return 0;
  716. }
  717. digits = Math.floor(Math.log(Math.abs(val)) / Math.log(10));
  718. decs = Math.max(0, num - digits);
  719. return decs;
  720. }
  721. function randomString(len, bits)
  722. {
  723. bits = bits || 36;
  724. var outStr = "", newStr;
  725. while (outStr.length < len)
  726. {
  727. newStr = Math.random().toString(bits).slice(2);
  728. outStr += newStr.slice(0, Math.min(newStr.length, (len - outStr.length)));
  729. }
  730. return outStr.toLowerCase();
  731. }
  732. function isEmptyObject(obj) {
  733. var name;
  734. for (name in obj) {
  735. return false;
  736. }
  737. return true;
  738. }
  739. function debounce(func, wait) {
  740. var timeout, args, context, timestamp, result, again;
  741. var later = function() {
  742. var last = Date.now() - timestamp;
  743. if (last < wait) {
  744. timeout = setTimeout(later, wait - last);
  745. } else {
  746. timeout = null;
  747. if (again) {
  748. result = func.apply(context, args);
  749. context = args = null;
  750. again = false;
  751. }
  752. }
  753. };
  754. return function() {
  755. context = this;
  756. args = arguments;
  757. timestamp = Date.now();
  758. var callNow = !timeout;
  759. if (!timeout) {
  760. timeout = setTimeout(later, wait);
  761. result = func.apply(context, args);
  762. context = args = null;
  763. } else {
  764. again = true;
  765. }
  766. return result;
  767. };
  768. }
  769. syncthing.filter('natural', function () {
  770. return function (input, valid) {
  771. return input.toFixed(decimals(input, valid));
  772. };
  773. });
  774. syncthing.filter('binary', function () {
  775. return function (input) {
  776. if (input === undefined) {
  777. return '0 ';
  778. }
  779. if (input > 1024 * 1024 * 1024) {
  780. input /= 1024 * 1024 * 1024;
  781. return input.toFixed(decimals(input, 2)) + ' Gi';
  782. }
  783. if (input > 1024 * 1024) {
  784. input /= 1024 * 1024;
  785. return input.toFixed(decimals(input, 2)) + ' Mi';
  786. }
  787. if (input > 1024) {
  788. input /= 1024;
  789. return input.toFixed(decimals(input, 2)) + ' Ki';
  790. }
  791. return Math.round(input) + ' ';
  792. };
  793. });
  794. syncthing.filter('metric', function () {
  795. return function (input) {
  796. if (input === undefined) {
  797. return '0 ';
  798. }
  799. if (input > 1000 * 1000 * 1000) {
  800. input /= 1000 * 1000 * 1000;
  801. return input.toFixed(decimals(input, 2)) + ' G';
  802. }
  803. if (input > 1000 * 1000) {
  804. input /= 1000 * 1000;
  805. return input.toFixed(decimals(input, 2)) + ' M';
  806. }
  807. if (input > 1000) {
  808. input /= 1000;
  809. return input.toFixed(decimals(input, 2)) + ' k';
  810. }
  811. return Math.round(input) + ' ';
  812. };
  813. });
  814. syncthing.filter('short', function () {
  815. return function (input) {
  816. return input.substr(0, 6);
  817. };
  818. });
  819. syncthing.filter('alwaysNumber', function () {
  820. return function (input) {
  821. if (input === undefined) {
  822. return 0;
  823. }
  824. return input;
  825. };
  826. });
  827. syncthing.filter('shortPath', function () {
  828. return function (input) {
  829. if (input === undefined)
  830. return "";
  831. var parts = input.split(/[\/\\]/);
  832. if (!parts || parts.length <= 3) {
  833. return input;
  834. }
  835. return ".../" + parts.slice(parts.length-2).join("/");
  836. };
  837. });
  838. syncthing.filter('basename', function () {
  839. return function (input) {
  840. if (input === undefined)
  841. return "";
  842. var parts = input.split(/[\/\\]/);
  843. if (!parts || parts.length < 1) {
  844. return input;
  845. }
  846. return parts[parts.length-1];
  847. };
  848. });
  849. syncthing.filter('clean', function () {
  850. return function (input) {
  851. return encodeURIComponent(input).replace(/%/g, '');
  852. };
  853. });
  854. syncthing.directive('optionEditor', function () {
  855. return {
  856. restrict: 'C',
  857. replace: true,
  858. transclude: true,
  859. scope: {
  860. setting: '=setting',
  861. },
  862. template: '<input type="text" ng-model="config.Options[setting.id]"></input>',
  863. };
  864. });
  865. syncthing.directive('uniqueRepo', function() {
  866. return {
  867. require: 'ngModel',
  868. link: function(scope, elm, attrs, ctrl) {
  869. ctrl.$parsers.unshift(function(viewValue) {
  870. if (scope.editingExisting) {
  871. // we shouldn't validate
  872. ctrl.$setValidity('uniqueRepo', true);
  873. } else if (scope.repos[viewValue]) {
  874. // the repo exists already
  875. ctrl.$setValidity('uniqueRepo', false);
  876. } else {
  877. // the repo is unique
  878. ctrl.$setValidity('uniqueRepo', true);
  879. }
  880. return viewValue;
  881. });
  882. }
  883. };
  884. });
  885. syncthing.directive('validNodeid', function($http) {
  886. return {
  887. require: 'ngModel',
  888. link: function(scope, elm, attrs, ctrl) {
  889. ctrl.$parsers.unshift(function(viewValue) {
  890. if (scope.editingExisting) {
  891. // we shouldn't validate
  892. ctrl.$setValidity('validNodeid', true);
  893. } else {
  894. $http.get(urlbase + '/nodeid?id='+viewValue).success(function (resp) {
  895. if (resp.error) {
  896. ctrl.$setValidity('validNodeid', false);
  897. } else {
  898. ctrl.$setValidity('validNodeid', true);
  899. }
  900. });
  901. }
  902. return viewValue;
  903. });
  904. }
  905. };
  906. });
  907. syncthing.directive('modal', function () {
  908. return {
  909. restrict: 'E',
  910. templateUrl: 'modal.html',
  911. replace: true,
  912. transclude: true,
  913. scope: {
  914. title: '@',
  915. status: '@',
  916. icon: '@',
  917. close: '@',
  918. large: '@',
  919. },
  920. }
  921. });