-
Notifications
You must be signed in to change notification settings - Fork 3
/
utils.ts
404 lines (368 loc) · 9.25 KB
/
utils.ts
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
// Import the functions you need from the SDKs you need
import { initializeApp } from 'firebase/app'
//Database Storage
import {
getFirestore,
collection,
addDoc,
setDoc,
getDoc,
updateDoc,
getDocs,
doc,
query,
where,
serverTimestamp,
orderBy,
} from 'firebase/firestore'
//Firebase Auth
import {
getAuth,
onAuthStateChanged,
createUserWithEmailAndPassword,
signInWithEmailAndPassword,
signOut,
UserCredential,
User as FirebaseAuthUser,
UserMetadata,
} from 'firebase/auth'
import { getStorage, ref, uploadBytes, getDownloadURL } from 'firebase/storage'
//Interfaces
interface NewUser {
email: string
username: string
avatarIMG: string
googleAuth: boolean
partner_username: string
in_relationship: boolean
}
interface Timestamp {
timestamp: {
nanoseconds: number
seconds: number
}
}
interface Game {
gameContent: any
gameName: string
}
interface MessageEgg {
contentMsg: string
game: Game
isLocked: boolean
recipient: string
sender: string
timestamp: Timestamp
typeEgg: 'message'
}
interface FileEgg {
caption: string
fileURL: string
game: Game
isLocked: boolean
recipient: string
sender: string
timestamp: Timestamp
typeEgg: 'image'
}
type Egg = MessageEgg | FileEgg
// Your web app's Firebase configuration
const firebaseConfig = {
apiKey: 'AIzaSyBnlb5QLZkR3xp2KBb8wQwheNHb2WgE14s',
authDomain: 'love-birds-a5bd6.firebaseapp.com',
projectId: 'love-birds-a5bd6',
storageBucket: 'love-birds-a5bd6.appspot.com',
messagingSenderId: '1048606210807',
appId: '1:1048606210807:web:9735998c7b9fd4753cf1f2',
}
// Initialise Firebase
const app = initializeApp(firebaseConfig)
//Initialise Services
const storage = getStorage(app)
const db = getFirestore(app)
const auth = getAuth(app)
//Collections/Tables
const usersRef = collection(db, 'users')
const eggsRef = collection(db, 'eggs')
// Subscribe to changes
onAuthStateChanged(auth, (user: FirebaseAuthUser | null) => {
console.log('user status changed: ', user)
})
export function handleSignUpWithEmail(
email: string,
password: string
): Promise<void> {
return createUserWithEmailAndPassword(auth, email, password).then(
(userCredential: UserCredential) => {
const user = userCredential.user
if (user) {
attachUserDataToUser(user)
}
}
)
}
//Attach data to the user in Firestore
function attachUserDataToUser(user: FirebaseAuthUser): Promise<void> {
const uid = user.uid
const userData: NewUser = {
email: user.email || '',
username: user.email?.split('@')[0] || '',
avatarIMG: '',
googleAuth: user.emailVerified,
partner_username: '',
in_relationship: false,
// Add other relevant data fields
}
const usersCollection = doc(db, 'users', uid)
return setDoc(usersCollection, userData)
.then(() => {
console.log('User data attached successfully!')
})
.catch((error: any) => {
console.error('Error attaching user data:', error)
})
}
//Check User's connection
export function checkConnection(): boolean {
return !!auth.currentUser
}
//Get Main User's Data
export function getUserData(): Promise<UserMetadata> {
const user = auth.currentUser
if (!user) {
return Promise.reject(new Error('User is not authenticated'))
}
const userId = user.uid
const documentRef = doc(db, `users/${userId}`)
return getDoc(documentRef)
.then((docSnapshot) => {
if (docSnapshot.exists()) {
const documentData = docSnapshot.data()
return documentData
} else {
throw new Error('There is no username')
}
})
.catch((error) => {
console.error('Error getting document:', error)
throw error
})
}
//Log-in/Log-out functions
export function logIn(
email: string,
password: string
): Promise<UserCredential> {
return signInWithEmailAndPassword(auth, email, password)
}
export function logOut(): void {
signOut(auth)
.then(() => {
console.log('user signed out')
})
.catch((error) => {
console.error('Error logging out:', error)
})
}
export function updatePartner(newPartner: string): Promise<any> {
return updateDoc(doc(db, 'users', auth.currentUser!.uid), {
partner_username: newPartner,
})
}
export function removePartner(): Promise<any> {
return updateDoc(doc(db, 'users', auth.currentUser!.uid), {
partner_username: '',
in_relationship: false,
})
}
export function checkRelationship(partner: string): Promise<any> {
const isPartnerQuery = query(usersRef, where('username', '==', partner))
let oneSide = false
return getDocs(isPartnerQuery)
.then((querySnapshot) => {
querySnapshot.forEach((document) => {
oneSide = true
const { username } = document.data()
const isMutualQuery = query(
usersRef,
where('partner_username', '==', username)
)
updateDoc(doc(db, 'users', document.id), {
in_relationship: true,
})
getDocs(isMutualQuery)
.then((querySnapshot) => {
querySnapshot.forEach((document) => {
updateDoc(doc(db, 'users', document.id), {
in_relationship: true,
})
})
})
.catch((error) => {
console.error('Error getting documents:', error)
})
})
})
.then(() => {
if (!oneSide) {
throw Error('Not partner found')
}
})
}
export function checkUser() {
console.log(auth.currentUser)
}
//we need to send the file along with the metadata to this file
export async function uploadMediaFromGallery(
uri: string,
userData: NewUser,
metadataGame: Game,
caption: string | undefined
): Promise<void> {
const { partner_username, username } = userData
//BlobFroUri transforms the URL we retrieve from the phone to Binary Data
//Ready to be uploaded into Firebase db.
const getBlobFroUri = async (uri: string): Promise<Blob> => {
const blob = await new Promise<Blob>((resolve, reject) => {
const xhr = new XMLHttpRequest()
xhr.onload = function () {
resolve(xhr.response as Blob)
}
xhr.onerror = function (e) {
reject(new TypeError('Network request failed'))
}
xhr.responseType = 'blob'
xhr.open('GET', uri, true)
xhr.send(null)
})
return blob
}
const imageBlob: Blob = await getBlobFroUri(uri)
if (imageBlob) {
const fileRef = ref(storage, `images/${partner_username}/` + Date.now())
uploadBytes(fileRef, imageBlob)
.then(() => {
getDownloadURL(fileRef)
.then((fileUrl) => {
addDoc(collection(db, `eggs`), {
fileURL: fileUrl,
recipient: partner_username,
caption: caption || '',
sender: username,
timestamp: serverTimestamp(),
isLocked: true,
typeEgg: 'image',
game: metadataGame,
})
})
.catch((error) => {
console.log(error.message)
})
})
.catch((error) => {
console.log(error.message)
})
.catch((error) => {
console.log(error.message)
})
}
}
//Send messages as an Egg:
export function uploadText(
text: string,
metadata: any,
metadataGame: Game
): void {
const { partner_username, username } = metadata
console.log(text, "text", metadata, "metadata", metadataGame, "metadataGame")
addDoc(collection(db, 'eggs'), {
typeEgg: 'message',
contentMsg: text,
recipient: partner_username,
sender: username,
timestamp: serverTimestamp(),
isLocked: true,
game: metadataGame,
}).catch((error) => {
console.log(error.message)
})
}
//fetch Eggs for "Eggs Page"
export function getEggs(
username: string,
partner_username: string
): Promise<Egg[]> {
const recipientQuery = query(
eggsRef,
where('recipient', '==', username),
where('sender', '==', partner_username),
orderBy('timestamp', 'desc')
)
return getDocs(recipientQuery).then((querySnapshot) => {
let eggArray: Egg[] = []
querySnapshot.forEach((document) => {
const data = document.data()
if (data.typeEgg === 'message') {
const messageEgg = data as MessageEgg
eggArray.push(messageEgg)
} else {
const fileEgg = data as FileEgg
eggArray.push(fileEgg)
}
})
return eggArray
})
}
//upload Image for your profile picture
export async function updateProfilePicture(uri: string): Promise<void> {
//BlobFroUri transforms the URL we retrieve from the phone to Binary Data
//Ready to be uploaded into Firebase db.
const getBlobFroUri = async (uri: string): Promise<Blob> => {
const blob = await new Promise<Blob>((resolve, reject) => {
const xhr = new XMLHttpRequest()
xhr.onload = function () {
resolve(xhr.response as Blob)
}
xhr.onerror = function () {
reject(new TypeError('Network request failed'))
}
xhr.responseType = 'blob'
xhr.open('GET', uri, true)
xhr.send(null)
})
return blob
}
const imageBlob: Blob = await getBlobFroUri(uri)
if (imageBlob) {
const fileRef = ref(storage, 'profilePictures/' + Date.now())
uploadBytes(fileRef, imageBlob)
.then(() => {
getDownloadURL(fileRef)
.then((fileUrl) => {
updateDoc(doc(db, 'users', auth.currentUser!.uid), {
avatarIMG: fileUrl,
})
})
.catch((error) => {
console.log(error.message)
})
})
.catch((error) => {
console.log(error.message)
})
.catch((error) => {
console.log(error.message)
})
}
}
//Update isLocked to false when passed the game:
export function updateLock({ timestamp }: Timestamp): Promise<void> {
const LockQuery = query(eggsRef, where('timestamp', '==', timestamp))
return getDocs(LockQuery).then((querySnapshot) => {
querySnapshot.forEach((document) => {
updateDoc(doc(db, 'eggs', document.id), {
isLocked: false,
})
})
})
}