HyeonJun Jeon

[Add] ICal parser

const fs = require("fs");
function parseICal(text) {
const schedules = [];
let sche = {};
let reading = false;
for (const line of text.replace(/\r\n /g, "").split("\r\n")) {
if (reading) {
if (line === "END:VEVENT") {
reading = false;
schedules.push(sche);
sche = {};
} else {
const i = line.indexOf(":");
process(sche, line.slice(0, i), line.slice(i + 1));
}
} else if (line === "BEGIN:VEVENT") reading = true;
}
return schedules;
}
const errArr = [];
function process(sche, k, v) {
switch (k) {
case "DTSTAMP":
k = "CREATED";
v = dateTimeToDate(v);
break;
case "UID":
v = v.split("-")[2];
break;
case "DTSTART":
k = "START";
v = dateTimeToDate(v);
break;
case "DTEND":
k = "END";
v = dateTimeToDate(v);
break;
case "DTSTART;VALUE=DATE":
case "DTEND;VALUE=DATE":
k = "DATE";
v = dateToDate(v);
break;
case "X-ALT-DESC;FMTTYPE=text/html":
k = "DETAIL";
break;
case "SUMMARY":
k = "LABEL";
let b;
[v, b] = v.split(" [");
sche["SUBJECT"] = b.substring(0, b.length - 1);
break;
case "CLASS":
case "SEQUENCE":
return;
case "DESCRIPTION":
case "URL":
break;
default:
errArr.push(k);
}
sche[k] = v;
}
function insert(str, idxs, char) {
let nstr = str.substring(0, idxs[0]);
for (let i = 0; i < idxs.length - 1; i++)
nstr += char + str.substring(idxs[i], idxs[i + 1]);
return nstr;
}
function dateTimeToDate(str) {
const [a, b] = str.split("T");
return new Date(insert(a, [4, 6, 8], "-") + "T" + insert(b, [2, 4, 6], ":"));
}
function dateToDate(str) {
return new Date(insert(str, [4, 6, 8], "-"));
}
// let result;
// fs.readFile("C:/Users/teddy/Downloads/data.ics", "utf8", (err, data) => {
// if (err) console.log(err);
// else result = parseICal(data);
// });
export { parseICal };