app.js 39 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300
  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. if (device.DeviceID != $scope.myID) {
  761. names.push($scope.deviceName($scope.findDevice(device.DeviceID)));
  762. }
  763. });
  764. names.sort();
  765. return names.join(", ");
  766. };
  767. $scope.deleteFolder = function () {
  768. $('#editFolder').modal('hide');
  769. if (!$scope.editingExisting) {
  770. return;
  771. }
  772. delete $scope.folders[$scope.currentFolder.ID];
  773. $scope.config.Folders = folderList($scope.folders);
  774. $scope.saveConfig();
  775. };
  776. $scope.editIgnores = function () {
  777. if (!$scope.editingExisting) {
  778. return;
  779. }
  780. $('#editIgnoresButton').attr('disabled', 'disabled');
  781. $http.get(urlbase + '/ignores?folder=' + encodeURIComponent($scope.currentFolder.ID))
  782. .success(function (data) {
  783. data.ignore = data.ignore || [];
  784. $('#editFolder').modal('hide');
  785. var textArea = $('#editIgnores textarea');
  786. textArea.val(data.ignore.join('\n'));
  787. $('#editIgnores').modal()
  788. .on('hidden.bs.modal', function () {
  789. $('#editFolder').modal();
  790. })
  791. .on('shown.bs.modal', function () {
  792. textArea.focus();
  793. });
  794. })
  795. .then(function () {
  796. $('#editIgnoresButton').removeAttr('disabled');
  797. });
  798. };
  799. $scope.saveIgnores = function () {
  800. if (!$scope.editingExisting) {
  801. return;
  802. }
  803. $http.post(urlbase + '/ignores?folder=' + encodeURIComponent($scope.currentFolder.ID), {
  804. ignore: $('#editIgnores textarea').val().split('\n')
  805. });
  806. };
  807. $scope.setAPIKey = function (cfg) {
  808. cfg.APIKey = randomString(30, 32);
  809. };
  810. $scope.showURPreview = function () {
  811. $('#settings').modal('hide');
  812. $('#urPreview').modal().on('hidden.bs.modal', function () {
  813. $('#settings').modal();
  814. });
  815. };
  816. $scope.acceptUR = function () {
  817. $scope.config.Options.URAccepted = 1000; // Larger than the largest existing report version
  818. $scope.saveConfig();
  819. $('#ur').modal('hide');
  820. };
  821. $scope.declineUR = function () {
  822. $scope.config.Options.URAccepted = -1;
  823. $scope.saveConfig();
  824. $('#ur').modal('hide');
  825. };
  826. $scope.showNeed = function (folder) {
  827. $scope.neededLoaded = false;
  828. $('#needed').modal();
  829. $http.get(urlbase + "/need?folder=" + encodeURIComponent(folder)).success(function (data) {
  830. $scope.needed = data;
  831. $scope.neededLoaded = true;
  832. });
  833. };
  834. $scope.needAction = function (file) {
  835. var fDelete = 4096;
  836. var fDirectory = 16384;
  837. if ((file.Flags & (fDelete + fDirectory)) === fDelete + fDirectory) {
  838. return 'rmdir';
  839. } else if ((file.Flags & fDelete) === fDelete) {
  840. return 'rm';
  841. } else if ((file.Flags & fDirectory) === fDirectory) {
  842. return 'touch';
  843. } else {
  844. return 'sync';
  845. }
  846. };
  847. $scope.override = function (folder) {
  848. $http.post(urlbase + "/model/override?folder=" + encodeURIComponent(folder));
  849. };
  850. $scope.about = function () {
  851. $('#about').modal('show');
  852. };
  853. $scope.showReportPreview = function () {
  854. $scope.reportPreview = true;
  855. };
  856. $scope.rescanFolder = function (folder) {
  857. $http.post(urlbase + "/scan?folder=" + encodeURIComponent(folder));
  858. };
  859. $scope.init();
  860. setInterval($scope.refresh, 10000);
  861. });
  862. function deviceCompare(a, b) {
  863. if (typeof a.Name !== 'undefined' && typeof b.Name !== 'undefined') {
  864. if (a.Name < b.Name)
  865. return -1;
  866. return a.Name > b.Name;
  867. }
  868. if (a.DeviceID < b.DeviceID) {
  869. return -1;
  870. }
  871. return a.DeviceID > b.DeviceID;
  872. }
  873. function folderCompare(a, b) {
  874. if (a.ID < b.ID) {
  875. return -1;
  876. }
  877. return a.ID > b.ID;
  878. }
  879. function folderMap(l) {
  880. var m = {};
  881. l.forEach(function (r) {
  882. m[r.ID] = r;
  883. });
  884. return m;
  885. }
  886. function folderList(m) {
  887. var l = [];
  888. for (var id in m) {
  889. l.push(m[id]);
  890. }
  891. l.sort(folderCompare);
  892. return l;
  893. }
  894. function decimals(val, num) {
  895. var digits, decs;
  896. if (val === 0) {
  897. return 0;
  898. }
  899. digits = Math.floor(Math.log(Math.abs(val)) / Math.log(10));
  900. decs = Math.max(0, num - digits);
  901. return decs;
  902. }
  903. function randomString(len, bits) {
  904. bits = bits || 36;
  905. var outStr = "",
  906. newStr;
  907. while (outStr.length < len) {
  908. newStr = Math.random().toString(bits).slice(2);
  909. outStr += newStr.slice(0, Math.min(newStr.length, (len - outStr.length)));
  910. }
  911. return outStr.toLowerCase();
  912. }
  913. function isEmptyObject(obj) {
  914. var name;
  915. for (name in obj) {
  916. return false;
  917. }
  918. return true;
  919. }
  920. function debounce(func, wait) {
  921. var timeout, args, context, timestamp, result, again;
  922. var later = function () {
  923. var last = Date.now() - timestamp;
  924. if (last < wait) {
  925. timeout = setTimeout(later, wait - last);
  926. } else {
  927. timeout = null;
  928. if (again) {
  929. again = false;
  930. result = func.apply(context, args);
  931. context = args = null;
  932. }
  933. }
  934. };
  935. return function () {
  936. context = this;
  937. args = arguments;
  938. timestamp = Date.now();
  939. var callNow = !timeout;
  940. if (!timeout) {
  941. timeout = setTimeout(later, wait);
  942. result = func.apply(context, args);
  943. context = args = null;
  944. } else {
  945. again = true;
  946. }
  947. return result;
  948. };
  949. }
  950. syncthing.filter('natural', function () {
  951. return function (input, valid) {
  952. return input.toFixed(decimals(input, valid));
  953. };
  954. });
  955. syncthing.filter('binary', function () {
  956. return function (input) {
  957. if (input === undefined) {
  958. return '0 ';
  959. }
  960. if (input > 1024 * 1024 * 1024) {
  961. input /= 1024 * 1024 * 1024;
  962. return input.toFixed(decimals(input, 2)) + ' Gi';
  963. }
  964. if (input > 1024 * 1024) {
  965. input /= 1024 * 1024;
  966. return input.toFixed(decimals(input, 2)) + ' Mi';
  967. }
  968. if (input > 1024) {
  969. input /= 1024;
  970. return input.toFixed(decimals(input, 2)) + ' Ki';
  971. }
  972. return Math.round(input) + ' ';
  973. };
  974. });
  975. syncthing.filter('metric', function () {
  976. return function (input) {
  977. if (input === undefined) {
  978. return '0 ';
  979. }
  980. if (input > 1000 * 1000 * 1000) {
  981. input /= 1000 * 1000 * 1000;
  982. return input.toFixed(decimals(input, 2)) + ' G';
  983. }
  984. if (input > 1000 * 1000) {
  985. input /= 1000 * 1000;
  986. return input.toFixed(decimals(input, 2)) + ' M';
  987. }
  988. if (input > 1000) {
  989. input /= 1000;
  990. return input.toFixed(decimals(input, 2)) + ' k';
  991. }
  992. return Math.round(input) + ' ';
  993. };
  994. });
  995. syncthing.filter('alwaysNumber', function () {
  996. return function (input) {
  997. if (input === undefined) {
  998. return 0;
  999. }
  1000. return input;
  1001. };
  1002. });
  1003. syncthing.filter('basename', function () {
  1004. return function (input) {
  1005. if (input === undefined)
  1006. return "";
  1007. var parts = input.split(/[\/\\]/);
  1008. if (!parts || parts.length < 1) {
  1009. return input;
  1010. }
  1011. return parts[parts.length - 1];
  1012. };
  1013. });
  1014. syncthing.directive('uniqueFolder', function () {
  1015. return {
  1016. require: 'ngModel',
  1017. link: function (scope, elm, attrs, ctrl) {
  1018. ctrl.$parsers.unshift(function (viewValue) {
  1019. if (scope.editingExisting) {
  1020. // we shouldn't validate
  1021. ctrl.$setValidity('uniqueFolder', true);
  1022. } else if (scope.folders[viewValue]) {
  1023. // the folder exists already
  1024. ctrl.$setValidity('uniqueFolder', false);
  1025. } else {
  1026. // the folder is unique
  1027. ctrl.$setValidity('uniqueFolder', true);
  1028. }
  1029. return viewValue;
  1030. });
  1031. }
  1032. };
  1033. });
  1034. syncthing.directive('validDeviceid', function ($http) {
  1035. return {
  1036. require: 'ngModel',
  1037. link: function (scope, elm, attrs, ctrl) {
  1038. ctrl.$parsers.unshift(function (viewValue) {
  1039. if (scope.editingExisting) {
  1040. // we shouldn't validate
  1041. ctrl.$setValidity('validDeviceid', true);
  1042. } else {
  1043. $http.get(urlbase + '/deviceid?id=' + viewValue).success(function (resp) {
  1044. if (resp.error) {
  1045. ctrl.$setValidity('validDeviceid', false);
  1046. } else {
  1047. ctrl.$setValidity('validDeviceid', true);
  1048. }
  1049. });
  1050. }
  1051. return viewValue;
  1052. });
  1053. }
  1054. };
  1055. });
  1056. syncthing.directive('modal', function () {
  1057. return {
  1058. restrict: 'E',
  1059. templateUrl: 'modal.html',
  1060. replace: true,
  1061. transclude: true,
  1062. scope: {
  1063. title: '@',
  1064. status: '@',
  1065. icon: '@',
  1066. close: '@',
  1067. large: '@',
  1068. },
  1069. };
  1070. });
  1071. syncthing.directive('identicon', ['$window', function ($window) {
  1072. var svgNS = 'http://www.w3.org/2000/svg';
  1073. function Identicon (value, size) {
  1074. var svg = document.createElementNS(svgNS, 'svg');
  1075. var shouldFillRectAt = function (row, col) {
  1076. return !($window.parseInt(value.charCodeAt(row + col * size), 10) % 2);
  1077. };
  1078. var shouldMirrorRectAt = function (row, col) {
  1079. return !(size % 2 && col === middleCol)
  1080. };
  1081. var mirrorColFor = function (col) {
  1082. return size - col - 1;
  1083. };
  1084. var fillRectAt = function (row, col) {
  1085. var rect = document.createElementNS(svgNS, 'rect');
  1086. rect.setAttribute('x', (col * rectSize) + '%');
  1087. rect.setAttribute('y', (row * rectSize) + '%');
  1088. rect.setAttribute('width', rectSize + '%');
  1089. rect.setAttribute('height', rectSize + '%');
  1090. svg.appendChild(rect);
  1091. };
  1092. var rect;
  1093. var row;
  1094. var col;
  1095. var middleCol;
  1096. var rectSize;
  1097. svg.setAttribute('class', 'identicon');
  1098. size = size || 5;
  1099. rectSize = 100 / size;
  1100. middleCol = Math.ceil(size / 2) - 1;
  1101. if (value) {
  1102. value = value.toString().replace(/[\W_]/i, '');
  1103. for (row = 0; row < size; ++row) {
  1104. for (col = middleCol; col > -1; --col) {
  1105. if (shouldFillRectAt(row, col)) {
  1106. fillRectAt(row, col);
  1107. if (shouldMirrorRectAt(row, col)) {
  1108. fillRectAt(row, mirrorColFor(col));
  1109. }
  1110. }
  1111. }
  1112. }
  1113. }
  1114. return svg;
  1115. }
  1116. return {
  1117. restrict: 'E',
  1118. scope: {
  1119. value: '='
  1120. },
  1121. link: function (scope, element, attributes) {
  1122. element.append(new Identicon(scope.value));
  1123. }
  1124. }
  1125. }]);