app.js 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233
  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. $http.get(urlbase + '/discovery')
  577. .success(function (registry) {
  578. $scope.discovery = registry;
  579. })
  580. .then(function () {
  581. $scope.currentDevice = {
  582. AddressesStr: 'dynamic',
  583. Compression: true,
  584. Introducer: false
  585. };
  586. $scope.editingExisting = false;
  587. $scope.editingSelf = false;
  588. $scope.deviceEditor.$setPristine();
  589. $('#editDevice').modal();
  590. });
  591. };
  592. $scope.deleteDevice = function () {
  593. $('#editDevice').modal('hide');
  594. if (!$scope.editingExisting) {
  595. return;
  596. }
  597. $scope.devices = $scope.devices.filter(function (n) {
  598. return n.DeviceID !== $scope.currentDevice.DeviceID;
  599. });
  600. $scope.config.Devices = $scope.devices;
  601. for (var id in $scope.folders) {
  602. $scope.folders[id].Devices = $scope.folders[id].Devices.filter(function (n) {
  603. return n.DeviceID !== $scope.currentDevice.DeviceID;
  604. });
  605. }
  606. $scope.saveConfig();
  607. };
  608. $scope.saveDevice = function () {
  609. var deviceCfg, done, i;
  610. $('#editDevice').modal('hide');
  611. deviceCfg = $scope.currentDevice;
  612. deviceCfg.Addresses = deviceCfg.AddressesStr.split(',').map(function (x) {
  613. return x.trim();
  614. });
  615. done = false;
  616. for (i = 0; i < $scope.devices.length; i++) {
  617. if ($scope.devices[i].DeviceID === deviceCfg.DeviceID) {
  618. $scope.devices[i] = deviceCfg;
  619. done = true;
  620. break;
  621. }
  622. }
  623. if (!done) {
  624. $scope.devices.push(deviceCfg);
  625. }
  626. $scope.devices.sort(deviceCompare);
  627. $scope.config.Devices = $scope.devices;
  628. $scope.saveConfig();
  629. };
  630. $scope.otherDevices = function () {
  631. return $scope.devices.filter(function (n) {
  632. return n.DeviceID !== $scope.myID;
  633. });
  634. };
  635. $scope.thisDevice = function () {
  636. var i, n;
  637. for (i = 0; i < $scope.devices.length; i++) {
  638. n = $scope.devices[i];
  639. if (n.DeviceID === $scope.myID) {
  640. return n;
  641. }
  642. }
  643. };
  644. $scope.allDevices = function () {
  645. var devices = $scope.otherDevices();
  646. devices.push($scope.thisDevice());
  647. return devices;
  648. };
  649. $scope.errorList = function () {
  650. return $scope.errors.filter(function (e) {
  651. return e.Time > $scope.seenError;
  652. });
  653. };
  654. $scope.clearErrors = function () {
  655. $scope.seenError = $scope.errors[$scope.errors.length - 1].Time;
  656. $http.post(urlbase + '/error/clear');
  657. };
  658. $scope.friendlyDevices = function (str) {
  659. for (var i = 0; i < $scope.devices.length; i++) {
  660. var cfg = $scope.devices[i];
  661. str = str.replace(cfg.DeviceID, $scope.deviceName(cfg));
  662. }
  663. return str;
  664. };
  665. $scope.folderList = function () {
  666. return folderList($scope.folders);
  667. };
  668. $scope.editFolder = function (deviceCfg) {
  669. $scope.currentFolder = angular.copy(deviceCfg);
  670. $scope.currentFolder.selectedDevices = {};
  671. $scope.currentFolder.Devices.forEach(function (n) {
  672. $scope.currentFolder.selectedDevices[n.DeviceID] = true;
  673. });
  674. if ($scope.currentFolder.Versioning && $scope.currentFolder.Versioning.Type === "simple") {
  675. $scope.currentFolder.simpleFileVersioning = true;
  676. $scope.currentFolder.FileVersioningSelector = "simple";
  677. $scope.currentFolder.simpleKeep = +$scope.currentFolder.Versioning.Params.keep;
  678. } else if ($scope.currentFolder.Versioning && $scope.currentFolder.Versioning.Type === "staggered") {
  679. $scope.currentFolder.staggeredFileVersioning = true;
  680. $scope.currentFolder.FileVersioningSelector = "staggered";
  681. $scope.currentFolder.staggeredMaxAge = Math.floor(+$scope.currentFolder.Versioning.Params.maxAge / 86400);
  682. $scope.currentFolder.staggeredCleanInterval = +$scope.currentFolder.Versioning.Params.cleanInterval;
  683. $scope.currentFolder.staggeredVersionsPath = $scope.currentFolder.Versioning.Params.versionsPath;
  684. } else {
  685. $scope.currentFolder.FileVersioningSelector = "none";
  686. }
  687. $scope.currentFolder.simpleKeep = $scope.currentFolder.simpleKeep || 5;
  688. $scope.currentFolder.staggeredCleanInterval = $scope.currentFolder.staggeredCleanInterval || 3600;
  689. $scope.currentFolder.staggeredVersionsPath = $scope.currentFolder.staggeredVersionsPath || "";
  690. // staggeredMaxAge can validly be zero, which we should not replace
  691. // with the default value of 365. So only set the default if it's
  692. // actually undefined.
  693. if (typeof $scope.currentFolder.staggeredMaxAge === 'undefined') {
  694. $scope.currentFolder.staggeredMaxAge = 365;
  695. }
  696. $scope.editingExisting = true;
  697. $scope.folderEditor.$setPristine();
  698. $('#editFolder').modal();
  699. };
  700. $scope.addFolder = function () {
  701. $scope.currentFolder = {
  702. selectedDevices: {}
  703. };
  704. $scope.currentFolder.RescanIntervalS = 60;
  705. $scope.currentFolder.FileVersioningSelector = "none";
  706. $scope.currentFolder.simpleKeep = 5;
  707. $scope.currentFolder.staggeredMaxAge = 365;
  708. $scope.currentFolder.staggeredCleanInterval = 3600;
  709. $scope.currentFolder.staggeredVersionsPath = "";
  710. $scope.editingExisting = false;
  711. $scope.folderEditor.$setPristine();
  712. $('#editFolder').modal();
  713. };
  714. $scope.saveFolder = function () {
  715. var folderCfg, done, i;
  716. $('#editFolder').modal('hide');
  717. folderCfg = $scope.currentFolder;
  718. folderCfg.Devices = [];
  719. folderCfg.selectedDevices[$scope.myID] = true;
  720. for (var deviceID in folderCfg.selectedDevices) {
  721. if (folderCfg.selectedDevices[deviceID] === true) {
  722. folderCfg.Devices.push({
  723. DeviceID: deviceID
  724. });
  725. }
  726. }
  727. delete folderCfg.selectedDevices;
  728. if (folderCfg.FileVersioningSelector === "simple") {
  729. folderCfg.Versioning = {
  730. 'Type': 'simple',
  731. 'Params': {
  732. 'keep': '' + folderCfg.simpleKeep,
  733. }
  734. };
  735. delete folderCfg.simpleFileVersioning;
  736. delete folderCfg.simpleKeep;
  737. } else if (folderCfg.FileVersioningSelector === "staggered") {
  738. folderCfg.Versioning = {
  739. 'Type': 'staggered',
  740. 'Params': {
  741. 'maxAge': '' + (folderCfg.staggeredMaxAge * 86400),
  742. 'cleanInterval': '' + folderCfg.staggeredCleanInterval,
  743. 'versionsPath': '' + folderCfg.staggeredVersionsPath,
  744. }
  745. };
  746. delete folderCfg.staggeredFileVersioning;
  747. delete folderCfg.staggeredMaxAge;
  748. delete folderCfg.staggeredCleanInterval;
  749. delete folderCfg.staggeredVersionsPath;
  750. } else {
  751. delete folderCfg.Versioning;
  752. }
  753. $scope.folders[folderCfg.ID] = folderCfg;
  754. $scope.config.Folders = folderList($scope.folders);
  755. $scope.saveConfig();
  756. };
  757. $scope.sharesFolder = function (folderCfg) {
  758. var names = [];
  759. folderCfg.Devices.forEach(function (device) {
  760. names.push($scope.deviceName($scope.findDevice(device.DeviceID)));
  761. });
  762. names.sort();
  763. return names.join(", ");
  764. };
  765. $scope.deleteFolder = function () {
  766. $('#editFolder').modal('hide');
  767. if (!$scope.editingExisting) {
  768. return;
  769. }
  770. delete $scope.folders[$scope.currentFolder.ID];
  771. $scope.config.Folders = folderList($scope.folders);
  772. $scope.saveConfig();
  773. };
  774. $scope.editIgnores = function () {
  775. if (!$scope.editingExisting) {
  776. return;
  777. }
  778. $('#editIgnoresButton').attr('disabled', 'disabled');
  779. $http.get(urlbase + '/ignores?folder=' + encodeURIComponent($scope.currentFolder.ID))
  780. .success(function (data) {
  781. data.ignore = data.ignore || [];
  782. $('#editFolder').modal('hide');
  783. var textArea = $('#editIgnores textarea');
  784. textArea.val(data.ignore.join('\n'));
  785. $('#editIgnores').modal()
  786. .on('hidden.bs.modal', function () {
  787. $('#editFolder').modal();
  788. })
  789. .on('shown.bs.modal', function () {
  790. textArea.focus();
  791. });
  792. })
  793. .then(function () {
  794. $('#editIgnoresButton').removeAttr('disabled');
  795. });
  796. };
  797. $scope.saveIgnores = function () {
  798. if (!$scope.editingExisting) {
  799. return;
  800. }
  801. $http.post(urlbase + '/ignores?folder=' + encodeURIComponent($scope.currentFolder.ID), {
  802. ignore: $('#editIgnores textarea').val().split('\n')
  803. });
  804. };
  805. $scope.setAPIKey = function (cfg) {
  806. cfg.APIKey = randomString(30, 32);
  807. };
  808. $scope.showURPreview = function () {
  809. $('#settings').modal('hide');
  810. $('#urPreview').modal().on('hidden.bs.modal', function () {
  811. $('#settings').modal();
  812. });
  813. };
  814. $scope.acceptUR = function () {
  815. $scope.config.Options.URAccepted = 1000; // Larger than the largest existing report version
  816. $scope.saveConfig();
  817. $('#ur').modal('hide');
  818. };
  819. $scope.declineUR = function () {
  820. $scope.config.Options.URAccepted = -1;
  821. $scope.saveConfig();
  822. $('#ur').modal('hide');
  823. };
  824. $scope.showNeed = function (folder) {
  825. $scope.neededLoaded = false;
  826. $('#needed').modal();
  827. $http.get(urlbase + "/need?folder=" + encodeURIComponent(folder)).success(function (data) {
  828. $scope.needed = data;
  829. $scope.neededLoaded = true;
  830. });
  831. };
  832. $scope.needAction = function (file) {
  833. var fDelete = 4096;
  834. var fDirectory = 16384;
  835. if ((file.Flags & (fDelete + fDirectory)) === fDelete + fDirectory) {
  836. return 'rmdir';
  837. } else if ((file.Flags & fDelete) === fDelete) {
  838. return 'rm';
  839. } else if ((file.Flags & fDirectory) === fDirectory) {
  840. return 'touch';
  841. } else {
  842. return 'sync';
  843. }
  844. };
  845. $scope.override = function (folder) {
  846. $http.post(urlbase + "/model/override?folder=" + encodeURIComponent(folder));
  847. };
  848. $scope.about = function () {
  849. $('#about').modal('show');
  850. };
  851. $scope.showReportPreview = function () {
  852. $scope.reportPreview = true;
  853. };
  854. $scope.rescanFolder = function (folder) {
  855. $http.post(urlbase + "/scan?folder=" + encodeURIComponent(folder));
  856. };
  857. $scope.init();
  858. setInterval($scope.refresh, 10000);
  859. });
  860. function deviceCompare(a, b) {
  861. if (typeof a.Name !== 'undefined' && typeof b.Name !== 'undefined') {
  862. if (a.Name < b.Name)
  863. return -1;
  864. return a.Name > b.Name;
  865. }
  866. if (a.DeviceID < b.DeviceID) {
  867. return -1;
  868. }
  869. return a.DeviceID > b.DeviceID;
  870. }
  871. function folderCompare(a, b) {
  872. if (a.ID < b.ID) {
  873. return -1;
  874. }
  875. return a.ID > b.ID;
  876. }
  877. function folderMap(l) {
  878. var m = {};
  879. l.forEach(function (r) {
  880. m[r.ID] = r;
  881. });
  882. return m;
  883. }
  884. function folderList(m) {
  885. var l = [];
  886. for (var id in m) {
  887. l.push(m[id]);
  888. }
  889. l.sort(folderCompare);
  890. return l;
  891. }
  892. function decimals(val, num) {
  893. var digits, decs;
  894. if (val === 0) {
  895. return 0;
  896. }
  897. digits = Math.floor(Math.log(Math.abs(val)) / Math.log(10));
  898. decs = Math.max(0, num - digits);
  899. return decs;
  900. }
  901. function randomString(len, bits) {
  902. bits = bits || 36;
  903. var outStr = "",
  904. newStr;
  905. while (outStr.length < len) {
  906. newStr = Math.random().toString(bits).slice(2);
  907. outStr += newStr.slice(0, Math.min(newStr.length, (len - outStr.length)));
  908. }
  909. return outStr.toLowerCase();
  910. }
  911. function isEmptyObject(obj) {
  912. var name;
  913. for (name in obj) {
  914. return false;
  915. }
  916. return true;
  917. }
  918. function debounce(func, wait) {
  919. var timeout, args, context, timestamp, result, again;
  920. var later = function () {
  921. var last = Date.now() - timestamp;
  922. if (last < wait) {
  923. timeout = setTimeout(later, wait - last);
  924. } else {
  925. timeout = null;
  926. if (again) {
  927. again = false;
  928. result = func.apply(context, args);
  929. context = args = null;
  930. }
  931. }
  932. };
  933. return function () {
  934. context = this;
  935. args = arguments;
  936. timestamp = Date.now();
  937. var callNow = !timeout;
  938. if (!timeout) {
  939. timeout = setTimeout(later, wait);
  940. result = func.apply(context, args);
  941. context = args = null;
  942. } else {
  943. again = true;
  944. }
  945. return result;
  946. };
  947. }
  948. syncthing.filter('natural', function () {
  949. return function (input, valid) {
  950. return input.toFixed(decimals(input, valid));
  951. };
  952. });
  953. syncthing.filter('binary', function () {
  954. return function (input) {
  955. if (input === undefined) {
  956. return '0 ';
  957. }
  958. if (input > 1024 * 1024 * 1024) {
  959. input /= 1024 * 1024 * 1024;
  960. return input.toFixed(decimals(input, 2)) + ' Gi';
  961. }
  962. if (input > 1024 * 1024) {
  963. input /= 1024 * 1024;
  964. return input.toFixed(decimals(input, 2)) + ' Mi';
  965. }
  966. if (input > 1024) {
  967. input /= 1024;
  968. return input.toFixed(decimals(input, 2)) + ' Ki';
  969. }
  970. return Math.round(input) + ' ';
  971. };
  972. });
  973. syncthing.filter('metric', function () {
  974. return function (input) {
  975. if (input === undefined) {
  976. return '0 ';
  977. }
  978. if (input > 1000 * 1000 * 1000) {
  979. input /= 1000 * 1000 * 1000;
  980. return input.toFixed(decimals(input, 2)) + ' G';
  981. }
  982. if (input > 1000 * 1000) {
  983. input /= 1000 * 1000;
  984. return input.toFixed(decimals(input, 2)) + ' M';
  985. }
  986. if (input > 1000) {
  987. input /= 1000;
  988. return input.toFixed(decimals(input, 2)) + ' k';
  989. }
  990. return Math.round(input) + ' ';
  991. };
  992. });
  993. syncthing.filter('alwaysNumber', function () {
  994. return function (input) {
  995. if (input === undefined) {
  996. return 0;
  997. }
  998. return input;
  999. };
  1000. });
  1001. syncthing.filter('basename', function () {
  1002. return function (input) {
  1003. if (input === undefined)
  1004. return "";
  1005. var parts = input.split(/[\/\\]/);
  1006. if (!parts || parts.length < 1) {
  1007. return input;
  1008. }
  1009. return parts[parts.length - 1];
  1010. };
  1011. });
  1012. syncthing.directive('uniqueFolder', function () {
  1013. return {
  1014. require: 'ngModel',
  1015. link: function (scope, elm, attrs, ctrl) {
  1016. ctrl.$parsers.unshift(function (viewValue) {
  1017. if (scope.editingExisting) {
  1018. // we shouldn't validate
  1019. ctrl.$setValidity('uniqueFolder', true);
  1020. } else if (scope.folders[viewValue]) {
  1021. // the folder exists already
  1022. ctrl.$setValidity('uniqueFolder', false);
  1023. } else {
  1024. // the folder is unique
  1025. ctrl.$setValidity('uniqueFolder', true);
  1026. }
  1027. return viewValue;
  1028. });
  1029. }
  1030. };
  1031. });
  1032. syncthing.directive('validDeviceid', function ($http) {
  1033. return {
  1034. require: 'ngModel',
  1035. link: function (scope, elm, attrs, ctrl) {
  1036. ctrl.$parsers.unshift(function (viewValue) {
  1037. if (scope.editingExisting) {
  1038. // we shouldn't validate
  1039. ctrl.$setValidity('validDeviceid', true);
  1040. } else {
  1041. $http.get(urlbase + '/deviceid?id=' + viewValue).success(function (resp) {
  1042. if (resp.error) {
  1043. ctrl.$setValidity('validDeviceid', false);
  1044. } else {
  1045. ctrl.$setValidity('validDeviceid', true);
  1046. }
  1047. });
  1048. }
  1049. return viewValue;
  1050. });
  1051. }
  1052. };
  1053. });
  1054. syncthing.directive('modal', function () {
  1055. return {
  1056. restrict: 'E',
  1057. templateUrl: 'modal.html',
  1058. replace: true,
  1059. transclude: true,
  1060. scope: {
  1061. title: '@',
  1062. status: '@',
  1063. icon: '@',
  1064. close: '@',
  1065. large: '@',
  1066. },
  1067. };
  1068. });