app.js 33 KB

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