-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathgas.js
429 lines (379 loc) · 12.6 KB
/
gas.js
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
// PUBNUB CONFIG
var PUB_KEY = 'pub-c-KEY-HERE';
var SUB_KEY = 'sub-c-KEY-HERE';
var CHANNEL = 'channel_name';
function pingPubNub(req) {
var msg = req.parameter.text;
var url = 'http://pubsub.pubnub.com/publish/' + PUB_KEY + '/' + SUB_KEY + '/0/' + CHANNEL + '/0/' + escape('"' + msg + '"');
var response = UrlFetchApp.fetch(url);
}
////////////////////////////////////////////////////// TRIGGERS AND STUFF
function setMeUp(e) {
displayAPIEndpoint();
}
function displayAPIEndpoint() {
var scriptProperties = PropertiesService.getScriptProperties();
scriptProperties.setProperty('ssid', SpreadsheetApp.getActiveSpreadsheet().getId());
var ep = ScriptApp.getService().getUrl();
Browser.msgBox("Your API Endpoint: " + ep);
}
////////////////////////////////////////////////////// RESTful API STUFF
function doGet(req) {
if (req.parameter._method && req.parameter._method.toLowerCase() == "post") return lePost(req);
var sheet = getSheet(req);
var returnData = {success: true}; // optimism FTW
var offset = req.parameter.offset ? parseInt(req.parameter.offset) : 0;
var limit = req.parameter.limit ? parseInt(req.parameter.limit) : 30;
limit = Math.min(100, limit);
var metaObj = {total_results:0, limit:limit, offset: offset};
var results = getRowsData(sheet);
metaObj.total_results = results.length;
var limited = results.slice(offset, offset+limit);
var strippedQueryString = '';
if (req.queryString) strippedQueryString = req.queryString.replace(/(limit|offset)=[0-9]*&?/g, '').replace(/&$/, '');
if (offset + limit < metaObj.total_results) {
metaObj.next = '?' + strippedQueryString + '&limit=' + limit + '&offset=' + (offset + limit);
}
if (offset > 0) {
metaObj.prev = '?' + strippedQueryString + '&limit=' + limit + '&offset=' + (Math.max(offset - limit, 0));
}
returnData.results = limited
returnData.meta = metaObj;
return sendResponse(req, returnData)
}
function doPost(req) {
// do the actual POST commands in this separate function, to allow using GET with "_method" parameter to point to the same function
return lePost(req);
}
function lePost(req) {
// If your entry requires a simple date stamp:
// simpleDate(new Date(req.parameter.date));
//if you need a unique id
//req.parameter.id = Utils.uuid(10);
var saveObj = {
text : req.parameter.text,
id : req.parameter.messageId,
timestamp : req.parameter['message-timestamp'],
from : req.parameter.msisdn
}
pingPubNub(req);
// make sure we've already got this person in the directory
var directorySheet = SpreadsheetApp.openById(getId()).getSheetByName('directory');
var person = findRow(directorySheet, {phone: saveObj.from});
if (person == false) {
saveToSpreadsheet(directorySheet, {phone: saveObj.from, name: saveObj.text});
} else {
var answersSheet = getSheet(req);
saveToSpreadsheet(answersSheet, saveObj);
}
var returnData = {success: true};
return sendResponse(req, returnData);
}
////////////////////////////////////////////////////// HELPERS
/**
* send off the final response
* @param {req} the HTTP request object
* @param {returnData} the object to send
*
*/
function sendResponse(req, returnData) {
//if you want a quick send-to-email kind of debugging:
if (req.parameter.callback) { //JSONP
return ContentService.createTextOutput(req.parameter.callback + '(' + JSON.stringify(returnData) + ')' ).setMimeType(ContentService.MimeType.JAVASCRIPT);
} else {
return ContentService.createTextOutput(JSON.stringify(returnData)).setMimeType(ContentService.MimeType.JSON);
}
}
/**
* @param {req} the HTTP request object
*
*/
function getSheet(req) {
var sheet;
if (req.parameter.sheet) {
sheet = SpreadsheetApp.openById(getId()).getSheetByName(req.parameter.sheet);
} else {
sheet = SpreadsheetApp.openById(getId()).getSheets()[0];
}
return sheet;
}
/**
* Iterates row by row in the input range and returns an array of objects. Each object contains all the data for a given row, indexed by its normalized column name.
*
* @param {sheet} the sheet object that contains the data to be processed
* @param {nestedProps} use dot notation as nested properties
* @param {integer} (optional): 1-based (NOT zero-based) specifies the row number where the column names are stored, defaults to first row.
* @return {array} array of objects
*/
function getRowsData(sheet, nestedProps, columnHeadersRowIndex) {
columnHeadersRowIndex = columnHeadersRowIndex || 1;
nestedProps = (nestedProps === false) ? false : true;
var range = sheet.getDataRange();
var numColumns = range.getLastColumn() - range.getColumn() + 1;
var headersRange = sheet.getRange(columnHeadersRowIndex, range.getColumn(), 1, numColumns);
var headers = headersRange.getValues()[0];
var dataRange = range.getValues();
dataRange.splice(0, columnHeadersRowIndex);
return getObjects(dataRange, normalizeHeaders(headers), nestedProps);
}
/**
* Gets a single row based on index.
*
* @param {sheet} the sheet object that contains the data to be processed
* @param {object} one or more key:val pairs to match on
* @return {object} matched row as an object
*/
function getRowByIndex(sheet, ind, nestedProps, columnHeadersRowIndex) {
columnHeadersRowIndex = columnHeadersRowIndex || 1;
nestedProps = (nestedProps === false) ? false : true;
var range = sheet.getDataRange();
var numColumns = range.getLastColumn() - range.getColumn() + 1;
var headersRange = sheet.getRange(columnHeadersRowIndex, range.getColumn(), 1, numColumns);
var headers = headersRange.getValues()[0];
//Now we have the info we need to get the range for just a single row and make an object
var singleRowRange = sheet.getRange(ind,range.getColumn(),1,range.getLastColumn());
var dataRange = singleRowRange.getValues();
return getObjects(dataRange, normalizeHeaders(headers), nestedProps)[0];
}
/**
* Finds a single row based on matching field(s).
*
* @param {sheet} the sheet object that contains the data to be processed
* @param {object} one or more key:val pairs to match on
* @return {object} matched row as an object
*/
function findRow(sheet, matchingObj) {
var allRows = getRowsData(sheet, false);
var numRows = allRows.length;
for (var i=0; i<numRows; i++) {
var leRow = allRows[i];
var isMatch = true;
for (var prop in matchingObj) {
if (leRow[prop] != matchingObj[prop]) {
isMatch = false;
break;
};
}
if (isMatch) {
// plus 1 because rows are 1-based, another plus one because getRowsData assumes a header row
return {index: i+2, data: leRow};
}
}
return false;
}
/**
* Takes an object and saves it to spreadsheet matching up column headers with object properties
* @param {sheet}
* @param {object}
*/
function objectToRow(sheet,record) {
var headersRange = sheet.getRange(1, 1, 1, sheet.getMaxColumns());
var headers = normalizeHeaders(headersRange.getValues()[0]);
var values = [];
for (j = 0; j < headers.length; ++j) {
var header = headers[j];
var objVal;
var headerBits = header.split('.');
var evalable = "record";
for (var h=0; h<headerBits.length; h++) {
evalable+= '["' + headerBits[h] + '"]';
objVal = eval(evalable);
if (typeof objVal === "undefined") {
break;
}
}
// If the header is empty or the object value is empty...
if ( (!header.length > 0) || typeof objVal === 'undefined' || objVal == '' ) {
values.push('');
}
else {
values.push(objVal);
}
}
return values;
}
/**
* Takes an object and saves it to spreadsheet matching up column headers with object properties
* @param {sheet}
* @param {object}
*/
function saveToSpreadsheet(sheet,record) {
var headersRange = sheet.getRange(1, 1, 1, sheet.getMaxColumns());
var headers = normalizeHeaders(headersRange.getValues()[0]);
var values = [];
for (j = 0; j < headers.length; ++j) {
var header = headers[j];
var objVal;
var headerBits = header.split('.');
var evalable = "record";
for (var h=0; h<headerBits.length; h++) {
evalable+= '["' + headerBits[h] + '"]';
objVal = eval(evalable);
if (typeof objVal === "undefined") {
break;
}
}
// If the header is empty or the object value is empty...
if ( (!header.length > 0) || typeof objVal === 'undefined' || objVal == '' ) {
values.push('');
}
else {
values.push(objVal);
}
}
sheet.appendRow(values);
}
/**
* For every row of data in data, generates an object that contains the data. Names of object fields are defined in keys.
*
* @param {array} JavaScript 2d array
* @param {array} array of strings that define the property names for the objects to create
* @return {array} array of objects
*/
function getObjects(data, keys, nestedProps) {
var objects = [];
// each row
for (var i = 0; i < data.length; ++i) {
var obj = {};
var hasData = false;
// each column
for (var j = 0; j < data[i].length; ++j) {
var cellData = data[i][j];
if (isCellEmpty(cellData)) {
cellData = null;
} else {
hasData = true;
}
if (nestedProps) {
var keyBits = keys[j].split('.');
var finalProp = keyBits.pop();
var evalable = "obj";
for (var h=0; h<keyBits.length; h++) {
evalable+= "['" + keyBits[h] + "']";
var checkDef = eval(evalable);
if (typeof checkDef === "undefined") {
eval(evalable + " = {}");
}
}
if (typeof cellData === "string") {
cellData = cellData.replace(/\\/g,'\\\\').replace(/'/g,"\\'").replace(/\r?\n/g, "\\n");
evalable+= "['" + finalProp + "'] = '" + cellData + "'";
} else if (typeof cellData === "object") {
evalable+= "['" + finalProp + "'] = " + JSON.stringify(cellData);
} else {
evalable+= "['" + finalProp + "'] = " + cellData;
}
eval(evalable);
} else {
obj[keys[j]] = cellData;
}
}
if (hasData) {
objects.push(obj);
}
}
return objects;
}
/**
* @param {array} array of strings to normalize
* @return {array} array of normalized strings
*/
function normalizeHeaders(headers) {
var keys = [];
for (var i = 0; i < headers.length; ++i) {
var key = normalizeHeader(headers[i]);
if (key.length > 0) {
keys.push(key);
}
}
return keys;
}
/**
* Normalizes a string, by removing all alphanumeric characters and using mixed case
* to separate words. The output will always start with a lower case letter.
* This function is designed to produce JavaScript object property names.
* Examples:
* "First Name" -> "firstName"
* "Market Cap (millions) -> "marketCapMillions
* "1 number at the beginning is ignored" -> "numberAtTheBeginningIsIgnored"
* @param {string} string to normalize
* @return {string} normalized string
*/
function normalizeHeader(header) {
var key = "";
var upperCase = false;
for (var i = 0; i < header.length; ++i) {
var letter = header[i];
if (letter == " " && key.length > 0) {
upperCase = true;
continue;
}
if (!isAlnum(letter) && !isDot(letter) && !isUnderscore(letter)) {
continue;
}
if (key.length == 0 && isDigit(letter)) {
continue; // first character must be a letter
}
if (upperCase) {
upperCase = false;
key += letter.toUpperCase();
} else {
key += letter.toLowerCase();
}
}
return key;
}
/**
*
* @param {string}
* @return {boolean} true if the cell where cellData was read from is empty.
*/
function isCellEmpty(cellData) {
return typeof(cellData) == "string" && cellData == "";
}
/**
* @param {string}
* @return {boolean} true if the character char is alphabetical, false otherwise.
*/
function isAlnum(char) {
return char >= 'A' && char <= 'Z' ||
char >= 'a' && char <= 'z' ||
isDigit(char);
}
/**
* @param {string}
* @return {boolean} true if the character is a .
*/
function isDot(char) {
return char === ".";
}
/**
* @param {string}
* @return {boolean} true if the character is a .
*/
function isUnderscore(char) {
return char === "_";
}
/**
* @param {array}
* @param {string} the key to sort on
* @return {array} the sorted array
*/
function alphabetize(arr, key) {
return arr.sort(function compare(a, b) {
if (a[key].toLowerCase() > b[key].toLowerCase()){return 1;}
if (a[key].toLowerCase() < b[key].toLowerCase()){return -1;}
return 0;
});
}
/**
* @param {string}
* @return {boolean} Returns true if the character char is a digit, false otherwise.
*/
function isDigit(char) {
return char >= '0' && char <= '9';
}
function getId() {
var scriptProperties = PropertiesService.getScriptProperties();
return scriptProperties.getProperty('ssid');
}