RSVP to Calendar Event with Google App Script - google-apps-script

Let me first express that programming is not my speciality so I will do my best to explain what I'm working on. At my employer, we have a company activity calendar on a free Gmail account and then we have separate accounts through Google Apps (paid) for each employee. I'm working on a script that pulls the events from said calendar, adds them to an agenda-styled email, and then sends the email to the Google Apps accounts. Our goal is to allow the employee to open the email, click an event he/she is interested in, and then RSVP to the event. It might be worth noting, the script is saved/running under the free account.
We have most of the code working but the RSVP feature is not appearing when the event is opened. We are making sure that the Google App account is logged in when the agenda email is viewed and that the account is an invited guest to the event. I suspect this is due to some type of authentication issue in the way we are generating the eventURL. I also believe this isn't working because the script is running as the "user" who already owns the calendar. If these two suspicions are true, I'm not sure how to fix it.
Here is the code for your review. I've removed the HTML formatting and our private calendar addresses.
function ordinal_suffix_of(i) {
var j = i % 10,
k = i % 100;
if (j == 1 && k != 11) {
return i + "st";
}
if (j == 2 && k != 12) {
return i + "nd";
}
if (j == 3 && k != 13) {
return i + "rd";
}
return i + "th";
}
function myFunction() {
var calendar = CalendarApp.getCalendarById('HIDDEN#group.calendar.google.com');
var now = new Date();
var oneWeekFromNow = new Date(now.getTime() + 604800000);
var twoWeeksFromNow = new Date(now.getTime() + 1209600000);
var threeWeeksFromNow = new Date(now.getTime() + 1814400000);
var eventsOneWeek = calendar.getEvents(now, oneWeekFromNow);
var eventsTwoWeeks = calendar.getEvents(oneWeekFromNow, twoWeeksFromNow);
var eventsThreeWeeks = calendar.getEvents(twoWeeksFromNow, threeWeeksFromNow);
var body = '';
for (i = 0; i < eventsOneWeek.length; i++) {
var day = ordinal_suffix_of(Utilities.formatDate(eventsOneWeek[i].getStartTime(), "GMT-0400", "d"));
var splitEventId = eventsOneWeek[i].getId().split('#');
var eventURL = "https://www.google.com/calendar/event?eid=" + Utilities.base64Encode(splitEventId[0] + " " + "HIDDEN#group.calendar.google.com");
var eventTitle = eventsOneWeek[i].getTitle();
var eventStart = Utilities.formatDate(eventsOneWeek[i].getStartTime(), "GMT-0400", "MMMMM");
eventStart += ' ' + day;
eventStart += Utilities.formatDate(eventsOneWeek[i].getStartTime(), "GMT-0400", " 'at' hh:mm a");
body += '';
}
for (i = 0; i < eventsTwoWeeks.length; i++) {
var day = ordinal_suffix_of(Utilities.formatDate(eventsTwoWeeks[i].getStartTime(), "GMT-0400", "d"));
var splitEventId = eventsTwoWeeks[i].getId().split('#');
var eventURL = "https://www.google.com/calendar/event?eid=" + Utilities.base64Encode(splitEventId[0] + " " + "HIDDEN#group.calendar.google.com");
var eventTitle = eventsTwoWeeks[i].getTitle();
var eventStart = Utilities.formatDate(eventsTwoWeeks[i].getStartTime(), "GMT-0400", "MMMMM");
eventStart += ' ' + day;
eventStart += Utilities.formatDate(eventsTwoWeeks[i].getStartTime(), "GMT-0400", " 'at' hh:mm a");
body += '';
}
for (i = 0; i < eventsThreeWeeks.length; i++) {
var day = ordinal_suffix_of(Utilities.formatDate(eventsThreeWeeks[i].getStartTime(), "GMT-0400", "d"));
var splitEventId = eventsThreeWeeks[i].getId().split('#');
var eventURL = "https://www.google.com/calendar/event?eid=" + Utilities.base64Encode(splitEventId[0] + " " + "HIDDEN#group.calendar.google.com");
var eventTitle = eventsThreeWeeks[i].getTitle();
var eventStart = Utilities.formatDate(eventsThreeWeeks[i].getStartTime(), "GMT-0400", "MMMMM");
eventStart += ' ' + day;
eventStart += Utilities.formatDate(eventsThreeWeeks[i].getStartTime(), "GMT-0400", " 'at' hh:mm a");
body += '';
}
GmailApp.sendEmail('HIDDEN#email.com', 'Testing Calendar Agenda', body,{'htmlBody':body});
}
Thank you in advance for any insight/help you can share! We greatly appreciate it!
Edit:
I copied the script over to my Google Apps account and adjusted the code to pull from my default calendar instead. I then created a new event on my calendar and invited my colleague to it. When I run the script and open the event, it displays an option to change my RSVP. When my colleague opens the same link, it displays the exact same option to change my RSVP status and nothing for his RSVP. This confirms that it's not isolated to the calendar or account and is specific to the link and how it's generated.

Related

Daily agenda for all Google owned calendars

I'm trying to get daily agenda of the events from all my calendars (personal, holidays, specific tasks etc) sent in one email.
I use the following code for one specific calendar, but don't know how to add all other owned calendars in the same code, is that even possible?
function sendAllCalendarsAgenda() {
var cal = CalendarApp.getOwnedCalendarById('?????????#group.calendar.google.com');
var events = cal.getEventsForDay(new Date());
var mailto = 'myEmailAddress#gmail.com';
if (events.length > 0) {
var body = 'Google Calendar - Events' + 'nn';
var tz = Session.getScriptTimeZone();
for (var i = 0; i < events.length; i++) {
body += Utilities.formatDate(events[i].getStartTime(), tz, 'MM:dd HH:mm') + ' ~ ';
body += Utilities.formatDate(events[i].getEndTime(), tz, 'MM:dd HH:mm') + ' :';
body += events[i].getTitle() + 'n';
}
MailApp.sendEmail(mailto, 'Google Calender - Summary', body);
}
}
Try this:
function sendAllCalendarsAgenda() {
const cals = CalendarApp.getAllCalendars();
let o = [];
var body = 'Google Calendar - Events Summary' + '\n\n';
cals.forEach(cal => {
var events = cal.getEventsForDay(new Date());
var mailto = 'myEmailAddress#gmail.com';
if (events.length > 0) {
var tz = Session.getScriptTimeZone();
for (var i = 0; i < events.length; i++) {
body += event[i].getTitle();
body += Utilities.formatDate(events[i].getStartTime(), tz, 'MM:dd HH:mm') + ' ~ ';
body += Utilities.formatDate(events[i].getEndTime(), tz, 'MM:dd HH:mm') + ' :';
}
o.push(body);
}
});
MailApp.sendEmail(mailto, 'Google Calendar - Summary', a.join('\n\n'));
}

Exception: Service invoked too many times for one day: gmail - Gmail Auto Archive

Triggering code below every 15 minutes to archive labels fed from a google sheet and getting this error:
Exception: Service invoked too many times for one day: gmail.
at archiveThreadsByLabel(archiveOldMessagesByLabelAndCategory:52:24)
at go(archiveOldMessagesByLabelAndCategory:21:15)
Any edit suggestions so I can run it every 15 minutes? Super new to this so any help would be greatly appreciated.
Original source:
https://github.com/warwickallen/GMail-Archive-old-messages-by-label-and-category
Code:
function go() {
var fname = "Archive old messages by label and category";
var files = DriveApp.getFilesByName(fname);
var spreadsheet;
while ((typeof spreadsheet !== 'object') && files.hasNext())
{
try
{
spreadsheet = SpreadsheetApp.openById(files.next().getId());
}
catch (e)
{
Logger.log("WARNING: " + e.message)
}
}
if (typeof spreadsheet !== 'object')
{
Logger.log("FATAL: Cannot find a Google speadsheet called '" + fname + "'.");
return -1;
}
var count = archiveThreadsByLabel(getSheetData(spreadsheet, "label"));
count += archiveThreadsByCategory(getSheetData(spreadsheet, "category"));
Logger.log("INFO: Archived " + count + " threads.");
}
function getSheetData(spreadsheet, sheet_name)
{
var data_array = spreadsheet.getSheetByName(sheet_name).getDataRange().getValues();
data_array.shift(); // Remove the headings row.
var data_object = new Object;
data_array.forEach(function(datum) {data_object[datum[0]] = datum[1]});
return data_object;
}
function archiveThreadsByLabel(minAgesInHours) {
var blockSize = 50;
var start = 0;
var count = 0;
while (1)
{
var threads = GmailApp.getInboxThreads(start, blockSize);
if (threads.length < 1) break;
start += threads.length;
for (var label in minAgesInHours)
{
var maxTime = new Date();
var localCount = 0;
maxTime.setTime(maxTime.getTime() - minAgesInHours[label]*3600000);
for (var i = 0; i < threads.length; i++)
if (threads[i].getLastMessageDate() < maxTime)
{
var labels = threads[i].getLabels();
for (var j = 0; j < labels.length; j++)
if (labels[j].getName() == label)
{
Logger.log("INFO:\n " + threads[i].getFirstMessageSubject() + "\n " + threads[i].getLastMessageDate());
threads[i].moveToArchive();
localCount++;
break;
}
}
Logger.log("INFO: Archived " + localCount + " threads labelled '" + label + "' that are older than " + maxTime);
count += localCount;
}
Utilities.sleep(1000); // Google doesn't like it if GmailApp API calls are called too often in a short period of time.
}
return count;
}
function archiveThreadsByCategory(minAgesInHours) {
var blockSize = 50;
var count = 0;
for (var category in minAgesInHours)
{
var start = 0;
var localCount = 0;
var maxTime = new Date();
maxTime.setTime(maxTime.getTime() - minAgesInHours[category]*3600000);
var query = 'in:inbox category:' + category + ' before:' + maxTime.getFullYear() + '-' + (maxTime.getMonth() + 1) + '-' + (maxTime.getDate() + 1);
while (1)
{
var threads = GmailApp.search(query, start, blockSize);
if (threads.length < 1) break;
start += threads.length;
for (var i = 0; i < threads.length; i++)
if (threads[i].getLastMessageDate() < maxTime)
{
Logger.log("\n " + threads[i].getFirstMessageSubject() + "\n " + threads[i].getLastMessageDate());
threads[i].moveToArchive();
localCount++;
}
Utilities.sleep(1000); // Google doesn't like it if GmailApp API calls are called too often in a short period of time.
}
Logger.log("INFO: Archived " + localCount + " threads categorisaed as '" + category + "' that are older than " + maxTime);
count += localCount;
}
return count;
}
We have quotas in apps script.
Your error means that you reached the quota of reading/writing emails in a day.
20000 for consumer/free edition, 50000 for workspace accounts.
Easiest thing you can do is make the trigger interval longer that it won't go past the quota.
Note:
The quota resets daily (as per name suggests) although I'm not sure what time exactly.
Use MailApp.getRemainingDailyQuota() to check the remaining quota you have. You can check what methods does affect the quota by checking this everytime a method is executed in a test script. That way, you can estimate what your interval should be so you will not get past it.

Apps Script - creating google form but get respond in same database (spreadsheet)

Overall idea:
Creating a form2 according to form1 that submitted by 1st user for higher level approval by sending form2 through email
Amended
problem:
I need to create form2 where all data vary according to what form1 responses, overall arrangement of form item question will be same, but content would be different. By chance if anyone know, I can amend a form (let's call v1) to person1, and amend the same form (v2) to person2, where I'm using same form ID for the purpose of approval workflow, in anywhere the details in v1 wont be updated as according to details in v2 (as generally google form will update all item question changes and republish automatically), maybe add UID to each form?
method tried: creating new form, too much spreadsheet that link to different form
method2 tried: using same form, changing the content inside, but error happen when amending form2 more than 1 time. when send out two form, the version1 of form2 would be live update to version2 of form2
Please help. if you have any other suggestion, please feedback.
Codes added later time:
function myFunction() {
var ss = SpreadsheetApp.openByUrl("https://docs.google.com/spreadsheets/d/1_ANufFqk/edit#gid=681916147");
var formsDB = SpreadsheetApp.openByUrl("https://docs.google.com/spreadsheets/d/1hGe1oStPoft9kfUNFA/edit#gid=138650439");
var ws = ss.getSheetByName('ManagerRequest');
var AllRange = ws.getRange(2, 1, ws.getRange("A1").getDataRegion().getLastRow(), 12).getValues();
var LastRequest = ws.getRange(1, 1, ws.getRange("B1").getDataRegion().getLastRow(), 12).getValues();
ws.getRange(1, 9).setValue("Operation Lead Approval");
ws.getRange(1, 10).setValue("NOC Approval");
var data = ws.getDataRange().getValues();
// to find last request proceed
LastTicket = LastRequest.length;
while(LastTicket > 0 && data[LastTicket][1] == "") {
LastTicket--;
if (data[LastTicket][1] == "Request Number"){ NewTicket = 0}
else {NewTicket = data[LastTicket][1]}
}
Logger.log("LastRequestNo " + LastTicket + " and NewRequestNo " + (+NewTicket + 1));
for (var i = (+LastTicket); i < AllRange.length - 1; i++) {
NewTicket += 1
ws.getRange(i+2, 2).setValue(NewTicket);
var session = AllRange[i];
var TicketNo = NewTicket;
var ManagerName = session[2];
var Country = session[4];
var RequestReason = session[5];
var ManRequest = session[6];
var OperationLead = session[7];
Logger.log("Request Number " + NewTicket + "; " + ManagerName + " is requesting " + ManRequest + " manpower for country " + Country + " because " + RequestReason );
var form = FormApp.openByUrl('https://docs.google.com/forms/d/1xeNFpSxxmQUqfDdFo504/edit')
var formid = form.getId();
Logger.log(formid);
form.getTitle('Request ticket:-').setHelpText(NewTicket);
form.getTitle('Detail for recruitment:-').setHelpText("Requester: " + ManagerName + "\nManpower Requesting: " + ManRequest + "\nCountry: " + Country + "\nReason: " + RequestReason);
var publishURL = form.getPublishedUrl();
GmailApp.sendEmail(OperationLead, 'Manpower request from ' + Country , "Hi "+Country +" Operation Lead,\n\n\nPlease review the google form link below and make decision upon the request.\n "+publishURL+"\n\nThanks and Regards,\nHuman Resource Auto Sender");
ScriptApp.newTrigger('onFormSubmit').forForm(FormApp.getActiveForm()).onFormSubmit().create();
}
}
function onFormSubmit(e){
//var forms = FormApp.openById(e);
var forms = FormApp.getActiveForm();
var formResponses = forms.response();
for (var i=0; i < formResponses.length; i++){
var formResponse = formResponses[i];
var itemReponses = formResponse.getItemResponses();
for ( var j = 0; j < itemResponses.length; j ++){
itemReponse = itemReponses[j];
Logger.log('Response #%s to the question "%s" was "%s"',
(i + 1).toString(),
itemResponse.getItem().getTitle(),
itemResponse.getResponse());
}
}
var formsDB = SpreadsheetApp.openByUrl("https://docs.google.com/spreadsheets/d/1hGe1oPoft9kfUNFA/edit#gid=138650439");
var ss = SpreadsheetApp.openByUrl("https://docs.google.com/spreadsheets/d/1ebobAddzEP3i_ANufFqk/edit#gid=681916147");
var ws = ss.getSheetByName('ManagerRequest');
var AllRange = ws.getRange(2, 1, ws.getRange("A1").getDataRegion().getLastRow(), 12).getValues();
for (var j=1; j< AllRange.length; j++){
if (ws.getRange(j, 2).getValue() == ResponsesTicket)
{ws.getRange(j, 9).setValue(OlApproval);
ws.getRange(j, 10).setValue(Comment);}
}
}

Script for scheduling busy times, similar to a calendar

I am working on a "vehicle scheduler" for my workplace that will display the dates and times a truck will be unavailable. Here's the link to the Google Sheets where the script runs. I have set up two example "busy times" to show what I am doing
One adjustment that was requested from me is to do 30 minute increments, but then the amount of columns gets absolutely bonkers.
I am open to any recommendations to improve this tool, even if it means something better (and free) already exists.
I appreciate your input!
See code below... (I am RIDICULOUSLY novice at coding, so be kind :)
function processForm(formObject){
var day = formObject.dow;
var vehicle = formObject.vehicle;
var jobName = formObject.job;
var driverName = formObject.driver;
var duration = formObject.duration;
var startTime = formObject.startTime;
var ampm = formObject.ampm;
var location = formObject.location;
var returnArray = [day, vehicle, jobName, driverName, duration, startTime, ampm, location]
var startTimeColumn = 0;
var startDayColumn = 2;
var sduration = startTime;
var ss = SpreadsheetApp.getActive().getSheetByName("Week View");
if (day=="Monday"){
startDayColumn = 26;
}
else if (day=="Tuesday"){
startDayColumn = 50;
}
else if (day=="Wednesday"){
startDayColumn = 74;
}
else if (day=="Thursday"){
startDayColumn = 98;
}
else if (day=="Friday"){
startDayColumn = 122;
}
else if (day=="Saturday"){
startDayColumn = 146;
}
if (ampm=="PM"){
startDayColumn+=12;
}
if (startTime==12){
startTime = 0;
}
startTimeColumn = parseInt(startTimeColumn) + parseInt(startDayColumn) + parseInt(startTime);
var columnA = ss.getRange(1,1,ss.getLastRow(),1).getValues();
for (var rr=0;rr<ss.getLastRow();rr++){
if (columnA[rr]==vehicle){
break;
}
}
rr +=1;
for (var cc=0; cc<duration; cc++){
var checkColumn = parseInt(cc) + parseInt(startTimeColumn);
if (ss.getRange(rr, checkColumn).isBlank()){}
else return "It looks like that time is booked :(";
}
var displayString = "Job: " + jobName + String.fromCharCode(10) + "Driver: " + driverName + String.fromCharCode(10) + sduration + ":00 " + ampm + String.fromCharCode(10) + location;
var merging = ss.getRange(rr,startTimeColumn,1,duration).mergeAcross();
var enterInfo = ss.getRange(rr, startTimeColumn).setValue(displayString);
if (rr % 2 == 0){
enterInfo.setBackgroundRGB(45, 114, 157);
}
else {enterInfo.setBackgroundRGB(26, 153, 136);}
enterInfo.setFontColor('white')
return "Success! Load has been booked to the scheduler.";
}
Instead of making Sheets jump thru hoops and create a interface for inserting data and a Calendar to show it, why not use Forms and Calendar to do it all?
What I have in mind
Sheets as a long-time database for Truck Information and schedules
Calendar as a way to visualize the availability of Trucks
Forms as a interface for data-input
Set-up
A Spreadsheet file with a "List of Trucks" Sheet.
A Form attached to it that allows users to insert information about the truck booking.
To make this work, I have inputted some data on out List of Trucks:
Then I associated a form with that sheet and setup some basic questions:
I also modified the forms settings to allow people to edit it on the future, this will allow us to add information to the calendar to tie an event with a response form the form.
I added a script to the Forms that populates the first question with the data from our sheets:
function populateForm() {
var form = FormApp.getActiveForm();
var TruckIdQ = form.getItems()[0];
var truckList = SpreadsheetApp.openByUrl("YOUR SHEET URL").getSheetByName("List of Trucks").getDataRange().getValues().map(function (row) { return row[0]});
truckList.shift(); //Remove header
var choices = [];
for (var i=0; i< truckList.length; i++) {
choices.push(TruckIdQ.asListItem().createChoice(truckList[i]));
}
TruckIdQ.asListItem().setChoices(choices);
}
And set it to be run when the form is opened:
After that I went back to my sheets and modified the automatic Responses sheet to have a more understandable name: "Bookings".
Now we need to create a shared calendar to put all this information on it.
I created one named "Truck Booking Calendar" in the following way:
I then created a new Script on the Forms responsible for populating the calendar with information.
function populateCalendar(e) {
var bookingCalendar = CalendarApp.getCalendarById("CALENDAR ID");
var questions = FormApp.getActiveForm().getItems();
var response = e.response.getItemResponses();
var eventDescription = "";
var truckname;
var fromDate, toDate;
var fromTime, toTime;
for (var i=0; i< questions.length; i++) {
eventDescription = eventDescription + questions[i].getTitle() + " : " + response[i].getResponse() + "\n";
switch (i) {
case 0:
//Truck Id
truckname = response[i].getResponse();
break;
case 1:
//From Date
fromDate = response[i].getResponse();
break;
case 2:
//To Date
toDate = response[i].getResponse();
break;
case 3:
//From Time
fromTime = response[i].getResponse();
break;
case 4:
//To Time
toTime = response[i].getResponse();
break;
}
}
var startDateTime = new Date(fromDate + " " + fromTime);
var endDateTime = new Date(toDate + " " + toTime);
var newEvent = bookingCalendar.createEvent("Booking "+truckname, startDateTime, endDateTime, {description:eventDescription});
newEvent.setTag("truck", truckname);
newEvent.setTag("responseId", e.response.getEditResponseUrl());
newEvent.setTag("responseUrl", e.response.getId());
}
And created a trigger for it like this:
Now, when I submit this into the form:
I get this entry on my calendar:
Hope this helps you!

Google Apps script stops randomly or refuses to launch

I have developed a Google Apps script in a Google Drive spreadsheet that processes e-mails with a certain label (download notifications) and adds these to the spreadsheet. I'm running this through the script editor of the spreadsheet.
My initial solution was quite inefficient - the whole analysis was repeated each time on all e-mails, which caused the runtime to increase for each day. A few days ago I got an error message "runtime exceeded", which is not strange.
My problem is that when trying to update the script to be more efficient, I get some weird problems. The script either stops randomly after processing a few e-mails, or simply refuses to start. Especially the script debugger, it begins to load but never starts.
I have tried several times over the last few days, and even created a new spreadsheet with the same code (in the same account), but still having these problems.
Sometimes when the script manages to run for a while, I have noted that the script output log does not match recent changes in the logging. I have of course saved the script before running it. It feels like there is some lock preventing my script from running/updating/refreshing?
Is there anyone here that recognize these problems?
The code is attached below.
The two relevant entry points are:
processInbox: Updates the spreadsheet based on new (starred) e-mails with a specific label. The label and star is set by an e-mail filter on reception. The star (indicating "new") is removed from each message after processing.
resetAllMsgs: Clears the spreadsheet and stars all relevant messages, causing processInbox to process all messages received with the relevant label.
function resetAllMsgs() {
Logger.log("Starting ResetAll");
var d = SpreadsheetApp.getActive();
var dl_sheet = d.getSheetByName("Download List");
var dlperday_sheet = d.getSheetByName("DownloadsPerDay");
dl_sheet.clear();
dlperday_sheet.clear();
Logger.log("Clearing spreadsheet");
dl_sheet.appendRow(["", "", "Downloads", ""]);
dl_sheet.appendRow(["", "", "Downloaders", ""]);
dl_sheet.appendRow(["Last Download Date", "First Download Date", "Email" , "Product", "Download Count"]);
dlperday_sheet.appendRow(["Date", "Download Count"]);
var label = GmailApp.getUserLabelByName("Download Notification");
// get all threads of the label
var threads = label.getThreads();
for (var i = 0; i < threads.length; i++) {
// get all messages in a given thread
var messages = threads[i].getMessages();
Logger.log("Starring thread " + i);
for (var j = 0; j < messages.length; j++) {
Logger.log(" Starring message " + j);
// Only starred messages are processed by processInbox
messages[j].star();
Utilities.sleep(100);
}
}
};
function processInbox() {
var d = SpreadsheetApp.getActive();
var dl_sheet = d.getSheetByName("Download List");
var dlperday_sheet = d.getSheetByName("DownloadsPerDay");
// If empty spreadsheet, reset the status of all relevant e-mails and add the spreadsheet headers
if (dl_sheet.getLastRow() <= 1) {
resetAll();
}
var label = GmailApp.getUserLabelByName("Download Notification");
var k = 0;
// get all threads of the label
var threads = label.getThreads();
for (var i = 0; i < threads.length; i++) {
if (threads[i].hasStarredMessages()) {
// get all messages in a given thread
var messages = threads[i].getMessages();
// iterate over each message
for (var j = 0; j < messages.length; j++) {
// Unread messages are not previously processed...
if (messages[j].isStarred()) {
var msg = messages[j].getBody();
msg = msg.replace(/\r?\n/g, "");
var email = getDownloader(msg);
if (email == "") {
Logger.log("Found no downloader info: " + messages[j].getSubject() + " " + messages[j].getDate());
}
var date = formatDate(getDownloadDate(msg));
// Check if a new date
var dateCell = find(date, dlperday_sheet.getDataRange(), 0);
if (dateCell == null) {
// If new date, append row in "downloads per day"
dlperday_sheet.appendRow([date, 1]);
dlperday_sheet.getRange(2, 1, dl_sheet.getLastRow()-1, 2).sort([1]);
}
else
{
// If existing date, update row in "downloads per day"
var dlcount = dlperday_sheet.getRange(dateCell.getRow(), dateCell.getColumn()+1).getValue();
}
var productname = getProductName(msg);
// Check if e-mail (user) already exists in the downloads list
var matchingCell = find(email, dl_sheet.getDataRange(), 0);
if ( matchingCell != null ) {
// If user e-mail exists, update this row
var lastDownloadDate = dl_sheet.getRange(matchingCell.getRow(), matchingCell.getColumn()-1).getValue();
var lastDownloadCount = dl_sheet.getRange(matchingCell.getRow(), matchingCell.getColumn()+2).getValue();
if (lastDownloadDate != date) {
dl_sheet.getRange(matchingCell.getRow(), matchingCell.getColumn()-1).setValue(date);
}
dl_sheet.getRange(matchingCell.getRow(), matchingCell.getColumn()+2).setValue(lastDownloadCount+1);
}
else // If new user e-mail, add new download row
{
dl_sheet.appendRow([date, date, email, productname, 1]);
dl_sheet.getRange(2, 4).setValue(dl_sheet.getRange(2, 4).getValue() + 1);
dl_sheet.getRange(4, 1, dl_sheet.getLastRow()-3, 5).sort([1]);
}
// Mark message as processed, to avoid processing it on the next run
messages[j].unstar();
}
}
}
}
};
/**
* Finds a value within a given range.
* #param value The value to find.
* #param range The range to search in.
* #return A range pointing to the first cell containing the value,
* or null if not found.
*/
function find(value, range, log) {
var data = range.getValues();
for (var i = 0; i < data.length; i++) {
for (var j = 0; j < data[i].length; j++) {
if (log == 1)
{
Logger.log("Comparing " + data[i][j] + " and " + value);
}
if (data[i][j] == value) {
return range.getCell(i + 1, j + 1);
}
}
}
return null;
};
function getDownloader(bodystring) {
var marker = "Buyer Info";
var marker_begin_index = bodystring.indexOf(marker, 1000);
var email_begin_index = bodystring.indexOf("mailto:", marker_begin_index) + 7;
var email_end_index = bodystring.indexOf("\"", email_begin_index);
if (email_end_index < 1000)
{
return "";
}
var email = bodystring.substring(email_begin_index, email_end_index);
if (log == 1)
{
Logger.log("Found e-mail address: " + email + "");
Logger.log(" marker_begin_index: " + marker_begin_index);
Logger.log(" email_begin_index: " + email_begin_index);
Logger.log(" email_end_index: " + email_end_index);
}
latestIndex = email_end_index;
return email;
};
function formatDate(mydate)
{
var str = "" + mydate;
var dateParts = str.split("/");
var day = dateParts[1];
if (day.length == 1)
day = "0" + day;
var month = dateParts[0];
if (month.length == 1)
month = "0" + month;
return dateParts[2] + "-" + month + "-" + day;
};
function getDownloadDate(bodystring) {
var marker = "Download Date:</strong>";
var marker_begin_index = bodystring.indexOf(marker, latestIndex);
var date_begin_index = marker_begin_index + marker.length;
var date_end_index = bodystring.indexOf("<br>", date_begin_index);
latestIndex = date_end_index;
return bodystring.substring(date_begin_index, date_end_index).trim();
};
function getProductName(bodystring) {
var marker = "Item:</strong>";
var marker_begin_index = bodystring.indexOf(marker, latestIndex);
var pname_begin_index = marker_begin_index + marker.length;
var pname_end_index = bodystring.indexOf("</td>", pname_begin_index);
latestIndex = pname_end_index;
return bodystring.substring(pname_begin_index, pname_end_index).trim();
};
Update: Any script I run stops after about 5 seconds, even if it does not call any services.
I tried the following code:
function test() {
Logger.log("Test begins");
Utilities.sleep(5000);
Logger.log("Test ends");
}
The script terminates after about 5 sec, but the last line is not printed. If decreasing the delay to 3 seconds it behaves as expected.
Moreover, to make the script update properly after modifying it, I need to save it, start it, click cancel, and then start it again, otherwise it the log output seems to come from the old version. (I'm running this through the script editor.)
Also, the debugger refuses to start, even for the small script above. Seems to be some problem with my account (johan.kraft#percepio.se). Are there any google employee out there that can check this?