-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscripts.js
704 lines (648 loc) · 19.6 KB
/
scripts.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
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
/// *********************
/// * UTILITY FUNCTIONS *
/// *********************
function isoDate(dateObj){
// LOCAL ISO: YYYY-MM-DD HH:MM:SS
return dateObj.getFullYear()+"-"+padZeroes(2,dateObj.getMonth()+1)+"-"+padZeroes(2,dateObj.getDate())+" "+padZeroes(2,dateObj.getHours())+":"+padZeroes(2,dateObj.getMinutes())+":"+padZeroes(2,dateObj.getSeconds());
}
function padZeroes(width, num){
width -= num.toString().length;
if (width > 0){
return new Array(width+(/\./.test(num) ? 2 : 1)).join('0')+num;
}
return num+"";
}
function readCookie(key){
var result;
return (result = new RegExp('(?:^|; )' + encodeURIComponent(key) + '=([^;]*)').exec(document.cookie)) ? (result[1]) : null;
}
function getHashmark(){
if (window.location.hash != ""){
return window.location.hash.substring(1);
}
return undefined;
}
function setHashmark(value){
return window.location.hash = value;
}
function whatIsTheTimeout(message) {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
console.log(message+"TOKEN TIMEOUT: "+JSON.parse(this.responseText).expires_in);
startTimeoutKeeper(JSON.parse(this.responseText).expires_in);
}
}
xhttp.open("GET", "https://www.googleapis.com/oauth2/v1/tokeninfo?access_token="+GoogleAuth.currentUser.get().getAuthResponse().access_token, true);
xhttp.send();
}
/// ******************************
/// * GOOGLE AUTH API AND CONFIG *
/// ******************************
var GoogleAuth; // Stores auth token and other info
/// ***** BUTTON FUNCTIONS *****
// Hangles sign in and out with one press
function toggleAuth() {
if (GoogleAuth.isSignedIn.get()) {
GoogleAuth.signOut();
}
else {
GoogleAuth.signIn();
}
}
/// ***** INTERNAL FUNCTIONS *****
// Called from HTML to finish loading API
function loadAuth() {
gapi.load("client:auth2", initClient);
}
// Generates auth client instance, stored in GoogleAuth
function initClient() {
gapi.client.init({ // Initialize a client with these properties
"apiKey":"AIzaSyDIptkXtN8vcrOr5LPBvk21WuAk8UmVwAs",
"discoveryDocs":["https://www.googleapis.com/discovery/v1/apis/drive/v3/rest","https://www.googleapis.com/discovery/v1/apis/sheets/v4/rest"],
"clientId":"1031491199015-pbjmtfn9kj0tvcl24k7vntelua6glb90.apps.googleusercontent.com",
"scope":"https://www.googleapis.com/auth/drive.file https://www.googleapis.com/auth/drive.metadata.readonly https://www.googleapis.com/auth/spreadsheets"
}).then(function() {
GoogleAuth = gapi.auth2.getAuthInstance();
GoogleAuth.isSignedIn.listen(onAuthUpdate);
if (document.URL == "https://gmferise.github.io/osmium/" && readCookie("keepAuth") == null) { GoogleAuth.signOut(); }
else { onAuthUpdate(); } // Still must be called, tells frontend auth has loaded
});
}
/// ***********************
/// * DATABASE MANAGEMENT *
/// ***********************
// Dictionary of known databases which is kept up to date using getDatabases()
// Stored as 'id':'name'
var knownDatabases = {};
var databaseId; // Currently selected database in the form of it's spreadsheet id1
var pageId = 0; // Second page of spreadsheet
/// ***** ASYNC FUNCTIONS *****
// Creates new database in user's Drive using given name
// Returns new database id through catch
function createDatabase(name){
name = '[OsDB] '+name;
gapi.client.sheets.spreadsheets.create({
properties: {
title: name
}
}).then(function(response){
var id = response.result.spreadsheetId;
getDatabases(id);
var requests = [];
// Rename first page
requests.push({
"updateSheetProperties": {
"properties": {
"sheetId": 0,
"title": "DATABASE",
},
"fields": "title",
}
});
// Format database columns
requests.push({ // int id (>= 0)
"repeatCell": {
"range": {
"startRowIndex": 1,
"startColumnIndex": 0,
"endColumnIndex": 1
},
"cell": {
"userEnteredFormat": {
"numberFormat": {
"type": "NUMBER",
"pattern": "0"
},
},
"dataValidation": {
"condition": { "type": "NUMBER_GREATER_THAN_EQ", "values": [{"userEnteredValue": "0"}] },
"strict": true
}
},
"fields": "userEnteredFormat.numberFormat,dataValidation"
}
});
requests.push({ // str name (no validation)
"repeatCell": {
"range": {
"startRowIndex": 1,
"startColumnIndex": 1,
"endColumnIndex": 2
},
"cell": {
"userEnteredFormat": {
"numberFormat": {
"type": "TEXT",
"pattern": ""
}
}
},
"fields": "userEnteredFormat.numberFormat"
}
});
requests.push({ // str event (no validation)
"repeatCell": {
"range": {
"startRowIndex": 1,
"startColumnIndex": 2,
"endColumnIndex": 3
},
"cell": {
"userEnteredFormat": {
"numberFormat": {
"type": "TEXT",
"pattern": ""
}
}
},
"fields": "userEnteredFormat.numberFormat"
}
});
requests.push({ // DateTime timestamp (no validation)
"repeatCell": {
"range": {
"startRowIndex": 1,
"startColumnIndex": 3,
"endColumnIndex": 4
},
"cell": {
"userEnteredFormat": {
"numberFormat": {
"type": "DATE_TIME",
"pattern": "h:mm am/pm mmm dd"
}
}
},
"fields": "userEnteredFormat.numberFormat"
}
});
requests.push({ // str comments (no validation)
"repeatCell": {
"range": {
"startRowIndex": 1,
"startColumnIndex": 4,
"endColumnIndex": 5
},
"cell": {
"userEnteredFormat": {
"numberFormat": {
"type": "TEXT",
"pattern": ""
}
}
},
"fields": "userEnteredFormat.numberFormat"
}
});
requests.push({ // bool studying (strict)
"repeatCell": {
"range": {
"startRowIndex": 1,
"startColumnIndex": 5,
"endColumnIndex": 6
},
"cell": {
"dataValidation": {
"condition": {
"type": "BOOLEAN"
}
}
},
"fields": "dataValidation"
}
});
requests.push({ // bool technology (strict)
"repeatCell": {
"range": {
"startRowIndex": 1,
"startColumnIndex": 6,
"endColumnIndex": 7
},
"cell": {
"dataValidation": {
"condition": {
"type": "BOOLEAN"
}
}
},
"fields": "dataValidation"
}
});
requests.push({ // bool printing (strict)
"repeatCell": {
"range": {
"startRowIndex": 1,
"startColumnIndex": 7,
"endColumnIndex": 8
},
"cell": {
"dataValidation": {
"condition": { "type": "BOOLEAN" },
"strict": true,
"showCustomUi": true
}
},
"fields": "dataValidation"
}
});
// Give database columns headers
requests.push({
"updateCells": {
"rows": [{
"values": [
{"userEnteredValue": {"stringValue": "id"}},
{"userEnteredValue": {"stringValue": "name"}},
{"userEnteredValue": {"stringValue": "event"}},
{"userEnteredValue": {"stringValue": "timestamp"}},
{"userEnteredValue": {"stringValue": "comments"}},
{"userEnteredValue": {"stringValue": "library"}},
{"userEnteredValue": {"stringValue": "technology"}},
{"userEnteredValue": {"stringValue": "printing"}}
]
}],
"fields": "userEnteredValue",
"start": {
"rowIndex": 0,
"columnIndex": 0
},
}
});
// Make second page
requests.push({
"addSheet": {
"properties": {
"title":"ID_REFERENCE"
}
}
});
// Do first batch of requests
var batch = {requests: requests};
gapi.client.sheets.spreadsheets.batchUpdate({
spreadsheetId: id,
resource: batch
}).then(function(response){
// Then get the second page's id
var id = response.result.spreadsheetId;
gapi.client.sheets.spreadsheets.get({
spreadsheetId: id
}).then(function(response){
var id = response.result.spreadsheetId;
var pageId = response.result.sheets[1].properties.sheetId;
// Third round of requests, configuring the second page
var requests = [];
// Format reference page columns
requests.push({
"repeatCell": {
"range": {
"sheetId": pageId,
"startRowIndex": 0,
"startColumnIndex": 0,
"endColumnIndex": 1
},
"cell": {
"userEnteredFormat": {
"numberFormat": {
"type": "NUMBER",
"pattern": "0"
}
}
},
"fields": "userEnteredFormat.numberFormat"
}
});
requests.push({
"repeatCell": {
"range": {
"sheetId": pageId,
"startRowIndex": 0,
"startColumnIndex": 1,
"endColumnIndex": 2
},
"cell": {
"userEnteredFormat": {
"numberFormat": {
"type": "TEXT",
"pattern": ""
}
}
},
"fields": "userEnteredFormat.numberFormat"
}
});
// Give reference page columns headers
requests.push({
"updateCells": {
"rows": [{
"values": [
{"userEnteredValue": {"stringValue": "id"}},
{"userEnteredValue": {"stringValue": "name"}},
]
}],
"fields": "userEnteredValue",
"start": {
"sheetId": pageId,
"rowIndex": 0,
"columnIndex": 0
},
}
});
// Do requests
var batch = {requests: requests};
gapi.client.sheets.spreadsheets.batchUpdate({
spreadsheetId: id,
resource: batch
}).then(function(response){
if (response.status != 200){
throw new Error("Failed to configure the spreadsheet");
}
});
});
});
});
}
// Pulls list of [OsDB] sheets from user's Drive to update knownDatabases
// Returns new knownDatabases through catch
// newDatabase is an optional parameter that is used during database creation to act as a callback
function getDatabases(newDatabase){
// Do not place params directly in the array, must be evaluated beforehand
var params = "mimeType='application/vnd.google-apps.spreadsheet' and '"+GoogleAuth.currentUser.get().getBasicProfile().getEmail()+"' in writers and name contains '[OsDB]' and trashed = false";
gapi.client.drive.files.list({
q: params,
}).then(function(response) {
var dbs = response.result.files
for (var i = 0; i < dbs.length; i++){
knownDatabases[dbs[i].id] = dbs[i].name;
}
if (newDatabase != undefined) { catchCreateDatabase(newDatabase); }
catchGetDatabases(knownDatabases);
},function(err) { console.error("Failed to search Drive for Databases"); });
}
// Gets second page id of currently selected database
// Returns through catch
function getPageId(){
if (databaseId == undefined) { showError("no-database-selected"); return; }
return gapi.client.sheets.spreadsheets.get({
spreadsheetId: databaseId
}).then(function(response){
pageId = response.result.sheets[1].properties.sheetId;
});
}
/// ***** STANDARD FUNCTIONS *****
// Assigns databaseId a database from knownDatabases given it's id
// Returns selected database name through catch
function selectDatabase(id){
databaseId = id;
getPageId();
return id;
}
function getDatabaseName(id){
return knownDatabases[id];
}
function selectDatabaseFromUrl() {
var url = new URLSearchParams(window.location.search).get('id');
if (url != null) {
selectDatabase(url);
} else {
showError('no-url-database');
}
}
/// ******************
/// * UPDATE QUERIES *
/// ******************
/// ***** ASYNC FUNCTIONS *****
// Input: id, event name, comments, bool[](studying, technology, printing)
function pushEvent(id, type, comments, flags, forceunknown) {
// Get name from uid
getName(id, function(response){
name = response.getDataTable().getDistinctValues(1)[0];
if (name == "undefined") {
if (forceunknown) {
name = "Unknown Student";
} else {
catchUnknownId(id,type);
return;
}
}
// Update values
gapi.client.sheets.spreadsheets.values.append({
"spreadsheetId": databaseId,
"range": "A:H",
"valueInputOption": "USER_ENTERED",
"resource": {
"values": [
[id, name, type,
isoDate(new Date()),
comments, flags[0], flags[1], flags[2] ]
]
}
}).then(function(response){
if (response.status != 200){
throw new Error("Failed to add new rows.");
}
else {
catchPushEvent(name, type, flags);
}
});
}, pageId);
}
// Input: id, event, timestamp to identify a row
// Sets the comments column of the given a rowIndex
function updateComment(id, type, dateObject, newComment){
// First get the number of rows with dates older than or exactly the target date
var dateString = isoDate(dateObject);
gvzQuery("SELECT COUNT(D) WHERE D <= datetime '"+dateString+"'",
function(response){
var lteq = response.getDataTable().getDistinctValues(0)[0];
// Then get the data in any rows with the target date
gvzQuery("SELECT A, B, C, D, E, F, G, H WHERE D = datetime '"+dateString+"'",
function(response){
var eq = response.getDataTable().getNumberOfRows();
var rawtbl = response.getDataTable();
// Process the data into an array
var tbl = [];
for (var i = 0; i < rawtbl.getNumberOfRows(); i++){
var row = []
for (var j = 0; j < rawtbl.getNumberOfColumns(); j++){
if (rawtbl.getColumnType(j) == "datetime"){
row.push(isoDate(rawtbl.getValue(i,j)));
}
else {
row.push(rawtbl.getValue(i,j));
}
}
tbl.push(row);
}
// Update the comment for the row with the correct event and id
// Any extra rows selected because of matching date are unchanged
for (var i = 0; i < tbl.length; i++){
if (tbl[i][0] == id && tbl[i][2] == type){
tbl[i][4] = newComment;
}
}
// Now update ALL of the matching date rows in the database
// Definitely an ugly workaround for no UPDATE query
var a1range = "A"+(2+lteq-eq)+":H"+(1+lteq);
gapi.client.sheets.spreadsheets.values.update({
"spreadsheetId": databaseId,
"range": a1range,
"valueInputOption": "USER_ENTERED",
"resource": {
"values": tbl
}
}).then(function(response){
if (response.status != 200){
throw new Error("Failed to update comments.");
}
else {
catchUpdateComment();
}
});
});
});
}
// Sets a name for an id in the reference table and then fixes the database
function setReferenceName(id, newName){
if (pageId == 0 || pageId == undefined){ showError("bad-pageid"); }
// Get entire reference page
gvzQuery("SELECT A, B",
function(response){
var rawtbl = response.getDataTable();
var tbl = [];
for (var i = 0; i < rawtbl.getNumberOfRows(); i++){
var row = []
for (var j = 0; j < rawtbl.getNumberOfColumns(); j++){
row.push(rawtbl.getValue(i,j));
}
tbl.push(row);
}
// Update new id with name
var foundAndUpdated = false;
for (var i = 0; i < tbl.length; i++){
if (tbl[i][0] == id){
tbl[i][1] = newName
foundAndUpdated = true;
}
if (tbl[i][1] == "undefined" || tbl[i][1] == undefined){
tbl[i][1] == "Unknown Student";
}
}
// If it never found the id, add it
if (!foundAndUpdated){ tbl.push([id,newName]); }
// Update spreadsheet with new values
var a1range = "ID_REFERENCE!A2"+":B"+(tbl.length+1);
gapi.client.sheets.spreadsheets.values.update({
"spreadsheetId": databaseId,
"range": a1range,
"valueInputOption": "USER_ENTERED",
"resource": {
"values": tbl
}
}).then(function(response){
if (response.status != 200){
throw new Error("Failed to update name.");
}
else {
fixDatabaseNameColumn();
}
});
}, pageId);
}
// Updates the names in the database columns to reflect the new state of the reference page
function fixDatabaseNameColumn(){
// Select the entire database of names and ids column
gvzQuery("SELECT A, B",
function(response){
// Process the names and ids into a table array
var rawtbl = response.getDataTable();
var tbl = [];
for (var i = 0; i < rawtbl.getNumberOfRows(); i++){
var row = []
for (var j = 0; j < rawtbl.getNumberOfColumns(); j++){
row.push(rawtbl.getValue(i,j));
}
tbl.push(row);
}
// Then select the reference names and ids
gvzQuery("SELECT A, B",
function(response){
// Process the names and ids into a dictionary
var rawtbl = response.getDataTable();
var ref = {};
for (var i = 0; i < rawtbl.getNumberOfRows(); i++){
ref[rawtbl.getValue(i,0)] = rawtbl.getValue(i,1);
}
// Update names in table to match dictionary
for (var i = 0; i < tbl.length; i++){
tbl[i][1] = ref[tbl[i][0]];
}
// Update spreadsheet with new values
var a1range = "A2"+":B"+(tbl.length+1);
gapi.client.sheets.spreadsheets.values.update({
"spreadsheetId": databaseId,
"range": a1range,
"valueInputOption": "USER_ENTERED",
"resource": {
"values": tbl
}
}).then(function(response){
if (response.status != 200){
throw new Error("Failed to perform name fix.");
}
else {
catchEditStudentName();
}
});
}, pageId);
});
}
/// ******************
/// * SELECT QUERIES *
/// ******************
/// ***** INTERNAL FUNCTIONS *****
// Executes the Google Visualization query then passes the result into the callback function
function gvzQuery(query, callback, page){
if (page == undefined) { page = "0"; }
var request = new google.visualization.Query('https://docs.google.com/spreadsheets/d/'+databaseId+'/gviz/tq?headers=1&gid='+page+'&access_token='+encodeURIComponent(GoogleAuth.currentUser.get().getAuthResponse().access_token));
request.setQuery(query);
request.send(callback);
}
/// ***** ASYNC FUNCTIONS *****
// Queries the reference page for the name of a user given their id
// Returns through catch
function getName(id, callback){
if (pageId == 0 || pageId == undefined){ showError("bad-pageid"); }
gvzQuery("SELECT A, B, COUNT(A), COUNT(B) WHERE A = "+id+" GROUP BY A, B LIMIT 1", callback, pageId);
}
// Queries the reference page for the name of a user given their id
// Returns through catch
function searchById(id){
if (pageId == 0 || pageId == undefined){ showError("bad-pageid"); }
gvzQuery("SELECT A, B, COUNT(A), COUNT(B) WHERE A = "+id+" GROUP BY A, B LIMIT 1", catchSearch, pageId);
}
// Gets list of names/ids pairs matching name
// Returns through catch
function searchByName(name, maxSize){
if (pageId == 0 || pageId == undefined){ showError("bad-pageid"); }
gvzQuery("SELECT A, B, COUNT(A), COUNT(B) WHERE lower(B) CONTAINS lower('"+name+"') GROUP BY A, B LIMIT "+maxSize, catchSearch, pageId);
}
//Selects single most recent date of given student id
// Returns through catch to a given callback
function getLastSeen(id, callback){
gvzQuery("SELECT D WHERE A = "+id+" ORDER BY D DESC LIMIT 1", callback);
}
// Gets all table rows later than the given time up to the end of the day
// dateTo is optional
// Returns through catch
function getEventsAfter(dateFrom, dateTo){
if (dateTo == undefined) {
dateTo = new Date(dateFrom);
dateTo.setHours(23,59,59);
}
gvzQuery("SELECT A, B, C, D, E, F, G, H WHERE D >= datetime '"+isoDate(dateFrom)+"' AND D < datetime '"+isoDate(dateTo)+"' ORDER BY D ASC", catchEventsAfter);
}
// Gets all table rows with a student's id
// Returns through catch
function getStudentHistory(id){
gvzQuery("SELECT A, B, C, D, E, F, G, H WHERE A = "+id+" ORDER BY D DESC", catchStudentHistory);
}