app.js 31 KB

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