-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathcode.gs
428 lines (393 loc) · 14 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
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
/**
* @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 Code Generator';
/**
* A global constant 'notice' text to include with each email
* notification.
*/
var NOTICE = "Form Code Generator was created for lightweight use cases only. \
It should not be used for complex or important workflows, as the security of \
these hash codes are not generated per state-of-the-art standards \
(e.g., does not support nonce values). ";
/**
* 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 generator', '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();
}
/**
* 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')
.setSandboxMode(HtmlService.SandboxMode.IFRAME)
.setTitle('Form Code Generator');
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')
.setSandboxMode(HtmlService.SandboxMode.IFRAME)
.setWidth(420)
.setHeight(270);
FormApp.getUi().showModalDialog(ui, 'About Form Code Generator');
}
/**
* 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();
}
/**
* Convert the current form into a quiz.
*/
function convertToQuiz() {
var form = FormApp.getActiveForm();
if (form.isQuiz()) {
return 'Nice! Already a quiz.';
} else {
form.setIsQuiz(true);
return 'Converted to quiz.';
}
}
/**
* 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 code salt if the salt hasn't been provided yet.
if (!settings.codeSalt) {
settings.codeSalt = Session.getEffectiveUser().getEmail();
}
// Use a default code legnth if length hasn't been provided yet.
if (!settings.codeLength) {
settings.codeLength = 32;
}
if (!settings.emailMeAddress) {
settings.emailMeAddress = 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);
// 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 (existingTrigger) {
console.log("Removing old trigger")
ScriptApp.deleteTrigger(existingTrigger);
}
console.log("Adding new trigger");
var trigger = ScriptApp.newTrigger('respondToFormSubmit')
.forForm(form)
.onFormSubmit()
.create();
}
/**
* Responds to a form submission event if an 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 form = FormApp.getActiveForm();
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 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 have been granted, so continue to respond to
// the trigger event.
var code = '';
var message = '';
var passed = false;
var respondentEmail = getRespondentEmail(e.response);
// Generate a code if need be, and notify the respondent.
if (settings.getProperty('quizScore') != 'true') {
code = generateCode(e.response);
message = 'Thank you for submitting! (Tester: ' + respondentEmail + ') Here is your code.';
passed = true;
} else {
var percentage = evaluatePercentage(e.response);
var requiredPercentage = parseFloat(settings.getProperty('requiredScore'));
if (percentage >= requiredPercentage) {
code = generateCode(e.response);
message = 'Congratulations! (Tester: ' + respondentEmail + ') You received ' + percentage + '% and needed ' + requiredPercentage + '%. Here is your code.';
passed = true;
} else {
message = 'Ack. :( You received ' + percentage + '% but needed ' + requiredPercentage + '% . Please try again.';
}
}
// 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 (MailApp.getRemainingDailyQuota() > 0) {
sendNotification(respondentEmail, code, message);
}
// Check if the form creator needs to be notified.
if (MailApp.getRemainingDailyQuota() > 0 && settings.getProperty('emailMe') === 'true' && passed) {
var emailAddress = settings.getProperty('emailMeAddress');
if (!emailAddress) {
emailAddress = Session.getActiveUser().getEmail();
}
Logger.log('Sending email to' + emailAddress);
sendNotification(emailAddress, code, message);
}
}
}
/**
* Generate code for a successfully completed response.
*
* @param {FormResponse} response FormResponse object of the event
* that triggered this notification
*/
function generateCode(response) {
var settings = PropertiesService.getDocumentProperties();
var respondentEmail = getRespondentEmail(response);
var salt = settings.getProperty('codeSalt');
var length = settings.getProperty('codeLength');
return MD5(respondentEmail + salt + 'dEstr0yR@1nB0wTAb1es', length);
}
/**
* MD5 hash function
* https://stackoverflow.com/a/11868113/4855984
*
* @param {string} input The text to hash using md5
* @param {number} length Length of the outputted hash. Max 32.
*/
function MD5 (input="test", length=16) {
var rawHash = Utilities.computeDigest(Utilities.DigestAlgorithm.MD5, input);
var txtHash = '';
for (i = 0; i < rawHash.length; i++) {
var hashVal = rawHash[i];
if (hashVal < 0) {
hashVal += 256;
}
if (hashVal.toString(16).length == 1) {
txtHash += '0';
}
txtHash += hashVal.toString(16);
}
txtHash = txtHash.slice(0, length);
return txtHash;
}
/**
* Compute score for provided quiz.
*
* @param {FormResponse} response FormResponse object of the event
* that triggered this notification
*/
function evaluatePercentage(response) {
var totalScore = 0;
var maximumScore = 0;
var responseItems = response.getGradableItemResponses();
for (var i = 0; i < responseItems.length; i++) {
var itemResponse = responseItems[i];
var responseScore = itemResponse.getScore();
var itemMaximumScore = toItem(itemResponse.getItem()).getPoints();
totalScore += responseScore;
maximumScore += itemMaximumScore;
Logger.log('Response #%s to the question "%s" was "%s" (Score: %s/%s)',
(i + 1).toString(),
itemResponse.getItem().getTitle(),
itemResponse.getResponse(),
responseScore,
itemMaximumScore);
}
if (maximumScore == 0) {
return 0;
}
return totalScore / maximumScore * 100;
}
/**
* Extract point value for question.
*
* @param {Item} item The item associated with a form response.
*/
function toItem(item) {
if (item.getType() == FormApp.ItemType.CHECKBOX) {
return item.asCheckboxItem();
} else if (item.getType() == FormApp.ItemType.DATE) {
return item.asDateItem();
} else if (item.getType() == FormApp.ItemType.DATETIME) {
return item.asDateTimeItem();
} else if (item.getType() == FormApp.ItemType.DURATION) {
return item.asDurationItem();
} else if (item.getType() == FormApp.ItemType.LIST) {
return item.asListItem();
} else if (item.getType() == FormApp.ItemType.MULTIPLE_CHOICE) {
return item.asMultipleChoiceItem();
} else if (item.getType() == FormApp.ItemType.PARAGRAPH_TEXT) {
return item.asParagraphTextItem();
} else if (item.getType() == FormApp.ItemType.SCALE) {
return item.asScaleItem();
} else if (item.getType() == FormApp.ItemType.TEXT) {
return item.asTextItem();
} else if (item.getType() == FormApp.ItemType.TIME) {
return item.asTimeItem();
// end gradable items
} else if (item.getType() == FormApp.ItemType.GRID) {
return item.asGridItem();
} else if (item.getType() == FormApp.ItemType.IMAGE) {
return item.asImageItem();
} else if (item.getType() == FormApp.ItemType.PAGE_BREAK) {
return item.asPageBreakItem();
} else if (item.getType() == FormApp.ItemType.SECTION_HEADER) {
return item.asSectionHeaderItem();
} else if (item.getType() == FormApp.ItemType.VIDEO) {
return item.asVideoItem();
} else {
Logger.log('Impossibility! Found an item that doesn\'t exist');
}
}
/**
* 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);
}
}
/**
* Get email item from current form.
*/
function getEmailItem() {
var form = FormApp.getActiveForm();
var settings = PropertiesService.getDocumentProperties();
var emailId = settings.getProperty('respondentEmailItemId');
var emailItem = form.getItemById(parseInt(emailId));
return emailItem;
}
/**
* Get respondent email address from form response.
*
* @param {FormResponse} response FormResponse object of the event
* that triggered this notification
*/
function getRespondentEmail(response) {
var respondentEmail = response.getResponseForItem(getEmailItem())
.getResponse();
return respondentEmail;
}
/**
* Sends email to the provided email.
*
* @param {string} emailAddress The destination
* @param {string} code Newly generated to send
* @param {string} message Message placing the code in context
*/
function sendNotification(emailAddress, code, message) {
var form = FormApp.getActiveForm();
var settings = PropertiesService.getDocumentProperties();
if (emailAddress) {
var template =
HtmlService.createTemplateFromFile('RespondentNotification');
template.paragraphs = settings.getProperty('responseText').split('\n');
template.notice = NOTICE;
template.message = message;
template.code = code;
var message = template.evaluate();
MailApp.sendEmail(emailAddress,
settings.getProperty('responseSubject'),
message.getContent(), {
name: form.getTitle(),
htmlBody: message.getContent()
});
}
}