Skip to content

Instantly share code, notes, and snippets.

@andreafalzetti
Last active April 3, 2022 00:22
Show Gist options
  • Save andreafalzetti/de1c0825b36940be5c75 to your computer and use it in GitHub Desktop.
Save andreafalzetti/de1c0825b36940be5c75 to your computer and use it in GitHub Desktop.
This is a basic function to add an event into a calendar using Node.js and the CalDAV protocol
/**
* On message callback, called when a message (of any type) is detected with the real time messaging API
* @param {object} event
* @param {string} url (CalDAV Server URL)
* @param {string} user (CalDAV Username/Email)
* @param {string} user (CalDAV Password)
* @param {function} cb (Callback function)
*
* The object event needs the following attributes:
* event.key - A random string which will be the unique ID of the event in CalDAV
* event.summary - Description/Title of the event
* event.startDate - Starting time of the event
* event.endDate - Ending time of the event
*
* I have used moment.js to convert the startDate/endDate in actual Dates, so the date
* doesn't need to be formatted, the function will format it.
*/
addEvent: function (event, url, user, pass, 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] + event.key;
var body = 'BEGIN:VCALENDAR\n' +
'BEGIN:VEVENT\n' +
'UID:' + event.key + '\n' +
'SUMMARY:' + event.summary + '\n';
var _startDateBody, _endDateBody;
var format_allDay = "YYYYMMDDTHHmms";
var format_singleEvent = "YYYYMMDD";
if(moment(event.startDate).hour() === 0) {
_startDateBody = 'DTSTART;VALUE=DATE:' + moment(event.startDate).format(format_singleEvent) + '\n';
} else {
_startDateBody = 'DTSTART:' + moment(event.startDate).format(format_allDay) + 'Z\n';
}
if(moment(event.endDate).hour() === 0) {
_endDateBody = 'DTEND;VALUE=DATE:' + moment(event.endDate).add(1, 'days').format(format_singleEvent) + '\n';
} else {
_endDateBody = 'DTEND:' + moment(event.endDate).format(format_allDay) + 'Z\n';
}
body += _startDateBody +
_endDateBody +
'END:VEVENT\n' +
'END:VCALENDAR';
var options = {
rejectUnauthorized: false,
hostname : host,
port : port,
path : path,
method : 'PUT',
headers : {
"Content-type" : "text/calendar",
"Content-Length": body.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 () {
if(s === "") {
cb(true);
} else {
cb(false);
}
});
});
req.end(body);
req.on('error', function (e) {
console.log('problem with request: ' + e.message);
});
}
@LovikaJain
Copy link

Hi I tried adding event and getting event using node-caldav-mod but it is failing if I am using caldav URL and adding is not working at all.

This is the js file which I created. Could you please help me out with this? I have been breaking my head over this from more than a week

var caldav = require("node-caldav-mod");
var moment = require('moment-timezone');
var express = require('express');
var app = express();
var xmljs = require("libxmljs");
var https = require("https");
var parseString = require('xml2js').parseString;


var url = "https://calendar.zoho.com/caldav/";
var username = "username"
var password = "password"
var timeFormat = "YYYYMMDDTHHmms";

var addTodayEvents = function(callback){
var start_date = moment().set({'hour': 0, 'minute': 0, 'second': 10}).format(timeFormat) + "Z";
var end_date = moment().set({'hour': 23, 'minute': 59, 'second': 59}).format(timeFormat) + "Z";
var output = {};
var event = {
	key: "1231",
	summary: "Meeting",
	startDate: "20161016",
	endDate: "20161016"
	}
  console.log("-----event------")
  console.log(event);
  caldav.addEvent(event,url,username,password,function (res){
  console.log("........URL..........")
  console.log(url);
  callback(res);
  })
}



var getTodayEvents = function(callback){
    var query_start_date = moment().set({'hour': 0, 'minute': 0, 'second': 10}).format(timeFormat) + "Z";
    var query_end_date = moment().set({'hour': 23, 'minute': 59, 'second': 59}).format(timeFormat) + "Z";
    var output = {};
    output.start_date = query_start_date;
    output.end_date = query_end_date;

    caldav.getEvents(url, username, password, query_start_date, query_end_date, function(res){
        callback(res);
    });
}


app.get('/today', function(request, response){
    getTodayEvents(function(events){
        response.send(events);
    }) 
});

	app.post('/event',function(request,response){
	addTodayEvents(function(request){
	response.status(200).send(events);
	})
	})

app.listen(3000,function(){
    console.log("Listening on port 3000..");
})

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment