-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp_script.js
More file actions
322 lines (261 loc) · 8.58 KB
/
Copy pathapp_script.js
File metadata and controls
322 lines (261 loc) · 8.58 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
function doPost(e) {
try {
const body = JSON.parse(e.postData.contents);
const jobId = body.jobId || Utilities.getUuid();
const {
formUrl,
submissionCount,
geminiApiKey,
geminiModel,
geminiSystemPrompt
} = body;
if (!formUrl) {
return respond(false, "Form URL is required", jobId);
}
log("Job started", jobId);
// Gemini is OPTIONAL
if (geminiApiKey) {
PropertiesService.getScriptProperties()
.setProperty("GEMINI_API_KEY", geminiApiKey);
PropertiesService.getScriptProperties()
.setProperty(
"GEMINI_MODEL",
geminiModel || "gemini-2.5-flash"
);
if (geminiSystemPrompt && String(geminiSystemPrompt).trim()) {
PropertiesService.getScriptProperties()
.setProperty("GEMINI_SYSTEM_PROMPT", String(geminiSystemPrompt).trim());
} else {
PropertiesService.getScriptProperties()
.deleteProperty("GEMINI_SYSTEM_PROMPT");
}
log("Gemini enabled", jobId);
} else {
PropertiesService.getScriptProperties()
.deleteProperty("GEMINI_API_KEY");
PropertiesService.getScriptProperties()
.deleteProperty("GEMINI_MODEL");
PropertiesService.getScriptProperties()
.deleteProperty("GEMINI_SYSTEM_PROMPT");
log("Gemini disabled (fallback mode)", jobId);
}
const COUNT = Math.min(Number(submissionCount || 1), 50);
// 🔒 Prevent parallel heavy jobs
const lock = LockService.getScriptLock();
lock.waitLock(20000);
try {
submitRandomResponsesAllSupported(formUrl, COUNT, jobId);
} finally {
lock.releaseLock();
}
log("Job completed successfully", jobId);
return respond(true, "Completed", jobId);
} catch (err) {
log("ERROR: " + err.message, jobId);
return respond(false, err.message, jobId);
}
}
function doGet(e) {
// Health check / root
if (!e || !e.parameter || !e.parameter.jobId) {
return ContentService
.createTextOutput("OK")
.setMimeType(ContentService.MimeType.TEXT);
}
const jobId = e.parameter.jobId;
const cache = CacheService.getScriptCache();
const logs = cache.get(`logs_${jobId}`);
return ContentService.createTextOutput(
JSON.stringify({
success: true,
logs: logs ? JSON.parse(logs) : []
})
).setMimeType(ContentService.MimeType.JSON);
}
function submitRandomResponsesAllSupported(formUrl, COUNT, jobId) {
log(`Opening form`, jobId);
const form = FormApp.openByUrl(formUrl);
const items = form.getItems();
log(`Found ${items.length} items`, jobId);
for (let i = 0; i < COUNT; i++) {
log(`Creating response ${i + 1}/${COUNT}`, jobId);
const response = form.createResponse();
items.forEach(item => {
const type = item.getType();
const title = item.getTitle();
try {
switch (type) {
// ───── TEXT ─────
case FormApp.ItemType.TEXT: {
const answer = isGeminiEnabled()
? generateAnswerWithGemini(title, "short", jobId)
: randomShortText();
response.withItemResponse(
item.asTextItem().createResponse(answer)
);
log(`TEXT answered`, jobId);
break;
}
case FormApp.ItemType.PARAGRAPH_TEXT: {
const answer = isGeminiEnabled()
? generateAnswerWithGemini(title, "paragraph", jobId)
: randomParagraph();
response.withItemResponse(
item.asParagraphTextItem().createResponse(answer)
);
log(`PARAGRAPH answered`, jobId);
break;
}
// ───── CHOICES ─────
case FormApp.ItemType.MULTIPLE_CHOICE: {
const c = item.asMultipleChoiceItem().getChoices();
response.withItemResponse(
item.asMultipleChoiceItem()
.createResponse(c[rand(c.length)].getValue())
);
break;
}
case FormApp.ItemType.CHECKBOX: {
const c = item.asCheckboxItem().getChoices();
response.withItemResponse(
item.asCheckboxItem()
.createResponse([c[rand(c.length)].getValue()])
);
break;
}
case FormApp.ItemType.LIST: {
const c = item.asListItem().getChoices();
response.withItemResponse(
item.asListItem()
.createResponse(c[rand(c.length)].getValue())
);
break;
}
// ───── SCALE ─────
case FormApp.ItemType.SCALE: {
const it = item.asScaleItem();
response.withItemResponse(
it.createResponse(
randRange(it.getLowerBound(), it.getUpperBound())
)
);
break;
}
// ───── RATING (SKIPPED) ─────
case FormApp.ItemType.RATING:
log(`RATING skipped: ${title}`, jobId);
break;
// ───── GRIDS ─────
case FormApp.ItemType.GRID: {
const it = item.asGridItem();
const answers = it.getRows().map(
() => it.getColumns()[rand(it.getColumns().length)]
);
response.withItemResponse(it.createResponse(answers));
break;
}
case FormApp.ItemType.CHECKBOX_GRID: {
const it = item.asCheckboxGridItem();
const answers = it.getRows().map(
() => [it.getColumns()[rand(it.getColumns().length)]]
);
response.withItemResponse(it.createResponse(answers));
break;
}
// ───── DATE / TIME ─────
case FormApp.ItemType.DATE:
response.withItemResponse(
item.asDateItem().createResponse(new Date())
);
break;
case FormApp.ItemType.TIME:
response.withItemResponse(
item.asTimeItem().createResponse(10, 30)
);
break;
// ───── FILE UPLOAD ─────
case FormApp.ItemType.FILE_UPLOAD:
log(`FILE_UPLOAD skipped`, jobId);
break;
}
} catch (e) {
log(`ERROR on "${title}": ${e.message}`, jobId);
}
});
response.submit();
log(`Response ${i + 1} submitted`, jobId);
}
}
function isGeminiEnabled() {
return !!PropertiesService
.getScriptProperties()
.getProperty("GEMINI_API_KEY");
}
function generateAnswerWithGemini(question, type, jobId) {
const apiKey = PropertiesService
.getScriptProperties()
.getProperty("GEMINI_API_KEY");
const systemPrompt = PropertiesService
.getScriptProperties()
.getProperty("GEMINI_SYSTEM_PROMPT") || "";
const model =
PropertiesService
.getScriptProperties()
.getProperty("GEMINI_MODEL") ||
"gemini-2.5-flash";
const url =
`https://generativelanguage.googleapis.com/v1beta/models/${model}:generateContent?key=${apiKey}`;
const seed =
new Date().toISOString() +
Math.random().toString(36).slice(2);
const prompt =
(systemPrompt ? `System instructions:\n${systemPrompt}\n\n` : "") +
`Answer the question uniquely.\nQuestion: ${question}\nType: ${type}\nSeed: ${seed}`;
const payload = {
contents: [{
parts: [{
text: prompt
}]
}]
};
const res = UrlFetchApp.fetch(url, {
method: "post",
contentType: "application/json",
payload: JSON.stringify(payload),
muteHttpExceptions: true
});
Utilities.sleep(300);
const json = JSON.parse(res.getContentText());
return (
json?.candidates?.[0]?.content?.parts?.[0]?.text ||
randomShortText()
);
}
function respond(success, message, jobId) {
return ContentService.createTextOutput(
JSON.stringify({ success, message, jobId })
).setMimeType(ContentService.MimeType.JSON);
}
function rand(max) {
return Math.floor(Math.random() * max);
}
function randRange(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
function randomShortText() {
return "Auto_" + Math.random().toString(36).slice(2, 7);
}
function randomParagraph() {
return "Auto-generated test response at " + new Date().toISOString();
}
function log(message, jobId) {
const cache = CacheService.getScriptCache();
const key = `logs_${jobId}`;
const existing = cache.get(key);
const logs = existing ? JSON.parse(existing) : [];
logs.push({
time: new Date().toISOString(),
message
});
cache.put(key, JSON.stringify(logs), 600);
}