fn.js 40 KB

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