app.js 34 KB

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