forked from lclontz/google_forms_to_fusion_tables
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscript for Google forms.txt
428 lines (372 loc) · 13 KB
/
script for Google forms.txt
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
/**
* AppsScript script to run in a Google Spreadsheet that synchronizes
* Google Forms responses with a Fusion Table.
* All cedits to Lee clonts
* A video can be found here https://www.youtube.com/watch?v=sxR4ZETbK3U&list=FLVSFQ9XrsCDEvsoz_XpTj8A
* This script is better than
* https://gist.github.com/chrislkeller/3013360 because
* -This script doesn't make duplicates from the original.
* -This script also sync's when a Form is submitted.
*/
var DOCID;
var ADDRESS_COLUMN;
var LOCATION_COLUMN;
var TIME_ZONE;
/**
* Do-nothing method to trigger the authorization dialog if not already done.
*/
function checkAuthorization() {
}
/**
* Syncs the Fusion Table to the form data. Run this every hour or so.
*/
function sync() {
init();
// Get the data in the spreadsheet and convert it to a dictionary.
var sheet = SpreadsheetApp.getActiveSheet();
var lastRow = sheet.getLastRow();
var lastColumn = sheet.getLastColumn();
var spreadsheetData = sheet.getRange(1, 1, lastRow, lastColumn);
var spreadsheetValues = spreadsheetData.getValues();
var columns = spreadsheetValues[0];
var spreadsheetMap = mapRowsByRowId(columns,
spreadsheetValues.slice(1, spreadsheetValues.length));
// Get the columns in the spreadsheet and escape any single quotes
var escapedColumns = [];
for (var i = 0; i < columns.length; i++) {
var columnName = columns[i];
columnName = escapeQuotes(columnName);
escapedColumns.push(columnName);
}
// Get the data from the table and convert to a dictionary.
var query = "SELECT '" + escapedColumns.join("','") + "' FROM " + DOCID;
var ftResults = runSqlWithRetry(query);
if (!ftResults) {
return;
}
var ftMap = mapRowsByRowId(ftResults.columns, ftResults.rows);
// For each row in the Fusion Table, find if the row still exists in the
// spreadsheet. If it exists, make sure the values are the same. If
// they are different, update the Fusion Table data.
// If the row doesn't exist in the spreadsheet, delete the row from the table.
for (var rowId in ftMap) {
var spreadsheetRow = spreadsheetMap[rowId];
if (spreadsheetRow) {
var updates = [];
var tableRow = ftMap[rowId];
for (var column in tableRow) {
if (column === 'rowid') {
continue;
}
var tableValue = tableRow[column];
var spreadsheetValue = spreadsheetRow[column];
if (tableValue != spreadsheetValue) {
spreadsheetValue = processSpreadsheetValue(column, spreadsheetValue);
updates.push("'" + escapeQuotes(column) + "' = '" +
spreadsheetValue + "'");
}
}
// If there are updates, send the UPDATE query.
if (updates.length) {
var query = [];
query.push('UPDATE ');
query.push(DOCID);
query.push(' SET ');
query.push(updates.join(','));
query.push(" WHERE rowid = '");
query.push(rowId);
query.push("'");
runSqlWithRetry(query.join(''));
waitBetweenCalls();
}
} else {
// If the row doesn't exist in the spreadsheet, delete it from the table
runSqlWithRetry('DELETE FROM ' + DOCID + " WHERE rowid = '" +
rowId + "'");
waitBetweenCalls();
}
}
// Insert all the data into the Fusion Table that failed to insert.
// These rows were given a rowid of -1 or have a blank rowid.
var failedInserts = spreadsheetMap[-1];
for (var i = 0; failedInserts && i < failedInserts.length; i++) {
var rowId = createRecord(failedInserts[i]);
if (!rowId) {
rowId = -1;
}
insertRowId(rowId, failedInserts[i].spreadsheetRowNum);
waitBetweenCalls();
}
}
/**
* Submits the data to Fusion Tables when the form is submitted.
* @param {Object} e The form object.
*/
function onFormSubmit(e) {
if (!e) {
// Don't try to do anything when run directly from the script editor
return;
}
// Get the row number of the newly entered data.
var sheet = SpreadsheetApp.getActiveSheet();
var row = sheet.getLastRow();
// Check to make sure the rowid column is there.
init();
// The values entered into the form, mapped by question.
var formValues = e.namedValues;
Logger.log('Form values are ' + formValues);
// Insert the data into the Fusion Table.
var rowId = createRecord(formValues);
if (!rowId) {
rowId = -1;
}
insertRowId(rowId, row);
}
/**
* Ensures the docid property for the target table is set, that if the
* address column is set the latlngColumn is also set, and adds a rowid
* column to the sheet if it doesn't have one.
*/
function init() {
// Update for deprecated ScriptProperties API call
var docProperties = PropertiesService.getScriptProperties();
DOCID = docProperties.getProperty('docid');
Logger.log(DOCID)
// Here is the first of two modifications to make the Address and Location work -- lc
if (!DOCID) {
throw 'The script is missing the required docid Project Property';
}
ADDRESS_COLUMN = docProperties.getProperty('addressColumn');
Logger.log('Address Column is ' + ADDRESS_COLUMN);
LOCATION_COLUMN = docProperties.getProperty('latlngColumn');
Logger.log ('latlngColumn is ' + LOCATION_COLUMN);
if (ADDRESS_COLUMN && !LOCATION_COLUMN) {
throw('Since you added an ADDRESS_COLUMN project property, ' +
'you also need to add a latlngColumn property');
}
TIME_ZONE = Session.getScriptTimeZone();
var sheet = SpreadsheetApp.getActiveSheet();
var lastColumn = sheet.getLastColumn();
var lastHeaderValue = sheet.getRange(1, lastColumn).getValue();
if (lastHeaderValue != 'rowid') {
sheet.getRange(1, lastColumn + 1).setValue('rowid');
}
}
/**
* Creates a record in the Fusion Table.
* @param {Object} dictionary of columns mapped to values.
* @return {?string} the rowid if successful, otherwise null.
*/
function createRecord(columnValues) {
Logger.log('Column values are ' + columnValues);
// Create lists of the column names and values to create the INSERT Statement.
var columns = [];
var values = [];
var originalAddress = '';
for (var column in columnValues) {
// If the column is not the spreadsheetRowNum,
// add it and the value to the lists.
if (column != 'spreadsheetRowNum') {
// Here is the second of two modifications to make the Address and Location work -- lc
originalAddress = columnValues[column];
if (column == ADDRESS_COLUMN) {
geoCodedAddress = processSpreadsheetValue(column, columnValues[column])
values.push(geoCodedAddress);
Logger.log('geoCodedAddress is ' + geoCodedAddress);
values.push(originalAddress);
Logger.log('originalAddress is ' + originalAddress);
column = escapeQuotes(column);
columns.push(LOCATION_COLUMN);
columns.push(ADDRESS_COLUMN)
} else if (column == 'Timestamp') {
columns.push('Timestamp');
values.push(columnValues[column]);
}
else {columns.push(column);
values.push(columnValues[column]);
}
}
}
var query = [];
query.push('INSERT INTO ');
query.push(DOCID);
query.push(" ('");
query.push(columns.join("','"));
query.push("') ");
query.push("VALUES ('");
query.push(values.join("','"));
query.push("')");
var response = runSqlWithRetry(query.join(''));
if (response) {
var rowId = response.rows[0][0];
return rowId;
}
}
/**
* Adds the rowid from the INSERT to the corresponding row in the spreadsheet.
* @param {string} rowId The row id of the inserted row.
* @param {number} row The row number to enter the rowid in.
*/
function insertRowId(rowId, row) {
var sheet = SpreadsheetApp.getActiveSheet();
var lastColumn = sheet.getLastColumn();
lastCell = sheet.getRange(row, lastColumn);
lastCell.setValue(rowId);
}
/**
* Returns the geocoded address.
* @param {string} address The user-entered address.
* @return {string} The geocoded results as a lat,long pair.
*/
function geocode(address) {
if (!address) {
return '0,0';
}
var results = Maps.newGeocoder().geocode(address);
// If all your form responses will be within a given area, you may get better
// geocoding results by biasing to that area. Uncomment the code below and set
// the desired region, bounding box, or component filter. The example shows
// how to indicate that the addresses should be in Spain. For full details, see
// https://developers.google.com/maps/documentation/javascript/geocoding#GeocodingRequests
//
// var results = Maps.newGeocoder().geocode({ address: address, region: 'es' });
Logger.log('Geocoding: ' + address);
if (results.status == 'OK') {
var bestResult = results.results[0];
var lat = bestResult.geometry.location.lat;
var lng = bestResult.geometry.location.lng;
var latLng = lat + ',' + lng;
Logger.log('Results: ' + latLng);
return latLng;
} else {
Logger.log('Error geocoding: ' + address);
Logger.log(results.status);
return '0,0';
}
}
/**
* Geocodes the value if this is the address column, or formats it as a date if
* this is the timestamp column, escapes quotes, and returns the value.
* @param {string} column Column name.
* @param {string} column Spreadsheet value.
* @return {string} The converted or escaped value.
*/
function processSpreadsheetValue(column, value) {
Logger.log('In processSpreadSheetValue. Column is ' + column + ' and ADDRESS_COLUMN is ' + ADDRESS_COLUMN);
Logger.log('In pSSV. Value is ' + value);
if (column === ADDRESS_COLUMN) {
return geocode(value);
}
if (column === 'Timestamp') {
// Ensure this is a format Fusion Tables understands
return Utilities.formatDate(new Date(value), TIME_ZONE,
'yyyy-MM-dd HH:mm:ss');
}
return escapeQuotes(value);
}
var TOO_MANY_REQUESTS = 'The sync script has exceeded rate limits';
/**
* Runs a Fusion Tables SQL statement. Reruns the query if not successful.
* @param {string} query The query to execute
* @return {?Array} the Fusion Table response formatted as a JSON object if the
* query was successful. Returns null if not.
*/
function runSqlWithRetry(sql) {
try {
return runSql(sql);
} catch (e) {
if (e == TOO_MANY_REQUESTS) {
// If there were too many requests being sent, sleep for a bit
waitBetweenCalls();
return runSql(sql);
} else {
throw e;
}
}
}
/**
* Runs a Fusion Tables SQL statement and catches any errors. Logs errors
* and rethrows based on whether the error is retryable.
* @param {string} sql The SQL to execute.
* @return {Object} the Fusion Table response object if successful.
*/
function runSql(sql) {
try {
return FusionTables.Query.sql(sql, { hdrs: false });
} catch(err) {
if (err.message.search('Rate Limit Exceeded') != -1) {
throw TOO_MANY_REQUESTS;
} else {
var msg = 'Problem running SQL: ' + sql + ': ' + err + '.';
if (err.message.search(/Column .* does not exist/) != -1 ||
err.message.search('Bad column reference') != -1) {
msg += ' Looks like the column names in the form do not match ' +
'the column names in the table. Make sure these match!';
}
throw msg;
}
}
}
/**
* Converts the spreadsheet contents to a dictionary, mapping rowid
* to column values. If rowid == -1 or null, the rowid is mapped to a list
* of column values representing the failed inserts.
* @param {Array} array An array of data, the first row contains headers.
* @param {Object} map The resulting dictionary of row id mapped to columns.
* {rowid:{column:value,...} | [{{column:value,...}}],}.
*/
function mapRowsByRowId(columns, rows) {
var map = {};
if (!rows) {
return;
}
for (var i = 0; i < rows.length; i++) {
var row = rows[i];
var rowId = row[row.length - 1];
var columnMap = {};
for (var j = 0; j < columns.length; j++) {
var columnName = columns[j];
var columnValue = row[j];
columnMap[columnName] = columnValue;
}
if (rowId == -1 || !rowId) {
if (!map[-1]) {
map[-1] = [];
}
// Add the (one-based) spreadsheet row number to the map.
// Since we've excluded the headers from the row, spreadsheet
// row numbers for data start at 2.
columnMap.spreadsheetRowNum = i + 2;
map[-1].push(columnMap);
} else {
map[rowId] = columnMap;
}
}
return map;
}
/**
* Sleeps for two seconds to avoid API quota problems.
*/
function waitBetweenCalls() {
Utilities.sleep(2000);
}
/**
* Returns the value with single quotes and backslashes escaped.
*/
function escapeQuotes(value) {
if (!value) {
return "";
}
if (typeof value != 'string') {
value = value.toString();
}
return value.replace(/\\/g, '\\\\').replace(/'/g, "\\\'");
}
// create menu buttons
function onOpen() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var menuEntries = [{
name: "Update Fusion Table",
functionName: "sync"
}];
ss.addMenu("Sync Spreadsheet To Fusion Table", menuEntries);