forked from cwlsn/ics-to-json
-
Notifications
You must be signed in to change notification settings - Fork 0
/
icsToJson.js
86 lines (75 loc) · 2.01 KB
/
icsToJson.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
const NEW_LINE = /\r\n|\n|\r/;
const EVENT = "VEVENT";
const EVENT_START = "BEGIN";
const EVENT_END = "END";
const START_DATE = "DTSTART";
const END_DATE = "DTEND";
const DESCRIPTION = "DESCRIPTION";
const SUMMARY = "SUMMARY";
const LOCATION = "LOCATION";
const ALARM = "VALARM";
const keyMap = {
[START_DATE]: "startDate",
[END_DATE]: "endDate",
[DESCRIPTION]: "description",
[SUMMARY]: "summary",
[LOCATION]: "location"
};
const clean = string => unescape(string).trim();
const icsToJson = icsData => {
const array = [];
let currentObj = {};
let lastKey = "";
const lines = icsData.split(NEW_LINE);
let isAlarm = false;
for (let i = 0, iLen = lines.length; i < iLen; ++i) {
const line = lines[i];
const lineData = line.split(":");
let key = lineData[0];
const value = lineData[1];
if (key.indexOf(";") !== -1) {
const keyParts = key.split(";");
key = keyParts[0];
// Maybe do something with that second part later
}
if (lineData.length < 2) {
if (key.startsWith(" ") && lastKey !== undefined && lastKey.length) {
currentObj[lastKey] += clean(line.substr(1));
}
continue;
} else {
lastKey = keyMap[key];
}
switch (key) {
case EVENT_START:
if (value === EVENT) {
currentObj = {};
} else if (value === ALARM) {
isAlarm = true;
}
break;
case EVENT_END:
isAlarm = false;
if (value === EVENT) array.push(currentObj);
break;
case START_DATE:
currentObj[keyMap[START_DATE]] = value;
break;
case END_DATE:
currentObj[keyMap[END_DATE]] = value;
break;
case DESCRIPTION:
if (!isAlarm) currentObj[keyMap[DESCRIPTION]] = clean(value);
break;
case SUMMARY:
currentObj[keyMap[SUMMARY]] = clean(value);
break;
case LOCATION:
currentObj[keyMap[LOCATION]] = clean(value);
default:
continue;
}
}
return array;
};
export default icsToJson;