Skip to content

Instantly share code, notes, and snippets.

@ckalegi
Created October 10, 2018 21:18
Show Gist options
  • Save ckalegi/3c8294961dd2105b663305a6988575ad to your computer and use it in GitHub Desktop.
Save ckalegi/3c8294961dd2105b663305a6988575ad to your computer and use it in GitHub Desktop.
Auto-archive past Gcal Invitations - for use in google apps scripts
function findInvites(e) {
console.log('Starting Calendar Archive');
// Find all calendar invitations
var threads = GmailApp.search("has:attachment .ics in:inbox");
console.log('Found ' + threads.length + ' calendar invitations');
for (var threadCounter = 0; threadCounter < threads.length; threadCounter++) {
var messages = threads[threadCounter].getMessages();
// iterate through each invit
for (var messageCounter = 0; messageCounter < messages.length; messageCounter++) {
// retrieve time info from subject line
var subj = messages[messageCounter].getSubject();
var subObj = subj.split('@').pop();
subObj = subObj.split('(')[0];
var subStr = subObj.toString();
// Ignore recurring invites and invoices
var ignore = /Weekly|Every|INVOICE/g;
if (!subStr.match(ignore)){
// Match the full date string fron invite
var dateRegex = /(Mon|Tue|Wed|Thu|Fri|Sat|Sun)\s(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\s+\d{1,2},\s\d{4}\s+(1[0-2]|0?[1-9])(:?|(am|pm))([0-5][0-9]|)(am|pm)/;
var dayStr = subStr.match(dateRegex)[0];
// Match the year from string
var yearRegex = /\d{4}/;
var year = dayStr.match(yearRegex)[0];
// Match the month from string
var monthDayRegex = /(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\s+\d{1,2}/;
var monthDay = dayStr.match(monthDayRegex)[0];
// Match the time from string
var timeRegex = /(1[0-2]|0?[1-9])(:?|(am|pm))([0-5][0-9]|)(am|pm)/;
var time = dayStr.match(timeRegex)[0];
// convert 12hr to 24hr
time = timeConvertor(time);
var dateStr = year+' '+monthDay+' '+time
// convert date string to date object
var dayDate = new Date(dateStr);
// Compare current time to date object
var todayDate = Date.now();
// If past, archive message
if (dayDate < todayDate){
GmailApp.moveThreadToArchive(threads[threadCounter])
console.log("Archiving: "+subj);
}
}
}
}
console.log('Calendar archive finished');
};
function timeConvertor(time) {
var output;
var PM = !time.match('am');
time = time.split(':')
if (time[1]) {
if (PM) {
var hour = 12 + parseInt(time[0],10)
var min = time[1].replace('pm', '')
} else {
var hour = time[0]
var min = time[1].replace('am', '')
}
output = hour + ':' + min + ':00';
} else {
if (PM) {
var hour = 12+parseInt(time[0].replace('pm', ''),10)
} else {
var hour = time[0].replace('am', '')
}
output = hour + ':00:00'
}
return output
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment