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

Dev chat #101

Merged
merged 9 commits into from
Nov 15, 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
1 change: 1 addition & 0 deletions backend/code/src/game/game.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,7 @@ export class GameService {
//NOTE: add game modes here
private launchGame() {
setInterval(() => {
// console.log('waitingPlayers', this.classicwaitingPlayers.length);
console.log('waitingPlayers classic', this.classicwaitingPlayers.length);
console.log('waitingPlayers extra', this.extraWaitingPlayers.length);

Expand Down
4 changes: 2 additions & 2 deletions backend/code/src/gateways/gateways.gateway.ts
Original file line number Diff line number Diff line change
Expand Up @@ -443,9 +443,9 @@ export class Gateways implements OnGatewayConnection, OnGatewayDisconnect {
const friendId = data.friendId;
if (this.server.sockets.adapter.rooms.get(`User:${friendId}`)?.size) {
client.emit('friendOnline', friendId);
return true;
} else {
client.emit('friendOffline', friendId);
}
return false;
}

@SubscribeMessage('unban')
Expand Down
14 changes: 14 additions & 0 deletions backend/code/src/rooms/rooms.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,20 @@ export class RoomsService {
delete roomData.secondMember;

if (roomData.type === 'dm') {
if (roomOwnerId === secondMember) {
throw new HttpException(
'you cannot create a dm room with yourself',
HttpStatus.BAD_REQUEST,
);
}
const user = await this.prisma.user.findUnique({
where: {
userId: secondMember,
},
});
if (!user) {
throw new HttpException('user not found', HttpStatus.NOT_FOUND);
}
const friendshipId = [roomOwnerId, secondMember].sort().join('-');
const blocked = await this.prisma.blockedUsers.findUnique({
where: {
Expand Down
7 changes: 5 additions & 2 deletions backend/code/src/users/users.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,11 @@ export class UsersController {
@Get('search')
@HttpCode(HttpStatus.OK)
@UseGuards(AtGuard)
async getUsers(@Query() query: usersSearchDto) {
return this.usersService.getUsers(query.q);
async getUsers(
@Query() query: usersSearchDto,
@GetCurrentUser('userId') userId: string,
) {
return this.usersService.getUsers(query.q, userId);
}

@Post('enableTwoFactorAuth')
Expand Down
40 changes: 15 additions & 25 deletions backend/code/src/users/users.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,7 @@ export class UsersService {
});
}

async getUsers(name: string) {
async getUsers(name: string, currentUserId: string) {
const users = await this.prisma.user.findMany({
take: 5,
where: {
Expand All @@ -114,32 +114,22 @@ export class UsersService {
},
],
NOT: {
blocked_by: {
some: {
Blcoked_by: {
OR: [
{
firstName: {
contains: name,
mode: 'insensitive',
},
},
{
lastName: {
contains: name,
mode: 'insensitive',
},
},
{
Username: {
contains: name,
mode: 'insensitive',
},
},
],
OR: [
{
blocked_by: {
some: {
blocked_id: currentUserId,
},
},
},
},
{
blocked: {
some: {
blocked_by_id: currentUserId,
},
},
},
],
},
},
});
Expand Down
100 changes: 74 additions & 26 deletions frontend/code/src/Components/Chat/Components/Conversation.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,8 @@ import { useUserStore } from "../../../Stores/stores";
import { formatTime } from "./tools/utils";
import { useSocketStore } from "../Services/SocketsServices";
import { useNavigate } from "react-router-dom";
import { blockUserCall } from "../Services/FriendsServices";
import { InvitationWaiting } from "../../Layout/Assets/Invitationacceptance";

export interface ChatPaceHolderProps {
username: string;
Expand Down Expand Up @@ -99,6 +101,8 @@ export const ConversationHeader: React.FC<ConversationProps> = ({
const currentUser = useChatStore((state) => state.currentDmUser);
const selectedChatType = useChatStore((state) => state.selectedChatType);
const socketStore = useSocketStore();
const inviteWaitingModalRef = useRef<HTMLDialogElement>(null);
const user = useUserStore();

const currentRoom = chatRooms.find((room) => room.id === SelectedChat);

Expand Down Expand Up @@ -195,13 +199,44 @@ export const ConversationHeader: React.FC<ConversationProps> = ({
tabIndex={0}
className="p-2 shadow menu dropdown-content z-[1] bg-base-100 rounded-box w-52 absolute right-full "
>
<li>
<li
onClick={async () => {
ChatState.setIsLoading(true);
await blockUserCall(currentUser?.secondUserId).then((res) => {
ChatState.setIsLoading(false);
if (res?.status === 200 || res?.status === 201) {
toast.success("User Blocked");
// ChatState.selectNewChatID("1");
} else {
toast.error("Could Not Block User");
}
});
}}
>
<span className="hover:bg-[#7940CF]">Block</span>
</li>
<li>
<span className="hover:bg-[#7940CF]">
invite for a Pong Game
</span>
<li
className="hover:bg-[#7940CF] hover:rounded"
onClick={() => {
socketStore?.socket?.emit(
"inviteToGame",
{
inviterId: user.id,
opponentId: currentUser.secondUserId,
gameMode: "classic",
},
(data: { error: string | null; gameId: string }) => {
if (data.error) {
toast.error(data.error);
return;
}
user.setGameWaitingId(data.gameId);
inviteWaitingModalRef.current?.showModal();
}
);
}}
>
<span>Invite to a game</span>
</li>
<li
onClick={() => {
Expand Down Expand Up @@ -276,26 +311,26 @@ export const ConversationHeader: React.FC<ConversationProps> = ({
: "hide Room Info"}
</span>
</li>
{currentRoom?.isOwner === false && (
<div>
<li
onClick={async () => {
ChatState.setIsLoading(true);
await leaveRoomCall(currentRoom?.id as string).then(
(res) => {
ChatState.setIsLoading(false);
if (res?.status === 200 || res?.status === 201) {
toast.success("Room Left Successfully");
ChatState.deleteRoom(currentRoom?.id as string);
}
{/* {currentRoom?.isOwner === false && ( */}
<div>
<li
onClick={async () => {
ChatState.setIsLoading(true);
await leaveRoomCall(currentRoom?.id as string).then(
(res) => {
ChatState.setIsLoading(false);
if (res?.status === 200 || res?.status === 201) {
toast.success("Room Left Successfully");
// ChatState.changeChatType(ChatType.Chat);
ChatState.deleteRoom(currentRoom?.id as string);
}
);
}}
>
<span className="hover:bg-[#7940CF]">leave The Room</span>
</li>
</div>
)}
}
);
}}
>
<span className="hover:bg-[#7940CF]">leave The Room</span>
</li>
</div>
</ul>
<ConfirmationModal
isOpen={isModalOpen}
Expand All @@ -304,6 +339,18 @@ export const ConversationHeader: React.FC<ConversationProps> = ({
</div>
)}
</div>
<InvitationWaiting
ref={inviteWaitingModalRef}
oppenent={{
picture: currentUser.avatar,
name: {
first: currentUser.name,
last: "",
},
username: "",
}}
user={user}
/>
</>
);
};
Expand Down Expand Up @@ -386,6 +433,7 @@ export const Conversation: React.FC<ConversationProps> = ({
socketStore.socket.on("message", handleMessage);

const fetch = async () => {
// const offset = chatState.currentMessages.length;
setLoading(true);
chatState.selectedChatID !== "1" &&
getRoomMessagesCall(chatState.selectedChatID, 0, 20)
Expand Down Expand Up @@ -415,7 +463,7 @@ export const Conversation: React.FC<ConversationProps> = ({
});
}
);
chatState.fillCurrentMessages(messages.reverse());
chatState.fillCurrentMessages(messages);
}
})
.finally(() => {
Expand All @@ -438,8 +486,8 @@ export const Conversation: React.FC<ConversationProps> = ({

const sendMessage = async () => {
if (inputValue.length === 0) return;
setInputValue("");
await sendMessageCall(chatState.selectedChatID, inputValue).then((res) => {
setInputValue("");
if (res?.status !== 200 && res?.status !== 201) {
setFail(true);
chatState.selectedChatType === ChatType.Room
Expand Down
110 changes: 58 additions & 52 deletions frontend/code/src/Components/Chat/Components/RecentChat.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { useEffect, useState } from "react";
import { useCallback, useEffect, useState } from "react";
import { ChatType, useChatStore } from "../Controllers/RoomChatControllers";
import { ChatPaceHolderProps } from "./Conversation";
import {
Expand Down Expand Up @@ -33,65 +33,71 @@ export const RecentConversations = () => {

const [ref, inView] = useInView();
const [EndOfFetching, setEndOfFetching] = useState(false);
useEffect(() => {
const fetch = async () => {
const offset = ChatRoomsState.recentDms.length;
offset === 0 && setLoading(true);
await fetchDmsCall(offset, 7).then((res) => {
setLoading(false);
if (res?.status !== 200 && res?.status !== 201) {
} else {
const rooms: DmRoom[] = [];
res.data.forEach(
(room: {
secondMemberId: string;
id: string;
last_message?: {
content?: string;
createdAt?: string;
};
name: string;

avatar: {
thumbnail: string;
medium: string;
large: string;
};
bio: string;
}) => {
rooms.push({
secondUserId: room.secondMemberId,
id: room.id,
name: room.name,
avatar: room.avatar,
last_message: {
content: room.last_message?.content,
createdAt: room.last_message?.createdAt,
},
bio: room.bio,
});
}
);
const fetchRecentDms = useCallback(async () => {
const offset = ChatRoomsState.recentDms.length;
offset === 0 && setLoading(true);
await fetchDmsCall(offset, 7).then((res) => {
setLoading(false);
if (res?.status !== 200 && res?.status !== 201) {
} else {
const rooms: DmRoom[] = [];
res.data.forEach(
(room: {
secondMemberId: string;
id: string;
last_message?: {
content?: string;
createdAt?: string;
};
name: string;

if (res.data.length > 0) {
ChatRoomsState.fillRecentDms([
...ChatRoomsState.recentDms,
...rooms,
]);
} else {
setEndOfFetching(true);
avatar: {
thumbnail: string;
medium: string;
large: string;
};
bio: string;
}) => {
// to check if not exist
rooms.push({
secondUserId: room.secondMemberId,
id: room.id,
name: room.name,
avatar: room.avatar,
last_message: {
content: room.last_message?.content,
createdAt: room.last_message?.createdAt,
},
bio: room.bio,
});
}
);

if (res.data.length > 0) {
ChatRoomsState.fillRecentDms([...ChatRoomsState.recentDms, ...rooms]);
} else {
setEndOfFetching(true);
}
});
};
if (!EndOfFetching) {
fetch();
}
}
});
// eslint-disable-next-line
}, [ChatRoomsState.recentDms]);

useEffect(() => {
fetchRecentDms();
return () => {
setEndOfFetching(false);
};
// eslint-disable-next-line
}, [ChatRoomsState.selectedChatID, ChatRoomsState.selectedChatType, inView]);
}, []);

useEffect(() => {
if (inView && !EndOfFetching) {
fetchRecentDms();
}
// eslint-disable-next-line
}, [inView]);

return selectedChatType === ChatType.Chat ? (
<div className="h-full flex flex-col ">
Expand Down
Loading
Loading