app.js 34 KB

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