Showing
1 changed file
with
88 additions
and
0 deletions
server/libs/ICal.js
0 → 100644
1 | +const fs = require("fs"); | ||
2 | + | ||
3 | +function parseICal(text) { | ||
4 | + const schedules = []; | ||
5 | + let sche = {}; | ||
6 | + let reading = false; | ||
7 | + for (const line of text.replace(/\r\n /g, "").split("\r\n")) { | ||
8 | + if (reading) { | ||
9 | + if (line === "END:VEVENT") { | ||
10 | + reading = false; | ||
11 | + schedules.push(sche); | ||
12 | + sche = {}; | ||
13 | + } else { | ||
14 | + const i = line.indexOf(":"); | ||
15 | + process(sche, line.slice(0, i), line.slice(i + 1)); | ||
16 | + } | ||
17 | + } else if (line === "BEGIN:VEVENT") reading = true; | ||
18 | + } | ||
19 | + return schedules; | ||
20 | +} | ||
21 | + | ||
22 | +const errArr = []; | ||
23 | +function process(sche, k, v) { | ||
24 | + switch (k) { | ||
25 | + case "DTSTAMP": | ||
26 | + k = "CREATED"; | ||
27 | + v = dateTimeToDate(v); | ||
28 | + break; | ||
29 | + case "UID": | ||
30 | + v = v.split("-")[2]; | ||
31 | + break; | ||
32 | + case "DTSTART": | ||
33 | + k = "START"; | ||
34 | + v = dateTimeToDate(v); | ||
35 | + break; | ||
36 | + case "DTEND": | ||
37 | + k = "END"; | ||
38 | + v = dateTimeToDate(v); | ||
39 | + break; | ||
40 | + case "DTSTART;VALUE=DATE": | ||
41 | + case "DTEND;VALUE=DATE": | ||
42 | + k = "DATE"; | ||
43 | + v = dateToDate(v); | ||
44 | + break; | ||
45 | + case "X-ALT-DESC;FMTTYPE=text/html": | ||
46 | + k = "DETAIL"; | ||
47 | + break; | ||
48 | + case "SUMMARY": | ||
49 | + k = "LABEL"; | ||
50 | + let b; | ||
51 | + [v, b] = v.split(" ["); | ||
52 | + sche["SUBJECT"] = b.substring(0, b.length - 1); | ||
53 | + break; | ||
54 | + case "CLASS": | ||
55 | + case "SEQUENCE": | ||
56 | + return; | ||
57 | + case "DESCRIPTION": | ||
58 | + case "URL": | ||
59 | + break; | ||
60 | + default: | ||
61 | + errArr.push(k); | ||
62 | + } | ||
63 | + sche[k] = v; | ||
64 | +} | ||
65 | + | ||
66 | +function insert(str, idxs, char) { | ||
67 | + let nstr = str.substring(0, idxs[0]); | ||
68 | + for (let i = 0; i < idxs.length - 1; i++) | ||
69 | + nstr += char + str.substring(idxs[i], idxs[i + 1]); | ||
70 | + return nstr; | ||
71 | +} | ||
72 | + | ||
73 | +function dateTimeToDate(str) { | ||
74 | + const [a, b] = str.split("T"); | ||
75 | + return new Date(insert(a, [4, 6, 8], "-") + "T" + insert(b, [2, 4, 6], ":")); | ||
76 | +} | ||
77 | + | ||
78 | +function dateToDate(str) { | ||
79 | + return new Date(insert(str, [4, 6, 8], "-")); | ||
80 | +} | ||
81 | + | ||
82 | +// let result; | ||
83 | +// fs.readFile("C:/Users/teddy/Downloads/data.ics", "utf8", (err, data) => { | ||
84 | +// if (err) console.log(err); | ||
85 | +// else result = parseICal(data); | ||
86 | +// }); | ||
87 | + | ||
88 | +export { parseICal }; |
-
Please register or login to post a comment