fn.js 47 KB

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