app.js 33 KB

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