-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscripts.js
More file actions
257 lines (230 loc) · 8.39 KB
/
scripts.js
File metadata and controls
257 lines (230 loc) · 8.39 KB
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
// Import Firebase modules
import { initializeApp } from "https://www.gstatic.com/firebasejs/9.6.1/firebase-app.js";
import {
getAuth,
createUserWithEmailAndPassword,
signInWithEmailAndPassword,
signOut,
onAuthStateChanged
} from "https://www.gstatic.com/firebasejs/9.6.1/firebase-auth.js";
import {
getFirestore,
collection,
addDoc,
doc,
setDoc,
onSnapshot,
query,
where,
serverTimestamp,
getDoc,
getDocs // Add this import
} from "https://www.gstatic.com/firebasejs/9.6.1/firebase-firestore.js";
// Firebase Configuration
const firebaseConfig = {
apiKey: "AIzaSyAn_zNl4kzmMIXPjG0EE9IJTUwPEXK_mL8",
authDomain: "valohq.firebaseapp.com",
databaseURL: "https://valohq-default-rtdb.asia-southeast1.firebasedatabase.app",
projectId: "valohq",
storageBucket: "valohq.firebasestorage.app",
messagingSenderId: "368885437583",
appId: "1:368885437583:web:7124c203a9466cfc25ccfa",
measurementId: "G-FQRMHJ06YQ"
};
// Initialize Firebase
const app = initializeApp(firebaseConfig);
const auth = getAuth(app);
const db = getFirestore(app);
// Authentication Functions
export function signUp(email, password, displayName, riotId) {
createUserWithEmailAndPassword(auth, email, password)
.then((userCredential) => {
console.log('User registered:', userCredential.user.email);
saveUserData(userCredential.user, displayName, riotId); // Save user data
})
.catch((error) => {
console.error('Error signing up:', error.message);
});
}
export function signIn(email, password) {
signInWithEmailAndPassword(auth, email, password)
.then((userCredential) => {
console.log('User logged in:', userCredential.user.email);
window.location.href = '/'; // Redirect to homepage
})
.catch((error) => {
console.error('Error signing in:', error.message);
});
}
export function signOutUser() {
signOut(auth)
.then(() => {
console.log('User signed out');
window.location.href = '/login.html'; // Redirect to login page after sign out
})
.catch((error) => {
console.error('Error signing out:', error.message);
});
}
// Save User Data to Firestore
export function saveUserData(user, displayName, riotId) {
setDoc(doc(db, 'users', user.uid), {
email: user.email,
displayName: displayName,
riotId: riotId
}).then(() => {
console.log('User data saved to Firestore');
window.location.href = '/'; // Redirect to homepage
}).catch((error) => {
console.error('Error saving user data:', error);
});
}
// Fetch User Data from Firestore
export function fetchUserData(userId) {
getDoc(doc(db, 'users', userId))
.then((doc) => {
if (doc.exists()) {
console.log('User data:', doc.data());
} else {
console.error('User data not found');
}
})
.catch((error) => {
console.error('Error fetching user data:', error);
});
}
// Send Invite
export function sendInvite(toUserId) {
const fromUserId = auth.currentUser?.uid;
if (!fromUserId) {
console.error('User not logged in');
return;
}
// Fetch the sender's display name
getDoc(doc(db, 'users', fromUserId))
.then((doc) => {
if (doc.exists()) {
const senderData = doc.data();
const senderDisplayName = senderData.displayName;
// Send the invite with the sender's display name
addDoc(collection(db, 'invites'), {
from: fromUserId,
fromDisplayName: senderDisplayName, // Add sender's display name
to: toUserId,
timestamp: serverTimestamp()
}).then(() => {
console.log('Invite sent');
}).catch((error) => {
console.error('Error sending invite:', error);
});
} else {
console.error('Sender data not found');
}
})
.catch((error) => {
console.error('Error fetching sender data:', error);
});
}
// Listen for Invites
let unsubscribeInvites = null; // Store the unsubscribe function for the Firestore listener
export function listenForInvites() {
const currentUserId = auth.currentUser?.uid;
if (!currentUserId) {
console.error('User not logged in');
return;
}
const q = query(collection(db, 'invites'), where('to', '==', currentUserId));
unsubscribeInvites = onSnapshot(q, (snapshot) => {
console.log('Received snapshot:', snapshot); // Log the snapshot
snapshot.docChanges().forEach((change) => {
if (change.type === 'added') {
const invite = change.doc.data();
console.log('New invite from:', invite.fromDisplayName);
showInvitePrompt(invite); // Pass the entire invite object
}
});
}, (error) => {
console.error('Error listening for invites:', error);
});
}
// Show Invite Prompt
export function showInvitePrompt(invite) {
const prompt = document.getElementById('invitePrompt');
const inviteFrom = document.getElementById('inviteFrom');
if (!prompt || !inviteFrom) {
console.error('Invite prompt elements not found');
return;
}
// Display the sender's display name
inviteFrom.textContent = invite.fromDisplayName;
prompt.style.display = 'block';
document.getElementById('acceptInvite').addEventListener('click', () => {
alert('You accepted the invite from ' + invite.fromDisplayName);
prompt.style.display = 'none';
});
document.getElementById('rejectInvite').addEventListener('click', () => {
alert('You rejected the invite from ' + invite.fromDisplayName);
prompt.style.display = 'none';
});
}
// Fetch recipient's UID
export function getUserIdByEmail(email) {
const q = query(collection(db, 'users'), where('email', '==', email));
return getDocs(q)
.then((querySnapshot) => {
if (!querySnapshot.empty) {
return querySnapshot.docs[0].id; // Return the first matching user's UID
} else {
console.error('User not found');
return null;
}
})
.catch((error) => {
console.error('Error fetching user ID:', error);
return null;
});
}
// Initialize App
export function initApp() {
onAuthStateChanged(auth, (user) => {
const currentPage = window.location.pathname.split('/').pop();
if (user) {
console.log('User is signed in:', user.email);
fetchUserData(user.uid); // Fetch user data
listenForInvites(); // Listen for invites
// Update UI
const userEmailElement = document.getElementById('userEmail');
const loginButton = document.getElementById('loginButton');
if (userEmailElement && loginButton) {
userEmailElement.textContent = user.email;
loginButton.textContent = 'Logout';
loginButton.href = '#'; // Prevent default behavior
loginButton.addEventListener('click', () => {
signOutUser();
});
}
// Example: Send an invite to a recipient
const recipientEmail = 'recipient@example.com'; // Replace with the recipient's email
getUserIdByEmail(recipientEmail)
.then((toUserId) => {
if (toUserId) {
sendInvite(toUserId); // Send the invite
} else {
console.error('Recipient not found');
}
});
} else {
console.log('User is signed out');
// Redirect to login page only if not already on login or register page
if (currentPage !== 'login.html' && currentPage !== 'register.html') {
window.location.href = '/login.html';
}
}
});
}
// Cleanup Firestore listeners when the page is unloaded
window.addEventListener('beforeunload', () => {
if (unsubscribeInvites) {
unsubscribeInvites(); // Unsubscribe from the Firestore listener
}
});