app.js 30 KB

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