fn.js 40 KB

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