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