-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
325 lines (282 loc) · 10.2 KB
/
server.js
File metadata and controls
325 lines (282 loc) · 10.2 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
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
const express = require('express');
const cors = require('cors'); // Import CORS package
const {db, realTimeDatabase} = require('./firebase.js');
const app = express();
const port = process.env.PORT || 8383;
const bodyParser = require('body-parser');
const admin = require('firebase-admin');
const http = require('http');
const socketio = require('socket.io');
const server = http.createServer(app);
const io = socketio(server, {
cors: {
origin: "*", // Allow all origins
methods: ["GET", "POST"] // Allow only GET and POST requests
}
});
app.use(cors()); // Enable CORS for all routes
app.use(express.json());
app.use(bodyParser.json());
// Middleware to authenticate requests using Firebase Admin SDK
const authenticate = async (req, res, next) => {
const token = req.headers.authorization?.split('Bearer ')[1]; // Extract the token from the Authorization header
if (!token) {
return res.status(403).send('Unauthorized');
}
try {
const decodedToken = await admin.auth().verifyIdToken(token);
req.user = decodedToken; // Optionally, attach the decoded token to the request object
next(); // Proceed to the next middleware or route handler
} catch (error) {
console.error('Error verifying auth token', error);
res.status(403).send('Unauthorized');
}
};
// Add a root route handler
app.get('/', (req, res) => {
res.send('Hello World!');
});
// Register New User
app.post('/api/users', async (req, res) => {
try {
const {uid, email, displayName, photoURL, bio, location} = req.body;
// Ensure all required fields are provided
if (!uid || !displayName) {
return res.status(400).json({message: 'Missing required fields'});
}
const createdAt = new Date();
const updatedAt = createdAt; // For registration, createdAt and updatedAt will be the same
// Create the user document in Firestore
await db.collection('users').doc(uid).set({
uid,
email,
displayName,
photoURL,
bio,
location,
createdAt,
updatedAt,
chats: [] // Initialize with an empty array
});
res.status(201).json({
createdAt,
updatedAt,
message: 'User profile created successfully.'
});
} catch (error) {
console.error('Error registering user:', error);
res.status(500).json({message: 'Failed to register user'});
}
});
// Fetch a user by ID
app.get('/api/user/:id', async (req, res) => {
const {id} = req.params;
const doc = await db.collection('users').doc(id).get();
if (!doc.exists) {
return res.sendStatus(404);
}
res.status(200).json(doc.data());
});
// Update a user's information
app.patch('/api/user/:id', authenticate, async (req, res) => {
const {id} = req.params;
const updates = req.body;
updates.updatedAt = new Date(); // Update the 'updatedAt' timestamp
await db.collection('users').doc(id).update(updates);
res.sendStatus(200);
});
// Delete a user
app.delete('/api/user/:id', authenticate, async (req, res) => {
const {id} = req.params;
await db.collection('users').doc(id).delete();
res.sendStatus(204);
});
app.get('/api/users/search', async (req, res) => {
const query = req.query.query.toLowerCase();
if (!query) {
return res.status(400).json({error: "Missing 'query' parameter."});
}
try {
const usersRef = db.collection('users');
let snapshot = await usersRef.get();
let users = [];
snapshot.forEach(doc => {
let userData = doc.data();
// Convert searchable fields to lowercase before matching
if (userData.email?.toLowerCase().includes(query) ||
userData.displayName.toLowerCase().includes(query) ||
userData.uid.includes(query)) { // Assuming userId is case-sensitive and exact
users.push({
uid: doc.id,
displayName: userData.displayName,
photoURL: userData.photoURL
});
}
});
if (users.length === 0) {
return res.status(200).json([]);
}
res.status(200).json(users);
} catch (error) {
console.error('Error searching users:', error);
res.status(500).json({error: "An unexpected error occurred. Please try again later."});
}
});
///////////////////// Chat /////////////////////
app.post('/api/chats/select', async (req, res) => {
const {currentUserUid, userUid} = req.body; // Extract user IDs from request body
// Combine user IDs to create a unique identifier for the chat
const combinedId = currentUserUid > userUid ? currentUserUid + userUid : userUid + currentUserUid;
try {
const chatRef = db.collection('chats').doc(combinedId);
const chatSnap = await chatRef.get();
if (!chatSnap.exists) {
// If chat does not exist, create a new chat document
await chatRef.set({messages: []});
// Update userChats collection for currentUser
await db.collection('userChats').doc(currentUserUid).set({
[`${combinedId}.userInfo`]: {uid: userUid, displayName: 'User Display Name', photoURL: 'User Photo URL'},
[`${combinedId}.date`]: admin.firestore.FieldValue.serverTimestamp(),
}, {merge: true});
// Update userChats collection for the other user
await db.collection('userChats').doc(userUid).set({
[`${combinedId}.userInfo`]: {
uid: currentUserUid,
displayName: 'Current User Display Name',
photoURL: 'Current User Photo URL'
},
[`${combinedId}.date`]: admin.firestore.FieldValue.serverTimestamp(),
}, {merge: true});
}
res.json({message: 'Chat selected or created successfully'});
} catch (error) {
console.error('Error selecting or creating chat: ', error);
res.status(500).send('Error selecting or creating chat');
}
});
// API to get chats for a user
app.get('/api/chats/:userId', async (req, res) => {
try {
const userChatsRef = db.collection('userChats').doc(req.params.userId);
const doc = await userChatsRef.get();
if (!doc.exists) {
return res.status(200).json([]); // Return an empty array instead of sending a 404 error
}
return res.status(200).json(doc.data());
} catch (error) {
return res.status(500).json({error: error.message});
}
});
// API to update or create a chat
app.post('/api/chats/:userId', async (req, res) => {
const {chatId, chatData} = req.body;
try {
await db.collection('userChats').doc(req.params.userId).set({
[chatId]: chatData
}, {merge: true});
return res.status(200).send('Chat updated successfully.');
} catch (error) {
return res.status(500).json({error: error.message});
}
});
/////////////////////////////// Video WebRTC, Socket.io Server ///////////////////////////////
// Store users' connections
let users = {};
io.on('connection', socket => {
console.log('New client connected');
socket.on('register', ({userId}) => {
users[socket.id] = userId;
// Set user online status in Firebase
const usersRef = realTimeDatabase.ref('users');
usersRef.child(userId).set({online: true, socketId: socket.id});
console.log(`User ${userId} connected with socket ID ${socket.id}`);
});
socket.on('disconnect', () => {
const userId = users[socket.id];
if (userId) {
// Optionally update the user's status to offline or remove the user
const usersRef = realTimeDatabase.ref('users');
usersRef.child(userId).remove(); // Or update to set online status to false
console.log(`User ${userId} disconnected`);
}
delete users[socket.id];
});
socket.on('callUser', ({userToCall, signalData, from}) => {
const usersRef = realTimeDatabase.ref('users');
usersRef.child(userToCall).get().then((snapshot) => {
if (snapshot.exists()) {
const receiverData = snapshot.val();
if (receiverData.online) {
console.log(`Calling user: ${userToCall} (Socket ID: ${receiverData.socketId}) from user: ${from}`);
// Use receiver's socketId from the database to emit the call
io.to(receiverData.socketId).emit('callUser', {signal: signalData, from, name: from});
} else {
console.log(`User ${userToCall} is not online.`);
}
} else {
console.log(`User ${userToCall} does not exist.`);
}
}).catch((error) => {
console.error(error);
});
usersRef.child(from).get().then((snapshot) => {
if (!snapshot.exists() || !snapshot.val().online) {
console.log(`Caller ${from} not found or not connected.`);
}
}).catch((error) => {
console.error(error);
});
});
socket.on('answerCall', (data) => {
const {signal, to} = data; // 'to' is the caller's userId
// Fetch the caller's socketId from the database
const usersRef = realTimeDatabase.ref('users');
usersRef.child(to).get().then((snapshot) => {
if (snapshot.exists()) {
const callerData = snapshot.val();
if (callerData.online) {
console.log(`Notifying the caller with userId: ${to} at socketId: ${callerData.socketId}`);
io.to(callerData.socketId).emit('callAccepted', signal);
} else {
console.log(`Caller userId: ${to} is not online.`);
}
} else {
console.log(`Caller userId: ${to} does not exist.`);
}
}).catch((error) => {
console.error(error);
});
});
socket.on('hangUp', ({to}) => {
const usersRef = realTimeDatabase.ref('users');
usersRef.child(to).get().then((snapshot) => {
if (snapshot.exists()) {
const receiverData = snapshot.val();
if (receiverData.online) {
console.log(`Hanging up call with user: ${to} (Socket ID: ${receiverData.socketId})`);
io.to(receiverData.socketId).emit('hangUp');
}
}
}).catch((error) => {
console.error(error);
});
});
});
server.listen(port, () => console.log(`Server is running on port ${port}`));
// Function to gracefully close the server and cleanup resources
function closeApp() {
return new Promise((resolve, reject) => {
server.close((err) => {
if (err) {
console.error('Failed to close the server', err);
reject(err);
return;
}
// Optional: Add any cleanup logic for Firebase or other services here
console.log('Server closed');
resolve();
});
});
}
// Exporting the closeApp function along with the app
module.exports = { app, closeApp };