Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Object based source calendar list and error emails #307

Open
wants to merge 5 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
86 changes: 71 additions & 15 deletions Code.gs
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
*=========================================
*/

// Below is the old format. You may still use this format, but it is recommended to use the new format below.
var sourceCalendars = [ // The ics/ical urls that you want to get events from along with their target calendars (list a new row for each mapping of ICS url to Google Calendar)
// For instance: ["https://p24-calendars.icloud.com/holidays/us_en.ics", "US Holidays"]
// Or with colors following mapping https://developers.google.com/apps-script/reference/calendar/event-color,
Expand All @@ -31,6 +32,35 @@ var sourceCalendars = [ // The ics/ical urls that you want to get

];

var sourceCalendarMap = [
{
name: "targetCalendar1", // The name of the target calendar
sources: [ // A list of the ics/ical urls that you want to get events from
{
url: "icsUrl1", // Required: the ics/ical url
authorization: { // Optional: authorization information
basic: "username:password", // Basic authorization uses a username-password pair separated by a colon
},
color: 4 // Optional: color for events in this calendar
},
{
url: "icsUrl2",
authorization: {
bearer: "token",
},
},
],
},

{ // A second calendar
name: "targetCalendar2",
sources: [
{ url: "icsUrl3", color: 11 },
{ url: "icsUrl4" },
],
},
];

var howFrequent = 15; // What interval (minutes) to run this script on to check for new events. Any integer can be used, but will be rounded up to 5, 10, 15, 30 or to the nearest hour after that.. 60, 120, etc. 1440 (24 hours) is the maximum value. Anything above that will be replaced with 1440.
var onlyFutureEvents = false; // If you turn this to "true", past events will not be synced (this will also removed past events from the target calendar if removeEventsFromCalendar is true)
var addEventsToCalendar = true; // If you turn this to "false", you can check the log (View > Logs) to make sure your events are being read correctly before turning this on
Expand All @@ -48,6 +78,7 @@ var overrideVisibility = ""; // Changes the visibility of the event
var addTasks = false;

var emailSummary = false; // Will email you when an event is added/modified/removed to your calendar
var emailOnError = true; // Will email when an error occurs
var email = ""; // OPTIONAL: If "emailSummary" is set to true or you want to receive update notifications, you will need to provide your email address
var customEmailSubject = ""; // OPTIONAL: If you want to change the email subject, provide a custom one here. Default: "GAS-ICS-Sync Execution Summary"
var dateFormat = "YYYY-MM-DD" // date format in the email summary (e.g. "YYYY-MM-DD", "DD.MM.YYYY", "MM/DD/YYYY". separators are ".", "-" and "/")
Expand Down Expand Up @@ -144,9 +175,11 @@ var targetCalendarName;
var addedEvents = [];
var modifiedEvents = [];
var removedEvents = [];
var errors = [];

// Syncing logic can set this to true to cause the Google Apps Script "Executions" dashboard to report failure
var reportOverallFailure = false;
function clearRunning(){
PropertiesService.getUserProperties().setProperty('LastRun', 0);
}

function startSync(){
if (PropertiesService.getUserProperties().getProperty('LastRun') > 0 && (new Date().getTime() - PropertiesService.getUserProperties().getProperty('LastRun')) < 360000) {
Expand All @@ -156,29 +189,56 @@ function startSync(){

PropertiesService.getUserProperties().setProperty('LastRun', new Date().getTime());

let error = undefined;

try {
_startSync();
} catch (e) {
error = e;
}

PropertiesService.getUserProperties().setProperty('LastRun', 0);

if (error === undefined) {
Logger.log("Sync finished!");
} else {
Logger.log("Sync failed with error:");
Logger.log(error);

if (emailOnError) {
sendError(error);
}

throw error;
}
}

function _startSync(){
if (typeof sourceCalendarMap == "undefined" && typeof sourceCalendars != "undefined")
sourceCalendarMap = convertCalendarSourceArray(sourceCalendars);

if (onlyFutureEvents)
startUpdateTime = new ICAL.Time.fromJSDate(new Date(), true);

//Disable email notification if no mail adress is provided
emailSummary = emailSummary && email != "";

sourceCalendars = condenseCalendarMap(sourceCalendars);
for (var calendar of sourceCalendars){

for (var calendar of sourceCalendarMap){
//------------------------ Reset globals ------------------------
calendarEvents = [];
calendarEventsIds = [];
icsEventsIds = [];
calendarEventsMD5s = [];
recurringEvents = [];

targetCalendarName = calendar[0];
var sourceCalendarURLs = calendar[1];
targetCalendarName = calendar.name;
var sourceCalendarURLs = calendar.sources;
var vevents;

//------------------------ Fetch URL items ------------------------
var responses = fetchSourceCalendars(sourceCalendarURLs);
Logger.log("Syncing " + responses.length + " calendars to " + targetCalendarName);

//------------------------ Get target calendar information------------------------
var targetCalendar = setupTargetCalendar(targetCalendarName);
targetCalendarId = targetCalendar.id;
Expand Down Expand Up @@ -229,7 +289,7 @@ function startSync(){
}

//------------------------ Remove old events from calendar ------------------------
if(removeEventsFromCalendar){
if(removeEventsFromCalendar && errors.length == 0){
Logger.log("Checking " + calendarEvents.length + " events for removal");
processEventCleanup();
Logger.log("Done checking events for removal");
Expand All @@ -250,12 +310,8 @@ function startSync(){
if ((addedEvents.length + modifiedEvents.length + removedEvents.length) > 0 && emailSummary){
sendSummary();
}
Logger.log("Sync finished!");
PropertiesService.getUserProperties().setProperty('LastRun', 0);

if (reportOverallFailure) {
// Cause the Google Apps Script "Executions" dashboard to show a failure
// (the message text does not seem to be logged anywhere)
throw new Error('The sync operation produced errors. See log for details.');
if (errors.length > 0) {
throw errors.join("\n\n");
}
}
Loading