Skip to content

Instantly share code, notes, and snippets.

@andreafalzetti
Last active April 21, 2022 02:43
Show Gist options
  • Save andreafalzetti/c6230f801c0f8d302a7d to your computer and use it in GitHub Desktop.
Save andreafalzetti/c6230f801c0f8d302a7d to your computer and use it in GitHub Desktop.
/**
* Get a list of Events from a given Calendarurl
*
* @param {String} url
* @param {String} user
* @param {String} pass
* @param {String} date from which to start like 20140101T120000Z
* @param {String} date from which to stop like 20140102T120000Z, optional (can be undefined)
* @param {function} cb
*/
getEvents: function (url, user, pass, start, end, cb) {
var urlparts = /(https?)\:\/\/(.*?):?(\d*)?(\/.*\/?)/gi.exec(url);
var protocol = urlparts[1];
var host = urlparts[2];
var port = urlparts[3] || (protocol === "https" ? 443 : 80);
var path = urlparts[4];
var endTimeRange = (end) ? ' end="'+end+'"' : "";
var xml = '<?xml version="1.0" encoding="utf-8" ?>\n' +
'<C:calendar-query xmlns:D="DAV:" xmlns:C="urn:ietf:params:xml:ns:caldav">\n' +
' <D:prop>\n' +
' <C:calendar-data/>\n' +
' </D:prop>\n' +
' <C:filter>\n' +
' <C:comp-filter name="VCALENDAR">\n' +
' <C:comp-filter name="VEVENT">\n' +
' <C:time-range start="'+start+'"'+endTimeRange+'/>\n' +
' </C:comp-filter>\n' +
' </C:comp-filter>\n' +
' </C:filter>\n' +
'</C:calendar-query>';
var options = {
rejectUnauthorized: false,
hostname : host,
port : port,
path : path,
method : 'REPORT',
headers : {
"Content-type" : "text/xml",
"Content-Length": xml.length,
"User-Agent" : "calDavClient",
"Connection" : "close",
"Depth" : "1"
}
};
if (user && pass) {
var userpass = new Buffer(user + ":" + pass).toString('base64');
options.headers["Authorization"] = "Basic " + userpass;
}
var req = https.request(options, function (res) {
var s = "";
res.on('data', function (chunk) {
s += chunk;
});
req.on('close', function () {
var reslist = [];
try {
var xmlDoc = xmljs.parseXml(s);
// console.log(xmlDoc.toString() );
var data = xmlDoc.find("d:response/d:propstat/d:prop/c:calendar-data",{ d: 'DAV:', c: "urn:ietf:params:xml:ns:caldav" });
for (var i in data) {
var ics = data[i].text();
var evs = ics.match(/BEGIN:VEVENT[\s\S]*END:VEVENT/gi);
for (var x in evs) {
var evobj = {};
var evstr = evs[x];
var regexFix = /[^\S\t]\n/gm;
evstr = evstr.replace(regexFix, "");
evstr = evstr.split("\n");
for (var y in evstr) {
var evpropstr = evstr[y];
if (evpropstr.match(/BEGIN:|END:/gi)) {
continue;
}
var sp = evpropstr.split(":");
var key = sp[0];
var val = sp[1];
if (key && val) {
evobj[key] = val;
}
}
reslist.push(evobj)
}
}
cb(reslist);
}
catch (e) {
console.log("Error parsing response")
}
});
});
req.end(xml);
req.on('error', function (e) {
console.log('problem with request: ' + e.message);
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment