app.js 42 KB

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