app.js 40 KB

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