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

Fix typo & reworked error handling #245

Merged
merged 2 commits into from
Mar 27, 2022
Merged
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
7 changes: 3 additions & 4 deletions Code.gs
Original file line number Diff line number Diff line change
Expand Up @@ -153,17 +153,16 @@ function startSync(){

targetCalendarName = calendar[0];
var sourceCalendarURLs = calendar[1];
var colorId = calendar[2];
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, colorId);
var targetCalendar = setupTargetCalendar(targetCalendarName);
targetCalendarId = targetCalendar.id;
Logger.log("Working on calendar: " + targetCalendarId + colorId !== undefined ? " with colorId: " + colorId : "");
Logger.log("Working on calendar: " + targetCalendarId);

//------------------------ Parse existing events --------------------------
if(addEventsToCalendar || modifyExistingEvents || removeEventsFromCalendar){
Expand Down Expand Up @@ -203,7 +202,7 @@ function startSync(){
}, defaultMaxRetries);

vevents.forEach(function(e){
processEvent(e, calendarTz, colorId);
processEvent(e, calendarTz);
});

Logger.log("Done processing events");
Expand Down
54 changes: 30 additions & 24 deletions Helpers.gs
Original file line number Diff line number Diff line change
Expand Up @@ -45,9 +45,9 @@ function condenseCalendarMap(calendarMap){
}

if (index > -1)
result[index][1].push(mapping[0]);
result[index][1].push([mapping[0],mapping[2]]);
else
result.push([ mapping[1], [ mapping[0] ], mapping[2] ]);
result.push([ mapping[1], [[mapping[0],mapping[2]]] ]);
}

return result;
Expand All @@ -73,25 +73,25 @@ function deleteAllTriggers(){
*/
function fetchSourceCalendars(sourceCalendarURLs){
var result = []
for (var url of sourceCalendarURLs){
url = url.replace("webcal://", "https://");
for (var source of sourceCalendarURLs){
var url = source[0].replace("webcal://", "https://");
var colorId = source[1];

callWithBackoff(function() {
var urlResponse = UrlFetchApp.fetch(url, { 'validateHttpsCertificates' : false });
var urlResponse = UrlFetchApp.fetch(url, { 'validateHttpsCertificates' : false, 'muteHttpExceptions' : true });
if (urlResponse.getResponseCode() == 200){
var urlContent = urlResponse.getContentText();
if(!urlContent.includes("BEGIN:VCALENDAR")){
var urlContent = RegExp("(BEGIN:VCALENDAR.*?END:VCALENDAR)", "s").exec(urlResponse.getContentText());
if(urlContent == null){
Logger.log("[ERROR] Incorrect ics/ical URL: " + url);
return;
}
else{
result.push(urlContent);
Logger.log("Result: " + result.length);
result.push([urlContent[0], colorId]);
return;
}
}
else{ //Throw here to make callWithBackoff run again
throw "Error: Encountered " + urlReponse.getReponseCode() + " when accessing " + url;
throw "Error: Encountered HTTP error " + urlResponse.getResponseCode() + " when accessing " + url;
}
}, defaultMaxRetries);
}
Expand All @@ -106,7 +106,7 @@ function fetchSourceCalendars(sourceCalendarURLs){
* @param {string} targetCalendarName - The name of the calendar to return
* @return {Calendar} The calendar retrieved or created
*/
function setupTargetCalendar(targetCalendarName, colorId){
function setupTargetCalendar(targetCalendarName){
var targetCalendar = Calendar.CalendarList.list({showHidden: true}).items.filter(function(cal) {
return ((cal.summaryOverride || cal.summary) == targetCalendarName) &&
(cal.accessRole == "owner" || cal.accessRole == "writer");
Expand All @@ -117,7 +117,6 @@ function setupTargetCalendar(targetCalendarName, colorId){
targetCalendar = Calendar.newCalendar();
targetCalendar.summary = targetCalendarName;
targetCalendar.description = "Created by GAS";
targetCalendar.colorId = colorId;
targetCalendar.timeZone = Calendar.Settings.get("timezone").value;
targetCalendar = Calendar.Calendars.insert(targetCalendar);
}
Expand All @@ -135,7 +134,9 @@ function setupTargetCalendar(targetCalendarName, colorId){
*/
function parseResponses(responses){
var result = [];
for (var resp of responses){
for (var itm of responses){
var resp = itm[0];
var colorId = itm[1];
var jcalData = ICAL.parse(resp);
var component = new ICAL.Component(jcalData);

Expand All @@ -146,6 +147,9 @@ function parseResponses(responses){
}

var allEvents = component.getAllSubcomponents("vevent");
if (colorId != undefined)
allEvents.forEach(function(event){event.addPropertyWithValue("color", colorId);});

var calName = component.getFirstPropertyValue("x-wr-calname") || component.getFirstPropertyValue("name");
if (calName != null)
allEvents.forEach(function(event){event.addPropertyWithValue("parentCal", calName); });
Expand Down Expand Up @@ -192,11 +196,10 @@ function parseResponses(responses){
*
* @param {ICAL.Component} event - The event to process
* @param {string} calendarTz - The timezone of the target calendar
* @param {string} colorId - The colorId for the target calendar
*/
function processEvent(event, calendarTz, colorId){
function processEvent(event, calendarTz){
//------------------------ Create the event object ------------------------
var newEvent = createEvent(event, calendarTz, colorId);
var newEvent = createEvent(event, calendarTz);
if (newEvent == null)
return;

Expand Down Expand Up @@ -246,10 +249,9 @@ function processEvent(event, calendarTz, colorId){
*
* @param {ICAL.Component} event - The event to process
* @param {string} calendarTz - The timezone of the target calendar
* @param {string} colorId - The color id for the target calendar events
* @return {?Calendar.Event} The Calendar.Event that will be added to the target calendar
*/
function createEvent(event, calendarTz, colorId){
function createEvent(event, calendarTz){
event.removeProperty('dtstamp');
var icalEvent = new ICAL.Event(event, {strictExceptions: true});
if (onlyFutureEvents && checkSkipEvent(event, icalEvent)){
Expand Down Expand Up @@ -450,8 +452,10 @@ function createEvent(event, calendarTz, colorId){
newEvent.extendedProperties.private['rec-id'] = newEvent.extendedProperties.private['id'] + "_" + newEvent.recurringEventId;
}

newEvent.colorId = colorId;

if (event.hasProperty('color')){
newEvent.colorId = event.getFirstPropertyValue('color').toString();
}

return newEvent;
}

Expand Down Expand Up @@ -907,12 +911,14 @@ function callWithBackoff(func, maxRetries) {
return result;
}
catch(err){
if ( err.message.includes("is not a function") || !backoffRecoverableErrors.some(function(e){
return err.message.toLowerCase().includes(e);
err = err.message || err;
if ( err.includes("HTTP error") ) {
Logger.log(err);
return null;
} else if ( err.includes("is not a function") || !backoffRecoverableErrors.some(function(e){
return err.toLowerCase().includes(e);
}) ) {
throw err;
} else if ( err.message.includes("Forbidden") ) {
return null;
} else if ( tries > maxRetries) {
Logger.log(`Error, giving up after trying ${maxRetries} times [${err}]`);
return null;
Expand Down