Browse Source

fix styles and start private messages

serg1557733 1 year ago
parent
commit
8822f65971

+ 37 - 6
backend/app.js

@@ -215,7 +215,7 @@ io.use( async (socket, next) => {
         const userName = user.userName;
         const dbUser = await getOneUser(userName);
 
-        if(dbUser.isBanned){
+        if(dbUser && dbUser.isBanned){
             socket.disconnect();
             return;
         }
@@ -239,9 +239,17 @@ io.on("connection", async (socket) => {
     const userName = socket.user.userName;
     const sockets = await io.fetchSockets();
     const dbUser = await getOneUser(userName);
+    const exist = sockets.find(current => current.user.userName == socket.user.userName)
+    const usersOnline = sockets.map(sock => sock.user)
 
 
-    io.emit('usersOnline', sockets.map(sock => sock.user)); // send array online users  
+    const usersOnlineID = usersOnline.map(users => Object.values(users)[0])
+    const userSet = new Set(usersOnlineID)
+
+    console.log(userSet)
+
+
+    io.emit('usersOnline', usersOnline); // send array online users  
 
     socket.emit('connected', dbUser); //socket.user
   
@@ -251,6 +259,7 @@ io.on("connection", async (socket) => {
 
     const messagesToShow = await Message.find({}).sort({ 'createDate': -1 }).limit(20).populate( {path:'user'});   
     socket.emit('allmessages', messagesToShow.reverse());
+
     socket.on("message", async (data) => {
         const dateNow = Date.now(); // for correct working latest post 
         const post = await Message.findOne({userName}).sort({ 'createDate': -1 })
@@ -291,9 +300,19 @@ io.on("connection", async (socket) => {
     
     try {
         socket.on("disconnect", async () => {
-            const sockets = await io.fetchSockets();
-            io.emit('usersOnline', sockets.map(sock => sock.user));
-            console.log(`user :${socket.user.userName} , disconnected to socket`); 
+
+            const exist = sockets.find(current => current.user.userName == socket.user.userName)
+            const usersOnline = sockets.map(sock => sock.user)
+        
+            const filteredUsersOnline = usersOnline.filter(user => exist.user.id !== user.id)
+        
+           
+           socket.emit('usersOnline', filteredUsersOnline);
+
+            // const sockets = await io.fetchSockets();
+            // io.emit('usersOnline', sockets.map(sock => sock.user));
+             console.log(`user :${socket.user.userName} , disconnected to socket`); 
+
         });
             console.log(`user :${socket.user.userName} , connected to socket`); 
         socket.on("muteUser",async (data) => {
@@ -313,6 +332,13 @@ io.on("connection", async (socket) => {
                     } 
                 // }
            });
+
+        socket.on('privat', (data) => {
+            console.log(data)
+        
+        })
+
+
     
         socket.on("banUser",async (data) => {
             if(!socket.user.isAdmin){
@@ -383,6 +409,12 @@ const start = async () => {
     try {
         await mongoose.connect('mongodb://localhost:27017/chat')
             .then(() => console.log(`DB started`))
+        
+
+        // await mongoose
+        //     .connect('mongodb+srv://serg1557733:1557733@cluster0.p9ltitx.mongodb.net/?retryWrites=true&w=majority')
+        //     .then(() => console.log(`DB started`))
+
         server.listen(PORT, () => {
             console.log(`Server started. Port: ${PORT}`);
         })
@@ -390,5 +422,4 @@ const start = async () => {
         console.log(e);
     }
 }
-
 start();

+ 23 - 3
frontend/public/service-worker.js

@@ -17,12 +17,32 @@ self.addEventListener('install', (e) => {
     )
 })
 
-self.addEventListener('fetch', () => {
-  
+self.addEventListener('fetch', (e) => {
+    e.respondWith(
+        caches.match(e.request)
+            .then(() => {
+                return fetch(e.request)
+                    .catch(() => caches.match('offline.html'))
+            })
+    )
 })
 
 
-self.addEventListener('activate', () => {
+self.addEventListener('activate', (e) => {
+    const cacheWersions = [];
+    cacheWersions.push(CASH);
+
+    e.waitUntil(
+        caches.keys().then(cachNames => Promise.all(
+            cachNames.map(cacheName => {
+                    if(!cacheWersions.includes(cacheName)){
+                        return caches.delete(cacheName);
+                    }
+                }
+            )
+        ))
+    )
+
   
 })
 // /* eslint-disable no-restricted-globals */

+ 1 - 1
frontend/src/components/chatPage/ChatPage.jsx

@@ -177,7 +177,7 @@ export const ChatPage = () => {
                                 backgroundImage:'url(' + imgBtn + ')' ,
                                 backgroundPosition: 'center', 
                                 backgroundRepeat: "no-repeat", 
-                                backgroundSize: '20px 40px'
+                                backgroundSize: '20px 20px'
 
                             }}
                             style = {{color: 'green'}}

+ 10 - 1
frontend/src/components/chatPage/chatPage.scss

@@ -24,15 +24,20 @@
 
 .rootMessageForm {
     display: flex;
+    border-radius: 5px;
     flex-grow:2;
+    border: 2px solid grey; 
     max-width: 75%;
     flex-direction: column;                 
 }
 .rootMessageFormMobile {
     margin: 0 auto;
     display: flex;
+    border-radius: 5px;
+
     flex-grow:1;
     max-width: 100%;
+    border: 2px solid grey; 
     height: 90vh;
     flex-direction: column;                 
 }
@@ -120,16 +125,18 @@
 .usersBox { 
     align-content: flex-end;
     text-align: center;
-    padding: 20px;
     margin-left: 10px;
     width: 20%;
     overflow: scroll;
     border-radius: 10px;
+    border: 2px solid grey; 
     background-color:rgb(243, 243, 243);
     .online {
         border-radius: 5px;
         padding: 5px;
+        border: 2px solid grey; 
         margin-bottom: 5px;
+        cursor: pointer;
         background-color:rgb(247, 233, 233);
         font-weight: 700;
 
@@ -144,12 +151,14 @@
     overflow: scroll;
     font-size: 11px;
     border-radius: 10px;
+    border: 2px solid grey; 
     background-color:rgb(243, 243, 243);
     transition: all 3s ease-in-out;    
     .online {
         border-radius: 5px;
         text-overflow: ellipsis;
         padding: 5px;
+        border: 2px solid grey;
         margin-bottom: 5px;
         background-color:rgb(247, 233, 233);
         font-weight: 500;

+ 9 - 3
frontend/src/components/chatPage/messageForm/MessegaForm.jsx

@@ -18,7 +18,7 @@ export const MessageForm = () => {
     const dispatch = useDispatch();
     const socket = useSelector(state => state.getUserSocketReducer.socket)
 
-    const SERVER_URL = process.env.REACT_APP_SERVER_URL;
+    const SERVER_URL =process.env.REACT_APP_SERVER_URL
 
     const startMessages = useSelector(state => state.getUserSocketReducer.startMessages)
     const user = useSelector(state => state.getUserSocketReducer.socketUserData)
@@ -40,12 +40,13 @@ export const MessageForm = () => {
         if (!isEditing) {
             scrollToBottom((endMessages)) 
         } 
-      }, [startMessages, messages]);
+      }, [startMessages, messages, newMessages]);
            
+    console.log(usersOnline)
 
     useEffect(()=> {
         if(newMessages.length > 0 && newMessages[newMessages.length-1].userName !== user.userName){
-            play()                 
+           // play()                 
         }
     }, [newMessages])
 
@@ -67,6 +68,11 @@ export const MessageForm = () => {
                         {storeMessageId === item._id ? <MessageEditorMenu />: ""} 
                         <StyledAvatar
 
+                            onClick={() => {
+                                socket.emit('privat', {data: item._id})
+                               
+                            }}
+
                             anchorOrigin={{ vertical: 'bottom', horizontal: 'right' }}  
                             variant = {userNamesOnlineSet.has(item.userName)? 'dot' : ''}
                                    

+ 7 - 3
frontend/src/components/chatPage/userInfo/UserInfo.jsx

@@ -34,7 +34,7 @@ export const UserInfo = () => {
             setDisplayType('none')
         }, 4000)
     }
-    const SERVER_URL = process.env.REACT_APP_SERVER_URL;
+    const SERVER_URL = process.env.REACT_APP_SERVER_URL
 
     const allUsers = useSelector(state => state.getUserSocketReducer.allUsers)
     const user = useSelector(state => state.getUserSocketReducer.socketUserData)
@@ -80,7 +80,9 @@ export const UserInfo = () => {
                         allUsers.map((item, key) =>
                             <div 
                                 key={item._id}
-                                className='online'>
+                                className='online'
+                                onClick={() => console.log(item.id)}
+                                >
                                 <div>
                                     {item.userName}
                                 </div>
@@ -137,7 +139,9 @@ export const UserInfo = () => {
                      !isTabletorMobile && usersOnline.map((item, i) =>
                         <div 
                             key={i}
-                            className='online'>  
+                            className='online'                        
+                            onClick={() => console.log(item.id)}
+>  
                                 <div style={{color: item.color}}>
                                     {item.userName}
                                 </div>

+ 1 - 3
frontend/src/reducers/messageReducer.js

@@ -13,9 +13,7 @@ const initialState = {
     ref: null
 }
 
-const SERVER_URL = process.env.REACT_APP_SERVER_URL;
-
-const POST_FILES_URL = SERVER_URL + '/files';
+const POST_FILES_URL = process.env.REACT_APP_SERVER_URL+`/files`;
 
 export const sendMessageToSocket = (state, data) => {
              if (!!state.message && state.message.length < 200) {    //remove to other file

+ 0 - 1
frontend/src/reducers/socketReducer.js

@@ -20,7 +20,6 @@ const SOCKET_URL = process.env.REACT_APP_SERVER_URL;
 
 
 const connectToSocket = (event) => {
- 
         try {
             const token = localStorage.getItem('token');
             if(token){

+ 4 - 3
frontend/src/reducers/userDataReducer.js

@@ -15,15 +15,16 @@ const initialState = {
     showUserInfoBox: false,
     avatar: ''
 }
-const SERVER_URL = process.env.REACT_APP_SERVER_URL;
+const SERVER_URL =  process.env.REACT_APP_SERVER_URL
 
-const POST_URL =  SERVER_URL + '/login';
-const GET_AVATAR_URL =  SERVER_URL + '/avatar';
+const POST_URL =  process.env.REACT_APP_SERVER_URL + '/login';
+const GET_AVATAR_URL = process.env.REACT_APP_SERVER_URL +  '/avatar';
 
 export const getUserData = createAsyncThunk(
     'userData/getUser',
      ( t , thunkAPI) => {
       const userData = thunkAPI.getState().userDataReducer;
+      console.log(POST_URL)
         if(userData.userName){
             if(isValidPayload({...userData}) && isValidUserName({...userData}))
                 try {

+ 1 - 1
frontend/src/serviceWorkerRegistration.js

@@ -19,7 +19,7 @@ const isLocalhost = true
 //       // 127.0.0.0/8 are considered localhost for IPv4.
 //       window.location.hostname.match(/^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/)
 //   );
-
+console.log('start sw...')
   export function register(config) {
     if ('serviceWorker' in navigator) {
       console.log('registering..')