Skip to content

Commit

Permalink
mostly everything working sorta
Browse files Browse the repository at this point in the history
  • Loading branch information
willhuff0 committed Nov 22, 2024
1 parent 77e6b1c commit 31a2f6a
Show file tree
Hide file tree
Showing 19 changed files with 232 additions and 174 deletions.
23 changes: 13 additions & 10 deletions client/app/components/chat/MessageChannel.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,25 +3,28 @@ import { FlatList } from "react-native";

import Message from "./ChatMessage";
import { MessageChannelProps } from "../../types/Props";
import { NearbyUsersProvider, useNearbyUsers } from "@app/contexts/NearbyUserContext";

const MessageChannel: React.FC<MessageChannelProps> = ({ messages }) => {
const MessageChannel: React.FC<MessageChannelProps> = ({ nearbyUsers, messages }) => {
const reverseMessages = [...messages].reverse();
const nearbyUsers = useNearbyUsers();

return (
<FlatList
contentContainerStyle={{
width: "100%",
}}
data={reverseMessages}
renderItem={({ item }) => (
<Message
messageContent={item.content.text!}
author={nearbyUsers[item.author].displayName}
time={item.timestamp}
/>
)}
renderItem={({ item }) => {
const user = nearbyUsers[item.author];
console.log(nearbyUsers);
if (user === undefined) return null;
return (
<Message
messageContent={item.content.text!}
author={user.displayName}
time={item.timestamp}
/>
);
}}
inverted // This will render items from the bottom
onLayout={() => { }} // This will make sure the list is scrolled to the bottom on first render
/>
Expand Down
2 changes: 1 addition & 1 deletion client/app/configs/firebaseConfig.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ const firebaseConfig = {
let app;
let auth: Auth;

// Checks if auth and app have already been initilized as Firebase will throw an error if we try to initialize twice!
// Checks if auth and app have already been initialized as Firebase will throw an error if we try to initialize twice!
if (!getApps().length) {
try {
app = initializeApp(firebaseConfig);
Expand Down
16 changes: 14 additions & 2 deletions client/app/contexts/LocationContext.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,16 @@ export const useLocation = () => {
return useContext(LocationContext);
};

var setLocationCallback: React.Dispatch<React.SetStateAction<LocationType>> | undefined = undefined;
export const forceRefreshLocation = async () => {
if (setLocationCallback === undefined) return;
const locationData = await getLocation();
if (locationData && locationData.coords) {
const { latitude, longitude } = locationData.coords;
setLocationCallback({ lat: latitude, lon: longitude });
}
}

// LocationProvider Component to Provide Location Context
export const LocationProvider = ({
children,
Expand All @@ -24,6 +34,7 @@ export const LocationProvider = ({
lon: 99999,
});
const [isLocationEnabled, setIsLocationEnabled] = useState(false);
setLocationCallback = undefined;

useEffect(() => {
let interval: NodeJS.Timeout;
Expand All @@ -33,6 +44,7 @@ export const LocationProvider = ({
if (!hasPermission) return;

setIsLocationEnabled(true);
setLocationCallback = setLocation;

// Set up the interval once after permission is granted
interval = setInterval(async () => {
Expand All @@ -42,7 +54,7 @@ export const LocationProvider = ({
if (latitude !== location.lat || longitude !== location.lon) {
setLocation({ lat: latitude, lon: longitude });
} else {
console.log("Location has not changed");
//console.log("Location has not changed");
}
}
}, Number(LOCATION_REFRESH_RATE));
Expand All @@ -57,7 +69,7 @@ export const LocationProvider = ({
console.log("[LOG]: Cleaning up location useEffect");
}
};
}, []);
}, [location.lat, location.lon]);


return (
Expand Down
13 changes: 13 additions & 0 deletions client/app/contexts/NearbyUserContext.tsx
Original file line number Diff line number Diff line change
@@ -1,14 +1,27 @@
import React, { createContext, useContext, useState } from "react";
import { UserProfile } from "../types/User";
import { getNearbyUsers } from "@app/services/SocketService";
import { Socket } from "socket.io-client";

const NearbyUsersContext = createContext<{ [uid: string]: UserProfile }>({});

export const useNearbyUsers = () => {
return useContext(NearbyUsersContext);
};

var setNearbyUsersCallback: React.Dispatch<React.SetStateAction<{
[uid: string]: UserProfile;
}>> | undefined = undefined;
export const refreshNearbyUsers = async (socket: Socket) => {
if (setNearbyUsersCallback === undefined) return;
const nearbyUsers = await getNearbyUsers(socket);
console.log(nearbyUsers);
setNearbyUsersCallback(nearbyUsers);
}

export const NearbyUsersProvider = ({ children }: { children: React.ReactNode }) => {
const [user, setNearbyUsers] = useState<{ [uid: string]: UserProfile }>({});
setNearbyUsersCallback = setNearbyUsers;

return <NearbyUsersContext.Provider value={user}>{children}</NearbyUsersContext.Provider>;
};
11 changes: 6 additions & 5 deletions client/app/contexts/SocketContext.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import React, { createContext, useContext, useEffect, useState } from "react";
import { Socket } from "socket.io-client";
import { useLocation } from "./LocationContext";
import { forceRefreshLocation, useLocation } from "./LocationContext";
import { initializeSocket, getToken, updateLocation } from "@app/services/SocketService";


Expand Down Expand Up @@ -33,13 +33,14 @@ export const SocketProvider = ({ children }: { children: React.ReactNode }) => {
socket?.disconnect();
console.log("[LOG]: Cleaning up initializeSocket useEffect");
};
}, [mounted]);
}, [mounted, socket]);

useEffect(() => {
if (!socket) return;

socket.on("connect", () => {
console.log("Connected to server");
forceRefreshLocation();
});

return () => {
Expand All @@ -54,12 +55,12 @@ export const SocketProvider = ({ children }: { children: React.ReactNode }) => {
if (
socket &&
locationContext &&
locationContext?.lat !== 9999 &&
locationContext?.lon !== 9999
locationContext?.lat !== 99999 &&
locationContext?.lon !== 99999
) {
updateLocation(socket, { lat: locationContext.lat, lon: locationContext.lon });
}
}, [locationContext?.lat, locationContext?.lon, socket]);
}, [locationContext, socket]);

return (
<SocketContext.Provider value={socket}>
Expand Down
17 changes: 11 additions & 6 deletions client/app/screens/chat/ChatScreen.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ import NearbyHeader from "@app/components/chat/NearbyHeader";
import React from "react";
import NearbyUserDrawer from "@app/components/chat/NearbyUserDrawer";
import { sendMessage } from "@app/services/SocketService";
import { useNearbyUsers } from "@app/contexts/NearbyUserContext";
import { refreshNearbyUsers, useNearbyUsers } from "@app/contexts/NearbyUserContext";

const ChatScreen = () => {
const settings = useSettings();
Expand All @@ -39,9 +39,14 @@ const ChatScreen = () => {
useEffect(() => {
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]);
const handleMessage = async (message: Message, ack?: any) => {
console.log("Message received from server:", message);
console.log(nearbyUsers);
if (message.author !in nearbyUsers) {
console.log(`${message.author} not in nearby users map. Requesting a new map of nearby users...`);
await refreshNearbyUsers(socket);
}
setMessages((prevMessages) => [...prevMessages, message]);
if (ack) console.log("Server acknowledged message:", ack);
};

Expand All @@ -50,7 +55,7 @@ const ChatScreen = () => {
return () => {
socket.off("message", handleMessage);
};
}, [messages, socket]);
}, [messages, nearbyUsers, socket]);

// For when the user sends a message (fired by the send button)
const onHandleSubmit = () => {
Expand Down Expand Up @@ -89,7 +94,7 @@ const ChatScreen = () => {
<View style={styles.mainContainer}>
<NearbyUserDrawer />
<View style={styles.chatContainer}>
<MessageChannel messages={messages} />
<MessageChannel nearbyUsers={nearbyUsers} messages={messages} />
</View>
<View style={styles.footerContainer}>
<ChatScreenFooter
Expand Down
4 changes: 1 addition & 3 deletions client/app/services/LocationService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,7 @@ import * as Location from "expo-location";
// Location Service to Handle Location Fetching
export const getLocation = async (): Promise<Location.LocationObject | null> => {
try {
return await Location.getCurrentPositionAsync({
accuracy: Location.Accuracy.Balanced,
});
return await Location.getCurrentPositionAsync();
} catch (error) {
console.error("Error fetching location:", error);
return null;
Expand Down
6 changes: 4 additions & 2 deletions client/app/services/SocketService.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,14 @@
import { io, Socket } from "socket.io-client";
import { AuthStore } from "../services/AuthStore";
import { EXPO_IP } from "@env";
import { SOCKET_IP, SOCKET_PORT } from "@env";
import { LocationType } from "@app/types/Location";
import { UserProfile } from "@app/types/User";
import { Completer } from "@app/utils/completer";
import { Message } from "@app/types/Message";
import { refreshNearbyUsers } from "@app/contexts/NearbyUserContext";

export const initializeSocket = async (token: string): Promise<Socket> => {
const socketIo = io(`http://10.0.2.2:8082`, {
const socketIo = io(`http://${SOCKET_IP}:${SOCKET_PORT}`, {
auth: {
token,
},
Expand Down Expand Up @@ -37,6 +38,7 @@ export const updateLocation = (
location,
(ack: string) => {
console.log("updateLocation ack:", ack);
refreshNearbyUsers(socket);
}
);
};
Expand Down
2 changes: 2 additions & 0 deletions client/app/types/Props.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import React from "react";

import { Message } from "./Message";
import { UserProfile } from "./User";

/* button props */
export type LargeTextButtonProps = {
Expand All @@ -26,6 +27,7 @@ export type MessageProps = {
};

export type MessageChannelProps = {
nearbyUsers: { [uid: string]: UserProfile };
messages: Message[];
};

Expand Down
9 changes: 0 additions & 9 deletions client/app/types/env.d.ts

This file was deleted.

4 changes: 3 additions & 1 deletion client/env.d.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
declare module "@env" {
export const EXPO_IP: string;
export const SOCKET_IP: string;
export const SOCKET_PORT: number;
export const API_KEY: string;
export const AUTH_DOMAIN: string;
export const PROJECT_ID: string;
export const LOCATION_REFRESH_RATE: string;
}
Loading

0 comments on commit 31a2f6a

Please sign in to comment.