app.js 33 KB

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