fn.js 51 KB

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