app.js 33 KB

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