app.js 42 KB

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