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

MERGE #83

Merged
merged 3 commits into from
Nov 9, 2023
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
2 changes: 1 addition & 1 deletion backend/code/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
"start": "nest start",
"start:dev": "npm run db:generate && nest start --watch",
"start:debug": "nest start --debug --watch",
"start:prod": "node dist/main",
"start:prod": "node dist/src/main",
"db:generate": "prisma generate",
"lint": "eslint \"{src,apps,libs,test}/**/*.ts\" --fix",
"test": "jest",
Expand Down
1 change: 1 addition & 0 deletions backend/code/src/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ async function bootstrap() {
const app = await NestFactory.create(AppModule);
const corsOptions = {
origin: [
'http://localhost:9000',
'http://localhost:3000',
'http://142.93.161.63',
'http://164.92.243.105',
Expand Down
6 changes: 6 additions & 0 deletions backend/code/src/messages/messages.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -137,6 +137,12 @@ export class MessagesService {
author: {
select: {
avatar: true,
Username: true,
},
},
room: {
select: {
type: true,
},
},
},
Expand Down
3 changes: 3 additions & 0 deletions docker-compose.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,9 @@ services :
depends_on:
- database
restart: always
ports:
- 3001:3001
- 3004:3004
init : true

nginx :
Expand Down
52 changes: 28 additions & 24 deletions frontend/code/src/Api/base.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,10 @@
import axios from "axios";

// import { useNavigate } from 'react-router-dom';
// import { useUserStore } from "../Stores/stores";
// const useNavigateCustom = () => {
// const navigate = useNavigate();
// return navigate;
// };
const api = axios.create({
baseURL: `${process.env.REACT_APP_API_ENDPOINT}`,
timeout: 10000,
Expand All @@ -10,27 +15,26 @@ const api = axios.create({
},
});

let refreshAttempted = false;

const errorHandler = async (error: any) => {
if (error.response.status === 401) {
if (!refreshAttempted) {
try {
refreshAttempted = true;
await api.get("auth/refresh");
return api.request(error.config);
} catch (refreshError) {}
} else {
refreshAttempted = false;
let refreshAttempted = false;

const errorHandler = async (error: any) => {

if (error?.response?.status === 401) {
if (!refreshAttempted) {
try {
refreshAttempted = true;
await api.get("auth/refresh");
return api.request(error.config);
} catch (refreshError) {}
} else {
refreshAttempted = false;
}
}
}

return Promise.reject({ ...error });
};

api.interceptors.response.use(
(response) => response,
(error) => errorHandler(error)
);

export default api;
return Promise.reject(error);
};
api.interceptors.response.use(
(response) => response,
(error) => errorHandler(error)
);

export default api;
21 changes: 10 additions & 11 deletions frontend/code/src/Components/Chat/Components/Conversation.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ import {

import { useUserStore } from "../../../Stores/stores";
import { formatTime } from "./tools/utils";
import { socket } from "../Services/SocketsServices";
import { useSocketStore } from "../Services/SocketsServices";

export interface ChatPaceHolderProps {
username: string;
Expand Down Expand Up @@ -92,7 +92,7 @@ export const ConversationHeader: React.FC<ConversationProps> = ({
const LayoutState = useModalStore((state) => state);
const ChatState = useChatStore((state) => state);
const SelectedChat = useChatStore((state) => state.selectedChatID);

const currentUser = useChatStore((state) => state.currentDmUser);
const selectedChatType = useChatStore((state) => state.selectedChatType);

Expand All @@ -102,7 +102,7 @@ export const ConversationHeader: React.FC<ConversationProps> = ({

const [isModalOpen, setIsModalOpen] = useState(false);
const [isOnline, SetOnline] = useState(false);

const sockerStore = useSocketStore();
const handleConfirmation = () => {
setIsModalOpen(false);
};
Expand All @@ -120,12 +120,12 @@ export const ConversationHeader: React.FC<ConversationProps> = ({
console.log("user offline", userId);
};

socket.on("friendOffline", handleOffline);
socket.on("friendOnline", handleOnline);
sockerStore.socket.on("friendOffline", handleOffline);
sockerStore.socket.on("friendOnline", handleOnline);

return () => {
socket.off("friendOffline", handleOffline);
socket.off("friendOnline", handleOnline);
sockerStore.socket.off("friendOffline", handleOffline);
sockerStore.socket.off("friendOnline", handleOnline);
};
// eslint-disable-next-line
}, [ChatState.selectedChatID]);
Expand Down Expand Up @@ -303,7 +303,7 @@ export const Conversation: React.FC<ConversationProps> = ({
}) => {
const chatState = useChatStore((state) => state);
const messageContainerRef = useRef<HTMLDivElement>(null);

const socketStore = useSocketStore();
const scrollToBottom = () => {
if (messageContainerRef.current) {
const container = messageContainerRef.current;
Expand Down Expand Up @@ -350,8 +350,7 @@ export const Conversation: React.FC<ConversationProps> = ({
scrollToBottom();
}
};

socket.on("message", handleMessage);
socketStore.socket.on("message", handleMessage);

const fetch = async () => {
setLoading(true);
Expand Down Expand Up @@ -390,7 +389,7 @@ export const Conversation: React.FC<ConversationProps> = ({
scrollToBottom();
});
return () => {
socket.off("message", handleMessage);
socketStore.socket.off("message", handleMessage);
};
// eslint-disable-next-line
}, [chatState.selectedChatID]);
Expand Down
18 changes: 13 additions & 5 deletions frontend/code/src/Components/Chat/Services/SocketsServices.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,15 @@
import { io } from 'socket.io-client';
import { io } from 'socket.io-client';
import { create } from 'zustand'

export const useSocketStore:any = create((set:any) => ({
socket:null,
setSocket : () => {
const s = io("http://localhost:3004", {
transports: ['websocket'],
withCredentials: true,
});
set(() => ({socket:s}))
return s;
}
}))

export const socket = io("http://localhost:3004", {
transports: ['websocket'],
withCredentials: true,
});
11 changes: 6 additions & 5 deletions frontend/code/src/Components/Layout/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ import { matchRoutes, useLocation } from "react-router-dom";
import { useUserStore } from "../../Stores/stores";
import { useNavigate } from "react-router-dom";
import { FirstLogin } from "../FirstLogin";
import { socket } from "../Chat/Services/SocketsServices";
import { useSocketStore } from "../Chat/Services/SocketsServices";
import toast from "react-hot-toast";
import { ShowLogoModal } from "../Chat/Components/RoomChatHelpers";

Expand Down Expand Up @@ -42,6 +42,7 @@ export const Layout: FC<PropsWithChildren> = (): JSX.Element => {

const user = useUserStore();
const navigate = useNavigate();
const socketStore = useSocketStore();

useLayoutEffect(() => {
const log = async () => {
Expand All @@ -58,9 +59,9 @@ export const Layout: FC<PropsWithChildren> = (): JSX.Element => {


};

socket.on("connect", onConnect);
socket.on("message",(msg) => {
socketStore.socket = socketStore.setSocket();
socketStore.socket.on("connect", onConnect);
socketStore.socket.on("message",(msg:any) => {
toast.custom((t) => (
<div
className={`${
Expand Down Expand Up @@ -99,7 +100,7 @@ export const Layout: FC<PropsWithChildren> = (): JSX.Element => {
})
log();
return () => {
socket.off("connect", onConnect);
socketStore.socket.off("connect", onConnect);
};
//eslint-disable-next-line
}, []);
Expand Down
10 changes: 8 additions & 2 deletions frontend/code/src/Components/Login/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -22,8 +22,14 @@ export const Login = () =>
const loggedin = await userStore.login();
if (loggedin)
navigate("/home")
} catch (error) {

} catch (error:any) {
if (error.response && error.response.status === 401) {
// This is a 401 error; you can choose to handle it silently
console.log("hit")
} else {
// Handle other errors
console.error(error);
}
}
}
check()
Expand Down
25 changes: 18 additions & 7 deletions frontend/code/src/Components/Play/index.tsx
Original file line number Diff line number Diff line change
@@ -1,18 +1,29 @@
import { VsUser } from './assets/VsUser'
import { VsBot } from './assets/VsBot'
import { Watch } from './assets/Watch'
import { Link } from 'react-router-dom'
// import { useSocketStore } from '../Chat/Services/SocketsServices'
import api from '../../Api/base'
import toast from 'react-hot-toast'
export const Play = () => {
// const socketStore = useSocketStore();
const subscribeToGame = async() => {
// socketStore.socket.emit
try {
const res = await api.post("/game/start");
console.log("res")
console.log(res.data)
} catch (error) {
toast.error("can not start game")
}
}
return(
<>
<div className="flex flex-col sm:flex-row justify-center items-center sm:justify-center sm:items-start p-10 gap-x-20">
<div className='max-w-[55vw] max-h-[55vh] w-[100%]'><Link to={"/Game"} ><VsBot/></Link></div>
<div className='max-w-[55vw] max-h-[55vh] w-[100%]'><VsUser/></div>
<div onClick={subscribeToGame} className='max-w-[55vw] max-h-[55vh] w-[100%]'><VsBot/></div>
{/* <div className='max-w-[55vw] max-h-[55vh] w-[100%]'><VsUser/></div> */}

</div>
{/* </div>
<h1 className='text-3xl font-poppins font-bold text-neutral text-center '>OR</h1>
<div className="flex flex-col sm:flex-row justify-center items-center sm:justify-center sm:items-start p-10 gap-x-20">
<div className='max-w-[55vw] max-h-[55vh] sm:max-w-[45vw] sm:max-h-[45vh] w-[100%]'><Watch/></div>
<div className='max-w-[55vw] max-h-[55vh] sm:max-w-[45vw] sm:max-h-[45vh] w-[100%]'><Watch/></div> */}
</div>
</>
)
Expand Down
21 changes: 0 additions & 21 deletions frontend/code/src/Components/Profile/test.ts

This file was deleted.

18 changes: 15 additions & 3 deletions frontend/code/src/Components/Settings/assets/Inputs.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -33,10 +33,11 @@ export const Inputs = (props:MyComponentProps) => {
//eslint-disable-next-line
const { register, handleSubmit, reset, formState: {errors} } = useForm();
const handleError = (errors : any) => {
console.log(errors)
if (errors[`${props.payload}`]?.type === "required") toast.error(`${props.name} ${ERROR_MESSAGES[0]} `);
if (errors[`${props.payload}`]?.type === "minLength") toast.error(`${props.name} ${ERROR_MESSAGES[1]} 4`);
if (errors[`${props.payload}`]?.type === "maxLength")toast.error(`${props.name} ${ERROR_MESSAGES[2]} 50 `);

if (errors[`email`].type === "pattern")toast.error(`${errors['email'].message}`);
}
const onSubmit = (data : any ) => {
toast.promise(
Expand Down Expand Up @@ -103,8 +104,19 @@ export const Inputs = (props:MyComponentProps) => {
<div className="flex items-center h-16">
<form className='gap-y-2 p-2 flex justify-center items-center'>
<div className="flex gap-x-2">
<input type="text" className={`h-12 w-full rounded-3xl text-center`} defaultValue={props.data} placeholder={props.payload} {...register(`${props.payload}`, {required: true, maxLength: 50 , minLength:4 , disabled:!input ? true:false})} />

{
props.name === "Email" ? (
<input type="email" className={`h-12 w-full rounded-3xl text-center`} defaultValue={props.data} placeholder={props.payload} {...register(`${props.payload}`, {required: true ,pattern: {
value: /\S+@\S+\.\S+/,
message: "Invalid Email format",

}, maxLength: 50 , minLength:4 , disabled:!input ? true:false})} />
):
(
<input type="text" className={`h-12 w-full rounded-3xl text-center`} defaultValue={props.data} placeholder={props.payload} {...register(`${props.payload}`, {required: true , maxLength: 50 , minLength:4 , disabled:!input ? true:false})} />

)
}
</div>
{!input && <animated.div
style={{
Expand Down
2 changes: 2 additions & 0 deletions frontend/code/src/Stores/stores.ts
Original file line number Diff line number Diff line change
Expand Up @@ -139,6 +139,8 @@ export const useUserStore = create<State & Action>()(
// console.log(userInitialValue)
set({ ...userInitialValue });
return userInitialValue.isLogged


},
logout: () => {
set({},true);
Expand Down
12 changes: 11 additions & 1 deletion nginx/default.conf
Original file line number Diff line number Diff line change
Expand Up @@ -38,4 +38,14 @@ server {
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
}
}
location /socket.io/ {
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Host $host;

proxy_pass http://backend:3001;

proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
}
}