app.js 34 KB

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