fn.js 41 KB

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