app.js 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149
  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] && debouncedFuncs[key] > Date.now()) {
  220. return;
  221. }
  222. debouncedFuncs[key] = Date.now() + 300000;
  223. $http.get(urlbase + '/model?repo=' + encodeURIComponent(repo)).success(function (data) {
  224. debouncedFuncs[key] = Date.now() + 5000;
  225. $scope.model[repo] = data;
  226. console.log("refreshRepo", repo, data);
  227. });
  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. var key = "refreshSystem"
  253. if (debouncedFuncs[key] && debouncedFuncs[key] > Date.now()) {
  254. return;
  255. }
  256. debouncedFuncs[key] = Date.now() + 300000;
  257. $http.get(urlbase + '/system').success(function (data) {
  258. debouncedFuncs[key] = Date.now() + 500;
  259. $scope.myID = data.myID;
  260. $scope.system = data;
  261. console.log("refreshSystem", data);
  262. });
  263. }
  264. function refreshCompletion(node, repo) {
  265. if (node === $scope.myID) {
  266. return;
  267. }
  268. var key = "refreshCompletion" + node + repo;
  269. if (debouncedFuncs[key] && debouncedFuncs[key] > Date.now()) {
  270. return;
  271. }
  272. debouncedFuncs[key] = Date.now() + 300000;
  273. $http.get(urlbase + '/completion?node=' + node + '&repo=' + encodeURIComponent(repo)).success(function (data) {
  274. debouncedFuncs[key] = Date.now() + 5000;
  275. if (!$scope.completion[node]) {
  276. $scope.completion[node] = {};
  277. }
  278. $scope.completion[node][repo] = data.completion;
  279. var tot = 0,
  280. cnt = 0;
  281. for (var cmp in $scope.completion[node]) {
  282. if (cmp === "_total") {
  283. continue;
  284. }
  285. tot += $scope.completion[node][cmp];
  286. cnt += 1;
  287. }
  288. $scope.completion[node]._total = tot / cnt;
  289. console.log("refreshCompletion", node, repo, $scope.completion[node]);
  290. });
  291. }
  292. function refreshConnectionStats() {
  293. var key = "refreshConnectionStats"
  294. if (debouncedFuncs[key] && debouncedFuncs[key] > Date.now()) {
  295. return;
  296. }
  297. debouncedFuncs[key] = Date.now() + 300000;
  298. $http.get(urlbase + '/connections').success(function (data) {
  299. debouncedFuncs[key] = Date.now() + 500;
  300. var now = Date.now(),
  301. td = (now - prevDate) / 1000,
  302. id;
  303. prevDate = now;
  304. for (id in data) {
  305. if (!data.hasOwnProperty(id)) {
  306. continue;
  307. }
  308. try {
  309. data[id].inbps = Math.max(0, 8 * (data[id].InBytesTotal - $scope.connections[id].InBytesTotal) / td);
  310. data[id].outbps = Math.max(0, 8 * (data[id].OutBytesTotal - $scope.connections[id].OutBytesTotal) / td);
  311. } catch (e) {
  312. data[id].inbps = 0;
  313. data[id].outbps = 0;
  314. }
  315. }
  316. $scope.connections = data;
  317. console.log("refreshConnections", data);
  318. });
  319. }
  320. function refreshErrors() {
  321. var key = "refreshErrors"
  322. if (debouncedFuncs[key] && debouncedFuncs[key] > Date.now()) {
  323. return;
  324. }
  325. debouncedFuncs[key] = Date.now() + 300000;
  326. $http.get(urlbase + '/errors').success(function (data) {
  327. debouncedFuncs[key] = Date.now() + 500;
  328. $scope.errors = data.errors;
  329. console.log("refreshErrors", data);
  330. });
  331. }
  332. function refreshConfig() {
  333. $http.get(urlbase + '/config').success(function (data) {
  334. updateLocalConfig(data);
  335. console.log("refreshConfig", data);
  336. });
  337. $http.get(urlbase + '/config/sync').success(function (data) {
  338. $scope.configInSync = data.configInSync;
  339. });
  340. }
  341. var refreshNodeStats = function () {
  342. var key = "refreshNode";
  343. if (debouncedFuncs[key] && debouncedFuncs[key] > Date.now()) {
  344. return;
  345. }
  346. debouncedFuncs[key] = Date.now() + 300000;
  347. $http.get(urlbase + "/stats/node").success(function (data) {
  348. debouncedFuncs[key] = Date.now() + 500;
  349. $scope.stats = data;
  350. for (var node in $scope.stats) {
  351. $scope.stats[node].LastSeen = new Date($scope.stats[node].LastSeen);
  352. $scope.stats[node].LastSeenDays = (new Date() - $scope.stats[node].LastSeen) / 1000 / 86400;
  353. }
  354. console.log("refreshNodeStats", data);
  355. });
  356. }
  357. $scope.init = function () {
  358. refreshSystem();
  359. refreshConfig();
  360. refreshConnectionStats();
  361. refreshNodeStats();
  362. $http.get(urlbase + '/version').success(function (data) {
  363. $scope.version = data.version;
  364. });
  365. $http.get(urlbase + '/report').success(function (data) {
  366. $scope.reportData = data;
  367. });
  368. $http.get(urlbase + '/upgrade').success(function (data) {
  369. $scope.upgradeInfo = data;
  370. }).error(function () {
  371. $scope.upgradeInfo = {};
  372. });
  373. };
  374. $scope.refresh = function () {
  375. refreshSystem();
  376. refreshConnectionStats();
  377. refreshErrors();
  378. };
  379. $scope.repoStatus = function (repo) {
  380. if (typeof $scope.model[repo] === 'undefined') {
  381. return 'unknown';
  382. }
  383. if ($scope.model[repo].invalid !== '') {
  384. return 'stopped';
  385. }
  386. return '' + $scope.model[repo].state;
  387. };
  388. $scope.repoClass = function (repo) {
  389. if (typeof $scope.model[repo] === 'undefined') {
  390. return 'info';
  391. }
  392. if ($scope.model[repo].invalid !== '') {
  393. return 'danger';
  394. }
  395. var state = '' + $scope.model[repo].state;
  396. if (state == 'idle') {
  397. return 'success';
  398. }
  399. if (state == 'syncing') {
  400. return 'primary';
  401. }
  402. if (state == 'scanning') {
  403. return 'primary';
  404. }
  405. return 'info';
  406. };
  407. $scope.syncPercentage = function (repo) {
  408. if (typeof $scope.model[repo] === 'undefined') {
  409. return 100;
  410. }
  411. if ($scope.model[repo].globalBytes === 0) {
  412. return 100;
  413. }
  414. var pct = 100 * $scope.model[repo].inSyncBytes / $scope.model[repo].globalBytes;
  415. return Math.floor(pct);
  416. };
  417. $scope.nodeIcon = function (nodeCfg) {
  418. if ($scope.connections[nodeCfg.NodeID]) {
  419. if ($scope.completion[nodeCfg.NodeID] && $scope.completion[nodeCfg.NodeID]._total === 100) {
  420. return 'ok';
  421. } else {
  422. return 'refresh';
  423. }
  424. }
  425. return 'minus';
  426. };
  427. $scope.nodeClass = function (nodeCfg) {
  428. if ($scope.connections[nodeCfg.NodeID]) {
  429. if ($scope.completion[nodeCfg.NodeID] && $scope.completion[nodeCfg.NodeID]._total === 100) {
  430. return 'success';
  431. } else {
  432. return 'primary';
  433. }
  434. }
  435. return 'info';
  436. };
  437. $scope.nodeAddr = function (nodeCfg) {
  438. var conn = $scope.connections[nodeCfg.NodeID];
  439. if (conn) {
  440. return conn.Address;
  441. }
  442. return '?';
  443. };
  444. $scope.nodeCompletion = function (nodeCfg) {
  445. var conn = $scope.connections[nodeCfg.NodeID];
  446. if (conn) {
  447. return conn.Completion + '%';
  448. }
  449. return '';
  450. };
  451. $scope.findNode = function (nodeID) {
  452. var matches = $scope.nodes.filter(function (n) {
  453. return n.NodeID == nodeID;
  454. });
  455. if (matches.length != 1) {
  456. return undefined;
  457. }
  458. return matches[0];
  459. };
  460. $scope.nodeName = function (nodeCfg) {
  461. if (typeof nodeCfg === 'undefined') {
  462. return "";
  463. }
  464. if (nodeCfg.Name) {
  465. return nodeCfg.Name;
  466. }
  467. return nodeCfg.NodeID.substr(0, 6);
  468. };
  469. $scope.thisNodeName = function () {
  470. var node = $scope.thisNode();
  471. if (typeof node === 'undefined') {
  472. return "(unknown node)";
  473. }
  474. if (node.Name) {
  475. return node.Name;
  476. }
  477. return node.NodeID.substr(0, 6);
  478. };
  479. $scope.editSettings = function () {
  480. // Make a working copy
  481. $scope.tmpOptions = angular.copy($scope.config.Options);
  482. $scope.tmpOptions.UREnabled = ($scope.tmpOptions.URAccepted > 0);
  483. $scope.tmpOptions.NodeName = $scope.thisNode().Name;
  484. $scope.tmpGUI = angular.copy($scope.config.GUI);
  485. $('#settings').modal();
  486. };
  487. $scope.saveConfig = function () {
  488. var cfg = JSON.stringify($scope.config);
  489. var opts = {
  490. headers: {
  491. 'Content-Type': 'application/json'
  492. }
  493. };
  494. $http.post(urlbase + '/config', cfg, opts).success(function () {
  495. $http.get(urlbase + '/config/sync').success(function (data) {
  496. $scope.configInSync = data.configInSync;
  497. });
  498. });
  499. };
  500. $scope.saveSettings = function () {
  501. // Make sure something changed
  502. var changed = !angular.equals($scope.config.Options, $scope.tmpOptions) ||
  503. !angular.equals($scope.config.GUI, $scope.tmpGUI);
  504. if (changed) {
  505. // Check if usage reporting has been enabled or disabled
  506. if ($scope.tmpOptions.UREnabled && $scope.tmpOptions.URAccepted <= 0) {
  507. $scope.tmpOptions.URAccepted = 1000;
  508. } else if (!$scope.tmpOptions.UREnabled && $scope.tmpOptions.URAccepted > 0) {
  509. $scope.tmpOptions.URAccepted = -1;
  510. }
  511. // Check if protocol will need to be changed on restart
  512. if ($scope.config.GUI.UseTLS !== $scope.tmpGUI.UseTLS) {
  513. $scope.protocolChanged = true;
  514. }
  515. // Apply new settings locally
  516. $scope.thisNode().Name = $scope.tmpOptions.NodeName;
  517. $scope.config.Options = angular.copy($scope.tmpOptions);
  518. $scope.config.GUI = angular.copy($scope.tmpGUI);
  519. $scope.config.Options.ListenAddress = $scope.config.Options.ListenStr.split(',').map(function (x) {
  520. return x.trim();
  521. });
  522. $scope.saveConfig();
  523. }
  524. $('#settings').modal("hide");
  525. };
  526. $scope.restart = function () {
  527. restarting = true;
  528. $('#restarting').modal();
  529. $http.post(urlbase + '/restart');
  530. $scope.configInSync = true;
  531. // Switch webpage protocol if needed
  532. if ($scope.protocolChanged) {
  533. var protocol = 'http';
  534. if ($scope.config.GUI.UseTLS) {
  535. protocol = 'https';
  536. }
  537. setTimeout(function () {
  538. window.location.protocol = protocol;
  539. }, 2500);
  540. $scope.protocolChanged = false;
  541. }
  542. };
  543. $scope.upgrade = function () {
  544. restarting = true;
  545. $('#upgrading').modal();
  546. $http.post(urlbase + '/upgrade').success(function () {
  547. $('#restarting').modal();
  548. $('#upgrading').modal('hide');
  549. }).error(function () {
  550. $('#upgrading').modal('hide');
  551. });
  552. };
  553. $scope.shutdown = function () {
  554. restarting = true;
  555. $http.post(urlbase + '/shutdown').success(function () {
  556. $('#shutdown').modal();
  557. });
  558. $scope.configInSync = true;
  559. };
  560. $scope.editNode = function (nodeCfg) {
  561. $scope.currentNode = $.extend({}, nodeCfg);
  562. $scope.editingExisting = true;
  563. $scope.editingSelf = (nodeCfg.NodeID == $scope.myID);
  564. $scope.currentNode.AddressesStr = nodeCfg.Addresses.join(', ');
  565. $scope.nodeEditor.$setPristine();
  566. $('#editNode').modal();
  567. };
  568. $scope.idNode = function () {
  569. $('#idqr').modal('show');
  570. };
  571. $scope.addNode = function () {
  572. $scope.currentNode = {
  573. AddressesStr: 'dynamic',
  574. Compression: true
  575. };
  576. $scope.editingExisting = false;
  577. $scope.editingSelf = false;
  578. $scope.nodeEditor.$setPristine();
  579. $('#editNode').modal();
  580. };
  581. $scope.deleteNode = function () {
  582. $('#editNode').modal('hide');
  583. if (!$scope.editingExisting) {
  584. return;
  585. }
  586. $scope.nodes = $scope.nodes.filter(function (n) {
  587. return n.NodeID !== $scope.currentNode.NodeID;
  588. });
  589. $scope.config.Nodes = $scope.nodes;
  590. for (var id in $scope.repos) {
  591. $scope.repos[id].Nodes = $scope.repos[id].Nodes.filter(function (n) {
  592. return n.NodeID !== $scope.currentNode.NodeID;
  593. });
  594. }
  595. $scope.saveConfig();
  596. };
  597. $scope.saveNode = function () {
  598. var nodeCfg, done, i;
  599. $('#editNode').modal('hide');
  600. nodeCfg = $scope.currentNode;
  601. nodeCfg.Addresses = nodeCfg.AddressesStr.split(',').map(function (x) {
  602. return x.trim();
  603. });
  604. done = false;
  605. for (i = 0; i < $scope.nodes.length; i++) {
  606. if ($scope.nodes[i].NodeID === nodeCfg.NodeID) {
  607. $scope.nodes[i] = nodeCfg;
  608. done = true;
  609. break;
  610. }
  611. }
  612. if (!done) {
  613. $scope.nodes.push(nodeCfg);
  614. }
  615. $scope.nodes.sort(nodeCompare);
  616. $scope.config.Nodes = $scope.nodes;
  617. $scope.saveConfig();
  618. };
  619. $scope.otherNodes = function () {
  620. return $scope.nodes.filter(function (n) {
  621. return n.NodeID !== $scope.myID;
  622. });
  623. };
  624. $scope.thisNode = function () {
  625. var i, n;
  626. for (i = 0; i < $scope.nodes.length; i++) {
  627. n = $scope.nodes[i];
  628. if (n.NodeID === $scope.myID) {
  629. return n;
  630. }
  631. }
  632. };
  633. $scope.allNodes = function () {
  634. var nodes = $scope.otherNodes();
  635. nodes.push($scope.thisNode());
  636. return nodes;
  637. };
  638. $scope.errorList = function () {
  639. return $scope.errors.filter(function (e) {
  640. return e.Time > $scope.seenError;
  641. });
  642. };
  643. $scope.clearErrors = function () {
  644. $scope.seenError = $scope.errors[$scope.errors.length - 1].Time;
  645. $http.post(urlbase + '/error/clear');
  646. };
  647. $scope.friendlyNodes = function (str) {
  648. for (var i = 0; i < $scope.nodes.length; i++) {
  649. var cfg = $scope.nodes[i];
  650. str = str.replace(cfg.NodeID, $scope.nodeName(cfg));
  651. }
  652. return str;
  653. };
  654. $scope.repoList = function () {
  655. return repoList($scope.repos);
  656. };
  657. $scope.editRepo = function (nodeCfg) {
  658. $scope.currentRepo = angular.copy(nodeCfg);
  659. $scope.currentRepo.selectedNodes = {};
  660. $scope.currentRepo.Nodes.forEach(function (n) {
  661. $scope.currentRepo.selectedNodes[n.NodeID] = true;
  662. });
  663. if ($scope.currentRepo.Versioning && $scope.currentRepo.Versioning.Type === "simple") {
  664. $scope.currentRepo.simpleFileVersioning = true;
  665. $scope.currentRepo.FileVersioningSelector = "simple";
  666. $scope.currentRepo.simpleKeep = +$scope.currentRepo.Versioning.Params.keep;
  667. } else if ($scope.currentRepo.Versioning && $scope.currentRepo.Versioning.Type === "staggered") {
  668. $scope.currentRepo.staggeredFileVersioning = true;
  669. $scope.currentRepo.FileVersioningSelector = "staggered";
  670. $scope.currentRepo.staggeredMaxAge = Math.floor(+$scope.currentRepo.Versioning.Params.maxAge / 86400);
  671. $scope.currentRepo.staggeredCleanInterval = +$scope.currentRepo.Versioning.Params.cleanInterval;
  672. $scope.currentRepo.staggeredVersionsPath = $scope.currentRepo.Versioning.Params.versionsPath;
  673. } else {
  674. $scope.currentRepo.FileVersioningSelector = "none";
  675. }
  676. $scope.currentRepo.simpleKeep = $scope.currentRepo.simpleKeep || 5;
  677. $scope.currentRepo.staggeredCleanInterval = $scope.currentRepo.staggeredCleanInterval || 3600;
  678. $scope.currentRepo.staggeredVersionsPath = $scope.currentRepo.staggeredVersionsPath || "";
  679. // staggeredMaxAge can validly be zero, which we should not replace
  680. // with the default value of 365. So only set the default if it's
  681. // actually undefined.
  682. if (typeof $scope.currentRepo.staggeredMaxAge === 'undefined') {
  683. $scope.currentRepo.staggeredMaxAge = 365;
  684. }
  685. $scope.editingExisting = true;
  686. $scope.repoEditor.$setPristine();
  687. $('#editRepo').modal();
  688. };
  689. $scope.addRepo = function () {
  690. $scope.currentRepo = {
  691. selectedNodes: {}
  692. };
  693. $scope.currentRepo.RescanIntervalS = 60;
  694. $scope.currentRepo.FileVersioningSelector = "none";
  695. $scope.currentRepo.simpleKeep = 5;
  696. $scope.currentRepo.staggeredMaxAge = 365;
  697. $scope.currentRepo.staggeredCleanInterval = 3600;
  698. $scope.currentRepo.staggeredVersionsPath = "";
  699. $scope.editingExisting = false;
  700. $scope.repoEditor.$setPristine();
  701. $('#editRepo').modal();
  702. };
  703. $scope.saveRepo = function () {
  704. var repoCfg, done, i;
  705. $('#editRepo').modal('hide');
  706. repoCfg = $scope.currentRepo;
  707. repoCfg.Nodes = [];
  708. repoCfg.selectedNodes[$scope.myID] = true;
  709. for (var nodeID in repoCfg.selectedNodes) {
  710. if (repoCfg.selectedNodes[nodeID] === true) {
  711. repoCfg.Nodes.push({
  712. NodeID: nodeID
  713. });
  714. }
  715. }
  716. delete repoCfg.selectedNodes;
  717. if (repoCfg.FileVersioningSelector === "simple") {
  718. repoCfg.Versioning = {
  719. 'Type': 'simple',
  720. 'Params': {
  721. 'keep': '' + repoCfg.simpleKeep,
  722. }
  723. };
  724. delete repoCfg.simpleFileVersioning;
  725. delete repoCfg.simpleKeep;
  726. } else if (repoCfg.FileVersioningSelector === "staggered") {
  727. repoCfg.Versioning = {
  728. 'Type': 'staggered',
  729. 'Params': {
  730. 'maxAge': '' + (repoCfg.staggeredMaxAge * 86400),
  731. 'cleanInterval': '' + repoCfg.staggeredCleanInterval,
  732. 'versionsPath': '' + repoCfg.staggeredVersionsPath,
  733. }
  734. };
  735. delete repoCfg.staggeredFileVersioning;
  736. delete repoCfg.staggeredMaxAge;
  737. delete repoCfg.staggeredCleanInterval;
  738. delete repoCfg.staggeredVersionsPath;
  739. } else {
  740. delete repoCfg.Versioning;
  741. }
  742. $scope.repos[repoCfg.ID] = repoCfg;
  743. $scope.config.Repositories = repoList($scope.repos);
  744. $scope.saveConfig();
  745. };
  746. $scope.sharesRepo = function (repoCfg) {
  747. var names = [];
  748. repoCfg.Nodes.forEach(function (node) {
  749. names.push($scope.nodeName($scope.findNode(node.NodeID)));
  750. });
  751. names.sort();
  752. return names.join(", ");
  753. };
  754. $scope.deleteRepo = function () {
  755. $('#editRepo').modal('hide');
  756. if (!$scope.editingExisting) {
  757. return;
  758. }
  759. delete $scope.repos[$scope.currentRepo.ID];
  760. $scope.config.Repositories = repoList($scope.repos);
  761. $scope.saveConfig();
  762. };
  763. $scope.setAPIKey = function (cfg) {
  764. cfg.APIKey = randomString(30, 32);
  765. };
  766. $scope.showURPreview = function () {
  767. $('#settings').modal('hide');
  768. $('#urPreview').modal().on('hidden.bs.modal', function () {
  769. $('#settings').modal();
  770. });
  771. };
  772. $scope.acceptUR = function () {
  773. $scope.config.Options.URAccepted = 1000; // Larger than the largest existing report version
  774. $scope.saveConfig();
  775. $('#ur').modal('hide');
  776. };
  777. $scope.declineUR = function () {
  778. $scope.config.Options.URAccepted = -1;
  779. $scope.saveConfig();
  780. $('#ur').modal('hide');
  781. };
  782. $scope.showNeed = function (repo) {
  783. $scope.neededLoaded = false;
  784. $('#needed').modal();
  785. $http.get(urlbase + "/need?repo=" + encodeURIComponent(repo)).success(function (data) {
  786. $scope.needed = data;
  787. $scope.neededLoaded = true;
  788. });
  789. };
  790. $scope.needAction = function (file) {
  791. var fDelete = 4096;
  792. var fDirectory = 16384;
  793. if ((file.Flags & (fDelete + fDirectory)) === fDelete + fDirectory) {
  794. return 'rmdir';
  795. } else if ((file.Flags & fDelete) === fDelete) {
  796. return 'rm';
  797. } else if ((file.Flags & fDirectory) === fDirectory) {
  798. return 'touch';
  799. } else {
  800. return 'sync';
  801. }
  802. };
  803. $scope.override = function (repo) {
  804. $http.post(urlbase + "/model/override?repo=" + encodeURIComponent(repo));
  805. };
  806. $scope.about = function () {
  807. $('#about').modal('show');
  808. };
  809. $scope.showReportPreview = function () {
  810. $scope.reportPreview = true;
  811. };
  812. $scope.rescanRepo = function (repo) {
  813. $http.post(urlbase + "/scan?repo=" + encodeURIComponent(repo));
  814. };
  815. $scope.init();
  816. setInterval($scope.refresh, 10000);
  817. });
  818. function nodeCompare(a, b) {
  819. if (typeof a.Name !== 'undefined' && typeof b.Name !== 'undefined') {
  820. if (a.Name < b.Name)
  821. return -1;
  822. return a.Name > b.Name;
  823. }
  824. if (a.NodeID < b.NodeID) {
  825. return -1;
  826. }
  827. return a.NodeID > b.NodeID;
  828. }
  829. function repoCompare(a, b) {
  830. if (a.ID < b.ID) {
  831. return -1;
  832. }
  833. return a.ID > b.ID;
  834. }
  835. function repoMap(l) {
  836. var m = {};
  837. l.forEach(function (r) {
  838. m[r.ID] = r;
  839. });
  840. return m;
  841. }
  842. function repoList(m) {
  843. var l = [];
  844. for (var id in m) {
  845. l.push(m[id]);
  846. }
  847. l.sort(repoCompare);
  848. return l;
  849. }
  850. function decimals(val, num) {
  851. var digits, decs;
  852. if (val === 0) {
  853. return 0;
  854. }
  855. digits = Math.floor(Math.log(Math.abs(val)) / Math.log(10));
  856. decs = Math.max(0, num - digits);
  857. return decs;
  858. }
  859. function randomString(len, bits) {
  860. bits = bits || 36;
  861. var outStr = "",
  862. newStr;
  863. while (outStr.length < len) {
  864. newStr = Math.random().toString(bits).slice(2);
  865. outStr += newStr.slice(0, Math.min(newStr.length, (len - outStr.length)));
  866. }
  867. return outStr.toLowerCase();
  868. }
  869. function isEmptyObject(obj) {
  870. var name;
  871. for (name in obj) {
  872. return false;
  873. }
  874. return true;
  875. }
  876. syncthing.filter('natural', function () {
  877. return function (input, valid) {
  878. return input.toFixed(decimals(input, valid));
  879. };
  880. });
  881. syncthing.filter('binary', function () {
  882. return function (input) {
  883. if (input === undefined) {
  884. return '0 ';
  885. }
  886. if (input > 1024 * 1024 * 1024) {
  887. input /= 1024 * 1024 * 1024;
  888. return input.toFixed(decimals(input, 2)) + ' Gi';
  889. }
  890. if (input > 1024 * 1024) {
  891. input /= 1024 * 1024;
  892. return input.toFixed(decimals(input, 2)) + ' Mi';
  893. }
  894. if (input > 1024) {
  895. input /= 1024;
  896. return input.toFixed(decimals(input, 2)) + ' Ki';
  897. }
  898. return Math.round(input) + ' ';
  899. };
  900. });
  901. syncthing.filter('metric', function () {
  902. return function (input) {
  903. if (input === undefined) {
  904. return '0 ';
  905. }
  906. if (input > 1000 * 1000 * 1000) {
  907. input /= 1000 * 1000 * 1000;
  908. return input.toFixed(decimals(input, 2)) + ' G';
  909. }
  910. if (input > 1000 * 1000) {
  911. input /= 1000 * 1000;
  912. return input.toFixed(decimals(input, 2)) + ' M';
  913. }
  914. if (input > 1000) {
  915. input /= 1000;
  916. return input.toFixed(decimals(input, 2)) + ' k';
  917. }
  918. return Math.round(input) + ' ';
  919. };
  920. });
  921. syncthing.filter('alwaysNumber', function () {
  922. return function (input) {
  923. if (input === undefined) {
  924. return 0;
  925. }
  926. return input;
  927. };
  928. });
  929. syncthing.filter('basename', function () {
  930. return function (input) {
  931. if (input === undefined)
  932. return "";
  933. var parts = input.split(/[\/\\]/);
  934. if (!parts || parts.length < 1) {
  935. return input;
  936. }
  937. return parts[parts.length - 1];
  938. };
  939. });
  940. syncthing.directive('uniqueRepo', function () {
  941. return {
  942. require: 'ngModel',
  943. link: function (scope, elm, attrs, ctrl) {
  944. ctrl.$parsers.unshift(function (viewValue) {
  945. if (scope.editingExisting) {
  946. // we shouldn't validate
  947. ctrl.$setValidity('uniqueRepo', true);
  948. } else if (scope.repos[viewValue]) {
  949. // the repo exists already
  950. ctrl.$setValidity('uniqueRepo', false);
  951. } else {
  952. // the repo is unique
  953. ctrl.$setValidity('uniqueRepo', true);
  954. }
  955. return viewValue;
  956. });
  957. }
  958. };
  959. });
  960. syncthing.directive('validNodeid', function ($http) {
  961. return {
  962. require: 'ngModel',
  963. link: function (scope, elm, attrs, ctrl) {
  964. ctrl.$parsers.unshift(function (viewValue) {
  965. if (scope.editingExisting) {
  966. // we shouldn't validate
  967. ctrl.$setValidity('validNodeid', true);
  968. } else {
  969. $http.get(urlbase + '/nodeid?id=' + viewValue).success(function (resp) {
  970. if (resp.error) {
  971. ctrl.$setValidity('validNodeid', false);
  972. } else {
  973. ctrl.$setValidity('validNodeid', true);
  974. }
  975. });
  976. }
  977. return viewValue;
  978. });
  979. }
  980. };
  981. });
  982. syncthing.directive('modal', function () {
  983. return {
  984. restrict: 'E',
  985. templateUrl: 'modal.html',
  986. replace: true,
  987. transclude: true,
  988. scope: {
  989. title: '@',
  990. status: '@',
  991. icon: '@',
  992. close: '@',
  993. large: '@',
  994. },
  995. };
  996. });