app.js 37 KB

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