app.js 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074
  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. $scope.restartingTitle = "Restarting"
  443. $scope.restartingBody = "Syncthing is restarting."
  444. $('#restarting').modal({backdrop: 'static', keyboard: false});
  445. $http.post(urlbase + '/restart');
  446. $scope.configInSync = true;
  447. // Switch webpage protocol if needed
  448. if($scope.protocolChanged){
  449. var protocol = 'http';
  450. if($scope.config.GUI.UseTLS){
  451. protocol = 'https';
  452. }
  453. setTimeout(function(){
  454. window.location.protocol = protocol;
  455. }, 1000);
  456. $scope.protocolChanged = false;
  457. }
  458. };
  459. $scope.upgrade = function () {
  460. $scope.restartingTitle = "Upgrading"
  461. $scope.restartingBody = "Syncthing is upgrading."
  462. $('#restarting').modal({backdrop: 'static', keyboard: false});
  463. $http.post(urlbase + '/upgrade').success(function () {
  464. restarting = true;
  465. $scope.restartingBody = "Syncthing is restarting into the new version."
  466. }).error(function () {
  467. $('#restarting').modal('hide');
  468. });
  469. };
  470. $scope.shutdown = function () {
  471. restarting = true;
  472. $http.post(urlbase + '/shutdown').success(function () {
  473. $('#shutdown').modal({backdrop: 'static', keyboard: false});
  474. });
  475. $scope.configInSync = true;
  476. };
  477. $scope.editNode = function (nodeCfg) {
  478. $scope.currentNode = $.extend({}, nodeCfg);
  479. $scope.editingExisting = true;
  480. $scope.editingSelf = (nodeCfg.NodeID == $scope.myID);
  481. $scope.currentNode.AddressesStr = nodeCfg.Addresses.join(', ');
  482. $scope.nodeEditor.$setPristine();
  483. $('#editNode').modal({backdrop: 'static', keyboard: true});
  484. };
  485. $scope.idNode = function () {
  486. $('#idqr').modal('show');
  487. };
  488. $scope.addNode = function () {
  489. $scope.currentNode = {AddressesStr: 'dynamic', Compression: true};
  490. $scope.editingExisting = false;
  491. $scope.editingSelf = false;
  492. $scope.nodeEditor.$setPristine();
  493. $('#editNode').modal({backdrop: 'static', keyboard: true});
  494. };
  495. $scope.deleteNode = function () {
  496. $('#editNode').modal('hide');
  497. if (!$scope.editingExisting) {
  498. return;
  499. }
  500. $scope.nodes = $scope.nodes.filter(function (n) {
  501. return n.NodeID !== $scope.currentNode.NodeID;
  502. });
  503. $scope.config.Nodes = $scope.nodes;
  504. for (var id in $scope.repos) {
  505. $scope.repos[id].Nodes = $scope.repos[id].Nodes.filter(function (n) {
  506. return n.NodeID !== $scope.currentNode.NodeID;
  507. });
  508. }
  509. $scope.saveConfig();
  510. };
  511. $scope.saveNode = function () {
  512. var nodeCfg, done, i;
  513. $('#editNode').modal('hide');
  514. nodeCfg = $scope.currentNode;
  515. nodeCfg.Addresses = nodeCfg.AddressesStr.split(',').map(function (x) { return x.trim(); });
  516. done = false;
  517. for (i = 0; i < $scope.nodes.length; i++) {
  518. if ($scope.nodes[i].NodeID === nodeCfg.NodeID) {
  519. $scope.nodes[i] = nodeCfg;
  520. done = true;
  521. break;
  522. }
  523. }
  524. if (!done) {
  525. $scope.nodes.push(nodeCfg);
  526. }
  527. $scope.nodes.sort(nodeCompare);
  528. $scope.config.Nodes = $scope.nodes;
  529. $scope.saveConfig();
  530. };
  531. $scope.otherNodes = function () {
  532. return $scope.nodes.filter(function (n){
  533. return n.NodeID !== $scope.myID;
  534. });
  535. };
  536. $scope.thisNode = function () {
  537. var i, n;
  538. for (i = 0; i < $scope.nodes.length; i++) {
  539. n = $scope.nodes[i];
  540. if (n.NodeID === $scope.myID) {
  541. return n;
  542. }
  543. }
  544. };
  545. $scope.allNodes = function () {
  546. var nodes = $scope.otherNodes();
  547. nodes.push($scope.thisNode());
  548. return nodes;
  549. };
  550. $scope.errorList = function () {
  551. return $scope.errors.filter(function (e) {
  552. return e.Time > $scope.seenError;
  553. });
  554. };
  555. $scope.clearErrors = function () {
  556. $scope.seenError = $scope.errors[$scope.errors.length - 1].Time;
  557. $http.post(urlbase + '/error/clear');
  558. };
  559. $scope.friendlyNodes = function (str) {
  560. for (var i = 0; i < $scope.nodes.length; i++) {
  561. var cfg = $scope.nodes[i];
  562. str = str.replace(cfg.NodeID, $scope.nodeName(cfg));
  563. }
  564. return str;
  565. };
  566. $scope.repoList = function () {
  567. return repoList($scope.repos);
  568. };
  569. $scope.editRepo = function (nodeCfg) {
  570. $scope.currentRepo = angular.copy(nodeCfg);
  571. $scope.currentRepo.selectedNodes = {};
  572. $scope.currentRepo.Nodes.forEach(function (n) {
  573. $scope.currentRepo.selectedNodes[n.NodeID] = true;
  574. });
  575. if ($scope.currentRepo.Versioning && $scope.currentRepo.Versioning.Type === "simple") {
  576. $scope.currentRepo.simpleFileVersioning = true;
  577. $scope.currentRepo.simpleKeep = +$scope.currentRepo.Versioning.Params.keep;
  578. }
  579. $scope.currentRepo.simpleKeep = $scope.currentRepo.simpleKeep || 5;
  580. $scope.editingExisting = true;
  581. $scope.repoEditor.$setPristine();
  582. $('#editRepo').modal({backdrop: 'static', keyboard: true});
  583. };
  584. $scope.addRepo = function () {
  585. $scope.currentRepo = {selectedNodes: {}};
  586. $scope.editingExisting = false;
  587. $scope.repoEditor.$setPristine();
  588. $('#editRepo').modal({backdrop: 'static', keyboard: true});
  589. };
  590. $scope.saveRepo = function () {
  591. var repoCfg, done, i;
  592. $('#editRepo').modal('hide');
  593. repoCfg = $scope.currentRepo;
  594. repoCfg.Nodes = [];
  595. repoCfg.selectedNodes[$scope.myID] = true;
  596. for (var nodeID in repoCfg.selectedNodes) {
  597. if (repoCfg.selectedNodes[nodeID] === true) {
  598. repoCfg.Nodes.push({NodeID: nodeID});
  599. }
  600. }
  601. delete repoCfg.selectedNodes;
  602. if (repoCfg.simpleFileVersioning) {
  603. repoCfg.Versioning = {
  604. 'Type': 'simple',
  605. 'Params': {
  606. 'keep': '' + repoCfg.simpleKeep,
  607. }
  608. };
  609. delete repoCfg.simpleFileVersioning;
  610. delete repoCfg.simpleKeep;
  611. } else {
  612. delete repoCfg.Versioning;
  613. }
  614. $scope.repos[repoCfg.ID] = repoCfg;
  615. $scope.config.Repositories = repoList($scope.repos);
  616. $scope.saveConfig();
  617. };
  618. $scope.sharesRepo = function(repoCfg) {
  619. var names = [];
  620. repoCfg.Nodes.forEach(function (node) {
  621. names.push($scope.nodeName($scope.findNode(node.NodeID)));
  622. });
  623. names.sort();
  624. return names.join(", ");
  625. };
  626. $scope.deleteRepo = function () {
  627. $('#editRepo').modal('hide');
  628. if (!$scope.editingExisting) {
  629. return;
  630. }
  631. delete $scope.repos[$scope.currentRepo.ID];
  632. $scope.config.Repositories = repoList($scope.repos);
  633. $scope.saveConfig();
  634. };
  635. $scope.setAPIKey = function (cfg) {
  636. cfg.APIKey = randomString(30, 32);
  637. };
  638. $scope.acceptUR = function () {
  639. $scope.config.Options.URAccepted = 1000; // Larger than the largest existing report version
  640. $scope.saveConfig();
  641. $('#ur').modal('hide');
  642. };
  643. $scope.declineUR = function () {
  644. $scope.config.Options.URAccepted = -1;
  645. $scope.saveConfig();
  646. $('#ur').modal('hide');
  647. };
  648. $scope.showNeed = function (repo) {
  649. $scope.neededLoaded = false;
  650. $('#needed').modal({backdrop: 'static', keyboard: true});
  651. $http.get(urlbase + "/need?repo=" + encodeURIComponent(repo)).success(function (data) {
  652. $scope.needed = data;
  653. $scope.neededLoaded = true;
  654. });
  655. };
  656. $scope.needAction = function (file) {
  657. var fDelete = 4096;
  658. var fDirectory = 16384;
  659. if ((file.Flags & (fDelete+fDirectory)) === fDelete+fDirectory) {
  660. return 'rmdir';
  661. } else if ((file.Flags & fDelete) === fDelete) {
  662. return 'rm';
  663. } else if ((file.Flags & fDirectory) === fDirectory) {
  664. return 'touch';
  665. } else {
  666. return 'sync';
  667. }
  668. };
  669. $scope.override = function (repo) {
  670. $http.post(urlbase + "/model/override?repo=" + encodeURIComponent(repo)).success(function () {
  671. $scope.refresh();
  672. });
  673. };
  674. $scope.about = function () {
  675. $('#about').modal('show');
  676. };
  677. $scope.showReportPreview = function () {
  678. $scope.reportPreview = true;
  679. };
  680. $scope.init();
  681. setInterval($scope.refresh, 10000);
  682. });
  683. function nodeCompare(a, b) {
  684. if (typeof a.Name !== 'undefined' && typeof b.Name !== 'undefined') {
  685. if (a.Name < b.Name)
  686. return -1;
  687. return a.Name > b.Name;
  688. }
  689. if (a.NodeID < b.NodeID) {
  690. return -1;
  691. }
  692. return a.NodeID > b.NodeID;
  693. }
  694. function repoCompare(a, b) {
  695. if (a.Directory < b.Directory) {
  696. return -1;
  697. }
  698. return a.Directory > b.Directory;
  699. }
  700. function repoMap(l) {
  701. var m = {};
  702. l.forEach(function (r) {
  703. m[r.ID] = r;
  704. });
  705. return m;
  706. }
  707. function repoList(m) {
  708. var l = [];
  709. for (var id in m) {
  710. l.push(m[id]);
  711. }
  712. l.sort(repoCompare);
  713. return l;
  714. }
  715. function decimals(val, num) {
  716. var digits, decs;
  717. if (val === 0) {
  718. return 0;
  719. }
  720. digits = Math.floor(Math.log(Math.abs(val)) / Math.log(10));
  721. decs = Math.max(0, num - digits);
  722. return decs;
  723. }
  724. function randomString(len, bits)
  725. {
  726. bits = bits || 36;
  727. var outStr = "", newStr;
  728. while (outStr.length < len)
  729. {
  730. newStr = Math.random().toString(bits).slice(2);
  731. outStr += newStr.slice(0, Math.min(newStr.length, (len - outStr.length)));
  732. }
  733. return outStr.toLowerCase();
  734. }
  735. function isEmptyObject(obj) {
  736. var name;
  737. for (name in obj) {
  738. return false;
  739. }
  740. return true;
  741. }
  742. function debounce(func, wait) {
  743. var timeout, args, context, timestamp, result, again;
  744. var later = function() {
  745. var last = Date.now() - timestamp;
  746. if (last < wait) {
  747. timeout = setTimeout(later, wait - last);
  748. } else {
  749. timeout = null;
  750. if (again) {
  751. result = func.apply(context, args);
  752. context = args = null;
  753. again = false;
  754. }
  755. }
  756. };
  757. return function() {
  758. context = this;
  759. args = arguments;
  760. timestamp = Date.now();
  761. var callNow = !timeout;
  762. if (!timeout) {
  763. timeout = setTimeout(later, wait);
  764. result = func.apply(context, args);
  765. context = args = null;
  766. } else {
  767. again = true;
  768. }
  769. return result;
  770. };
  771. }
  772. syncthing.filter('natural', function () {
  773. return function (input, valid) {
  774. return input.toFixed(decimals(input, valid));
  775. };
  776. });
  777. syncthing.filter('binary', function () {
  778. return function (input) {
  779. if (input === undefined) {
  780. return '0 ';
  781. }
  782. if (input > 1024 * 1024 * 1024) {
  783. input /= 1024 * 1024 * 1024;
  784. return input.toFixed(decimals(input, 2)) + ' Gi';
  785. }
  786. if (input > 1024 * 1024) {
  787. input /= 1024 * 1024;
  788. return input.toFixed(decimals(input, 2)) + ' Mi';
  789. }
  790. if (input > 1024) {
  791. input /= 1024;
  792. return input.toFixed(decimals(input, 2)) + ' Ki';
  793. }
  794. return Math.round(input) + ' ';
  795. };
  796. });
  797. syncthing.filter('metric', function () {
  798. return function (input) {
  799. if (input === undefined) {
  800. return '0 ';
  801. }
  802. if (input > 1000 * 1000 * 1000) {
  803. input /= 1000 * 1000 * 1000;
  804. return input.toFixed(decimals(input, 2)) + ' G';
  805. }
  806. if (input > 1000 * 1000) {
  807. input /= 1000 * 1000;
  808. return input.toFixed(decimals(input, 2)) + ' M';
  809. }
  810. if (input > 1000) {
  811. input /= 1000;
  812. return input.toFixed(decimals(input, 2)) + ' k';
  813. }
  814. return Math.round(input) + ' ';
  815. };
  816. });
  817. syncthing.filter('short', function () {
  818. return function (input) {
  819. return input.substr(0, 6);
  820. };
  821. });
  822. syncthing.filter('alwaysNumber', function () {
  823. return function (input) {
  824. if (input === undefined) {
  825. return 0;
  826. }
  827. return input;
  828. };
  829. });
  830. syncthing.filter('shortPath', function () {
  831. return function (input) {
  832. if (input === undefined)
  833. return "";
  834. var parts = input.split(/[\/\\]/);
  835. if (!parts || parts.length <= 3) {
  836. return input;
  837. }
  838. return ".../" + parts.slice(parts.length-2).join("/");
  839. };
  840. });
  841. syncthing.filter('basename', function () {
  842. return function (input) {
  843. if (input === undefined)
  844. return "";
  845. var parts = input.split(/[\/\\]/);
  846. if (!parts || parts.length < 1) {
  847. return input;
  848. }
  849. return parts[parts.length-1];
  850. };
  851. });
  852. syncthing.filter('clean', function () {
  853. return function (input) {
  854. return encodeURIComponent(input).replace(/%/g, '');
  855. };
  856. });
  857. syncthing.directive('optionEditor', function () {
  858. return {
  859. restrict: 'C',
  860. replace: true,
  861. transclude: true,
  862. scope: {
  863. setting: '=setting',
  864. },
  865. template: '<input type="text" ng-model="config.Options[setting.id]"></input>',
  866. };
  867. });
  868. syncthing.directive('uniqueRepo', function() {
  869. return {
  870. require: 'ngModel',
  871. link: function(scope, elm, attrs, ctrl) {
  872. ctrl.$parsers.unshift(function(viewValue) {
  873. if (scope.editingExisting) {
  874. // we shouldn't validate
  875. ctrl.$setValidity('uniqueRepo', true);
  876. } else if (scope.repos[viewValue]) {
  877. // the repo exists already
  878. ctrl.$setValidity('uniqueRepo', false);
  879. } else {
  880. // the repo is unique
  881. ctrl.$setValidity('uniqueRepo', true);
  882. }
  883. return viewValue;
  884. });
  885. }
  886. };
  887. });
  888. syncthing.directive('validNodeid', function($http) {
  889. return {
  890. require: 'ngModel',
  891. link: function(scope, elm, attrs, ctrl) {
  892. ctrl.$parsers.unshift(function(viewValue) {
  893. if (scope.editingExisting) {
  894. // we shouldn't validate
  895. ctrl.$setValidity('validNodeid', true);
  896. } else {
  897. $http.get(urlbase + '/nodeid?id='+viewValue).success(function (resp) {
  898. if (resp.error) {
  899. ctrl.$setValidity('validNodeid', false);
  900. } else {
  901. ctrl.$setValidity('validNodeid', true);
  902. }
  903. });
  904. }
  905. return viewValue;
  906. });
  907. }
  908. };
  909. });
  910. syncthing.directive('modal', function () {
  911. return {
  912. restrict: 'E',
  913. templateUrl: 'modal.html',
  914. replace: true,
  915. transclude: true,
  916. scope: {
  917. title: '@',
  918. status: '@',
  919. icon: '@',
  920. close: '@',
  921. large: '@',
  922. },
  923. }
  924. });