app.js 37 KB

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