Monday 26 March 2018

Making a simple Google Calendar events API with Google Apps Script

I was recently looking for a Rainmeter skin to display upcoming events from my Google Calendar on my Desktop. As GCal sadly no longer provides an XML feed for events these skins are few and far between. There is no client library provided by Google for what I needed as Rainmeter uses Lua as a scripting language.
I decided for simplicity's sake to minimise the work that needed to be done on the client as it is a lightweight desktop app and instead use Google Apps scripts to access the Calendar API to provide a simplified interface to it just providing the data that I need.

This is fairly straightforward and the documentation from Google is very helpful. There is a quickstart here to show you how to access events.

To publish the script as a web app, it must contain a doGet() or doPost() method.

My doGet() method when I has finished looked like this:
function doGet(e) {
    var events = listUpcomingEvents(e.parameter.calendarId);
    var jsonString = JSON.stringify(events);
    //Logger.log(jsonString);
    return ContentService.createTextOutput(jsonString).setMimeType(ContentService.MimeType.JSON);
}
The parameter calendarId can be set in the request which will choose which of my Google Calendars to access. My listUpcomingEvents method will list events from all calendars if the parameter is left null.

I convert the Javascript object returned by the method to a JSON string and output this as a response with a mime-type of JSON.

At note about colours:
When grabbing events using the API, colours are identified by an integer id based on the calendar colour scheme.
In order to actually get these (background) colours as hex values I used this:

function getColorById(id) {
     var colors = Calendar.Colors.get();
     var json = JSON.stringify(colors["event"]);
     var myObj = JSON.parse(json);
     return myObj[id].background;
}

That returns the Calendar event background colour for a particular id.





Notes on the Rainmeter scripts:
When I actually came to the Rainmeter end of the task I discovered that google apps scripts performs a redirect when executing and this isn't supported by the Rainmeter web parser. I solved this with the rather hacky approach of executing a libcurl command, writing the output to a file and then parsing the file.

No comments:

Post a Comment