fn.js 43 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192
  1. /**
  2. * This file is part of Radicale Server - Calendar Server
  3. * Copyright © 2017-2024 Unrud <unrud@outlook.com>
  4. *
  5. * This program is free software: you can redistribute it and/or modify
  6. * it under the terms of the GNU General Public License as published by
  7. * the Free Software Foundation, either version 3 of the License, or
  8. * (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU General Public License
  16. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  17. */
  18. /**
  19. * Server address
  20. * @const
  21. * @type {string}
  22. */
  23. const SERVER = location.origin;
  24. /**
  25. * Path of the root collection on the server (must end with /)
  26. * @const
  27. * @type {string}
  28. */
  29. const ROOT_PATH = location.pathname.replace(new RegExp("/+[^/]+/*(/index\\.html?)?$"), "") + '/';
  30. /**
  31. * Regex to match and normalize color
  32. * @const
  33. */
  34. const COLOR_RE = new RegExp("^(#[0-9A-Fa-f]{6})(?:[0-9A-Fa-f]{2})?$");
  35. /**
  36. * Escape string for usage in XML
  37. * @param {string} s
  38. * @return {string}
  39. */
  40. function escape_xml(s) {
  41. return (s
  42. .replace(/&/g, "&amp;")
  43. .replace(/"/g, "&quot;")
  44. .replace(/'/g, "&apos;")
  45. .replace(/</g, "&lt;")
  46. .replace(/>/g, "&gt;"));
  47. }
  48. /**
  49. * @enum {string}
  50. */
  51. const CollectionType = {
  52. PRINCIPAL: "PRINCIPAL",
  53. ADDRESSBOOK: "ADDRESSBOOK",
  54. CALENDAR_JOURNAL_TASKS: "CALENDAR_JOURNAL_TASKS",
  55. CALENDAR_JOURNAL: "CALENDAR_JOURNAL",
  56. CALENDAR_TASKS: "CALENDAR_TASKS",
  57. JOURNAL_TASKS: "JOURNAL_TASKS",
  58. CALENDAR: "CALENDAR",
  59. JOURNAL: "JOURNAL",
  60. TASKS: "TASKS",
  61. WEBCAL: "WEBCAL",
  62. is_subset: function(a, b) {
  63. let components = a.split("_");
  64. for (let i = 0; i < components.length; i++) {
  65. if (b.search(components[i]) === -1) {
  66. return false;
  67. }
  68. }
  69. return true;
  70. },
  71. union: function(a, b) {
  72. if (a.search(this.ADDRESSBOOK) !== -1 || b.search(this.ADDRESSBOOK) !== -1) {
  73. if (a && a !== this.ADDRESSBOOK || b && b !== this.ADDRESSBOOK) {
  74. throw "Invalid union: " + a + " " + b;
  75. }
  76. return this.ADDRESSBOOK;
  77. }
  78. let union = [];
  79. if (a.search(this.CALENDAR) !== -1 || b.search(this.CALENDAR) !== -1) {
  80. union.push(this.CALENDAR);
  81. }
  82. if (a.search(this.JOURNAL) !== -1 || b.search(this.JOURNAL) !== -1) {
  83. union.push(this.JOURNAL);
  84. }
  85. if (a.search(this.TASKS) !== -1 || b.search(this.TASKS) !== -1) {
  86. union.push(this.TASKS);
  87. }
  88. if (a.search(this.WEBCAL) !== -1 || b.search(this.WEBCAL) !== -1) {
  89. union.push(this.WEBCAL);
  90. }
  91. return union.join("_");
  92. }
  93. };
  94. /**
  95. * @constructor
  96. * @struct
  97. * @param {string} href Must always start and end with /.
  98. * @param {CollectionType} type
  99. * @param {string} displayname
  100. * @param {string} description
  101. * @param {string} color
  102. */
  103. function Collection(href, type, displayname, description, color, source) {
  104. this.href = href;
  105. this.type = type;
  106. this.displayname = displayname;
  107. this.color = color;
  108. this.description = description;
  109. this.source = source;
  110. }
  111. /**
  112. * Find the principal collection.
  113. * @param {string} user
  114. * @param {string} password
  115. * @param {function(?Collection, ?string)} callback Returns result or error
  116. * @return {XMLHttpRequest}
  117. */
  118. function get_principal(user, password, callback) {
  119. let request = new XMLHttpRequest();
  120. request.open("PROPFIND", SERVER + ROOT_PATH, true, user, encodeURIComponent(password));
  121. request.onreadystatechange = function() {
  122. if (request.readyState !== 4) {
  123. return;
  124. }
  125. if (request.status === 207) {
  126. let xml = request.responseXML;
  127. let principal_element = xml.querySelector("*|multistatus:root > *|response:first-of-type > *|propstat > *|prop > *|current-user-principal > *|href");
  128. let displayname_element = xml.querySelector("*|multistatus:root > *|response:first-of-type > *|propstat > *|prop > *|displayname");
  129. if (principal_element) {
  130. callback(new Collection(
  131. principal_element.textContent,
  132. CollectionType.PRINCIPAL,
  133. displayname_element ? displayname_element.textContent : "",
  134. "",
  135. ""), null);
  136. } else {
  137. callback(null, "Internal error");
  138. }
  139. } else {
  140. callback(null, request.status + " " + request.statusText);
  141. }
  142. };
  143. request.send('<?xml version="1.0" encoding="utf-8" ?>' +
  144. '<propfind xmlns="DAV:">' +
  145. '<prop>' +
  146. '<current-user-principal />' +
  147. '<displayname />' +
  148. '</prop>' +
  149. '</propfind>');
  150. return request;
  151. }
  152. /**
  153. * Find all calendars and addressbooks in collection.
  154. * @param {string} user
  155. * @param {string} password
  156. * @param {Collection} collection
  157. * @param {function(?Array<Collection>, ?string)} callback Returns result or error
  158. * @return {XMLHttpRequest}
  159. */
  160. function get_collections(user, password, collection, callback) {
  161. let request = new XMLHttpRequest();
  162. request.open("PROPFIND", SERVER + collection.href, true, user, encodeURIComponent(password));
  163. request.setRequestHeader("depth", "1");
  164. request.onreadystatechange = function() {
  165. if (request.readyState !== 4) {
  166. return;
  167. }
  168. if (request.status === 207) {
  169. let xml = request.responseXML;
  170. let collections = [];
  171. let response_query = "*|multistatus:root > *|response";
  172. let responses = xml.querySelectorAll(response_query);
  173. for (let i = 0; i < responses.length; i++) {
  174. let response = responses[i];
  175. let href_element = response.querySelector(response_query + " > *|href");
  176. let resourcetype_query = response_query + " > *|propstat > *|prop > *|resourcetype";
  177. let resourcetype_element = response.querySelector(resourcetype_query);
  178. let displayname_element = response.querySelector(response_query + " > *|propstat > *|prop > *|displayname");
  179. let calendarcolor_element = response.querySelector(response_query + " > *|propstat > *|prop > *|calendar-color");
  180. let addressbookcolor_element = response.querySelector(response_query + " > *|propstat > *|prop > *|addressbook-color");
  181. let calendardesc_element = response.querySelector(response_query + " > *|propstat > *|prop > *|calendar-description");
  182. let addressbookdesc_element = response.querySelector(response_query + " > *|propstat > *|prop > *|addressbook-description");
  183. let webcalsource_element = response.querySelector(response_query + " > *|propstat > *|prop > *|source");
  184. let components_query = response_query + " > *|propstat > *|prop > *|supported-calendar-component-set";
  185. let components_element = response.querySelector(components_query);
  186. let href = href_element ? href_element.textContent : "";
  187. let displayname = displayname_element ? displayname_element.textContent : "";
  188. let type = "";
  189. let color = "";
  190. let description = "";
  191. let source = "";
  192. if (resourcetype_element) {
  193. if (resourcetype_element.querySelector(resourcetype_query + " > *|addressbook")) {
  194. type = CollectionType.ADDRESSBOOK;
  195. color = addressbookcolor_element ? addressbookcolor_element.textContent : "";
  196. description = addressbookdesc_element ? addressbookdesc_element.textContent : "";
  197. } else if (resourcetype_element.querySelector(resourcetype_query + " > *|subscribed")) {
  198. type = CollectionType.WEBCAL;
  199. source = webcalsource_element ? webcalsource_element.textContent : "";
  200. color = calendarcolor_element ? calendarcolor_element.textContent : "";
  201. description = calendardesc_element ? calendardesc_element.textContent : "";
  202. } else if (resourcetype_element.querySelector(resourcetype_query + " > *|calendar")) {
  203. if (components_element) {
  204. if (components_element.querySelector(components_query + " > *|comp[name=VEVENT]")) {
  205. type = CollectionType.union(type, CollectionType.CALENDAR);
  206. }
  207. if (components_element.querySelector(components_query + " > *|comp[name=VJOURNAL]")) {
  208. type = CollectionType.union(type, CollectionType.JOURNAL);
  209. }
  210. if (components_element.querySelector(components_query + " > *|comp[name=VTODO]")) {
  211. type = CollectionType.union(type, CollectionType.TASKS);
  212. }
  213. }
  214. color = calendarcolor_element ? calendarcolor_element.textContent : "";
  215. description = calendardesc_element ? calendardesc_element.textContent : "";
  216. }
  217. }
  218. let sane_color = color.trim();
  219. if (sane_color) {
  220. let color_match = COLOR_RE.exec(sane_color);
  221. if (color_match) {
  222. sane_color = color_match[1];
  223. } else {
  224. sane_color = "";
  225. }
  226. }
  227. if (href.substr(-1) === "/" && href !== collection.href && type) {
  228. collections.push(new Collection(href, type, displayname, description, sane_color, source));
  229. }
  230. }
  231. collections.sort(function(a, b) {
  232. /** @type {string} */ let ca = a.displayname || a.href;
  233. /** @type {string} */ let cb = b.displayname || b.href;
  234. return ca.localeCompare(cb);
  235. });
  236. callback(collections, null);
  237. } else {
  238. callback(null, request.status + " " + request.statusText);
  239. }
  240. };
  241. request.send('<?xml version="1.0" encoding="utf-8" ?>' +
  242. '<propfind ' +
  243. 'xmlns="DAV:" ' +
  244. 'xmlns:C="urn:ietf:params:xml:ns:caldav" ' +
  245. 'xmlns:CR="urn:ietf:params:xml:ns:carddav" ' +
  246. 'xmlns:CS="http://calendarserver.org/ns/" ' +
  247. 'xmlns:I="http://apple.com/ns/ical/" ' +
  248. 'xmlns:INF="http://inf-it.com/ns/ab/" ' +
  249. 'xmlns:RADICALE="http://radicale.org/ns/"' +
  250. '>' +
  251. '<prop>' +
  252. '<resourcetype />' +
  253. '<RADICALE:displayname />' +
  254. '<I:calendar-color />' +
  255. '<INF:addressbook-color />' +
  256. '<C:calendar-description />' +
  257. '<C:supported-calendar-component-set />' +
  258. '<CR:addressbook-description />' +
  259. '<CS:source />' +
  260. '</prop>' +
  261. '</propfind>');
  262. return request;
  263. }
  264. /**
  265. * @param {string} user
  266. * @param {string} password
  267. * @param {string} collection_href Must always start and end with /.
  268. * @param {File} file
  269. * @param {function(?string)} callback Returns error or null
  270. * @return {XMLHttpRequest}
  271. */
  272. function upload_collection(user, password, collection_href, file, callback) {
  273. let request = new XMLHttpRequest();
  274. request.open("PUT", SERVER + collection_href, true, user, encodeURIComponent(password));
  275. request.onreadystatechange = function() {
  276. if (request.readyState !== 4) {
  277. return;
  278. }
  279. if (200 <= request.status && request.status < 300) {
  280. callback(null);
  281. } else {
  282. callback(request.status + " " + request.statusText);
  283. }
  284. };
  285. request.setRequestHeader("If-None-Match", "*");
  286. request.send(file);
  287. return request;
  288. }
  289. /**
  290. * @param {string} user
  291. * @param {string} password
  292. * @param {Collection} collection
  293. * @param {function(?string)} callback Returns error or null
  294. * @return {XMLHttpRequest}
  295. */
  296. function delete_collection(user, password, collection, callback) {
  297. let request = new XMLHttpRequest();
  298. request.open("DELETE", SERVER + collection.href, true, user, encodeURIComponent(password));
  299. request.onreadystatechange = function() {
  300. if (request.readyState !== 4) {
  301. return;
  302. }
  303. if (200 <= request.status && request.status < 300) {
  304. callback(null);
  305. } else {
  306. callback(request.status + " " + request.statusText);
  307. }
  308. };
  309. request.send();
  310. return request;
  311. }
  312. /**
  313. * @param {string} user
  314. * @param {string} password
  315. * @param {Collection} collection
  316. * @param {boolean} create
  317. * @param {function(?string)} callback Returns error or null
  318. * @return {XMLHttpRequest}
  319. */
  320. function create_edit_collection(user, password, collection, create, callback) {
  321. let request = new XMLHttpRequest();
  322. request.open(create ? "MKCOL" : "PROPPATCH", SERVER + collection.href, true, user, encodeURIComponent(password));
  323. request.onreadystatechange = function() {
  324. if (request.readyState !== 4) {
  325. return;
  326. }
  327. if (200 <= request.status && request.status < 300) {
  328. callback(null);
  329. } else {
  330. callback(request.status + " " + request.statusText);
  331. }
  332. };
  333. let displayname = escape_xml(collection.displayname);
  334. let calendar_color = "";
  335. let addressbook_color = "";
  336. let calendar_description = "";
  337. let addressbook_description = "";
  338. let calendar_source = "";
  339. let resourcetype;
  340. let components = "";
  341. if (collection.type === CollectionType.ADDRESSBOOK) {
  342. addressbook_color = escape_xml(collection.color + (collection.color ? "ff" : ""));
  343. addressbook_description = escape_xml(collection.description);
  344. resourcetype = '<CR:addressbook />';
  345. } else if (collection.type === CollectionType.WEBCAL) {
  346. calendar_color = escape_xml(collection.color + (collection.color ? "ff" : ""));
  347. calendar_description = escape_xml(collection.description);
  348. resourcetype = '<CS:subscribed />';
  349. calendar_source = collection.source;
  350. } else {
  351. calendar_color = escape_xml(collection.color + (collection.color ? "ff" : ""));
  352. calendar_description = escape_xml(collection.description);
  353. resourcetype = '<C:calendar />';
  354. if (CollectionType.is_subset(CollectionType.CALENDAR, collection.type)) {
  355. components += '<C:comp name="VEVENT" />';
  356. }
  357. if (CollectionType.is_subset(CollectionType.JOURNAL, collection.type)) {
  358. components += '<C:comp name="VJOURNAL" />';
  359. }
  360. if (CollectionType.is_subset(CollectionType.TASKS, collection.type)) {
  361. components += '<C:comp name="VTODO" />';
  362. }
  363. }
  364. let xml_request = create ? "mkcol" : "propertyupdate";
  365. request.send('<?xml version="1.0" encoding="UTF-8" ?>' +
  366. '<' + xml_request + ' xmlns="DAV:" xmlns:C="urn:ietf:params:xml:ns:caldav" xmlns:CR="urn:ietf:params:xml:ns:carddav" xmlns:CS="http://calendarserver.org/ns/" xmlns:I="http://apple.com/ns/ical/" xmlns:INF="http://inf-it.com/ns/ab/">' +
  367. '<set>' +
  368. '<prop>' +
  369. (create ? '<resourcetype><collection />' + resourcetype + '</resourcetype>' : '') +
  370. (components ? '<C:supported-calendar-component-set>' + components + '</C:supported-calendar-component-set>' : '') +
  371. (displayname ? '<displayname>' + displayname + '</displayname>' : '') +
  372. (calendar_color ? '<I:calendar-color>' + calendar_color + '</I:calendar-color>' : '') +
  373. (addressbook_color ? '<INF:addressbook-color>' + addressbook_color + '</INF:addressbook-color>' : '') +
  374. (addressbook_description ? '<CR:addressbook-description>' + addressbook_description + '</CR:addressbook-description>' : '') +
  375. (calendar_description ? '<C:calendar-description>' + calendar_description + '</C:calendar-description>' : '') +
  376. (calendar_source ? '<CS:source>' + calendar_source + '</CS:source>' : '') +
  377. '</prop>' +
  378. '</set>' +
  379. (!create ? ('<remove>' +
  380. '<prop>' +
  381. (!components ? '<C:supported-calendar-component-set />' : '') +
  382. (!displayname ? '<displayname />' : '') +
  383. (!calendar_color ? '<I:calendar-color />' : '') +
  384. (!addressbook_color ? '<INF:addressbook-color />' : '') +
  385. (!addressbook_description ? '<CR:addressbook-description />' : '') +
  386. (!calendar_description ? '<C:calendar-description />' : '') +
  387. '</prop>' +
  388. '</remove>'): '') +
  389. '</' + xml_request + '>');
  390. return request;
  391. }
  392. /**
  393. * @param {string} user
  394. * @param {string} password
  395. * @param {Collection} collection
  396. * @param {function(?string)} callback Returns error or null
  397. * @return {XMLHttpRequest}
  398. */
  399. function create_collection(user, password, collection, callback) {
  400. return create_edit_collection(user, password, collection, true, callback);
  401. }
  402. /**
  403. * @param {string} user
  404. * @param {string} password
  405. * @param {Collection} collection
  406. * @param {function(?string)} callback Returns error or null
  407. * @return {XMLHttpRequest}
  408. */
  409. function edit_collection(user, password, collection, callback) {
  410. return create_edit_collection(user, password, collection, false, callback);
  411. }
  412. /**
  413. * @return {string}
  414. */
  415. function random_uuid() {
  416. return random_hex(8) + "-" + random_hex(4) + "-" + random_hex(4) + "-" + random_hex(4) + "-" + random_hex(12);
  417. }
  418. /**
  419. * @interface
  420. */
  421. function Scene() {}
  422. /**
  423. * Scene is on top of stack and visible.
  424. */
  425. Scene.prototype.show = function() {};
  426. /**
  427. * Scene is no longer visible.
  428. */
  429. Scene.prototype.hide = function() {};
  430. /**
  431. * Scene is removed from scene stack.
  432. */
  433. Scene.prototype.release = function() {};
  434. /**
  435. * @type {Array<Scene>}
  436. */
  437. let scene_stack = [];
  438. /**
  439. * Push scene onto stack.
  440. * @param {Scene} scene
  441. * @param {boolean} replace Replace the scene on top of the stack.
  442. */
  443. function push_scene(scene, replace) {
  444. if (scene_stack.length >= 1) {
  445. scene_stack[scene_stack.length - 1].hide();
  446. if (replace) {
  447. scene_stack.pop().release();
  448. }
  449. }
  450. scene_stack.push(scene);
  451. scene.show();
  452. }
  453. /**
  454. * Remove scenes from stack.
  455. * @param {number} index New top of stack
  456. */
  457. function pop_scene(index) {
  458. if (scene_stack.length - 1 <= index) {
  459. return;
  460. }
  461. scene_stack[scene_stack.length - 1].hide();
  462. while (scene_stack.length - 1 > index) {
  463. let old_length = scene_stack.length;
  464. scene_stack.pop().release();
  465. if (old_length - 1 === index + 1) {
  466. break;
  467. }
  468. }
  469. if (scene_stack.length >= 1) {
  470. let scene = scene_stack[scene_stack.length - 1];
  471. scene.show();
  472. } else {
  473. throw "Scene stack is empty";
  474. }
  475. }
  476. /**
  477. * @constructor
  478. * @implements {Scene}
  479. */
  480. function LoginScene() {
  481. let html_scene = document.getElementById("loginscene");
  482. let form = html_scene.querySelector("[data-name=form]");
  483. let user_form = html_scene.querySelector("[data-name=user]");
  484. let password_form = html_scene.querySelector("[data-name=password]");
  485. let error_form = html_scene.querySelector("[data-name=error]");
  486. let logout_view = document.getElementById("logoutview");
  487. let logout_user_form = logout_view.querySelector("[data-name=user]");
  488. let logout_btn = logout_view.querySelector("[data-name=link]");
  489. /** @type {?number} */ let scene_index = null;
  490. let user = "";
  491. let error = "";
  492. /** @type {?XMLHttpRequest} */ let principal_req = null;
  493. function read_form() {
  494. user = user_form.value;
  495. }
  496. function fill_form() {
  497. user_form.value = user;
  498. password_form.value = "";
  499. if(error){
  500. error_form.textContent = "Error: " + error;
  501. error_form.classList.remove("hidden");
  502. }else{
  503. error_form.classList.add("hidden");
  504. }
  505. }
  506. function onlogin() {
  507. try {
  508. read_form();
  509. let password = password_form.value;
  510. if (user) {
  511. error = "";
  512. // setup logout
  513. logout_view.classList.remove("hidden");
  514. logout_btn.onclick = onlogout;
  515. logout_user_form.textContent = user + "'s Collections";
  516. // Fetch principal
  517. let loading_scene = new LoadingScene();
  518. push_scene(loading_scene, false);
  519. principal_req = get_principal(user, password, function(collection, error1) {
  520. if (scene_index === null) {
  521. return;
  522. }
  523. principal_req = null;
  524. if (error1) {
  525. error = error1;
  526. pop_scene(scene_index);
  527. } else {
  528. // show collections
  529. let saved_user = user;
  530. user = "";
  531. let collections_scene = new CollectionsScene(
  532. saved_user, password, collection, function(error1) {
  533. error = error1;
  534. user = saved_user;
  535. });
  536. push_scene(collections_scene, true);
  537. }
  538. });
  539. } else {
  540. error = "Username is empty";
  541. fill_form();
  542. }
  543. } catch(err) {
  544. console.error(err);
  545. }
  546. return false;
  547. }
  548. function onlogout() {
  549. try {
  550. if (scene_index === null) {
  551. return false;
  552. }
  553. user = "";
  554. pop_scene(scene_index);
  555. } catch (err) {
  556. console.error(err);
  557. }
  558. return false;
  559. }
  560. function remove_logout() {
  561. logout_view.classList.add("hidden");
  562. logout_btn.onclick = null;
  563. logout_user_form.textContent = "";
  564. }
  565. this.show = function() {
  566. remove_logout();
  567. fill_form();
  568. form.onsubmit = onlogin;
  569. html_scene.classList.remove("hidden");
  570. scene_index = scene_stack.length - 1;
  571. user_form.focus();
  572. };
  573. this.hide = function() {
  574. read_form();
  575. html_scene.classList.add("hidden");
  576. form.onsubmit = null;
  577. };
  578. this.release = function() {
  579. scene_index = null;
  580. // cancel pending requests
  581. if (principal_req !== null) {
  582. principal_req.abort();
  583. principal_req = null;
  584. }
  585. remove_logout();
  586. };
  587. }
  588. /**
  589. * @constructor
  590. * @implements {Scene}
  591. */
  592. function LoadingScene() {
  593. let html_scene = document.getElementById("loadingscene");
  594. this.show = function() {
  595. html_scene.classList.remove("hidden");
  596. };
  597. this.hide = function() {
  598. html_scene.classList.add("hidden");
  599. };
  600. this.release = function() {};
  601. }
  602. /**
  603. * @constructor
  604. * @implements {Scene}
  605. * @param {string} user
  606. * @param {string} password
  607. * @param {Collection} collection The principal collection.
  608. * @param {function(string)} onerror Called when an error occurs, before the
  609. * scene is popped.
  610. */
  611. function CollectionsScene(user, password, collection, onerror) {
  612. let html_scene = document.getElementById("collectionsscene");
  613. let template = html_scene.querySelector("[data-name=collectiontemplate]");
  614. let new_btn = html_scene.querySelector("[data-name=new]");
  615. let upload_btn = html_scene.querySelector("[data-name=upload]");
  616. /** @type {?number} */ let scene_index = null;
  617. /** @type {?XMLHttpRequest} */ let collections_req = null;
  618. /** @type {?Array<Collection>} */ let collections = null;
  619. /** @type {Array<Node>} */ let nodes = [];
  620. let filesInput = document.createElement("input");
  621. filesInput.setAttribute("type", "file");
  622. filesInput.setAttribute("accept", ".ics, .vcf");
  623. filesInput.setAttribute("multiple", "");
  624. let filesInputForm = document.createElement("form");
  625. filesInputForm.appendChild(filesInput);
  626. function onnew() {
  627. try {
  628. let create_collection_scene = new CreateEditCollectionScene(user, password, collection);
  629. push_scene(create_collection_scene, false);
  630. } catch(err) {
  631. console.error(err);
  632. }
  633. return false;
  634. }
  635. function onupload() {
  636. filesInput.click();
  637. return false;
  638. }
  639. function onfileschange() {
  640. try {
  641. let files = filesInput.files;
  642. if (files.length > 0) {
  643. let upload_scene = new UploadCollectionScene(user, password, collection, files);
  644. push_scene(upload_scene);
  645. }
  646. } catch(err) {
  647. console.error(err);
  648. }
  649. return false;
  650. }
  651. function onedit(collection) {
  652. try {
  653. let edit_collection_scene = new CreateEditCollectionScene(user, password, collection);
  654. push_scene(edit_collection_scene, false);
  655. } catch(err) {
  656. console.error(err);
  657. }
  658. return false;
  659. }
  660. function ondelete(collection) {
  661. try {
  662. let delete_collection_scene = new DeleteCollectionScene(user, password, collection);
  663. push_scene(delete_collection_scene, false);
  664. } catch(err) {
  665. console.error(err);
  666. }
  667. return false;
  668. }
  669. function show_collections(collections) {
  670. collections.forEach(function (collection) {
  671. let node = template.cloneNode(true);
  672. node.classList.remove("hidden");
  673. let title_form = node.querySelector("[data-name=title]");
  674. let description_form = node.querySelector("[data-name=description]");
  675. let url_form = node.querySelector("[data-name=url]");
  676. let color_form = node.querySelector("[data-name=color]");
  677. let delete_btn = node.querySelector("[data-name=delete]");
  678. let edit_btn = node.querySelector("[data-name=edit]");
  679. let download_btn = node.querySelector("[data-name=download]");
  680. if (collection.color) {
  681. color_form.style.background = collection.color;
  682. }
  683. let possible_types = [CollectionType.ADDRESSBOOK, CollectionType.WEBCAL];
  684. [CollectionType.CALENDAR, ""].forEach(function(e) {
  685. [CollectionType.union(e, CollectionType.JOURNAL), e].forEach(function(e) {
  686. [CollectionType.union(e, CollectionType.TASKS), e].forEach(function(e) {
  687. if (e) {
  688. possible_types.push(e);
  689. }
  690. });
  691. });
  692. });
  693. possible_types.forEach(function(e) {
  694. if (e !== collection.type) {
  695. node.querySelector("[data-name=" + e + "]").classList.add("hidden");
  696. }
  697. });
  698. title_form.textContent = collection.displayname || collection.href;
  699. if(title_form.textContent.length > 30){
  700. title_form.classList.add("smalltext");
  701. }
  702. description_form.textContent = collection.description;
  703. if(description_form.textContent.length > 150){
  704. description_form.classList.add("smalltext");
  705. }
  706. let href = SERVER + collection.href;
  707. url_form.value = href;
  708. download_btn.href = href;
  709. delete_btn.onclick = function() {return ondelete(collection);};
  710. edit_btn.onclick = function() {return onedit(collection);};
  711. node.classList.remove("hidden");
  712. nodes.push(node);
  713. template.parentNode.insertBefore(node, template);
  714. });
  715. }
  716. function update() {
  717. let loading_scene = new LoadingScene();
  718. push_scene(loading_scene, false);
  719. collections_req = get_collections(user, password, collection, function(collections1, error) {
  720. if (scene_index === null) {
  721. return;
  722. }
  723. collections_req = null;
  724. if (error) {
  725. onerror(error);
  726. pop_scene(scene_index - 1);
  727. } else {
  728. collections = collections1;
  729. pop_scene(scene_index);
  730. }
  731. });
  732. }
  733. this.show = function() {
  734. html_scene.classList.remove("hidden");
  735. new_btn.onclick = onnew;
  736. upload_btn.onclick = onupload;
  737. filesInputForm.reset();
  738. filesInput.onchange = onfileschange;
  739. if (collections === null) {
  740. update();
  741. } else {
  742. // from update loading scene
  743. show_collections(collections);
  744. }
  745. };
  746. this.hide = function() {
  747. html_scene.classList.add("hidden");
  748. scene_index = scene_stack.length - 1;
  749. new_btn.onclick = null;
  750. upload_btn.onclick = null;
  751. filesInput.onchange = null;
  752. collections = null;
  753. // remove collection
  754. nodes.forEach(function(node) {
  755. node.parentNode.removeChild(node);
  756. });
  757. nodes = [];
  758. };
  759. this.release = function() {
  760. scene_index = null;
  761. if (collections_req !== null) {
  762. collections_req.abort();
  763. collections_req = null;
  764. }
  765. collections = null;
  766. filesInputForm.reset();
  767. };
  768. }
  769. /**
  770. * @constructor
  771. * @implements {Scene}
  772. * @param {string} user
  773. * @param {string} password
  774. * @param {Collection} collection parent collection
  775. * @param {Array<File>} files
  776. */
  777. function UploadCollectionScene(user, password, collection, files) {
  778. let html_scene = document.getElementById("uploadcollectionscene");
  779. let template = html_scene.querySelector("[data-name=filetemplate]");
  780. let close_btn = html_scene.querySelector("[data-name=close]");
  781. /** @type {?number} */ let scene_index = null;
  782. /** @type {?XMLHttpRequest} */ let upload_req = null;
  783. /** @type {Array<string>} */ let errors = [];
  784. /** @type {?Array<Node>} */ let nodes = null;
  785. function upload_next() {
  786. try {
  787. if (files.length === errors.length) {
  788. if (errors.every(error => error === null)) {
  789. pop_scene(scene_index - 1);
  790. } else {
  791. close_btn.classList.remove("hidden");
  792. }
  793. } else {
  794. let file = files[errors.length];
  795. let upload_href = collection.href + random_uuid() + "/";
  796. upload_req = upload_collection(user, password, upload_href, file, function(error) {
  797. if (scene_index === null) {
  798. return;
  799. }
  800. upload_req = null;
  801. errors.push(error);
  802. updateFileStatus(errors.length - 1);
  803. upload_next();
  804. });
  805. }
  806. } catch(err) {
  807. console.error(err);
  808. }
  809. return false;
  810. }
  811. function onclose() {
  812. try {
  813. pop_scene(scene_index - 1);
  814. } catch(err) {
  815. console.error(err);
  816. }
  817. return false;
  818. }
  819. function updateFileStatus(i) {
  820. if (nodes === null) {
  821. return;
  822. }
  823. let pending_form = nodes[i].querySelector("[data-name=pending]");
  824. let success_form = nodes[i].querySelector("[data-name=success]");
  825. let error_form = nodes[i].querySelector("[data-name=error]");
  826. if (errors.length > i) {
  827. pending_form.classList.add("hidden");
  828. if (errors[i]) {
  829. success_form.classList.add("hidden");
  830. error_form.textContent = "Error: " + errors[i];
  831. error_form.classList.remove("hidden");
  832. } else {
  833. success_form.classList.remove("hidden");
  834. error_form.classList.add("hidden");
  835. }
  836. } else {
  837. pending_form.classList.remove("hidden");
  838. success_form.classList.add("hidden");
  839. error_form.classList.add("hidden");
  840. }
  841. }
  842. this.show = function() {
  843. html_scene.classList.remove("hidden");
  844. if (errors.length < files.length) {
  845. close_btn.classList.add("hidden");
  846. }
  847. close_btn.onclick = onclose;
  848. nodes = [];
  849. for (let i = 0; i < files.length; i++) {
  850. let file = files[i];
  851. let node = template.cloneNode(true);
  852. node.classList.remove("hidden");
  853. let name_form = node.querySelector("[data-name=name]");
  854. name_form.textContent = file.name;
  855. node.classList.remove("hidden");
  856. nodes.push(node);
  857. updateFileStatus(i);
  858. template.parentNode.insertBefore(node, template);
  859. }
  860. if (scene_index === null) {
  861. scene_index = scene_stack.length - 1;
  862. upload_next();
  863. }
  864. };
  865. this.hide = function() {
  866. html_scene.classList.add("hidden");
  867. close_btn.classList.remove("hidden");
  868. close_btn.onclick = null;
  869. nodes.forEach(function(node) {
  870. node.parentNode.removeChild(node);
  871. });
  872. nodes = null;
  873. };
  874. this.release = function() {
  875. scene_index = null;
  876. if (upload_req !== null) {
  877. upload_req.abort();
  878. upload_req = null;
  879. }
  880. };
  881. }
  882. /**
  883. * @constructor
  884. * @implements {Scene}
  885. * @param {string} user
  886. * @param {string} password
  887. * @param {Collection} collection
  888. */
  889. function DeleteCollectionScene(user, password, collection) {
  890. let html_scene = document.getElementById("deletecollectionscene");
  891. let title_form = html_scene.querySelector("[data-name=title]");
  892. let error_form = html_scene.querySelector("[data-name=error]");
  893. let delete_btn = html_scene.querySelector("[data-name=delete]");
  894. let cancel_btn = html_scene.querySelector("[data-name=cancel]");
  895. /** @type {?number} */ let scene_index = null;
  896. /** @type {?XMLHttpRequest} */ let delete_req = null;
  897. let error = "";
  898. function ondelete() {
  899. try {
  900. let loading_scene = new LoadingScene();
  901. push_scene(loading_scene);
  902. delete_req = delete_collection(user, password, collection, function(error1) {
  903. if (scene_index === null) {
  904. return;
  905. }
  906. delete_req = null;
  907. if (error1) {
  908. error = error1;
  909. pop_scene(scene_index);
  910. } else {
  911. pop_scene(scene_index - 1);
  912. }
  913. });
  914. } catch(err) {
  915. console.error(err);
  916. }
  917. return false;
  918. }
  919. function oncancel() {
  920. try {
  921. pop_scene(scene_index - 1);
  922. } catch(err) {
  923. console.error(err);
  924. }
  925. return false;
  926. }
  927. this.show = function() {
  928. this.release();
  929. scene_index = scene_stack.length - 1;
  930. html_scene.classList.remove("hidden");
  931. title_form.textContent = collection.displayname || collection.href;
  932. delete_btn.onclick = ondelete;
  933. cancel_btn.onclick = oncancel;
  934. if(error){
  935. error_form.textContent = "Error: " + error;
  936. error_form.classList.remove("hidden");
  937. }else{
  938. error_form.classList.add("hidden");
  939. }
  940. };
  941. this.hide = function() {
  942. html_scene.classList.add("hidden");
  943. cancel_btn.onclick = null;
  944. delete_btn.onclick = null;
  945. };
  946. this.release = function() {
  947. scene_index = null;
  948. if (delete_req !== null) {
  949. delete_req.abort();
  950. delete_req = null;
  951. }
  952. };
  953. }
  954. /**
  955. * Generate random hex number.
  956. * @param {number} length
  957. * @return {string}
  958. */
  959. function random_hex(length) {
  960. let bytes = new Uint8Array(Math.ceil(length / 2));
  961. window.crypto.getRandomValues(bytes);
  962. return bytes.reduce((s, b) => s + b.toString(16).padStart(2, "0"), "").substring(0, length);
  963. }
  964. /**
  965. * @constructor
  966. * @implements {Scene}
  967. * @param {string} user
  968. * @param {string} password
  969. * @param {Collection} collection if it's a principal collection, a new
  970. * collection will be created inside of it.
  971. * Otherwise the collection will be edited.
  972. */
  973. function CreateEditCollectionScene(user, password, collection) {
  974. let edit = collection.type !== CollectionType.PRINCIPAL;
  975. let html_scene = document.getElementById(edit ? "editcollectionscene" : "createcollectionscene");
  976. let title_form = edit ? html_scene.querySelector("[data-name=title]") : null;
  977. let error_form = html_scene.querySelector("[data-name=error]");
  978. let displayname_form = html_scene.querySelector("[data-name=displayname]");
  979. let displayname_label = html_scene.querySelector("label[for=displayname]");
  980. let description_form = html_scene.querySelector("[data-name=description]");
  981. let description_label = html_scene.querySelector("label[for=description]");
  982. let source_form = html_scene.querySelector("[data-name=source]");
  983. let source_label = html_scene.querySelector("label[for=source]");
  984. let type_form = html_scene.querySelector("[data-name=type]");
  985. let type_label = html_scene.querySelector("label[for=type]");
  986. let color_form = html_scene.querySelector("[data-name=color]");
  987. let color_label = html_scene.querySelector("label[for=color]");
  988. let submit_btn = html_scene.querySelector("[data-name=submit]");
  989. let cancel_btn = html_scene.querySelector("[data-name=cancel]");
  990. /** @type {?number} */ let scene_index = null;
  991. /** @type {?XMLHttpRequest} */ let create_edit_req = null;
  992. let error = "";
  993. /** @type {?Element} */ let saved_type_form = null;
  994. let href = edit ? collection.href : collection.href + random_uuid() + "/";
  995. let displayname = edit ? collection.displayname : "";
  996. let description = edit ? collection.description : "";
  997. let source = edit ? collection.source : "";
  998. let type = edit ? collection.type : CollectionType.CALENDAR_JOURNAL_TASKS;
  999. let color = edit && collection.color ? collection.color : "#" + random_hex(6);
  1000. function remove_invalid_types() {
  1001. if (!edit) {
  1002. return;
  1003. }
  1004. /** @type {HTMLOptionsCollection} */ let options = type_form.options;
  1005. // remove all options that are not supersets
  1006. for (let i = options.length - 1; i >= 0; i--) {
  1007. if (!CollectionType.is_subset(type, options[i].value)) {
  1008. options.remove(i);
  1009. }
  1010. }
  1011. }
  1012. function read_form() {
  1013. displayname = displayname_form.value;
  1014. description = description_form.value;
  1015. source = source_form.value;
  1016. type = type_form.value;
  1017. color = color_form.value;
  1018. }
  1019. function fill_form() {
  1020. displayname_form.value = displayname;
  1021. description_form.value = description;
  1022. source_form.value = source;
  1023. type_form.value = type;
  1024. color_form.value = color;
  1025. if(error){
  1026. error_form.textContent = "Error: " + error;
  1027. error_form.classList.remove("hidden");
  1028. }
  1029. error_form.classList.add("hidden");
  1030. onTypeChange();
  1031. type_form.addEventListener("change", onTypeChange);
  1032. }
  1033. function onsubmit() {
  1034. try {
  1035. read_form();
  1036. let sane_color = color.trim();
  1037. if (sane_color) {
  1038. let color_match = COLOR_RE.exec(sane_color);
  1039. if (!color_match) {
  1040. error = "Invalid color";
  1041. fill_form();
  1042. return false;
  1043. }
  1044. sane_color = color_match[1];
  1045. }
  1046. let loading_scene = new LoadingScene();
  1047. push_scene(loading_scene);
  1048. let collection = new Collection(href, type, displayname, description, sane_color, source);
  1049. let callback = function(error1) {
  1050. if (scene_index === null) {
  1051. return;
  1052. }
  1053. create_edit_req = null;
  1054. if (error1) {
  1055. error = error1;
  1056. pop_scene(scene_index);
  1057. } else {
  1058. pop_scene(scene_index - 1);
  1059. }
  1060. };
  1061. if (edit) {
  1062. create_edit_req = edit_collection(user, password, collection, callback);
  1063. } else {
  1064. create_edit_req = create_collection(user, password, collection, callback);
  1065. }
  1066. } catch(err) {
  1067. console.error(err);
  1068. }
  1069. return false;
  1070. }
  1071. function oncancel() {
  1072. try {
  1073. pop_scene(scene_index - 1);
  1074. } catch(err) {
  1075. console.error(err);
  1076. }
  1077. return false;
  1078. }
  1079. function onTypeChange(e){
  1080. if(type_form.value == CollectionType.WEBCAL){
  1081. source_label.classList.remove("hidden");
  1082. source_form.classList.remove("hidden");
  1083. }else{
  1084. source_label.classList.add("hidden");
  1085. source_form.classList.add("hidden");
  1086. }
  1087. }
  1088. this.show = function() {
  1089. this.release();
  1090. scene_index = scene_stack.length - 1;
  1091. // Clone type_form because it's impossible to hide options without removing them
  1092. saved_type_form = type_form;
  1093. type_form = type_form.cloneNode(true);
  1094. saved_type_form.parentNode.replaceChild(type_form, saved_type_form);
  1095. remove_invalid_types();
  1096. html_scene.classList.remove("hidden");
  1097. if (edit) {
  1098. title_form.textContent = collection.displayname || collection.href;
  1099. }
  1100. fill_form();
  1101. submit_btn.onclick = onsubmit;
  1102. cancel_btn.onclick = oncancel;
  1103. };
  1104. this.hide = function() {
  1105. read_form();
  1106. html_scene.classList.add("hidden");
  1107. // restore type_form
  1108. type_form.parentNode.replaceChild(saved_type_form, type_form);
  1109. type_form = saved_type_form;
  1110. saved_type_form = null;
  1111. submit_btn.onclick = null;
  1112. cancel_btn.onclick = null;
  1113. };
  1114. this.release = function() {
  1115. scene_index = null;
  1116. if (create_edit_req !== null) {
  1117. create_edit_req.abort();
  1118. create_edit_req = null;
  1119. }
  1120. };
  1121. }
  1122. function main() {
  1123. // Hide startup loading message
  1124. document.getElementById("loadingscene").classList.add("hidden");
  1125. push_scene(new LoginScene(), false);
  1126. }
  1127. window.addEventListener("load", main);