Browse Source

fix some bugs

serg1557733 1 year ago
parent
commit
8fb126354d

+ 4 - 0
backend/app.js

@@ -52,13 +52,17 @@ const getAllDbUsers = async (socket) => {
     socket.emit('allDbUsers', usersDb) 
 }
 
+
 const getOneUser = async (userName) => {
     const userInDb = await User.findOne({userName});
     return userInDb;
 }
 app.post('/login', async (req, res) => {
+    
+
     try {
         const {userName,password} = req.body;
+        console.log(userName,password)
         if (!isValidUserName(userName)){
             return res.status(400).json({message: 'Invalid username'})
         }

+ 115 - 0
backend/avatars/index.js

@@ -0,0 +1,115 @@
+import { initializeApp } from "firebase/app";
+import { getAnalytics } from "firebase/analytics";
+const functions = require('firebase-functions');
+
+
+// Your web app's Firebase configuration
+// For Firebase JS SDK v7.20.0 and later, measurementId is optional
+const firebaseConfig = {
+  apiKey: "AIzaSyCqJj50pTiXBAtRgTVlNY5AQCBySgGSHqY",
+  authDomain: "telegrambot-5f3ce.firebaseapp.com",
+  projectId: "telegrambot-5f3ce",
+  storageBucket: "telegrambot-5f3ce.appspot.com",
+  messagingSenderId: "39238727150",
+  appId: "1:39238727150:web:dbe83ac0c806527c7b0aff",
+  measurementId: "G-9H7RKXYBD1"
+};
+
+// Initialize Firebase
+const appFire = initializeApp(firebaseConfig);
+const analytics = getAnalytics(app);
+
+
+const  { Telegraf } = require('telegraf');
+const express = require('express')
+
+const token = '5717084656:AAET0Vzk61yjkhEO18yltR1GhvkDYtheZdg'
+
+const bot = new Telegraf(token, {polling: true})
+
+const app = express()
+const port = 3030
+
+const  RegExpLink = /(([a-z]+:\/\/)?(([a-z0-9\-]+\.)+([a-z]{2}|aero|arpa|biz|com|coop|edu|gov|info|int|jobs|mil|museum|name|nato|net|org|pro|travel|local|internal))(:[0-9]{1,5})?(\/[a-z0-9_\-\.~]+)*(\/([a-z0-9_\-\.]*)(\?[a-z0-9+_\-\.%=&]*)?)?(#[a-zA-Z0-9!$&'()*+.=-_~:@/?]*)?)(\s+|$)/gi;
+const idForBan = [];
+
+bot.on('message', async (ctx) => {
+    console.log(ctx.message.from)
+
+
+  if(ctx.message.text) {
+    const str = ctx.message.text.toLowerCase();
+    console.log(str)
+
+    if(str.includes('iptv')){
+        ctx.reply(`Message from ${ctx.update.message.from.first_name} edited by BOT
+         ${str.replaceAll('iptv', '****')}`)
+        ctx.deleteMessage(ctx.message.message_id)
+        return
+
+    }
+
+    
+    if(str.includes('шаринг')){
+        ctx.reply(`Message from ${ctx.update.message.from.first_name} edited by BOT
+         ${str.replaceAll('шаринг', '****')}`)
+        ctx.deleteMessage(ctx.message.message_id)
+        return
+
+    }
+
+
+
+
+    if(str.includes('playlist')){
+        ctx.reply(`Message from ${ctx.update.message.from.first_name} edited by BOT
+         ${str.replaceAll('playlist', '****')}`)
+        ctx.deleteMessage(ctx.message.message_id)
+
+    }
+
+
+    if(RegExpLink.test(str) && (ctx.message.from.id !== 432003706)){
+        console.log(ctx.message.from)
+        ctx.reply(`Message from ${ctx.update.message.from.first_name} edited by BOT
+        ${ctx.message.text.replace(RegExpLink, 'http****.***')}`)
+       
+
+        if(idForBan.includes(ctx.message.from.id)){
+            bot.telegram.banChatMember(ctx.message.chat.id, ctx.message.from.id)
+
+        }
+
+        idForBan.push(ctx.message.from.id)
+        ctx.deleteMessage(ctx.message.message_id)
+        return
+
+     }
+  }
+
+
+
+   if(ctx.message.document){
+      const isPlaylist = ctx.message.document.file_name.includes('.m3u')
+      if (isPlaylist){
+        ctx.reply(`Hello ${ctx.update.message.from.first_name} playlists banned in this group `)
+        ctx.deleteMessage(ctx.message.message_id)
+      }
+   } 
+  })
+
+  console.log(idForBan)
+
+bot.launch()
+
+
+app.get('/', (req, res) => {
+  res.send('Hello World!')
+})
+
+
+app.listen(port, () => {
+  console.log(`Server listening on port ${port}`)
+})
+
+exports.bot = functions.https.onRequest(app);

+ 28 - 0
backend/avatars/test.js

@@ -0,0 +1,28 @@
+const { spawn } = require('child_process');
+const got = require('got');
+const test = require('tape');
+
+// Start the app
+const env = Object.assign({}, process.env, {PORT: 5000});
+const child = spawn('node', ['index.js'], {env});
+
+test('responds to requests', (t) => {
+  t.plan(4);
+
+  // Wait until the server is ready
+  child.stdout.on('data', _ => {
+    // Make a request to our app
+    (async () => {
+      const response = await got('http://127.0.0.1:5000');
+      // stop the server
+      child.kill();
+      // No error
+      t.false(response.error);
+      // Successful response
+      t.equal(response.statusCode, 200);
+      // Assert content checks
+      t.notEqual(response.body.indexOf("<title>Node.js </title>"), -1);
+      t.notEqual(response.body.indexOf("Getting Started on Heroku with Node.js"), -1);
+    })();
+  });
+});

+ 10 - 7
frontend/src/components/chatPage/ChatPage.jsx

@@ -16,7 +16,7 @@ import imgBtnPhoto from '../../assets/img/photo.png'
 import './chatPage.scss';
 import WebcamCapture from './service/webCam/WebcamCapture';
 import useSound from 'use-sound';
-import getNotif from '../../assets/get.mp3'
+import getNotif from '../../assets/sendSound.mp3'
 
 export const ChatPage = () => {
 
@@ -95,11 +95,14 @@ export const ChatPage = () => {
                         component="form" 
                         onSubmit = {e  => {
                                         e.preventDefault()
-                                        dispatch(sendMessage({user, socket}))
-                                        dispatch(getSocket('allmessages'))
-                                        dispatch(editMessage({editMessage: ''}))
-                                        setMessage({message: ''})
-                                        play()
+                                        if (message.message.length){
+                                            dispatch(sendMessage({user, socket}))
+                                            dispatch(getSocket('allmessages'))
+                                            dispatch(editMessage({editMessage: ''}))
+                                            setMessage({message: ''})
+                                            play()
+                                        }
+                                      
                                     }}
                         sx={(isTabletorMobile)?{
                             display: 'flex',
@@ -178,7 +181,7 @@ export const ChatPage = () => {
                         <Button 
                             variant="contained" 
                             type='submit'
-                            disabled={user?.isMutted}
+                            disabled={user?.isMutted || !message.message.length}
                             style={{width: '20%'}}
                         >
                             Send

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

@@ -14,7 +14,7 @@ export const MessageEditorMenu = () => {
     const messageId = useSelector(state => state.messageReducer.messageId)
     const socket = useSelector(state => state.getUserSocketReducer.socket)
     const [message, setMessage] = useState({message: editOldMessage});
-    console.log(message)
+
 
 
     return (

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

@@ -8,6 +8,8 @@ import { editMessage } from '../../../reducers/messageReducer';
 import { StyledAvatar } from './StyledAvatar';
 import { MessageEditorMenu } from '../MessageEditorMenu.jsx';
 import imgBtn from '../../../assets/img/gg.png';
+import useSound from 'use-sound';
+import notifSound from '../../../assets/sendSound.mp3'
 
 
 export const MessageForm = () => {
@@ -23,11 +25,15 @@ export const MessageForm = () => {
     const userNamesOnlineSet =  new Set(usersOnline.map( i => i.userName))
     const storeMessageId = useSelector(state => state.messageReducer.messageId)
 
+  
+
     let endMessages = useRef(null);
     const [isEditing, setIsEditing] = useState(false)   
-    const [isEditiedMessage, setisEditiedMessage] = useState(false) //need to type in the bottom of message after message was edited
+    const [isEditiedMessage, setIsEditiedMessage] = useState(false) //need to type in the bottom of message after message was edited
 
     const regYoutube = /http(?:s?):\/\/(?:www\.)?youtu(?:be\.com\/watch\?v=|\.be\/)([\w\-\_]*)(&(amp;)?‌​[\w\?‌​=]*)?/; //for youtube video
+    
+    const [play] = useSound(notifSound);
 
     useEffect(() => {
         if (!isEditing) {
@@ -50,8 +56,7 @@ export const MessageForm = () => {
                         }}
                         > 
                         {storeMessageId === item._id ? <MessageEditorMenu />: ""} 
-                        
-
+                        {console.log(startMessages.length)}
                         <StyledAvatar
 
                             anchorOrigin={{ vertical: 'bottom', horizontal: 'right' }}  
@@ -62,7 +67,7 @@ export const MessageForm = () => {
                                 key={i} 
                                 src= {SERVER_URL + item?.user?.avatar}
                                 sx={
-                                    (item.userName == user.userName)
+                                    (item.userName === user.userName)
                                     ? 
                                     {
                                         alignSelf: 'flex-end',

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

@@ -4,7 +4,6 @@ import { createAsyncThunk } from '@reduxjs/toolkit';
 
 
 const initialState = {
-    startMessages: [],
     message:'',
     editMessage: '',
     messageId: '', 
@@ -16,7 +15,7 @@ const POST_FILES_URL = 'http://localhost:5000/files';
 
 
 export const sendMessageToSocket = (state, data) => {
-             if (state.message && state.message.length < 200) {    //remove to other file
+             if (!!state.message && state.message.length < 200) {    //remove to other file
                 data.socket.emit('message', {...data.user, message: state.message}); 
                    
             } 
@@ -30,7 +29,7 @@ export const deleteMessageHandler = (state, data) => {
 
     
 export const editMessageHandler = (state, data) => {
-    console.log( data.editMessage)
+   
     if(data.socket){
          data.socket.emit('editmessage', {messageNewText: data.editMessage.message, messageId: data.messageId, token: data.socket.auth.token}); //add backend functional later find by id and edit 
     }

+ 6 - 4
frontend/src/reducers/socketReducer.js

@@ -4,7 +4,6 @@ import { store } from '../store';
 import { removeToken } from './userDataReducer';
 
 
-
 const initialState = {
     socketStatus: 'idle',
     socket: null,
@@ -13,13 +12,15 @@ const initialState = {
     startMessages: [],
     allUsers: [],
     writing: false,
-    usersWriting: []
+    usersWriting: [],
+    newMessages : []
 }
 
 
 const SOCKET_URL =  process.env.REACT_APP_SERVER_URL || 'http://localhost:5000'; 
 
 const connectToSocket = (event) => {
+ 
         try {
             const token = localStorage.getItem('token');
             if(token){
@@ -44,6 +45,7 @@ const connectToSocket = (event) => {
                                 })
                             .on('newmessage', (data) => {
                                 store.dispatch(addNewMessage(data))
+
                                 })
                             .on('ban', (data) => {
                                 store.dispatch(removeToken()); 
@@ -92,8 +94,8 @@ export const getUserSocketSlice = createSlice({
         getUsersOnline: (state, action) => {state.usersOnline = action.payload},
         getAllUsers: (state, action) => {state.allUsers = action.payload},
         addNewMessage: (state, action) => {
-            state.startMessages.push(action.payload)
-            
+            state.newMessages.push(action.payload)
+
         }, 
 
         // writing: (state, action) => {