app.js 31 KB

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