forked from EddyVerbruggen/nativescript-plugin-firebase
-
Notifications
You must be signed in to change notification settings - Fork 0
/
firebase.android.js
executable file
·505 lines (467 loc) · 16.4 KB
/
firebase.android.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
var appModule = require("application");
var firebase = require("./firebase-common");
firebase.toHashMap = function(obj) {
var node = new java.util.HashMap();
for (var property in obj) {
if (obj.hasOwnProperty(property)) {
if (obj[property] !== null) {
switch (typeof obj[property]) {
case 'object':
node.put(property, firebase.toHashMap(obj[property], node));
break;
case 'boolean':
node.put(property, java.lang.Boolean.valueOf(String(obj[property])));
break;
case 'number':
if (Number(obj[property]) === obj[property] && obj[property] % 1 === 0)
node.put(property, java.lang.Long.valueOf(String(obj[property])));
else
node.put(property, java.lang.Double.valueOf(String(obj[property])));
break;
case 'string':
node.put(property, String(obj[property]));
break;
}
}
}
}
return node;
};
firebase.toJsObject = function(javaObj) {
if (javaObj === null || typeof javaObj != "object") {
return javaObj;
}
var node;
switch (javaObj.getClass().getName()) {
case 'java.lang.Boolean':
return Boolean(String(javaObj));
case 'java.lang.Long':
case 'java.lang.Double':
return Number(String(javaObj));
case 'java.util.ArrayList':
node = [];
for (var i = 0; i < javaObj.size(); i++) {
node[i] = firebase.toJsObject(javaObj.get(i));
}
break;
default:
node = {};
var iterator = javaObj.entrySet().iterator();
while (iterator.hasNext()) {
var item = iterator.next();
switch (item.getClass().getName()) {
case 'java.util.HashMap$HashMapEntry':
node[item.getKey()] = firebase.toJsObject(item.getValue());
break;
case 'java.lang.String':
node[item.getKey()] = String(item.getValue());
break;
case 'java.lang.Boolean':
node[item.getKey()] = Boolean(String(item.getValue()));
break;
case 'java.lang.Long':
case 'java.lang.Double':
node[item.getKey()] = Number(String(item.getValue()));
break;
default:
node[item.getKey()] = item.getValue();
}
}
}
return node;
};
firebase.getCallbackData = function(type, snapshot) {
return {
type: type,
key: snapshot.getKey(),
value: firebase.toJsObject(snapshot.getValue())
};
};
firebase.init = function (arg) {
return new Promise(function (resolve, reject) {
try {
var fDatabase = com.google.firebase.database.FirebaseDatabase;
// console.log("fDatabase: " + fDatabase);
if (arg.persist) {
fDatabase.getInstance().setPersistenceEnabled(true);
}
// the URL is picked up from google-services.json, so you can use it like this:
instance = fDatabase.getInstance().getReference();
// it is however still possible to pass the URL programmatically (which we'll do for now):
// instance = fDatabase.getInstance().getReferenceFromUrl(arg.url);
resolve(instance);
} catch (ex) {
console.log("Error in firebase.init: " + ex);
reject(ex);
}
});
};
firebase.logout = function (arg) {
return new Promise(function (resolve, reject) {
try {
com.google.firebase.auth.FirebaseAuth.getInstance().signOut();
resolve();
} catch (ex) {
console.log("Error in firebase.logout: " + ex);
reject(ex);
}
});
};
firebase.authStateListener = null;
firebase.login = function (arg) {
return new Promise(function (resolve, reject) {
try {
/*
var authorizer = new com.google.firebase.database.DatabaseReference.AuthResultHandler({
onAuthenticated: function (authData) {
resolve({
uid: authData.getUid(),
provider: authData.getProvider(),
expiresAtUnixEpochSeconds: authData.getExpires(),
profileImageURL: authData.getProviderData().get("profileImageURL"),
token: authData.getToken()
});
},
onAuthenticationError: function (databaseError) {
reject(databaseError.getMessage());
}
});
*/
var firebaseAuth = com.google.firebase.auth.FirebaseAuth.getInstance();
if (firebase.authStateListener !== null) {
firebaseAuth.removeAuthStateListener(firebase.authStateListener);
}
firebase.authStateListener = new com.google.firebase.auth.FirebaseAuth.AuthStateListener({
onAuthStateChanged: function (fbAuth) {
console.log("--- auth state changed: " + fbAuth);
var user = fbAuth.getCurrentUser();
console.log("--- user: " + user);
if (user !== null) {
// signed in
resolve({
uid: user.getUid(),
name: user.getDisplayName(),
email: user.getEmail(),
// TODO add these properties, see https://firebase.google.com/docs/auth/android/manage-users#get_a_users_profile
// provider: authData.getProvider(),
// expiresAtUnixEpochSeconds: authData.getExpires(),
profileImageURL: user.getPhotoUrl()
// token: user.getToken() // can be used to auth with a backend server
});
} else {
// reject("Logging in the user failed");
}
}
});
firebaseAuth.addAuthStateListener(firebase.authStateListener);
if (arg.type === firebase.LoginType.ANONYMOUS) {
var onFailureListener = new com.google.android.gms.tasks.OnFailureListener({
onFailure: function (throwable) {
reject("Anonymous login failed with message: " + throwable.getMessage());
}
});
firebaseAuth.signInAnonymously().addOnFailureListener(onFailureListener);
} else if (arg.type === firebase.LoginType.PASSWORD) {
if (!arg.email || !arg.password) {
reject("Auth type emailandpassword requires an email and password argument");
} else {
var onCompleteListener = new com.google.android.gms.tasks.OnCompleteListener({
onComplete: function (task) {
if (!task.isSuccessful()) {
reject("Logging in the user failed");
} else {
// the AuthStateListener.onAuthStateChanged callback will resolve the promise
}
}
});
firebaseAuth.signInWithEmailAndPassword(arg.email, arg.password).addOnCompleteListener(onCompleteListener);
}
} else {
reject ("Unsupported auth type: " + arg.type);
}
} catch (ex) {
console.log("Error in firebase.login: " + ex);
reject(ex);
}
});
};
firebase.resetPassword = function (arg) {
return new Promise(function (resolve, reject) {
try {
if (!arg.email) {
reject("Resetting a password requires an email argument");
} else {
var onCompleteListener = new com.google.android.gms.tasks.OnCompleteListener({
onComplete: function (task) {
console.log("--- reset pwd: " + task);
if (task.isSuccessful()) {
resolve();
} else {
// TODO extract error
reject("Sending password reset email failed");
}
}
});
var firebaseAuth = com.google.firebase.auth.FirebaseAuth.getInstance();
firebaseAuth.sendPasswordResetEmail(arg.email).addOnCompleteListener(onCompleteListener);
}
} catch (ex) {
console.log("Error in firebase.resetPassword: " + ex);
reject(ex);
}
});
};
firebase.changePassword = function (arg) {
return new Promise(function (resolve, reject) {
try {
if (!arg.email || !arg.oldPassword || !arg.newPassword) {
reject("Changing a password requires an email and an oldPassword and a newPassword arguments");
} else {
var onCompleteListener = new com.google.android.gms.tasks.OnCompleteListener({
onComplete: function (task) {
console.log("--- changed pwd: " + task);
if (task.isSuccessful()) {
resolve();
} else {
// TODO extract error
reject("Updating password failed");
}
}
});
var user = com.google.firebase.auth.FirebaseAuth.getInstance().getCurrentUser();
if (user === null) {
reject("Please log the user in first");
} else {
user.updatePassword(arg.newPassword).addOnCompleteListener(onCompleteListener);
}
}
} catch (ex) {
console.log("Error in firebase.changePassword: " + ex);
reject(ex);
}
});
};
firebase.createUser = function (arg) {
return new Promise(function (resolve, reject) {
try {
if (!arg.email || !arg.password) {
reject("Creating a user requires an email and password argument");
} else {
var firebaseAuth = com.google.firebase.auth.FirebaseAuth.getInstance();
var onCompleteListener = new com.google.android.gms.tasks.OnCompleteListener({
onComplete: function (task) {
if (!task.isSuccessful()) {
reject("Creating a user failed");
} else {
// the AuthStateListener.onAuthStateChanged callback will resolve the promise
}
}
});
if (firebase.authStateListener !== null) {
firebaseAuth.removeAuthStateListener(firebase.authStateListener);
}
firebase.authStateListener = new com.google.firebase.auth.FirebaseAuth.AuthStateListener({
onAuthStateChanged: function (fbAuth) {
console.log("--- auth state changed: " + fbAuth);
var user = fbAuth.getCurrentUser();
if (user !== null) {
// signed in
resolve({
key: user.getUid()
});
}
}
});
firebaseAuth.addAuthStateListener(firebase.authStateListener);
firebaseAuth.createUserWithEmailAndPassword(arg.email, arg.password).addOnCompleteListener(onCompleteListener);
}
} catch (ex) {
console.log("Error in firebase.createUser: " + ex);
reject(ex);
}
});
};
firebase._addObservers = function(to, updateCallback) {
var listener = new com.google.firebase.database.ChildEventListener({
onChildAdded: function (snapshot, previousChildKey) {
updateCallback(firebase.getCallbackData('ChildAdded', snapshot));
},
onChildRemoved: function (snapshot) {
updateCallback(firebase.getCallbackData('ChildRemoved', snapshot));
},
onChildChanged: function (snapshot, previousChildKey) {
updateCallback(firebase.getCallbackData('ChildChanged', snapshot));
},
onChildMoved: function (snapshot, previousChildKey) {
updateCallback(firebase.getCallbackData('ChildMoved', snapshot));
}
});
to.addChildEventListener(listener);
};
firebase.addChildEventListener = function (updateCallback, path) {
return new Promise(function (resolve, reject) {
try {
firebase._addObservers(instance.child(path), updateCallback);
resolve();
} catch (ex) {
console.log("Error in firebase.addChildEventListener: " + ex);
reject(ex);
}
});
};
firebase.addValueEventListener = function (updateCallback, path) {
return new Promise(function (resolve, reject) {
try {
var listener = new com.google.firebase.database.ValueEventListener({
onDataChange: function (snapshot) {
updateCallback(firebase.getCallbackData('ValueChanged', snapshot));
},
onCancelled: function (databaseError) {
updateCallback({
error: databaseError.getMessage()
});
}
});
instance.child(path).addValueEventListener(listener);
resolve();
} catch (ex) {
console.log("Error in firebase.addValueEventListener: " + ex);
reject(ex);
}
});
};
firebase.removeEventListener = function (listener, path) {
return new Promise(function (resolve, reject) {
try {
console.log("Removing at path " + path + ": " + listener);
instance.child(path).removeEventListener(listener);
resolve();
} catch (ex) {
console.log("Error in firebase.removeEventListener: " + ex);
reject(ex);
}
});
};
firebase.push = function (path, val) {
return new Promise(function (resolve, reject) {
try {
var pushInstance = instance.child(path).push();
pushInstance.setValue(firebase.toHashMap(val));
resolve({
key: pushInstance.getKey()
});
} catch (ex) {
console.log("Error in firebase.push: " + ex);
reject(ex);
}
});
};
firebase.setValue = function (path, val) {
return new Promise(function (resolve, reject) {
try {
instance.child(path).setValue(firebase.toHashMap(val));
resolve();
} catch (ex) {
console.log("Error in firebase.setValue: " + ex);
reject(ex);
}
});
};
firebase.update = function (path, val) {
return new Promise(function (resolve, reject) {
try {
instance.child(path).updateChildren(firebase.toHashMap(val));
resolve();
} catch (ex) {
console.log("Error in firebase.update: " + ex);
reject(ex);
}
});
};
firebase.query = function (updateCallback, path, options) {
return new Promise(function (resolve, reject) {
try {
var query;
// orderBy
if (options.orderBy.type === firebase.QueryOrderByType.KEY) {
query = instance.child(path).orderByKey();
} else if (options.orderBy.type === firebase.QueryOrderByType.VALUE) {
query = instance.child(path).orderByValue();
} else if (options.orderBy.type === firebase.QueryOrderByType.PRIORITY) {
query = instance.child(path).orderByPriority();
} else if (options.orderBy.type === firebase.QueryOrderByType.CHILD) {
if (!options.orderBy.value) {
reject("When orderBy.type is 'child' you must set orderBy.value as well.");
return;
}
query = instance.child(path).orderByChild(options.orderBy.value);
} else {
reject("Invalid orderBy.type, use constants like firebase.QueryOrderByType.VALUE");
return;
}
// range
if (options.range && options.range.type) {
if (!options.range.value) {
reject("Please set range.value");
return;
}
if (options.range.type === firebase.QueryRangeType.START_AT) {
query = query.startAt(options.range.value);
} else if (options.range.type === firebase.QueryRangeType.END_AT) {
query = query.endAt(options.range.value);
} else if (options.range.type === firebase.QueryRangeType.EQUAL_TO) {
query = query.equalTo(options.range.value);
} else {
reject("Invalid range.type, use constants like firebase.QueryRangeType.START_AT");
return;
}
}
// limit
if (options.limit && options.limit.type) {
if (!options.limit.value) {
reject("Please set limit.value");
return;
}
if (options.limit.type === firebase.QueryLimitType.FIRST) {
query = query.limitToFirst(options.limit.value);
} else if (options.limit.type === firebase.QueryLimitType.LAST) {
query = query.limitToLast(options.limit.value);
} else {
reject("Invalid limit.type, use constants like firebase.QueryLimitType.FIRST");
return;
}
}
if (options.singleEvent) {
var listener = new com.google.firebase.database.ValueEventListener({
onDataChange: function (snapshot) {
updateCallback(firebase.getCallbackData('ValueChanged', snapshot));
},
onCancelled: function (databaseError) {
updateCallback({
error: databaseError.getMessage()
});
}
});
query.addListenerForSingleValueEvent(listener);
} else {
firebase._addObservers(query, updateCallback);
}
resolve();
} catch (ex) {
console.log("Error in firebase.query: " + ex);
reject(ex);
}
});
};
firebase.remove = function (path) {
return new Promise(function (resolve, reject) {
try {
instance.child(path).setValue(null);
resolve();
} catch (ex) {
console.log("Error in firebase.remove: " + ex);
reject(ex);
}
});
};
module.exports = firebase;