fn.js 50 KB

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