forked from rajks24/google-forms-quiz-builder
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCode.js
More file actions
1115 lines (1023 loc) · 34.5 KB
/
Copy pathCode.js
File metadata and controls
1115 lines (1023 loc) · 34.5 KB
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
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/***** CONFIG *****/
const TEMPLATE_FORM_ID = ""; // '' to disable
const MAKE_PUBLIC_ANYONE_WITH_LINK = true; // set false if you only want your domain/responders list
/***** MENU *****/
function onOpen() {
SpreadsheetApp.getUi()
.createMenu("Form Builder")
.addItem("Create Form (Confirm)", "confirmAndCreateForm")
.addItem(
"Create Form & Post to Classroom",
"confirmCreateAndPostToClassroom",
)
.addSeparator()
.addItem("Post Last Form to Classroom", "postLastFormToClassroom")
.addToUi();
}
/***** ENTRYPOINT *****/
function confirmAndCreateForm() {
const ui = SpreadsheetApp.getUi();
const res = ui.alert(
"Create Form",
"Create a new Google Form quiz and link responses to this spreadsheet (new tab)?",
ui.ButtonSet.OK_CANCEL,
);
if (res !== ui.Button.OK) return;
try {
const result = createFormFromActiveSpreadsheet();
storeLastFormResult(result);
SpreadsheetApp.getActive().toast(
"Form created successfully.",
"Form Builder",
5,
);
ui.alert(
"Success",
"Form created. Responses will be stored in this spreadsheet (new tab).\n\n" +
"Form (student link):\n" +
result.publishedUrl +
"\n\n" +
"Form (edit link):\n" +
result.editUrl +
"\n\n" +
"Responses (this file):\n" +
result.responsesUrl +
"\n",
ui.ButtonSet.OK,
);
} catch (e) {
SpreadsheetApp.getActive().toast(
"Form creation failed.",
"Form Builder",
5,
);
ui.alert("Error", e && e.message ? e.message : String(e), ui.ButtonSet.OK);
}
}
/***** CORE LOGIC (Section, Question, Type, Points, AnswerA..D) *****/
function createFormFromActiveSpreadsheet() {
const ss = SpreadsheetApp.getActiveSpreadsheet();
// Find a sheet with our header
let sh = ss.getActiveSheet();
let values = sh.getDataRange().getDisplayValues();
let cfg = findConfig(values);
if (!cfg) {
for (const s of ss.getSheets()) {
const v = s.getDataRange().getDisplayValues();
const c = findConfig(v);
if (c) {
sh = s;
values = v;
cfg = c;
break;
}
}
}
if (!cfg)
throw new Error(
"Header row not found. Expected columns: Section, Question, Type, Points, AnswerA..D",
);
const {
formTitle = "Untitled Quiz",
formDescription = "",
limitOneResponse,
headerRowIndex,
} = cfg;
// Column indexes (by name)
const header = values[headerRowIndex].map(String);
const idx = headerIndex(header, [
"Section",
"Question",
"Type",
"Points",
"AnswerA",
"AnswerB",
"AnswerC",
"AnswerD",
]);
// Optional columns (question image + answer image mode)
const optIdx = optionalHeaderIndex(header, [
"ImageURL",
"AnswerAImageURL",
"AnswerBImageURL",
"AnswerCImageURL",
"AnswerDImageURL",
]);
// Section totals for headers
const sectionTotals = computeSectionTotals(values, headerRowIndex, idx);
// 1) Create shell (template copy or fresh)
const form = createFormShell(formTitle, formDescription, ss.getId());
const formId = form.getId();
// 2) Destination + basic settings (no publish yet)
form.setIsQuiz(true);
form.setCollectEmail(true);
if (parseBool(limitOneResponse, false)) form.setLimitOneResponsePerUser(true);
form.setProgressBar(true);
// Link responses to THIS spreadsheet
try {
form.setDestination(FormApp.DestinationType.SPREADSHEET, ss.getId());
} catch (_) {
Utilities.sleep(400);
form.setDestination(FormApp.DestinationType.SPREADSHEET, ss.getId());
}
// Student details (ensures at least one item exists)
form
.addSectionHeaderItem()
.setTitle("Student Details")
.setHelpText("Please enter your name before you begin.");
form.addTextItem().setTitle("Student Name").setRequired(true);
// 3) Build questions
let currentSection = null;
for (let r = headerRowIndex + 1; r < values.length; r++) {
const row = values[r];
if (!row || row.length === 0 || row.every((v) => v === "" || v == null))
continue;
const section = (row[idx.Section] || "").toString().trim();
const question = (row[idx.Question] || "").toString().trim();
const type = (row[idx.Type] || "").toString().trim().toUpperCase();
const pts = Number((row[idx.Points] || "").toString().trim()) || 0;
const rawAns = [
(row[idx.AnswerA] || "").toString().trim(),
(row[idx.AnswerB] || "").toString().trim(),
(row[idx.AnswerC] || "").toString().trim(),
(row[idx.AnswerD] || "").toString().trim(),
];
const rawAnsImageUrls = [
getOptionalCell(row, optIdx.AnswerAImageURL),
getOptionalCell(row, optIdx.AnswerBImageURL),
getOptionalCell(row, optIdx.AnswerCImageURL),
getOptionalCell(row, optIdx.AnswerDImageURL),
];
const hasAnswerImages = rawAnsImageUrls.some(Boolean);
const questionImageUrl = getOptionalCell(row, optIdx.ImageURL);
if (!section)
throw new Error(
`Missing "Section" in row ${r + 1} on sheet "${sh.getName()}"`,
);
if (!type)
throw new Error(
`Missing "Type" in row ${r + 1} on sheet "${sh.getName()}"`,
);
if (!question)
throw new Error(
`Missing "Question" in row ${r + 1} on sheet "${sh.getName()}"`,
);
if (section !== currentSection) {
currentSection = section;
const total = sectionTotals[section] || 0;
form
.addPageBreakItem()
.setTitle(`${section} Section — ${total} pts total`)
.setHelpText("Answer all questions. Marks vary.");
}
const title = pts > 0 ? `${question} (${pts} pts)` : question;
switch (type) {
case "SA": {
const item = form.addTextItem().setTitle(title).setRequired(true);
safeSetPoints(item, pts);
if (questionImageUrl) {
addQuestionImageItem(form, question, questionImageUrl, r + 1);
}
break;
}
case "PARA": {
const item = form
.addParagraphTextItem()
.setTitle(title)
.setRequired(true);
safeSetPoints(item, pts);
if (questionImageUrl) {
addQuestionImageItem(form, question, questionImageUrl, r + 1);
}
break;
}
case "MCQ": {
const mcqData = buildAnswerEntries(rawAns, rawAnsImageUrls, "MCQ");
const entries = mcqData.entries;
if (entries.length < 2) {
const item = form.addTextItem().setTitle(title).setRequired(true);
safeSetPoints(item, pts);
break;
}
const mcq = form
.addMultipleChoiceItem()
.setTitle(title)
.setRequired(true);
let formChoices = entries.map((entry) =>
mcq.createChoice(
formatChoiceText(entry, hasAnswerImages),
entry.isCorrect,
),
);
if (formChoices.length > 1) formChoices = shuffleArrayCopy(formChoices);
mcq.setChoices(formChoices);
safeSetPoints(mcq, pts);
if (questionImageUrl) {
addQuestionImageItem(form, question, questionImageUrl, r + 1);
}
if (hasAnswerImages) {
addAnswerImageItems(form, rawAns, rawAnsImageUrls, r + 1);
}
break;
}
case "MSQ": {
const msqData = buildAnswerEntries(rawAns, rawAnsImageUrls, "MSQ");
const cleaned = msqData.entries;
if (cleaned.length < 2) {
const item = form.addTextItem().setTitle(title).setRequired(true);
safeSetPoints(item, pts);
break;
}
if (!msqData.hasExplicitCorrectChoices) {
const mcq = form
.addMultipleChoiceItem()
.setTitle(title)
.setRequired(true);
let choices = cleaned.map((entry) =>
mcq.createChoice(
formatChoiceText(entry, hasAnswerImages),
entry.isCorrect,
),
);
if (choices.length > 1) choices = shuffleArrayCopy(choices);
mcq.setChoices(choices);
safeSetPoints(mcq, pts);
if (questionImageUrl) {
addQuestionImageItem(form, question, questionImageUrl, r + 1);
}
if (hasAnswerImages) {
addAnswerImageItems(form, rawAns, rawAnsImageUrls, r + 1);
}
break;
}
const cb = form.addCheckboxItem().setTitle(title).setRequired(true);
let formChoices = cleaned.map((entry) =>
cb.createChoice(
formatChoiceText(entry, hasAnswerImages),
entry.isCorrect,
),
);
formChoices = shuffleArrayCopy(formChoices);
cb.setChoices(formChoices);
safeSetPoints(cb, pts);
if (questionImageUrl) {
addQuestionImageItem(form, question, questionImageUrl, r + 1);
}
if (hasAnswerImages) {
addAnswerImageItems(form, rawAns, rawAnsImageUrls, r + 1);
}
break;
}
default:
throw new Error(
`Unsupported Type "${type}" in row ${
r + 1
}. Use SA, PARA, MCQ, or MSQ.`,
);
}
}
form.setAllowResponseEdits(false);
form.setShuffleQuestions(false);
// Small nudge so Drive finishes the copy & items commit
Utilities.sleep(400);
// Move near the spreadsheet (best effort)
try {
moveFormNextToSpreadsheet(formId, ss.getId());
} catch (_) {}
// 4) **Publish** and (optionally) set "Anyone with link"
const urls = ensurePublishedAndOpen(form);
if (MAKE_PUBLIC_ANYONE_WITH_LINK) {
try {
setAnyoneWithLinkResponder(formId);
} catch (e) {
Logger.log("setAnyoneWithLinkResponder: " + e);
}
}
return {
formId: formId,
formTitle: formTitle,
publishedUrl: urls.publishedUrl, // use this with students
editUrl: urls.editUrl,
responsesUrl: ss.getUrl(),
};
}
/***** CREATE FORM FROM TEMPLATE (or new) *****/
function createFormShell(formTitle, formDescription, spreadsheetId) {
let form;
if (TEMPLATE_FORM_ID) {
const templateFile = DriveApp.getFileById(TEMPLATE_FORM_ID);
const copyFile = templateFile.makeCopy(formTitle);
const newId = copyFile.getId();
form = FormApp.openById(newId);
Utilities.sleep(300);
// Clear template items (keep theme/settings)
form.getItems().forEach((it) => form.deleteItem(it));
form.setTitle(formTitle).setDescription(formDescription);
try {
moveFormNextToSpreadsheet(newId, spreadsheetId);
} catch (_) {}
} else {
// If your Forms service supports the 2nd param (isPublished), you could pass false here.
form = FormApp.create(formTitle)
.setDescription(formDescription)
.setIsQuiz(true);
}
return form;
}
/***** PUBLISH + RETURN STABLE URL *****/
function ensurePublishedAndOpen(form) {
// Ensure accepting responses after items exist
try {
form.setAcceptingResponses(true);
} catch (_) {}
// **NEW:** Publish the form (required for /d/e/... link to work)
for (let i = 0; i < 3; i++) {
try {
form.setPublished(true);
if (form.isPublished()) break;
} catch (e) {
Utilities.sleep(300);
}
}
// Wait a moment for the published URL to materialize
Utilities.sleep(400);
// Prefer the official published URL (/forms/d/e/...)
let publishedUrl = "";
for (let i = 0; i < 20; i++) {
try {
publishedUrl = form.getPublishedUrl();
if (publishedUrl && /\/forms\/d\/e\//.test(publishedUrl)) break;
} catch (e) {}
Utilities.sleep(250);
}
if (!publishedUrl) {
// Fallback (rare): file-id URL
publishedUrl = `https://docs.google.com/forms/d/${form.getId()}/viewform`;
}
const editUrl = form.getEditUrl();
return { publishedUrl, editUrl };
}
/***** “Anyone with the link can respond” (Drive permission with view:'published') *****/
function setAnyoneWithLinkResponder(formId) {
// Requires Advanced Service: Drive API enabled (and Drive API enabled in Cloud console)
const body = { type: "anyone", role: "reader", view: "published" };
// Drive API v3 in Advanced Service uses Permissions.create; older v2 uses Permissions.insert.
// Try v3 first, then fall back to v2 for older tenants.
try {
if (Drive.Permissions && typeof Drive.Permissions.create === "function") {
Drive.Permissions.create({
fileId: formId,
resource: body,
supportsAllDrives: true,
});
return;
}
} catch (e) {
Logger.log("Drive.Permissions.create failed, will try insert: " + e);
}
try {
if (Drive.Permissions && typeof Drive.Permissions.insert === "function") {
Drive.Permissions.insert(body, formId, { supportsAllDrives: true });
return;
}
} catch (e2) {
Logger.log("Drive.Permissions.insert failed: " + e2);
throw e2;
}
}
/***** CONFIG / HEADER HELPERS *****/
function findConfig(values) {
if (!values || !values.length) return null;
let formTitle = "",
formDescription = "",
limitOneResponse = "";
let headerRowIndex = -1;
for (let r = 0; r < values.length; r++) {
const k = (values[r][0] || "").toString().trim().toLowerCase();
if (!k) continue;
if (k === "formtitle") {
formTitle = (values[r][1] || "").toString().trim() || formTitle;
continue;
}
if (k === "formdescription") {
formDescription = (values[r][1] || "").toString().trim();
continue;
}
if (k === "limitoneresponse") {
limitOneResponse = (values[r][1] || "").toString().trim();
continue;
}
const row = values[r].map((x) => (x || "").toString().trim().toLowerCase());
if (
row.includes("section") &&
row.includes("question") &&
row.includes("type") &&
row.includes("points")
) {
headerRowIndex = r;
break;
}
}
if (headerRowIndex === -1) return null;
return { formTitle, formDescription, limitOneResponse, headerRowIndex };
}
function headerIndex(headerRow, requiredCols) {
const idx = {};
requiredCols.forEach((col) => {
const i = headerRow.findIndex(
(h) => h.toString().trim().toLowerCase() === col.toLowerCase(),
);
if (i === -1)
throw new Error(
`Header "${col}" not found. Got: ${headerRow.join(", ")}`,
);
idx[col] = i;
});
return idx;
}
/***** SECTION POINTS *****/
function computeSectionTotals(values, headerRowIndex, idx) {
const totals = {};
for (let r = headerRowIndex + 1; r < values.length; r++) {
const row = values[r];
if (!row || row.length === 0 || row.every((v) => v === "" || v == null))
continue;
const section = (row[idx.Section] || "").toString().trim();
const pts = Number((row[idx.Points] || "").toString().trim()) || 0;
if (!section) continue;
totals[section] = (totals[section] || 0) + pts;
}
return totals;
}
/***** UTILITIES *****/
function uniqueAnswers(arr) {
const seen = new Set();
const out = [];
for (const a of arr) {
const key = a.replace(/\s+/g, " ").trim().toLowerCase();
if (key && !seen.has(key)) {
seen.add(key);
out.push(a);
}
}
return out;
}
function stripStar(s) {
return s.replace(/^\s*\*/, "").trim();
}
function isStarred(s) {
return /^\s*\*/.test(s);
}
function parseBool(s, fallback) {
if (s == null || s === "") return fallback;
switch (String(s).trim().toLowerCase()) {
case "true":
case "yes":
case "y":
case "1":
return true;
case "false":
case "no":
case "n":
case "0":
return false;
default:
return fallback;
}
}
// Non-mutating shuffle
function shuffleArrayCopy(list) {
const a = list.slice();
for (let i = a.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[a[i], a[j]] = [a[j], a[i]];
}
return a;
}
function safeSetPoints(item, pts) {
if (!pts || pts <= 0) return;
try {
item.setPoints(pts);
} catch (_) {}
}
/***** MOVE HELPERS *****/
function moveFormNextToSpreadsheet(formId, spreadsheetId) {
try {
if (typeof Drive !== "undefined" && Drive.Files) {
const src = Drive.Files.get(spreadsheetId, { supportsAllDrives: true });
const dst = Drive.Files.get(formId, { supportsAllDrives: true });
const srcParents = parentsToIds(src.parents);
const dstParents = parentsToIds(dst.parents);
if (srcParents.length) {
const params = {
addParents: srcParents.join(","),
supportsAllDrives: true,
};
if (dstParents.length) params.removeParents = dstParents.join(",");
Drive.Files.update({}, formId, null, params);
return;
}
}
} catch (e) {
Logger.log("Advanced Drive move failed: " + e);
}
try {
const file = DriveApp.getFileById(formId);
const ssFile = DriveApp.getFileById(spreadsheetId);
const parents = ssFile.getParents();
if (parents.hasNext()) file.moveTo(parents.next());
} catch (e2) {
Logger.log("DriveApp move failed; leaving form in root: " + e2);
}
}
function parentsToIds(parents) {
if (!parents || !parents.length) return [];
return typeof parents[0] === "string"
? parents.slice()
: parents.map((p) => p.id);
}
/***** OPTIONAL COLUMN HELPER *****/
function optionalHeaderIndex(headerRow, cols) {
const idx = {};
cols.forEach(function (col) {
const i = headerRow.findIndex(function (h) {
return h.toString().trim().toLowerCase() === col.toLowerCase();
});
if (i !== -1) idx[col] = i;
});
return idx;
}
function getOptionalCell(row, index) {
if (index === undefined) return "";
return (row[index] || "").toString().trim();
}
function buildAnswerEntries(rawAns, rawAnsImageUrls, type) {
const entries = [];
const seen = new Set();
for (let i = 0; i < rawAns.length; i++) {
const raw = (rawAns[i] || "").toString().trim();
const imageUrl = (rawAnsImageUrls[i] || "").toString().trim();
if (!raw && !imageUrl) continue;
const label = String.fromCharCode(65 + i);
const text = stripStar(raw) || `Option ${label}`;
const dedupeKey = `${text.toLowerCase()}|${imageUrl}`;
if (seen.has(dedupeKey)) continue;
seen.add(dedupeKey);
entries.push({
label,
text,
imageUrl,
isCorrect: type === "MSQ" ? isStarred(raw) : false,
});
}
if (entries.length === 0) {
return { entries, hasExplicitCorrectChoices: false };
}
if (type === "MCQ") {
entries.forEach((entry, index) => {
entry.isCorrect = index === 0;
});
return { entries, hasExplicitCorrectChoices: true };
}
const hasExplicitCorrectChoices = entries.some((entry) => entry.isCorrect);
if (!hasExplicitCorrectChoices) {
entries.forEach((entry, index) => {
entry.isCorrect = index === 0;
});
}
return { entries, hasExplicitCorrectChoices };
}
function formatChoiceText(entry, hasAnswerImages) {
if (!hasAnswerImages) return entry.text;
return `${entry.label}`;
}
function addAnswerImageItems(form, rawAns, rawAnsImageUrls, rowNumber) {
for (let i = 0; i < rawAnsImageUrls.length; i++) {
const imageUrl = (rawAnsImageUrls[i] || "").toString().trim();
if (!imageUrl) continue;
const label = String.fromCharCode(65 + i);
const answerText =
stripStar((rawAns[i] || "").toString().trim()) || `Option ${label}`;
try {
const blob = fetchImageBlobFromUrl(imageUrl);
form.addImageItem().setTitle(`${label}. ${answerText}`).setImage(blob);
} catch (imgErr) {
Logger.log(
`Answer image fetch failed row ${rowNumber}, ${label}: ${imgErr}`,
);
}
}
}
function addQuestionImageItem(form, question, imageUrl, rowNumber) {
try {
const blob = fetchImageBlobFromUrl(imageUrl);
form
.addImageItem()
.setTitle("Image for: " + question)
.setImage(blob);
} catch (imgErr) {
Logger.log(`Question image fetch failed row ${rowNumber}: ${imgErr}`);
}
}
function fetchImageBlobFromUrl(imageUrl) {
const normalized = (imageUrl || "").toString().trim();
if (!normalized) throw new Error("Empty image URL");
validateImageUrl(normalized);
const driveFileId = extractDriveFileId(normalized);
if (driveFileId) {
const driveBlob = DriveApp.getFileById(driveFileId).getBlob();
validateImageBlob(driveBlob);
return driveBlob;
}
const response = UrlFetchApp.fetch(normalized, {
followRedirects: false,
muteHttpExceptions: true,
});
const status = response.getResponseCode();
if (status < 200 || status >= 300) {
throw new Error(`Image fetch failed with HTTP ${status}`);
}
const headers = response.getHeaders() || {};
const contentType =
headers["Content-Type"] || headers["content-type"] || "";
if (!/^image\//i.test(String(contentType))) {
throw new Error(`URL did not return an image content type: ${contentType}`);
}
const blob = response.getBlob();
validateImageBlob(blob);
return blob;
}
function validateImageUrl(url) {
if (!/^https?:\/\//i.test(url)) {
throw new Error("Image URL must start with http:// or https://");
}
let host = "";
try {
// Prefer a real URL parser to correctly handle userinfo, ports, and IPv6.
const parsed = new URL(String(url));
host = (parsed.hostname || "").toLowerCase();
} catch (e) {
// Fallback: handle optional userinfo and bracketed IPv6 literals.
const hostMatch = String(url).match(
/^https?:\/\/(?:[^@\/\?#]*@)?(\[[^\]]+\]|[^\/\?#:]+)/i,
);
host = hostMatch && hostMatch[1] ? hostMatch[1].toLowerCase() : "";
}
// Strip brackets from IPv6 literals (e.g., "[::1]" -> "::1").
if (host.startsWith("[") && host.endsWith("]")) {
host = host.slice(1, -1);
}
if (!host) {
throw new Error("Invalid image URL host");
}
if (host === "localhost" || host === "127.0.0.1" || host === "::1") {
throw new Error("Localhost image URLs are not allowed");
}
if (
/^10\./.test(host) ||
/^192\.168\./.test(host) ||
/^169\.254\./.test(host) ||
/^172\.(1[6-9]|2\d|3[0-1])\./.test(host)
) {
throw new Error("Private network image URLs are not allowed");
}
}
function validateImageBlob(blob) {
const contentType = blob.getContentType() || "";
if (!/^image\//i.test(contentType)) {
throw new Error(`Blob is not an image (content type: ${contentType})`);
}
const maxImageBytes = 5 * 1024 * 1024;
const bytes = blob.getBytes();
if (bytes.length > maxImageBytes) {
throw new Error("Image too large (max 5MB)");
}
}
function escapeHtml(value) {
return String(value)
.replace(/&/g, "&")
.replace(/</g, "<")
.replace(/>/g, ">")
.replace(/"/g, """)
.replace(/'/g, "'");
}
function extractDriveFileId(url) {
const value = (url || "").toString();
const patterns = [
/drive\.google\.com\/file\/d\/([a-zA-Z0-9_-]+)/,
/drive\.google\.com\/open\?id=([a-zA-Z0-9_-]+)/,
/drive\.google\.com\/uc\?.*id=([a-zA-Z0-9_-]+)/,
/docs\.google\.com\/uc\?.*id=([a-zA-Z0-9_-]+)/,
];
for (const pattern of patterns) {
const match = value.match(pattern);
if (match && match[1]) return match[1];
}
return "";
}
/***** GOOGLE CLASSROOM INTEGRATION *****/
/** Store last form result so "Post Last Form to Classroom" can reuse it */
function storeLastFormResult(result) {
const props = PropertiesService.getUserProperties();
props.setProperty("LAST_FORM_PUBLISHED_URL", result.publishedUrl || "");
props.setProperty("LAST_FORM_EDIT_URL", result.editUrl || "");
props.setProperty("LAST_FORM_TITLE", result.formTitle || "Untitled Quiz");
props.setProperty("LAST_FORM_ID", result.formId || "");
}
function getLastFormResult() {
const props = PropertiesService.getUserProperties();
return {
publishedUrl: props.getProperty("LAST_FORM_PUBLISHED_URL") || "",
editUrl: props.getProperty("LAST_FORM_EDIT_URL") || "",
formTitle: props.getProperty("LAST_FORM_TITLE") || "",
formId: props.getProperty("LAST_FORM_ID") || "",
};
}
/** Entrypoint: Create Form then immediately post to Classroom */
function confirmCreateAndPostToClassroom() {
const ui = SpreadsheetApp.getUi();
const res = ui.alert(
"Create Form & Post to Classroom",
"Create a new Google Form quiz, link responses to this spreadsheet, " +
"and then post it to Google Classroom?",
ui.ButtonSet.OK_CANCEL,
);
if (res !== ui.Button.OK) return;
try {
const result = createFormFromActiveSpreadsheet();
storeLastFormResult(result);
SpreadsheetApp.getActive().toast(
"Form created. Opening Classroom dialog...",
"Form Builder",
3,
);
showClassroomDialog();
} catch (e) {
SpreadsheetApp.getActive().toast(
"Form creation failed.",
"Form Builder",
5,
);
ui.alert("Error", e && e.message ? e.message : String(e), ui.ButtonSet.OK);
}
}
/** Entrypoint: Post last created form to Classroom */
function postLastFormToClassroom() {
const ui = SpreadsheetApp.getUi();
const last = getLastFormResult();
if (!last.publishedUrl) {
ui.alert(
"No Form Found",
"No form has been created yet from this spreadsheet.\n" +
'Please use "Create Form (Confirm)" first.',
ui.ButtonSet.OK,
);
return;
}
showClassroomDialog();
}
/** Show the Classroom course picker modal dialog */
function showClassroomDialog() {
const html = HtmlService.createHtmlOutput(getClassroomDialogHtml())
.setWidth(480)
.setHeight(560)
.setTitle("Post to Google Classroom");
SpreadsheetApp.getUi().showModalDialog(html, "Post to Google Classroom");
}
/** Fetch active courses where current user is a teacher (called from dialog) */
function getActiveCourses() {
const courses = [];
let pageToken = null;
do {
const params = { teacherId: "me", courseStates: ["ACTIVE"] };
if (pageToken) params.pageToken = pageToken;
const response = Classroom.Courses.list(params);
if (response.courses) {
response.courses.forEach(function (c) {
courses.push({ id: c.id, name: c.name, section: c.section || "" });
});
}
pageToken = response.nextPageToken;
} while (pageToken);
return courses;
}
/** Fetch topics for a course (called from dialog) */
function getTopicsForCourse(courseId) {
try {
const response = Classroom.Courses.Topics.list(courseId);
return (response.topic || []).map(function (t) {
return { id: t.topicId, name: t.name };
});
} catch (e) {
Logger.log("getTopicsForCourse: " + e);
return [];
}
}
/** Post the form to Google Classroom (called from dialog) */
function submitToClassroom(options) {
const last = getLastFormResult();
if (!last.publishedUrl)
throw new Error("No form URL found. Create a form first.");
const courseId = options.courseId;
if (!courseId) throw new Error("No course selected.");
const postType = options.postType || "assignment";
const title = options.title || last.formTitle || "Untitled Quiz";
const description = options.description || "";
let maxPoints = Number(options.maxPoints);
if (Number.isNaN(maxPoints) || maxPoints < 0) maxPoints = 100;
const dueDate = options.dueDate || "";
const dueTime = options.dueTime || "23:59";
const topicId = options.topicId || "";
if (postType === "material") {
// Post as class material (ungraded)
const material = {
title: title,
description: description,
state: "PUBLISHED",
materials: [{ link: { url: last.publishedUrl } }],
};
if (topicId) material.topicId = topicId;
Classroom.Courses.CourseWorkMaterials.create(material, courseId);
} else {
// Post as quiz assignment (graded)
const courseWork = {
title: title,
description: description,
workType: "ASSIGNMENT",
state: "PUBLISHED",
materials: [{ link: { url: last.publishedUrl } }],
maxPoints: maxPoints,
};
if (topicId) courseWork.topicId = topicId;
if (dueDate) {
const [yearStr, monthStr, dayStr] = dueDate.split("-");
const year = Number(yearStr);
const month = Number(monthStr);
const day = Number(dayStr);
if (Number.isNaN(year) || Number.isNaN(month) || Number.isNaN(day)) {
throw new Error("Invalid due date format. Expected YYYY-MM-DD.");
}
courseWork.dueDate = {
year: year,
month: month,
day: day,
};
const parts = dueTime.split(":").map(Number);
const hours = Number.isNaN(parts[0]) ? 23 : parts[0];
const minutes = Number.isNaN(parts[1]) ? 59 : parts[1];
courseWork.dueTime = { hours: hours, minutes: minutes };
}
Classroom.Courses.CourseWork.create(courseWork, courseId);
}
return {
success: true,
message: 'Posted "' + title + '" to Google Classroom successfully.',
};
}
/** Build the HTML for the Classroom dialog */
function getClassroomDialogHtml() {
const last = getLastFormResult();
const escapedTitle = escapeHtml(last.formTitle || "Untitled Quiz");
const escapedUrl = escapeHtml(last.publishedUrl || "(no URL)");
return (
"<!DOCTYPE html>" +
'<html><head><base target="_top">' +
"<style>" +
"body{font-family:Arial,sans-serif;padding:16px;margin:0;font-size:14px}" +
"label{display:block;margin:10px 0 4px;font-weight:bold;font-size:13px}" +
"select,input{width:100%;padding:7px;box-sizing:border-box;border:1px solid #dadce0;border-radius:4px;font-size:13px}" +
".row{margin-bottom:4px}" +
".actions{margin-top:16px;text-align:right}" +
"button{padding:8px 20px;margin-left:8px;cursor:pointer;font-size:13px}" +
".primary{background:#1a73e8;color:#fff;border:none;border-radius:4px}" +
".primary:hover{background:#1557b0}" +
".secondary{background:#f1f3f4;border:1px solid #dadce0;border-radius:4px}" +
"#status{margin-top:12px;padding:8px;border-radius:4px;display:none}" +
".success{background:#e6f4ea;color:#137333}" +
".error{background:#fce8e6;color:#c5221f}" +
".info{background:#e8f0fe;color:#1967d2}" +
".form-url{font-size:12px;color:#666;word-break:break-all;margin-bottom:8px;padding:8px;background:#f8f9fa;border-radius:4px}" +
"</style>" +
"</head><body>" +
'<div class="form-url"><strong>Form:</strong> ' +
escapedTitle +
"<br>" +
escapedUrl +
"</div>" +
'<div id="loading" class="info" style="display:block;padding:8px;border-radius:4px">Loading courses...</div>' +
'<div id="formArea" style="display:none">' +