-
Notifications
You must be signed in to change notification settings - Fork 0
/
Code.gs
287 lines (265 loc) · 10.1 KB
/
Code.gs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
/**
* @OnlyCurrentDoc
*
* The above comment directs Apps Script to limit the scope of file
* access for this add-on. It specifies that this add-on will only
* attempt to read or modify the files in which the add-on is used,
* and not all of the user's files. The authorization request message
* presented to users will reflect this limited scope.
*/
/**
* A global constant String holding the title of the add-on. This is
* used to identify the add-on in the notification emails.
*/
var ADDON_TITLE = 'Form Notifications';
/**
* A global constant 'notice' text to include with each email
* notification.
*/
var NOTICE = "Form Notifications was created as an sample add-on, and is meant for \
demonstration purposes only. It should not be used for complex or important \
workflows. The number of notifications this add-on produces are limited by the \
owner's available email quota; it will not send email notifications if the \
owner's daily email quota has been exceeded. Collaborators using this add-on on \
the same form will be able to adjust the notification settings, but will not be \
able to disable the notification triggers set by other collaborators.";
/**
* Adds a custom menu to the active form to show the add-on sidebar.
*
* @param {object} e The event parameter for a simple onOpen trigger. To
* determine which authorization mode (ScriptApp.AuthMode) the trigger is
* running in, inspect e.authMode.
*/
function onOpen(e) {
FormApp.getUi()
.createAddonMenu()
.addItem('Configure notifications', 'showSidebar')
.addItem('About', 'showAbout')
.addToUi();
}
/**
* Runs when the add-on is installed.
*
* @param {object} e The event parameter for a simple onInstall trigger. To
* determine which authorization mode (ScriptApp.AuthMode) the trigger is
* running in, inspect e.authMode. (In practice, onInstall triggers always
* run in AuthMode.FULL, but onOpen triggers may be AuthMode.LIMITED or
* AuthMode.NONE).
*/
function onInstall(e) {
onOpen(e);
}
/**
* Opens a sidebar in the form containing the add-on's user interface for
* configuring the notifications this add-on will produce.
*/
function showSidebar() {
var ui = HtmlService.createHtmlOutputFromFile('Sidebar')
.setTitle('Form Notifications');
FormApp.getUi().showSidebar(ui);
}
/**
* Opens a purely-informational dialog in the form explaining details about
* this add-on.
*/
function showAbout() {
var ui = HtmlService.createHtmlOutputFromFile('About')
.setWidth(420)
.setHeight(270);
FormApp.getUi().showModalDialog(ui, 'About Form Notifications');
}
/**
* Save sidebar settings to this form's Properties, and update the onFormSubmit
* trigger as needed.
*
* @param {Object} settings An Object containing key-value
* pairs to store.
*/
function saveSettings(settings) {
PropertiesService.getDocumentProperties().setProperties(settings);
adjustFormSubmitTrigger();
}
/**
* Queries the User Properties and adds additional data required to populate
* the sidebar UI elements.
*
* @return {Object} A collection of Property values and
* related data used to fill the configuration sidebar.
*/
function getSettings() {
var settings = PropertiesService.getDocumentProperties().getProperties();
// Use a default email if the creator email hasn't been provided yet.
if (!settings.creatorEmail) {
settings.creatorEmail = Session.getEffectiveUser().getEmail();
}
// Get text field items in the form and compile a list
// of their titles and IDs.
var form = FormApp.getActiveForm();
var textItems = form.getItems(FormApp.ItemType.TEXT);
settings.textItems = [];
for (var i = 0; i < textItems.length; i++) {
settings.textItems.push({
title: textItems[i].getTitle(),
id: textItems[i].getId()
});
}
return settings;
}
/**
* Adjust the onFormSubmit trigger based on user's requests.
*/
function adjustFormSubmitTrigger() {
var form = FormApp.getActiveForm();
var triggers = ScriptApp.getUserTriggers(form);
var settings = PropertiesService.getDocumentProperties();
var triggerNeeded =
settings.getProperty('creatorNotify') == 'true' ||
settings.getProperty('respondentNotify') == 'true';
// Create a new trigger if required; delete existing trigger
// if it is not needed.
var existingTrigger = null;
for (var i = 0; i < triggers.length; i++) {
if (triggers[i].getEventType() == ScriptApp.EventType.ON_FORM_SUBMIT) {
existingTrigger = triggers[i];
break;
}
}
if (triggerNeeded && !existingTrigger) {
var trigger = ScriptApp.newTrigger('respondToFormSubmit')
.forForm(form)
.onFormSubmit()
.create();
} else if (!triggerNeeded && existingTrigger) {
ScriptApp.deleteTrigger(existingTrigger);
}
}
/**
* Responds to a form submission event if a onFormSubmit trigger has been
* enabled.
*
* @param {Object} e The event parameter created by a form
* submission; see
* https://developers.google.com/apps-script/understanding_events
*/
function respondToFormSubmit(e) {
var settings = PropertiesService.getDocumentProperties();
var authInfo = ScriptApp.getAuthorizationInfo(ScriptApp.AuthMode.FULL);
// Check if the actions of the trigger require authorizations that have not
// been supplied yet -- if so, warn the active user via email (if possible).
// This check is required when using triggers with add-ons to maintain
// functional triggers.
if (authInfo.getAuthorizationStatus() ==
ScriptApp.AuthorizationStatus.REQUIRED) {
// Re-authorization is required. In this case, the user needs to be alerted
// that they need to reauthorize; the normal trigger action is not
// conducted, since it authorization needs to be provided first. Send at
// most one 'Authorization Required' email a day, to avoid spamming users
// of the add-on.
sendReauthorizationRequest();
} else {
// All required authorizations has been granted, so continue to respond to
// the trigger event.
// Check if the form creator needs to be notified; if so, construct and
// send the notification.
if (settings.getProperty('creatorNotify') == 'true') {
sendCreatorNotification();
}
// Check if the form respondent needs to be notified; if so, construct and
// send the notification. Be sure to respect the remaining email quota.
if (settings.getProperty('respondentNotify') == 'true' &&
MailApp.getRemainingDailyQuota() > 0) {
sendRespondentNotification(e.response);
}
}
}
/**
* Called when the user needs to reauthorize. Sends the user of the
* add-on an email explaining the need to reauthorize and provides
* a link for the user to do so. Capped to send at most one email
* a day to prevent spamming the users of the add-on.
*/
function sendReauthorizationRequest() {
var settings = PropertiesService.getDocumentProperties();
var authInfo = ScriptApp.getAuthorizationInfo(ScriptApp.AuthMode.FULL);
var lastAuthEmailDate = settings.getProperty('lastAuthEmailDate');
var today = new Date().toDateString();
if (lastAuthEmailDate != today) {
if (MailApp.getRemainingDailyQuota() > 0) {
var template =
HtmlService.createTemplateFromFile('AuthorizationEmail');
template.url = authInfo.getAuthorizationUrl();
template.notice = NOTICE;
var message = template.evaluate();
MailApp.sendEmail(Session.getEffectiveUser().getEmail(),
'Authorization Required',
message.getContent(), {
name: ADDON_TITLE,
htmlBody: message.getContent()
});
}
settings.setProperty('lastAuthEmailDate', today);
}
}
/**
* Sends out creator notification email(s) if the current number
* of form responses is an even multiple of the response step
* setting.
*/
function sendCreatorNotification() {
var form = FormApp.getActiveForm();
var settings = PropertiesService.getDocumentProperties();
var responseStep = settings.getProperty('responseStep');
responseStep = responseStep ? parseInt(responseStep) : 10;
// If the total number of form responses is an even multiple of the
// response step setting, send a notification email(s) to the form
// creator(s). For example, if the response step is 10, notifications
// will be sent when there are 10, 20, 30, etc. total form responses
// received.
if (form.getResponses().length % responseStep == 0) {
var addresses = settings.getProperty('creatorEmail').split(',');
if (MailApp.getRemainingDailyQuota() > addresses.length) {
var template =
HtmlService.createTemplateFromFile('CreatorNotification');
template.summary = form.getSummaryUrl();
template.responses = form.getResponses().length;
template.title = form.getTitle();
template.responseStep = responseStep;
template.formUrl = form.getEditUrl();
template.notice = NOTICE;
var message = template.evaluate();
MailApp.sendEmail(settings.getProperty('creatorEmail'),
form.getTitle() + ': Form submissions detected',
message.getContent(), {
name: ADDON_TITLE,
htmlBody: message.getContent()
});
}
}
}
/**
* Sends out respondent notificiation emails.
*
* @param {FormResponse} response FormResponse object of the event
* that triggered this notification
*/
function sendRespondentNotification(response, aboutText) {
var form = FormApp.getActiveForm();
var settings = PropertiesService.getDocumentProperties();
var emailId = settings.getProperty('respondentEmailItemId');
var emailItem = form.getItemById(parseInt(emailId));
var respondentEmail = response.getResponseForItem(emailItem)
.getResponse();
if (respondentEmail) {
var template =
HtmlService.createTemplateFromFile('RespondentNotification');
template.paragraphs = settings.getProperty('responseText').split('\n');
template.notice = NOTICE;
var message = template.evaluate();
MailApp.sendEmail(respondentEmail,
'Thank you for filling out form ' + form.getTitle() + '!',
message.getContent(), {
name: form.getTitle(),
htmlBody: message.getContent()
});
}
}