-
Notifications
You must be signed in to change notification settings - Fork 0
/
fb_io.js
389 lines (300 loc) · 10 KB
/
fb_io.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
var score;
var UID;
var databaseRef;
var UID;
/**************************************************************/
// fb_initialise()
// Initialize firebase, connect to the Firebase project.
//
// Find the config data in the Firebase consol. Cog wheel > Project Settings > General > Your Apps > SDK setup and configuration > Config
//
// Input: n/a
// Return: n/a
/**************************************************************/
function fb_initialise() {
// Your web app's Firebase configuration
const firebaseConfig = {
apiKey: "AIzaSyC_YI2XkIRIFNFr3Ivxjd-5wx5kxAOyrj8",
authDomain: "fir-rebuild-b3c92.firebaseapp.com",
databaseURL: "https://fir-rebuild-b3c92-default-rtdb.asia-southeast1.firebasedatabase.app",
projectId: "fir-rebuild-b3c92",
storageBucket: "fir-rebuild-b3c92.appspot.com",
messagingSenderId: "187367274216",
appId: "1:187367274216:web:c399d98ffaadb217befb5d"
};
// Initialize Firebase
databaseRef = firebase.initializeApp(firebaseConfig);
//let ref = firebase.database("https://ben-britton-12comp-default-rtdb.asia-southeast1.firebasedatabase.app/")
// This log prints the firebase object to the console to show that it is working.
// As soon as you have the script working, delete this log.
console.log(firebase);
}
/**************************************************************/
// fb_helloWorld()
// Demonstrate a minimal write to firebase
// This function replaces the entire database with the message "Hello World"
//
// This uses the set() operation to write the key:value pair "message":"Hello World"
// The ref('/') part tells the operation to write to the base level of the database "/"
// This means it replaces the whole database with message:Hello World
/**************************************************************/
function fb_clear() {
console.log("fb_clear()");
firebase.database().ref('/').set(
{
}
);
}
function fb_reset() {
console.log("Running fb_goodbye()")
firebase.database().ref('/').set(
{
users: {
mOXE9Ueh4ng4ssf048Vn4bn9dSU2: {
name: "Ben Britton",
scores: {
game1: 3,
game2: 74
}
},
asjB2op495Hsdfu34JFpasdmei39: {
name: "Dwayne J",
scores: {
game1: 300,
game2: 7400
},
}
},
highScores: {
game1: {
"Dwayne J": 300,
"Ben Britton": 30,
"Patrick": 30,
"Spongebob": 13,
"Gary": 31,
},
game2: {
"Dwayne J": 7400,
"Ben Britton": 74
}
}
}
)
}
/**************************************************************/
// Authentication functions.
// fb_authenticate handles the Google login. It is passed a
// function to run once the Google login is complete
/**************************************************************/
function fb_authenticate(_DOTHIS){
console.log("Handling the Google login")
firebase.auth().onAuthStateChanged((user) => {
if (user) {
//If user is already logged in, check that they have registered for the site
console.log("logged in")
//console.log(user.uid)
_DOTHIS(user.uid, user.displayName)
} else {
console.log("Not logged in")
// User is signed out
// Using a popup.
var provider = new firebase.auth.GoogleAuthProvider();
firebase.auth().signInWithPopup(provider).then(function(result) {
console.log("signInWithPopup")
// This gives you a Google Access Token.
var token = result.credential.accessToken;
// The signed-in user info.
var user = result.user;
_DOTHIS(user.uid, user.displayName)
});
}
});
}
/**************************************************************/
// fb_login()
// Use Google's login
// This function reads the current value from the 'message' field once
//
//
/**************************************************************/
function fb_login() {
console.log("logging in")
firebase.auth().onAuthStateChanged((user) => {
if (user) {
console.log("logged in")
// User is signed in, see docs for a list of available properties
// https://firebase.google.com/docs/reference/js/firebase.User
/*sessionStorage.userData = {
uid: user.uid,
name: user.displayName,
};*/
// ...
UID = user.uid;
console.log(user.uid)
//fb_setUID(user.uid)
} else {
console.log("Not logged in")
// User is signed out
// Using a popup.
var provider = new firebase.auth.GoogleAuthProvider();
firebase.auth().signInWithPopup(provider).then(function(result) {
// This gives you a Google Access Token.
var token = result.credential.accessToken;
// The signed-in user info.
var user = result.user;
//fb_setUID(user.uid)
});
}
});
}
function fb_readScore() {
var readPath = 'users/'+UID+"/scores/game1";
console.log("fb_readScore: reading "+readPath)
databaseRef.database().ref(readPath).once('value', fb_logDatabaseRead, fb_error)
function fb_logDatabaseRead(snapshot) {
console.log("You have "+snapshot.val().score + " points")
}
}
function fb_writeScore() {
var writePath = 'users/'+UID+"/scores/game1";
console.log("fb_writeScore: writing "+score+" to "+writePath)
firebase.database().ref(writePath + '/score').set(score);
}
function fb_getPoint() {
if (score) {
score++;
} else {
score = 1;
}
console.log("You have "+score+" points")
}
function fb_checkUser() {
console.log("fb_checkUser - your UID is:")
console.log(UID)
}
/**************************************************************/
// fb_readMessageOnce()
// Demonstrate a minimal read from firebase
// This function reads the current value from the 'message' field once
//
//
/**************************************************************/
function fb_readOnce() {
console.log("Read Once")
firebase.database().ref('/highScores/game1').orderByValue().limitToLast(3).once('value', fb_logDatabaseRead, fb_error)
}
function fb_logDatabaseRead(snapshot) {
snapshot.forEach(DO_THIS)
function DO_THIS(childSnapshot) {
console.log(childSnapshot.key + " " + childSnapshot.val())
}
}
//
/*
function fb_logDatabaseRead(snapshot){
if (snapshot.val()==null){
console.log ("There was no data, the values are null.");
}else{
console.log (snapshot.val());
}
}
*/
function fb_readListener() {
console.log("Read Listener");
firebase.database().ref('/message').on('value', fb_logDatabaseRead)
}
function fb_error(error) {
console.log("fb_error");
console.log(error)
}
/**************************************************************
// fb_readHighScores()
// Read and process the whole high score path
**************************************************************/
function fb_readHighScores() {
console.log("Reading High scores");
//https://firebase.google.com/docs/database/web/lists-of-data
firebase.database().ref('/highScores/game1').orderByValue().once('value', fb_displayHighScores, fb_error);
// firebase.database().ref('/highScores/game1').once('value', fb_displayHighScores, fb_error);
// firebase.database().ref('/highScores/game1').once('value', fb_displayHighScores, fb_error);
}
function fb_displayHighScores(snapshot) {
let highScores = snapshot.val()
snapshot.forEach(ARGH)
// console.log(highScores);
/*
let names = Object.keys(highScores);
console.log(names);
for(let i = 0; i < names.length;i++){
let key = names[i];
console.log("Score "+i+" is for "+names[i]+". "+highScores[names[i]].score+" points.");
}*/
function ARGH(child) {
console.log(child.val());
}
}
function DO_THIS(snapshot) {
console.log(snapshot.val());
console.log(snapshot.val()["Ben Britton"])
let scoreObject = {
"Dwayne J": 300,
"Ben Britton": 3
}
}
/**************************************************************/
// fb_readMessageOn()
// Demonstrate a minimal listener for firebase
// This function sets up a listener for the 'message' field.
// It will immediately run the appropriate callback.
// It will run the appropriate callback whenever the 'message' field is changed
// If the read is successful it will call the fb_readOK function
// If the read is not successful it will call the FB_readError function
// Input: n/a
// Return: n/a
/**************************************************************/
function fb_readMessageOn() {
//database.ref('/message').on('value', fb_readOK, fb_readError);
database.ref('/message').on('value').then(fb_readOK).catch(fb_readError);
//firebase.database().ref('/').child('message').on('value').then(fb_readOK).catch(fb_readError);
//firebase.database().ref('/').child('message').on('value').then(fb_readOK).catch(fb_readError);
}
function fb_readGet() {
database.ref("/").child("message").get('value').then(fb_readOK).catch(fb_readError);
//const dbRef = firebase.database().ref();
//dbRef.child("message").get('value').then(fb_readOK).catch(fb_readError);
//dbRef.child("message").get(fb_readOK, fb_readError)
/*
dbRef.child("message").get().then((snapshot) => {
if (snapshot.exists()) {
console.log(snapshot.val());
} else {
console.log("No data available");
}
}).catch((error) => {
console.error(error);
});*/
}
/*-----------------------------------------*/
// fb_readOK is a callback function. It will run when the database read has finished
// the database call will pass a snapshot of the data to fb_readOK
// Input: data returned from firebase
/*-----------------------------------------*/
function DO_THIS(snapshot) {
var dbData = snapshot.val();
if (dbData == null) {
console.log('There was no record when trying to read the message');
}
else {
console.log("The message is: " + dbData)
console.log(dbData)
}
}
/*-----------------------------------------*/
// fb_readError(error)
// DB read record failed
// Input: error message returned from firebase
/*-----------------------------------------*/
function fb_readError(error) {
console.log("There was an error reading the message");
console.error(error);
}