app.js 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851
  1. // Copyright (C) 2014 Jakob Borg and other contributors. All rights reserved.
  2. // Use of this source code is governed by an MIT-style license that can be
  3. // 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', []);
  8. var urlbase = 'rest';
  9. syncthing.config(function ($httpProvider) {
  10. $httpProvider.defaults.xsrfHeaderName = 'X-CSRF-Token';
  11. $httpProvider.defaults.xsrfCookieName = 'CSRF-Token';
  12. });
  13. syncthing.controller('SyncthingCtrl', function ($scope, $http) {
  14. var prevDate = 0;
  15. var getOK = true;
  16. var restarting = false;
  17. $scope.connections = {};
  18. $scope.config = {};
  19. $scope.myID = '';
  20. $scope.nodes = [];
  21. $scope.configInSync = true;
  22. $scope.protocolChanged = false;
  23. $scope.errors = [];
  24. $scope.seenError = '';
  25. $scope.model = {};
  26. $scope.repos = {};
  27. $scope.reportData = {};
  28. $scope.reportPreview = false;
  29. $scope.needActions = {
  30. 'rm': 'Del',
  31. 'rmdir': 'Del (dir)',
  32. 'sync': 'Sync',
  33. 'touch': 'Update',
  34. }
  35. $scope.needIcons = {
  36. 'rm': 'remove',
  37. 'rmdir': 'remove',
  38. 'sync': 'download',
  39. 'touch': 'asterisk',
  40. }
  41. // Strings before bools look better
  42. $scope.settings = [
  43. {id: 'ListenStr', descr: 'Sync Protocol Listen Addresses', type: 'text'},
  44. {id: 'MaxSendKbps', descr: 'Outgoing Rate Limit (KiB/s)', type: 'number'},
  45. {id: 'RescanIntervalS', descr: 'Rescan Interval (s)', type: 'number'},
  46. {id: 'ReconnectIntervalS', descr: 'Reconnect Interval (s)', type: 'number'},
  47. {id: 'ParallelRequests', descr: 'Max Outstanding Requests', type: 'number'},
  48. {id: 'MaxChangeKbps', descr: 'Max File Change Rate (KiB/s)', type: 'number'},
  49. {id: 'LocalAnnPort', descr: 'Local Discovery Port', type: 'number'},
  50. {id: 'LocalAnnEnabled', descr: 'Local Discovery', type: 'bool'},
  51. {id: 'GlobalAnnEnabled', descr: 'Global Discovery', type: 'bool'},
  52. {id: 'StartBrowser', descr: 'Start Browser', type: 'bool'},
  53. {id: 'UPnPEnabled', descr: 'Enable UPnP', type: 'bool'},
  54. {id: 'UREnabled', descr: 'Anonymous Usage Reporting', type: 'bool'},
  55. ];
  56. $scope.guiSettings = [
  57. {id: 'Address', descr: 'GUI Listen Addresses', type: 'text', restart: true},
  58. {id: 'User', descr: 'GUI Authentication User', type: 'text', restart: true},
  59. {id: 'Password', descr: 'GUI Authentication Password', type: 'password', restart: true},
  60. {id: 'UseTLS', descr: 'Use HTTPS for GUI', type: 'bool', restart: true},
  61. {id: 'APIKey', descr: 'API Key', type: 'apikey'},
  62. ];
  63. function getSucceeded() {
  64. if (!getOK) {
  65. $scope.init();
  66. $('#networkError').modal('hide');
  67. getOK = true;
  68. }
  69. if (restarting) {
  70. $scope.init();
  71. $('#restarting').modal('hide');
  72. $('#shutdown').modal('hide');
  73. restarting = false;
  74. }
  75. }
  76. function getFailed() {
  77. if (restarting) {
  78. return;
  79. }
  80. if (getOK) {
  81. $('#networkError').modal({backdrop: 'static', keyboard: false});
  82. getOK = false;
  83. }
  84. }
  85. $scope.refresh = function () {
  86. $http.get(urlbase + '/system').success(function (data) {
  87. getSucceeded();
  88. $scope.system = data;
  89. }).error(function () {
  90. getFailed();
  91. });
  92. Object.keys($scope.repos).forEach(function (id) {
  93. $http.get(urlbase + '/model?repo=' + encodeURIComponent(id)).success(function (data) {
  94. $scope.model[id] = data;
  95. });
  96. });
  97. $http.get(urlbase + '/connections').success(function (data) {
  98. var now = Date.now(),
  99. td = (now - prevDate) / 1000,
  100. id;
  101. prevDate = now;
  102. for (id in data) {
  103. if (!data.hasOwnProperty(id)) {
  104. continue;
  105. }
  106. try {
  107. data[id].inbps = Math.max(0, 8 * (data[id].InBytesTotal - $scope.connections[id].InBytesTotal) / td);
  108. data[id].outbps = Math.max(0, 8 * (data[id].OutBytesTotal - $scope.connections[id].OutBytesTotal) / td);
  109. } catch (e) {
  110. data[id].inbps = 0;
  111. data[id].outbps = 0;
  112. }
  113. }
  114. $scope.connections = data;
  115. });
  116. $http.get(urlbase + '/errors').success(function (data) {
  117. $scope.errors = data;
  118. });
  119. };
  120. $scope.repoStatus = function (repo) {
  121. if (typeof $scope.model[repo] === 'undefined') {
  122. return 'Unknown';
  123. }
  124. if ($scope.model[repo].invalid !== '') {
  125. return 'Stopped';
  126. }
  127. var state = '' + $scope.model[repo].state;
  128. state = state[0].toUpperCase() + state.substr(1);
  129. if (state == "Syncing" || state == "Idle") {
  130. state += " (" + $scope.syncPercentage(repo) + "%)";
  131. }
  132. return state;
  133. };
  134. $scope.repoClass = function (repo) {
  135. if (typeof $scope.model[repo] === 'undefined') {
  136. return 'info';
  137. }
  138. if ($scope.model[repo].invalid !== '') {
  139. return 'danger';
  140. }
  141. var state = '' + $scope.model[repo].state;
  142. if (state == 'idle') {
  143. return 'success';
  144. }
  145. if (state == 'syncing') {
  146. return 'primary';
  147. }
  148. return 'info';
  149. };
  150. $scope.syncPercentage = function (repo) {
  151. if (typeof $scope.model[repo] === 'undefined') {
  152. return 100;
  153. }
  154. if ($scope.model[repo].globalBytes === 0) {
  155. return 100;
  156. }
  157. var pct = 100 * $scope.model[repo].inSyncBytes / $scope.model[repo].globalBytes;
  158. return Math.floor(pct);
  159. };
  160. $scope.nodeStatus = function (nodeCfg) {
  161. var conn = $scope.connections[nodeCfg.NodeID];
  162. if (conn) {
  163. if (conn.Completion === 100) {
  164. return 'Up to Date';
  165. } else {
  166. return 'Syncing (' + conn.Completion + '%)';
  167. }
  168. }
  169. return 'Disconnected';
  170. };
  171. $scope.nodeIcon = function (nodeCfg) {
  172. var conn = $scope.connections[nodeCfg.NodeID];
  173. if (conn) {
  174. if (conn.Completion === 100) {
  175. return 'ok';
  176. } else {
  177. return 'refresh';
  178. }
  179. }
  180. return 'minus';
  181. };
  182. $scope.nodeClass = function (nodeCfg) {
  183. var conn = $scope.connections[nodeCfg.NodeID];
  184. if (conn) {
  185. if (conn.Completion === 100) {
  186. return 'success';
  187. } else {
  188. return 'primary';
  189. }
  190. }
  191. return 'info';
  192. };
  193. $scope.nodeAddr = function (nodeCfg) {
  194. var conn = $scope.connections[nodeCfg.NodeID];
  195. if (conn) {
  196. return conn.Address;
  197. }
  198. return '?';
  199. };
  200. $scope.nodeCompletion = function (nodeCfg) {
  201. var conn = $scope.connections[nodeCfg.NodeID];
  202. if (conn) {
  203. return conn.Completion + '%';
  204. }
  205. return '';
  206. };
  207. $scope.nodeVer = function (nodeCfg) {
  208. if (nodeCfg.NodeID === $scope.myID) {
  209. return $scope.version;
  210. }
  211. var conn = $scope.connections[nodeCfg.NodeID];
  212. if (conn) {
  213. return conn.ClientVersion;
  214. }
  215. return '?';
  216. };
  217. $scope.findNode = function (nodeID) {
  218. var matches = $scope.nodes.filter(function (n) { return n.NodeID == nodeID; });
  219. if (matches.length != 1) {
  220. return undefined;
  221. }
  222. return matches[0];
  223. };
  224. $scope.nodeName = function (nodeCfg) {
  225. if (typeof nodeCfg === 'undefined') {
  226. return "";
  227. }
  228. if (nodeCfg.Name) {
  229. return nodeCfg.Name;
  230. }
  231. return nodeCfg.NodeID.substr(0, 6);
  232. };
  233. $scope.thisNodeName = function () {
  234. var node = $scope.thisNode();
  235. if (typeof node === 'undefined') {
  236. return "(unknown node)";
  237. }
  238. if (node.Name) {
  239. return node.Name;
  240. }
  241. return node.NodeID.substr(0, 6);
  242. };
  243. $scope.editSettings = function () {
  244. // Make a working copy
  245. $scope.config.workingOptions = angular.copy($scope.config.Options);
  246. $scope.config.workingGUI = angular.copy($scope.config.GUI);
  247. $('#settings').modal({backdrop: 'static', keyboard: true});
  248. };
  249. $scope.saveConfig = function() {
  250. var cfg = JSON.stringify($scope.config);
  251. var opts = {headers: {'Content-Type': 'application/json'}};
  252. $http.post(urlbase + '/config', cfg, opts).success(function () {
  253. $http.get(urlbase + '/config/sync').success(function (data) {
  254. $scope.configInSync = data.configInSync;
  255. });
  256. });
  257. };
  258. $scope.saveSettings = function () {
  259. // Make sure something changed
  260. var changed = ! angular.equals($scope.config.Options, $scope.config.workingOptions) ||
  261. ! angular.equals($scope.config.GUI, $scope.config.workingGUI);
  262. if(changed){
  263. // see if protocol will need to be changed on restart
  264. if($scope.config.GUI.UseTLS !== $scope.config.workingGUI.UseTLS){
  265. $scope.protocolChanged = true;
  266. }
  267. // Apply new settings locally
  268. $scope.config.Options = angular.copy($scope.config.workingOptions);
  269. $scope.config.GUI = angular.copy($scope.config.workingGUI);
  270. $scope.config.Options.ListenAddress = $scope.config.Options.ListenStr.split(',').map(function (x) { return x.trim(); });
  271. $scope.saveConfig();
  272. }
  273. $('#settings').modal("hide");
  274. };
  275. $scope.restart = function () {
  276. restarting = true;
  277. $('#restarting').modal({backdrop: 'static', keyboard: false});
  278. $http.post(urlbase + '/restart');
  279. $scope.configInSync = true;
  280. // Switch webpage protocol if needed
  281. if($scope.protocolChanged){
  282. var protocol = 'http';
  283. if($scope.config.GUI.UseTLS){
  284. protocol = 'https';
  285. }
  286. setTimeout(function(){
  287. window.location.protocol = protocol;
  288. }, 1000);
  289. $scope.protocolChanged = false;
  290. }
  291. };
  292. $scope.shutdown = function () {
  293. restarting = true;
  294. $http.post(urlbase + '/shutdown').success(function () {
  295. $('#shutdown').modal({backdrop: 'static', keyboard: false});
  296. });
  297. $scope.configInSync = true;
  298. };
  299. $scope.editNode = function (nodeCfg) {
  300. $scope.currentNode = $.extend({}, nodeCfg);
  301. $scope.editingExisting = true;
  302. $scope.editingSelf = (nodeCfg.NodeID == $scope.myID);
  303. $scope.currentNode.AddressesStr = nodeCfg.Addresses.join(', ');
  304. $scope.nodeEditor.$setPristine();
  305. $('#editNode').modal({backdrop: 'static', keyboard: true});
  306. };
  307. $scope.idNode = function () {
  308. $('#idqr').modal('show');
  309. };
  310. $scope.addNode = function () {
  311. $scope.currentNode = {AddressesStr: 'dynamic'};
  312. $scope.editingExisting = false;
  313. $scope.editingSelf = false;
  314. $scope.nodeEditor.$setPristine();
  315. $('#editNode').modal({backdrop: 'static', keyboard: true});
  316. };
  317. $scope.deleteNode = function () {
  318. $('#editNode').modal('hide');
  319. if (!$scope.editingExisting) {
  320. return;
  321. }
  322. $scope.nodes = $scope.nodes.filter(function (n) {
  323. return n.NodeID !== $scope.currentNode.NodeID;
  324. });
  325. $scope.config.Nodes = $scope.nodes;
  326. for (var id in $scope.repos) {
  327. $scope.repos[id].Nodes = $scope.repos[id].Nodes.filter(function (n) {
  328. return n.NodeID !== $scope.currentNode.NodeID;
  329. });
  330. }
  331. $scope.saveConfig();
  332. };
  333. $scope.saveNode = function () {
  334. var nodeCfg, done, i;
  335. $('#editNode').modal('hide');
  336. nodeCfg = $scope.currentNode;
  337. nodeCfg.NodeID = nodeCfg.NodeID.replace(/ /g, '').replace(/-/g, '').toUpperCase().trim();
  338. nodeCfg.Addresses = nodeCfg.AddressesStr.split(',').map(function (x) { return x.trim(); });
  339. done = false;
  340. for (i = 0; i < $scope.nodes.length; i++) {
  341. if ($scope.nodes[i].NodeID === nodeCfg.NodeID) {
  342. $scope.nodes[i] = nodeCfg;
  343. done = true;
  344. break;
  345. }
  346. }
  347. if (!done) {
  348. $scope.nodes.push(nodeCfg);
  349. }
  350. $scope.nodes.sort(nodeCompare);
  351. $scope.config.Nodes = $scope.nodes;
  352. $scope.saveConfig();
  353. };
  354. $scope.otherNodes = function () {
  355. return $scope.nodes.filter(function (n){
  356. return n.NodeID !== $scope.myID;
  357. });
  358. };
  359. $scope.thisNode = function () {
  360. var i, n;
  361. for (i = 0; i < $scope.nodes.length; i++) {
  362. n = $scope.nodes[i];
  363. if (n.NodeID === $scope.myID) {
  364. return n;
  365. }
  366. }
  367. };
  368. $scope.allNodes = function () {
  369. var nodes = $scope.otherNodes();
  370. nodes.push($scope.thisNode());
  371. return nodes;
  372. };
  373. $scope.errorList = function () {
  374. return $scope.errors.filter(function (e) {
  375. return e.Time > $scope.seenError;
  376. });
  377. };
  378. $scope.clearErrors = function () {
  379. $scope.seenError = $scope.errors[$scope.errors.length - 1].Time;
  380. $http.post(urlbase + '/error/clear');
  381. };
  382. $scope.friendlyNodes = function (str) {
  383. for (var i = 0; i < $scope.nodes.length; i++) {
  384. var cfg = $scope.nodes[i];
  385. str = str.replace(cfg.NodeID, $scope.nodeName(cfg));
  386. }
  387. return str;
  388. };
  389. $scope.repoList = function () {
  390. return repoList($scope.repos);
  391. };
  392. $scope.editRepo = function (nodeCfg) {
  393. $scope.currentRepo = angular.copy(nodeCfg);
  394. $scope.currentRepo.selectedNodes = {};
  395. $scope.currentRepo.Nodes.forEach(function (n) {
  396. $scope.currentRepo.selectedNodes[n.NodeID] = true;
  397. });
  398. if ($scope.currentRepo.Versioning && $scope.currentRepo.Versioning.Type === "simple") {
  399. $scope.currentRepo.simpleFileVersioning = true;
  400. $scope.currentRepo.simpleKeep = +$scope.currentRepo.Versioning.Params.keep;
  401. }
  402. $scope.currentRepo.simpleKeep = $scope.currentRepo.simpleKeep || 5;
  403. $scope.editingExisting = true;
  404. $scope.repoEditor.$setPristine();
  405. $('#editRepo').modal({backdrop: 'static', keyboard: true});
  406. };
  407. $scope.addRepo = function () {
  408. $scope.currentRepo = {selectedNodes: {}};
  409. $scope.editingExisting = false;
  410. $scope.repoEditor.$setPristine();
  411. $('#editRepo').modal({backdrop: 'static', keyboard: true});
  412. };
  413. $scope.saveRepo = function () {
  414. var repoCfg, done, i;
  415. $('#editRepo').modal('hide');
  416. repoCfg = $scope.currentRepo;
  417. repoCfg.Nodes = [];
  418. repoCfg.selectedNodes[$scope.myID] = true;
  419. for (var nodeID in repoCfg.selectedNodes) {
  420. if (repoCfg.selectedNodes[nodeID] === true) {
  421. repoCfg.Nodes.push({NodeID: nodeID});
  422. }
  423. }
  424. delete repoCfg.selectedNodes;
  425. if (repoCfg.simpleFileVersioning) {
  426. repoCfg.Versioning = {
  427. 'Type': 'simple',
  428. 'Params': {
  429. 'keep': '' + repoCfg.simpleKeep,
  430. }
  431. };
  432. delete repoCfg.simpleFileVersioning;
  433. delete repoCfg.simpleKeep;
  434. } else {
  435. delete repoCfg.Versioning;
  436. }
  437. $scope.repos[repoCfg.ID] = repoCfg;
  438. $scope.config.Repositories = repoList($scope.repos);
  439. $scope.saveConfig();
  440. };
  441. $scope.sharesRepo = function(repoCfg) {
  442. var names = [];
  443. repoCfg.Nodes.forEach(function (node) {
  444. names.push($scope.nodeName($scope.findNode(node.NodeID)));
  445. });
  446. names.sort();
  447. return names.join(", ");
  448. };
  449. $scope.deleteRepo = function () {
  450. $('#editRepo').modal('hide');
  451. if (!$scope.editingExisting) {
  452. return;
  453. }
  454. delete $scope.repos[$scope.currentRepo.ID];
  455. $scope.config.Repositories = repoList($scope.repos);
  456. $scope.saveConfig();
  457. };
  458. $scope.setAPIKey = function (cfg) {
  459. cfg.APIKey = randomString(30, 32);
  460. };
  461. $scope.init = function() {
  462. $http.get(urlbase + '/version').success(function (data) {
  463. $scope.version = data;
  464. });
  465. $http.get(urlbase + '/system').success(function (data) {
  466. $scope.system = data;
  467. $scope.myID = data.myID;
  468. });
  469. $http.get(urlbase + '/config').success(function (data) {
  470. $scope.config = data;
  471. $scope.config.Options.ListenStr = $scope.config.Options.ListenAddress.join(', ');
  472. $scope.nodes = $scope.config.Nodes;
  473. $scope.nodes.sort(nodeCompare);
  474. $scope.repos = repoMap($scope.config.Repositories);
  475. $scope.refresh();
  476. if (!$scope.config.Options.UREnabled && !$scope.config.Options.URDeclined) {
  477. // If usage reporting has been neither accepted nor declined,
  478. // we want to ask the user to make a choice. But we don't want
  479. // to bug them during initial setup, so we set a cookie with
  480. // the time of the first visit. When that cookie is present
  481. // and the time is more than four hours ago, we ask the
  482. // question.
  483. var firstVisit = document.cookie.replace(/(?:(?:^|.*;\s*)firstVisit\s*\=\s*([^;]*).*$)|^.*$/, "$1");
  484. if (!firstVisit) {
  485. document.cookie = "firstVisit=" + Date.now() + ";max-age=" + 30*24*3600;
  486. } else {
  487. if (+firstVisit < Date.now() - 4*3600*1000){
  488. $('#ur').modal({backdrop: 'static', keyboard: false});
  489. }
  490. }
  491. }
  492. });
  493. $http.get(urlbase + '/config/sync').success(function (data) {
  494. $scope.configInSync = data.configInSync;
  495. });
  496. $http.get(urlbase + '/report').success(function (data) {
  497. $scope.reportData = data;
  498. });
  499. };
  500. $scope.acceptUR = function () {
  501. $scope.config.Options.UREnabled = true;
  502. $scope.config.Options.URDeclined = false;
  503. $scope.saveConfig();
  504. $('#ur').modal('hide');
  505. };
  506. $scope.declineUR = function () {
  507. $scope.config.Options.UREnabled = false;
  508. $scope.config.Options.URDeclined = true;
  509. $scope.saveConfig();
  510. $('#ur').modal('hide');
  511. };
  512. $scope.showNeed = function (repo) {
  513. $scope.neededLoaded = false;
  514. $('#needed').modal({backdrop: 'static', keyboard: true});
  515. $http.get(urlbase + "/need?repo=" + encodeURIComponent(repo)).success(function (data) {
  516. $scope.needed = data;
  517. $scope.neededLoaded = true;
  518. });
  519. };
  520. $scope.needAction = function (file) {
  521. var fDelete = 4096;
  522. var fDirectory = 16384;
  523. if ((file.Flags & (fDelete+fDirectory)) === fDelete+fDirectory) {
  524. return 'rmdir';
  525. } else if ((file.Flags & fDelete) === fDelete) {
  526. return 'rm';
  527. } else if ((file.Flags & fDirectory) === fDirectory) {
  528. return 'touch';
  529. } else {
  530. return 'sync';
  531. }
  532. };
  533. $scope.init();
  534. setInterval($scope.refresh, 10000);
  535. });
  536. function nodeCompare(a, b) {
  537. if (typeof a.Name !== 'undefined' && typeof b.Name !== 'undefined') {
  538. if (a.Name < b.Name)
  539. return -1;
  540. return a.Name > b.Name;
  541. }
  542. if (a.NodeID < b.NodeID) {
  543. return -1;
  544. }
  545. return a.NodeID > b.NodeID;
  546. }
  547. function repoCompare(a, b) {
  548. if (a.Directory < b.Directory) {
  549. return -1;
  550. }
  551. return a.Directory > b.Directory;
  552. }
  553. function repoMap(l) {
  554. var m = {};
  555. l.forEach(function (r) {
  556. m[r.ID] = r;
  557. });
  558. return m;
  559. }
  560. function repoList(m) {
  561. var l = [];
  562. for (var id in m) {
  563. l.push(m[id]);
  564. }
  565. l.sort(repoCompare);
  566. return l;
  567. }
  568. function decimals(val, num) {
  569. var digits, decs;
  570. if (val === 0) {
  571. return 0;
  572. }
  573. digits = Math.floor(Math.log(Math.abs(val)) / Math.log(10));
  574. decs = Math.max(0, num - digits);
  575. return decs;
  576. }
  577. function randomString(len, bits)
  578. {
  579. bits = bits || 36;
  580. var outStr = "", newStr;
  581. while (outStr.length < len)
  582. {
  583. newStr = Math.random().toString(bits).slice(2);
  584. outStr += newStr.slice(0, Math.min(newStr.length, (len - outStr.length)));
  585. }
  586. return outStr.toUpperCase();
  587. }
  588. syncthing.filter('natural', function () {
  589. return function (input, valid) {
  590. return input.toFixed(decimals(input, valid));
  591. };
  592. });
  593. syncthing.filter('binary', function () {
  594. return function (input) {
  595. if (input === undefined) {
  596. return '0 ';
  597. }
  598. if (input > 1024 * 1024 * 1024) {
  599. input /= 1024 * 1024 * 1024;
  600. return input.toFixed(decimals(input, 2)) + ' Gi';
  601. }
  602. if (input > 1024 * 1024) {
  603. input /= 1024 * 1024;
  604. return input.toFixed(decimals(input, 2)) + ' Mi';
  605. }
  606. if (input > 1024) {
  607. input /= 1024;
  608. return input.toFixed(decimals(input, 2)) + ' Ki';
  609. }
  610. return Math.round(input) + ' ';
  611. };
  612. });
  613. syncthing.filter('metric', function () {
  614. return function (input) {
  615. if (input === undefined) {
  616. return '0 ';
  617. }
  618. if (input > 1000 * 1000 * 1000) {
  619. input /= 1000 * 1000 * 1000;
  620. return input.toFixed(decimals(input, 2)) + ' G';
  621. }
  622. if (input > 1000 * 1000) {
  623. input /= 1000 * 1000;
  624. return input.toFixed(decimals(input, 2)) + ' M';
  625. }
  626. if (input > 1000) {
  627. input /= 1000;
  628. return input.toFixed(decimals(input, 2)) + ' k';
  629. }
  630. return Math.round(input) + ' ';
  631. };
  632. });
  633. syncthing.filter('short', function () {
  634. return function (input) {
  635. return input.substr(0, 6);
  636. };
  637. });
  638. syncthing.filter('alwaysNumber', function () {
  639. return function (input) {
  640. if (input === undefined) {
  641. return 0;
  642. }
  643. return input;
  644. };
  645. });
  646. syncthing.filter('chunkID', function () {
  647. return function (input) {
  648. if (input === undefined)
  649. return "";
  650. var parts = input.match(/.{1,6}/g);
  651. if (!parts)
  652. return "";
  653. return parts.join('-');
  654. };
  655. });
  656. syncthing.filter('shortPath', function () {
  657. return function (input) {
  658. if (input === undefined)
  659. return "";
  660. var parts = input.split(/[\/\\]/);
  661. if (!parts || parts.length <= 3) {
  662. return input;
  663. }
  664. return ".../" + parts.slice(parts.length-2).join("/");
  665. };
  666. });
  667. syncthing.filter('basename', function () {
  668. return function (input) {
  669. if (input === undefined)
  670. return "";
  671. var parts = input.split(/[\/\\]/);
  672. if (!parts || parts.length < 1) {
  673. return input;
  674. }
  675. return parts[parts.length-1];
  676. };
  677. });
  678. syncthing.filter('clean', function () {
  679. return function (input) {
  680. return encodeURIComponent(input).replace(/%/g, '');
  681. };
  682. });
  683. syncthing.directive('optionEditor', function () {
  684. return {
  685. restrict: 'C',
  686. replace: true,
  687. transclude: true,
  688. scope: {
  689. setting: '=setting',
  690. },
  691. template: '<input type="text" ng-model="config.Options[setting.id]"></input>',
  692. };
  693. });
  694. syncthing.directive('uniqueRepo', function() {
  695. return {
  696. require: 'ngModel',
  697. link: function(scope, elm, attrs, ctrl) {
  698. ctrl.$parsers.unshift(function(viewValue) {
  699. if (scope.editingExisting) {
  700. // we shouldn't validate
  701. ctrl.$setValidity('uniqueRepo', true);
  702. } else if (scope.repos[viewValue]) {
  703. // the repo exists already
  704. ctrl.$setValidity('uniqueRepo', false);
  705. } else {
  706. // the repo is unique
  707. ctrl.$setValidity('uniqueRepo', true);
  708. }
  709. return viewValue;
  710. });
  711. }
  712. };
  713. });
  714. syncthing.directive('validNodeid', function() {
  715. return {
  716. require: 'ngModel',
  717. link: function(scope, elm, attrs, ctrl) {
  718. ctrl.$parsers.unshift(function(viewValue) {
  719. if (scope.editingExisting) {
  720. // we shouldn't validate
  721. ctrl.$setValidity('validNodeid', true);
  722. } else {
  723. var cleaned = viewValue.replace(/ /g, '').replace(/-/g, '').toUpperCase().trim();
  724. if (cleaned.match(/^[A-Z2-7]{52}$/)) {
  725. ctrl.$setValidity('validNodeid', true);
  726. } else {
  727. ctrl.$setValidity('validNodeid', false);
  728. }
  729. }
  730. return viewValue;
  731. });
  732. }
  733. };
  734. });