Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Switched to publish subscribe model for messages #208

Merged
merged 9 commits into from
Apr 3, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 24 additions & 16 deletions client/src/components/Chat/ChatScreen.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ import MessageChannel from "../Common/MessageChannel";
import * as Crypto from "expo-crypto";
import { generateName } from "../../utils/scripts";
import { SignOutButton } from "../Common/AuthButtons"
import { MessageType } from "../../types/Message";
import { Message } from "../../types/Message";
import { LocationProvider } from "../../contexts/LocationContext";
import { useSocket } from "../../contexts/SocketContext";
import { useSettings } from "../../contexts/SettingsContext";
Expand All @@ -38,42 +38,50 @@ const ChatScreen = () => {
// Note: To prevent complexity, all user information is grabbed from different contexts and services. If we wanted most information inside of UserContext, we would have to import contexts within contexts and have state change as certain things mount, which could cause errors that are difficult to pinpoint.

// Message loading and sending logic
const [messages, setMessages] = React.useState<MessageType[]>([]);
const [messages, setMessages] = React.useState<Message[]>([]);
const [messageContent, setMessageContent] = React.useState<string>("");

useEffect(() => {
if (socket === null) return // This line might need to be changed.
socket.on("message", (data: MessageType, ack) => {
console.log("Message recieved from server:", data);
if (socket === null) return; // This line might need to be changed

const handleMessage = (data: any, ack?: any) => {
console.log("Message received from server:", data);
setMessages((prevMessages) => [...prevMessages, data]);
if (ack) console.log("Server acknowledged message:", ack);
setMessages([...messages, data])
})
};

socket.on("message", handleMessage);

return () => {
socket.off()
}
}, [messages])
socket.off("message", handleMessage);
};
}, [messages, socket]);

// For when the user sends a message (fired by the send button)
const onHandleSubmit = () => {
if (messageContent.trim() !== "") {
const newMessage: MessageType = {
const newMessage: Message = {
author: {
uid: String(userAuth.userAuthInfo?.uid),
uid: String(userAuth.userAuthInfo?.uid),
displayName: "Anonymous",
},
msgId: Crypto.randomUUID(),
msgContent: messageContent.trim(),
timeSent: Date.now(),
timestamp: Date.now(),
lastUpdated: Date.now(),
location: {
lat: Number(location?.latitude),
lon: Number(location?.longitude)
}
},
isReply: false,
replyTo: "",
reactions: {},
}

if (socket !== null) {
socket.emit("message", newMessage)
}

setMessages([...messages, newMessage]);

setMessageContent("");
}
};
Expand Down
4 changes: 2 additions & 2 deletions client/src/components/Common/MessageChannel.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,8 @@ const MessageChannel: React.FC<MessageChannelProps> = ({ messages }) => {
renderItem={({ item }) => (
<Message
messageContent={item.msgContent}
author={item.author.uid} // TODO: call server to get author name from UID. Or should this stored with MessageType?
time={item.timeSent}
author={item.author.displayName} // TODO: call server to get author name from UID. Or should this stored with MessageType?
time={item.timestamp}
/>
)}
inverted={true} // This will render items from the bottom
Expand Down
15 changes: 10 additions & 5 deletions client/src/types/Message.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,19 @@
export interface MessageType {
export interface Message {
author: {
uid: string
displayName?: string // To be only used for display purposes (do not send to server)
uid: string,
displayName: string,
}
msgId: string
msgContent: string
timeSent: number // Unix timestamp; Date.now() returns a Number.
timestamp: number
lastUpdated: number
location: {
lat: number
lon: number
geohash?: string
}
isReply: boolean
replyTo: string
reactions: {
[key: string]: number
}
}
2 changes: 1 addition & 1 deletion server/.gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -133,7 +133,7 @@ dist
build

# Private Key JSON
./private_key/*
./firebase-secrets.json

# Other
.env
Expand Down
18 changes: 18 additions & 0 deletions server/src/actions/calculateDistance.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
const degreesToRadians = (degrees: number) => {
return degrees * Math.PI / 180;
}

export const calculateDistanceInMeters = (lat1: number, lon1: number, lat2: number, lon2: number) => {
const earthRadiusKm = 6371;

const dLat = degreesToRadians(lat2-lat1);
const dLon = degreesToRadians(lon2-lon1);

lat1 = degreesToRadians(lat1);
lat2 = degreesToRadians(lat2);

const a = Math.sin(dLat/2) * Math.sin(dLat/2) +
Math.sin(dLon/2) * Math.sin(dLon/2) * Math.cos(lat1) * Math.cos(lat2);
const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
return earthRadiusKm * c * 1000;
}
71 changes: 32 additions & 39 deletions server/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@ import {geohashForLocation} from 'geofire-common';
import { ConnectedUser } from './types/User';
import { getAuth } from 'firebase-admin/auth';
import Mailgun from "mailgun.js";
import { messagesCollection } from './utilities/firebaseInit';
import { calculateDistanceInMeters } from './actions/calculateDistance';

const { createServer } = require("http");
const { Server } = require("socket.io");
Expand Down Expand Up @@ -68,9 +70,35 @@ io.on("connection", async (socket: any) => {
await createUser(defaultConnectedUser);
await toggleUserConnectionStatus(socket.id);

const observer = messagesCollection.where("lastUpdated", ">", Date.now()).onSnapshot((querySnapshot) => {
querySnapshot.docChanges().forEach((change) => {

if (change.type === "added"){
console.log("New message: ", change.doc.data());

const messageLat = change.doc.data().location.lat;
const messageLon = change.doc.data().location.lon;

const userLat = defaultConnectedUser.location.lat;
const userLon = defaultConnectedUser.location.lon;

const distance = calculateDistanceInMeters(messageLat, messageLon, userLat, userLon);

if (distance < 300) {
console.log("Message is within 300m of user");
socket.emit("message", change.doc.data());
} else {
console.log("Message is not within 300m of user");
}
}

});
});

socket.on("disconnect", () => {
console.log(`[WS] User <${socket.id}> exited.`);
deleteConnectedUserByUID(socket.id);
observer();
});
socket.on("ping", (ack) => {
// The (ack) parameter stands for "acknowledgement." This function sends a message back to the originating socket.
Expand All @@ -80,46 +108,9 @@ io.on("connection", async (socket: any) => {
socket.on("message", async (message: Message, ack) => {
// message post - when someone sends a message

console.log(`[WS] Recieved message from user <${socket.id}>.`);
console.log(message);
try {
if (isNaN(message.timeSent))
throw new Error("The timeSent parameter must be a valid number.");
if (isNaN(message.location.lat))
throw new Error("The lat parameter must be a valid number.");
if (isNaN(message.location.lon))
throw new Error("The lon parameter must be a valid number.");

if (
message.location.geohash == undefined ||
message.location.geohash === ""
) {
message.location.geohash = geohashForLocation([
Number(message.location.lat),
Number(message.location.lon),
]);
console.log(`New geohash generated: ${message.location.geohash}`);
}

const status = await createMessage(message);
if (status === false) throw new Error("Error creating message: ");

// Get nearby users and push the message to them.
const nearbyUserSockets = await findNearbyUsers(
Number(message.location.lat),
Number(message.location.lon),
Number(process.env.message_outreach_radius)
);
for (const recievingSocket of nearbyUserSockets) {
// Don't send the message to the sender (who will be included in list of nearby users).
if (recievingSocket === socket.id) {
continue;
} else {
console.log(`Sending new message to socket ${recievingSocket}`);
socket.broadcast.to(recievingSocket).emit("message", message);
}
}

const messageCreated = await createMessage(message);
if (!messageCreated) throw new Error("createMessage() failed.");
if (ack) ack("message recieved");
} catch (error) {
console.error("[WS] Error sending message:", error.message);
Expand All @@ -130,6 +121,8 @@ io.on("connection", async (socket: any) => {
try {
const lat = Number(location.lat);
const lon = Number(location.lon);
defaultConnectedUser.location.lat = lat;
defaultConnectedUser.location.lon = lon;
const success = await updateUserLocation(socket.id, lat, lon);
if (success) {
console.log("[WS] Location updated in database successfully.");
Expand Down
15 changes: 11 additions & 4 deletions server/src/types/Message.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,19 @@
export interface Message {
uid: string
author: {
uid: string,
displayName: string,
}
msgId: string
msgContent: string
timeSent: number
timestamp: number
lastUpdated: number
location: {
lat: number
lon: number
geohash?: string
}
visibleToUids?: Array<string>
isReply: boolean
replyTo: string
reactions: {
[key: string]: number
}
}
2 changes: 1 addition & 1 deletion server/src/utilities/firebaseInit.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
const admin = require('firebase-admin');
const serviceAccount = require("../../.firebase-secrets.json");
const serviceAccount = require("../../firebase-secrets.json");

export const adminApp = admin.initializeApp({
credential: admin.credential.cert(serviceAccount),
Expand Down
Loading