app.js 30 KB

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