app.js 37 KB

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