Skip to content

Commit

Permalink
roomTitleEdit
Browse files Browse the repository at this point in the history
  • Loading branch information
imdeveshshukla committed Aug 26, 2024
1 parent bc78c7e commit 05253f1
Show file tree
Hide file tree
Showing 7 changed files with 152 additions and 39 deletions.
Empty file added backend/public/img/.gitkeep
Empty file.
49 changes: 29 additions & 20 deletions backend/src/controller/rooms.js
Original file line number Diff line number Diff line change
Expand Up @@ -84,17 +84,19 @@ export const updateRoom = async(req,res)=>{
const userId = req.userId;

const title = data.title;

console.log(data.newTitle);
console.log(title);
try{
console.log("Inside UpdateRoom");
console.log(title);
// console.log("Inside UpdateRoom");
const room = await prisma.rooms.findFirst({
where:{
title
}
})
const temp = await prisma.rooms.findMany();
console.log(temp);
console.log(room);
// console.log(temp);
// console.log(room);
if(!room?.id)return res.status(404).json({msg:"Room Not Found!"});


Expand All @@ -107,9 +109,9 @@ export const updateRoom = async(req,res)=>{
})
}
let imgUrl = null,bgImgUrl = null;
console.log("data\n");
console.log(data);
if(req.file?.fieldname == 'roomImg')
// console.log("data\n");
console.log(req.file);
if(req.file && req.file?.fieldname === 'roomImg')
{

try {
Expand All @@ -123,28 +125,29 @@ export const updateRoom = async(req,res)=>{
}

}
if(req.file?.fieldname == 'bgImg')
if(req.file && req.file?.fieldname === 'bgImg')
{
try{
console.log("Uploading bgImg.......");
// console.log("Uploading bgImg.......");
bgImgUrl = await uploadOnCloudinary(req.file.path);
} catch (error) {
console.log("Inside bgImg chatch");
// console.log("Inside bgImg chatch");
// fs.unlinkSync(req.file.path); //Issue need to resolve
console.log(error);
return res.status(400).json({
msg: error.message,
error
})
}
}
}
console.log(bgImgUrl);
console.log(`${JSON.stringify(req.file.path)} = ${bgImgUrl}`);
// console.log(`${JSON.stringify(req.file.path)} = ${bgImgUrl}`);
const updatedRoom = await prisma.rooms.update({
where:{
id:room.id
},
data:{
title: data.title || room.title,
title: data.newTitle || room.title,
desc: data.desc || room.desc,
img: imgUrl || room.img,
bgImg: bgImgUrl || room.bgImg
Expand All @@ -158,12 +161,12 @@ export const updateRoom = async(req,res)=>{
}
catch(err)
{
console.log("Paht ",req.file?.path);


if(req.file?.path)fs.unlink(req.file.path,(err)=>
console.log("Error While Deleting img = ",err)
);

console.log("error");
console.log(err);
return res.status(500).json({
msg:"Database/Server Error",
error:err.message
Expand Down Expand Up @@ -626,15 +629,21 @@ export const sendJoiningRequest = async(req,res)=>{
if(!room)return res.status(404).json({msg:"Room Not Found"});
if(room.CreatorId != userID)return res.status(401).json({msg:"You are not authorised"});
let found =false;

let waiting = false;
// console.log("Above ForEach Bloco");
room.UsersEnrolled.forEach((rooms)=>{
if(rooms.userId === user.userID){
found = true;
if(rooms.joined)found = true;
else waiting = true;
}
})
// console.log("We Have found ",found)
if(found)
// console.log(found+" "+waiting)
if(found){
return res.status(200).json({
msg:"User Already Present"
})
}
if(waiting)
{
const enrollment = await prisma.enrolledRooms.update({
where:{
Expand Down
1 change: 1 addition & 0 deletions backend/src/routes/roomsRouter.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ const roomsRouter = express.Router()
roomsRouter.post('/create',verifyToken,upload.single('roomImg'),CreateRoom);
roomsRouter.post('/updatedp',verifyToken,upload.single('roomImg'),updateRoom);
roomsRouter.post('/updatebgImg',verifyToken,upload.single('bgImg'),updateRoom);
roomsRouter.post('/update',verifyToken,updateRoom);
roomsRouter.post('/delete',verifyToken,deleteRoom);


Expand Down
102 changes: 91 additions & 11 deletions frontend/src/components/AddMemBox.jsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { useEffect, useRef, useState } from "react";
import { IoClose } from "react-icons/io5";
import { useSelector } from "react-redux";
import { useDispatch, useSelector } from "react-redux";
import SmoothLoader from "../assets/SmoothLoader";
import axios from "axios";
import baseAddress from "../utils/localhost";
Expand All @@ -9,10 +9,13 @@ import dp from '../assets/dummydp.png'
import { useDebounce } from '../hooks/useDebounce';
import { fetchUsers } from "./Search";
import { v4 as uuidv4 } from "uuid";
import { changeTitle } from "../redux/roomSlice";
import { clearRooms, updateRoomDetail } from "../redux/userRooms";
import { useNavigate } from "react-router-dom";



export default function AddMemBox({ setShow, id }) {
export default function AddMemBox({ setShow, id, update}) {
const createPostRef = useRef(null);
const [title, setTitle] = useState('');
const [Btnloading, setLoading] = useState(false);
Expand All @@ -24,27 +27,85 @@ export default function AddMemBox({ setShow, id }) {
const [users, setUsers] = useState([]);
const [menu, setMenu] = useState(false);
const [canSend, setCanSend] = useState(false)



const dispatch = useDispatch();
const nav = useNavigate();
async function sendReq(){
const title2 = title.trim();
const res = await axios.get(baseAddress+"rooms/titleNameIsUnique?filter="+title2);
if(res.data.msg == true)
{
setColor("green");
setError(` Title is available`)
setTitleRequired(false);
}
else{
setColor("red");
setError(`Sorry ${title} is not available`);
setTitleRequired(true);
}
return res.data;
}
const containsWhitespace = str => /\s/.test(str);
useEffect(() => {
if (title.length == 0) {
setError("Username required!");
setError(update?update:"Username required!");
setTitleRequired(true);
setColor("red");
}
else if (title === userData?.username) {
else if (!update && title === userData?.username) {
setError("Don't Add Yourself in this room");
setTitleRequired(true);
setColor("red");
}
else if(update && update === title){
setTitleRequired(true);
setColor("red");
setError("Current Room Name!");
}
else if(update && title.length < 3){
setTitleRequired(true);
setColor("red");
setError("Title Length Should be greater then 3!");
}
else if(update && containsWhitespace(title)){
setTitleRequired(true);
setColor('red');
setError("Title should not contain spaces!!");
}
else if(update && update === title){
setError("Previous Name");
setTitleRequired(true);
setColor("red");
}
else {
setError("");
setColor("black");
setTitleRequired(false);
if(update)customDebouncer(sendReq,500);
}
}, [title])

const updateRoomTitle = async()=>{
if(titleRequired)return;
setLoading(true);
try{
const res = await axios.post(`${baseAddress}rooms/update`,{
title:id,
newTitle:title
})
toast.success(res.data.msg);
dispatch(changeTitle(res.data.updatedRoom.title));
dispatch(updateRoomDetail(res.data.updatedRoom));
nav(`/room/${res.data.updatedRoom.CreatorId}/${res.data.updatedRoom.title}`);
}
catch(err)
{
setLoading(false);
console.log(err);
toast.error(err.response.data.msg);
}
setLoading(false);
}
const handleSubmit = async () => {
// console.log(canSend);

Expand Down Expand Up @@ -74,7 +135,12 @@ export default function AddMemBox({ setShow, id }) {
setLoading(false);
}
}
let timeout;
var customDebouncer = function(func, delay) {
clearTimeout(timeout);

timeout = setTimeout(func, delay);
};
const handleClickOutside = (event) => {
if (createPostRef.current && !createPostRef.current.contains(event.target)) {
setShow(false)
Expand Down Expand Up @@ -114,7 +180,7 @@ export default function AddMemBox({ setShow, id }) {
<div className="fixed z-40 bg-[#0005] top-0 left-0 backdrop-blur-sm min-h-screen min-w-full pb-10">
<div ref={createPostRef} className=" absolute w-[85%] xs:w-[75%] sm:w-[60%] md:w-[50%] left-[50%] top-[50%] translate-y-[-50%] translate-x-[-50%] overflow-auto bg-[#d5d6b5] shadow-md shadow-current rounded-lg px-6 py-5 biggerTablet:h-5/6">
<div className="heading flex justify-between">
<h2 className="text-xl font-bold mb-4 text-[#656923]">Add Member</h2>
<h2 className="text-xl font-bold mb-4 text-[#656923]">{update?"Update Room Title":"Add Member"}</h2>
<button className="hover:bg-black w-5 h-5 rounded-full" onClick={() => { setShow(false) }}>
<IoClose className="text-[#656923] m-auto" />
</button>
Expand All @@ -125,14 +191,28 @@ export default function AddMemBox({ setShow, id }) {
{/* Title Input */}
<div className="mb-4 relative min-h-[20vh] ">
<div className="mb-5">
<label htmlFor="username-success"
{update?
<>
<label htmlFor="title-success"
className={`block mb-2 text-sm font-medium text-[#656923]`}>Title<span className="text-red-600">*</span></label>
<input
type="text"
className={`font-bold border border-${color}-500 text-${color}-900 placeholder-${color}-700 text-sm rounded-lg focus:ring-${color}-900 focus:border-${color}-500 block w-full p-2.5`}
placeholder="New Room Name"
value={title}
onChange={(e) => handleChange(e)}/>
<p className={`text-${color}-900 text-sm`}>{error}</p>
</>
:<><label htmlFor="username-success"
className={`block mb-2 text-sm font-medium text-[#656923]`}
>UserName<span className="text-red-600">*</span></label>
<input onClick={()=>setMenu(true)} type="text"
className={`bg-${color}-50 border border-${color}-500 text-${color}-900 placeholder-${color}-700 text-sm rounded-lg focus:ring-${color}-500 focus:border-${color}-500 block w-full p-2.5 `}
placeholder={userData?.username}
value={title}
onChange={(e) => handleChange(e)} />
</>
}

{menu && <div className='my-2 mx-16 flex gap-2 flex-col'>
{users.map(user => {
Expand All @@ -155,9 +235,9 @@ export default function AddMemBox({ setShow, id }) {
{/* Submit Button */}

<button
onClick={handleSubmit}
onClick={update?updateRoomTitle:handleSubmit}
className={titleRequired ? "bg-[#656923] w-32 1_5md:w-48 text-sm text-black font-bold py-2 px-4 rounded focus:outline-none cursor-not-allowed" : "bg-[#656923] hover:bg-[#a9aa88] w-48 text-sm text-black font-bold py-2 px-4 rounded focus:outline-none"}>
{Btnloading ? <SmoothLoader /> : "Send Request"}
{Btnloading ? <SmoothLoader /> : update?" Update ":"Send Request"}
</button>
<p className={`mt-4 text-xs text-red-500 self-end`}>
Required fields are marked with (*)
Expand Down
27 changes: 21 additions & 6 deletions frontend/src/pages/Room.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,8 @@ import { roomsApi, useGetRoomDetailsQuery } from "./RoomApis";
import { MdExitToApp } from "react-icons/md";
import { MdDelete } from "react-icons/md";
import banner from '../assets/banner.png'
import { BiEdit } from "react-icons/bi";
import { CiEdit } from "react-icons/ci";



Expand Down Expand Up @@ -67,6 +69,8 @@ const Room = function () {
const [privateRoom, setPrivateRoom] = useState(true);
const dropdownRef = useRef(null);
const [isOpen, setisOpen] = useState(false);

const [showChangeTitleBox,setBox] = useState(false);
function handleToggle() {
setisOpen((isOpen) => !isOpen)
}
Expand Down Expand Up @@ -277,12 +281,12 @@ const Room = function () {
};
}, []);

// console.log(roomDetail?.CreatorId + "==" + userData?.userID+" === ");

return (
<>
{showCP && <CreatePost showCP={showCP} onNewPost={onNewPost} setShowCP={setShowCP} roomTitle={title} setPost={setPost} />}
{showAddMem && <AddMemBox setShow={setShowAddMem} id={title} />}
{showChangeTitleBox && <AddMemBox setShow={setBox} id={roomDetail?.title} update={roomDetail?.title}/>}
<div className="w-full">
<div className=' flex flex-col gap-4 xxs:gap-2 sm:gap-4 2_sm:gap-6'>
<div className='border-black border-2 relative shadow-lg shadow-slate-300 rounded-2xl h-36 xs:h-44 sm:h-48 m-4 '>
Expand All @@ -302,7 +306,7 @@ const Room = function () {
</div>
</div>
<div className='flex items-center justify-end pr-8 w-full text-center text-lg xxs:text-2xl xs:text-3xl font-bold'>
<img className=" w-7 xxs:w-8 xs:w-9 rounded-l-lg " src={q} alt="" /><span className=" bg-white font-ubuntu rounded-r-lg px-1">{title}</span>
<img className=" w-7 xxs:w-8 xs:w-9 rounded-l-lg " src={q} alt="" /><span className=" bg-white font-ubuntu rounded-r-lg px-1">{roomDetail?.title}</span>
</div>
<div className="flex items-center justify-end pr-8 gap-2 w-full">
{
Expand Down Expand Up @@ -341,14 +345,25 @@ const Room = function () {
{isOpen && (
<div className="absolute right-0 top-10 bg-white rounded-md shadow-lg z-10">
<ul className=" bg-black rounded-md ">
<li className=" text-white hover:bg-grey">
{isOwner ? <>
<li className=" text-white rounded-md hover:bg-gray-700">
<button onClick={() => deleteRoom()} to={"/"} className="px-4 py-1 flex items-center gap-1 ">
{isOwner ? <>
<span>Delete</span> <MdDelete />
</> : <>
</button>
</li>
<hr/>
<li className=" text-white rounded-md hover:bg-gray-700">
<button onClick={() => setBox(true)} to={"/"} className="px-4 py-1 flex items-center m-auto gap-3 ">
<span className="m-auto text-center">Title</span> <CiEdit />
</button>
</li>
</>:<>
<li className=" text-white hover:bg-grey">
<button onClick={() => deleteRoom()} to={"/"} className="px-4 py-1 flex items-center gap-1 ">
<span>Leave</span> <MdExitToApp />
</>}</button>
</button>
</li>
</>}
</ul>

</div>
Expand Down
5 changes: 4 additions & 1 deletion frontend/src/redux/roomSlice.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,12 +18,15 @@ export const roomSlice = createSlice({
changeDpImg:(state,action)=>{
state.roomInfo.img = action.payload
},
changeTitle:(state,action)=>{
state.roomInfo.title = action.payload
},
clearRoomDetail:(state)=>{
state.roomInfo=null;
},
},
})

export const { setRoomDetail,changeBgImg,clearRoomDetail, changeDpImg } = roomSlice.actions;
export const { setRoomDetail,changeBgImg,clearRoomDetail, changeDpImg,changeTitle } = roomSlice.actions;

export default roomSlice.reducer
Loading

0 comments on commit 05253f1

Please sign in to comment.