-
Notifications
You must be signed in to change notification settings - Fork 2
/
icsToJson.js
111 lines (99 loc) · 2.73 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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
/* eslint-disable require-unicode-regexp */
/* eslint-disable no-const-assign */
/* eslint-disable no-continue */
/* eslint-disable no-plusplus */
/* eslint-disable arrow-parens */
/* eslint-disable func-style */
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 RRULE = "RRULE";
const DURATION = "DURATION";
const keyMap = {
[START_DATE]: "startDate",
[END_DATE]: "endDate",
[DESCRIPTION]: "description",
[SUMMARY]: "summary",
[LOCATION]: "location",
[RRULE]: "rrule",
[DURATION]:"duration"
};
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];
let 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:
if ( lineData.length > 2) {
// summary had colon's in the text, recombine
lineData.shift();
value = lineData.join(":"); // remove the key and then join remaining back seperated by :
}
currentObj[keyMap[SUMMARY]] = clean(value);
break;
case LOCATION:
currentObj[keyMap[LOCATION]] = clean(value);
break;
case RRULE:
currentObj[keyMap[RRULE]] = clean(value);
break;
case DURATION:
currentObj[keyMap[DURATION]] = clean(value);
break;
default:
continue;
}
}
return array;
};
module.exports = {
icsToJson
}