app.js 30 KB

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