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

adding online status indicator feature #214

Closed
wants to merge 2 commits into from
Closed
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
107 changes: 65 additions & 42 deletions backend/models/userModel.js
Original file line number Diff line number Diff line change
@@ -1,50 +1,73 @@
const mongoose=require('mongoose');
const bcrypt=require('bcryptjs');
const axios=require('axios')
const mongoose = require("mongoose");
const bcrypt = require("bcryptjs");
const axios = require("axios");

const userSchema=new mongoose.Schema({
name:{type:String,required:true},
email:{type:String,required:true,unique:true},
password:{type:String,required:true},
pic: {
type:String,
required: true,
default:
"https://icon-library.com/images/anonymous-avatar-icon/anonymous-avatar-icon-25.jpg",
},
isAdmin: {
type: Boolean,
required: true,
default: false,
},
gender:{
type:String,
}
})
const userSchema = new mongoose.Schema({
name: { type: String, required: true },
email: { type: String, required: true, unique: true },
password: { type: String, required: true },
pic: {
type: String,
required: true,
default:
"https://icon-library.com/images/anonymous-avatar-icon/anonymous-avatar-icon-25.jpg",
},
isAdmin: {
type: Boolean,
required: true,
default: false,
},
isOnline: {
type: Boolean,
default: false,
},
lastOnline: {
type: Date,
default: null,
},
gender: {
type: String,
},
});

userSchema.pre('save',async function(next) {
this.password=await bcrypt.hash(this.password,12);
this.passwordConfirm=undefined
userSchema.pre("save", async function (next) {
this.password = await bcrypt.hash(this.password, 12);
this.passwordConfirm = undefined;

let value=await axios.get(`https://api.genderize.io?name=${this.name.split(' ')[0]}`)
this.gender=value.data.gender;
let value = await axios.get(
`https://api.genderize.io?name=${this.name.split(" ")[0]}`
);
this.gender = value.data.gender;

const menImgList=['https://i.ibb.co/d2qRfFh/9434619.jpg','https://i.ibb.co/GF5K0Zx/9439678.jpg','https://i.ibb.co/LQvJbv1/27470334-7309681.jpg'];
const womenImgList=['https://i.ibb.co/4fSJHhf/27470349-7309670.jpg','https://i.ibb.co/KrCfzc3/27470336-7294793.jpg','https://i.ibb.co/WHQPSRX/7309700.jpg']
const menImgList = [
"https://i.ibb.co/d2qRfFh/9434619.jpg",
"https://i.ibb.co/GF5K0Zx/9439678.jpg",
"https://i.ibb.co/LQvJbv1/27470334-7309681.jpg",
];
const womenImgList = [
"https://i.ibb.co/4fSJHhf/27470349-7309670.jpg",
"https://i.ibb.co/KrCfzc3/27470336-7294793.jpg",
"https://i.ibb.co/WHQPSRX/7309700.jpg",
];

let randomNumber = Math.floor((Math.random() * 3));
if(this.pic==='https://icon-library.com/images/anonymous-avatar-icon/anonymous-avatar-icon-25.jpg')
{
this.pic=this.gender==='male'?menImgList[randomNumber]:womenImgList[randomNumber]
}
let randomNumber = Math.floor(Math.random() * 3);
if (
this.pic ===
"https://icon-library.com/images/anonymous-avatar-icon/anonymous-avatar-icon-25.jpg"
) {
this.pic =
this.gender === "male"
? menImgList[randomNumber]
: womenImgList[randomNumber];
}
});

userSchema.methods.correctPassword = async function (
passwordDB,
typedPassword
) {
return await bcrypt.compare(typedPassword, passwordDB);
};

userSchema.methods.correctPassword=async function(passwordDB,typedPassword)
{
return await bcrypt.compare(typedPassword,passwordDB);
}


const User=mongoose.model('User',userSchema);
module.exports=User;
const User = mongoose.model("User", userSchema);
module.exports = User;
8 changes: 8 additions & 0 deletions backend/node_modules/.package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

14 changes: 14 additions & 0 deletions backend/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 2 additions & 1 deletion backend/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "node server.js"
"start": "nodemon server.js"
},
"author": "Samarth Kadam",
"license": "ISC",
Expand All @@ -17,6 +17,7 @@
"dotenv": "^16.3.1",
"express": "^4.18.2",
"jsonwebtoken": "^9.0.1",
"moment": "^2.30.1",
"mongodb": "4.1",
"mongoose": "^7.6.11",
"multer": "^1.4.5-lts.1",
Expand Down
158 changes: 92 additions & 66 deletions backend/server.js
Original file line number Diff line number Diff line change
@@ -1,89 +1,115 @@
const express = require('express');
const express = require("express");
// const app = express();
const http = require('http');
const mongoose=require('mongoose');
const dotenv=require('dotenv');
const app=require('./app');
dotenv.config({path:'./config.env'});
const DBAuth=process.env.DB.replace('<password>',process.env.DBpassword);

mongoose.connect(DBAuth,{
useUnifiedTopology: true
}).then((con)=>{
const http = require("http");
const mongoose = require("mongoose");
const moment = require("moment");
const User = require("./models/userModel");
const dotenv = require("dotenv");
const app = require("./app");

dotenv.config({ path: "./config.env" });
const DBAuth = process.env.DB.replace("<password>", process.env.DBpassword);

mongoose
.connect(DBAuth, {
useUnifiedTopology: true,
})
.then((con) => {
console.log("DB connection successful");
})

process.on('unhandledRejection',err=>{
console.log(err.name,err.message);
console.log("Unhandled rejection");
})

const port=process.env.PORT;

const server=app.listen(port,()=>{
console.log(`SERVER RUNNING IN PORTNO:${port}`);
})














});

process.on("unhandledRejection", (err) => {
console.log(err.name, err.message);
console.log("Unhandled rejection");
});

const port = process.env.PORT;

const server = app.listen(port, () => {
console.log(`SERVER RUNNING IN PORTNO:${port}`);
});

const io = require('socket.io')(server, {
const io = require("socket.io")(server, {
cors: {
origin: ['https://chat-box-samarthkadam.vercel.app','http://localhost:3000'],
}
origin: [
"https://chat-box-samarthkadam.vercel.app",
"http://localhost:3000",
],
},
});

io.on('connection', (socket) => {
io.on("connection", (socket) => {
socket.on("setup", async (userData) => {
socket.userId = userData._id;
await User.findByIdAndUpdate(socket.userId, {
isOnline: true,
lastOnline: null,
});
socket.join(userData._id);
socket.emit("connected");
io.emit("status update", {
userId: socket.userId,
isOnline: true,
lastOnline: null,
});
});

socket.on("disconnect", async () => {
if (socket.userId) {
const lastOnline = moment().toISOString();
await User.findByIdAndUpdate(socket.userId, {
isOnline: false,
lastOnline,
});
io.emit("status update", {
userId: socket.userId,
isOnline: false,
lastOnline,
});
}
});


socket.on("setup", (userData) => {
console.log("a user connected");
socket.join(userData._id);
socket.emit("connected");
socket.on("logout", async () => {
if (socket.userId) {
const lastOnline = moment().toISOString();
await User.findByIdAndUpdate(socket.userId, {
isOnline: false,
lastOnline,
});
io.emit("status update", {
userId: socket.userId,
isOnline: false,
lastOnline,
});
socket.userId = null;
socket.emit("server processed logout..!");
}
});

socket.on("join chat", (room) => {
socket.join(room);
console.log("User Joined Room: " + room);
});

socket.on("typing",(room)=>{
socket.to(room).emit("typing",room)
})
socket.on("stop typing",(room)=>socket.to(room).emit("stop typing",room));


socket.on("removechatbar-send",(chatId)=>{

console.log('remove chat bar for this id',chatId);
socket.to(chatId).emit("removechatbar-recieve",chatId)
})

socket.on("new message",(newMessageRecieved)=>{
var chat=newMessageRecieved.chat;
socket.on("typing", (room) => {
socket.to(room).emit("typing", room);
});
socket.on("stop typing", (room) => socket.to(room).emit("stop typing", room));

if(!chat.users)return chat.users("users not defined");
socket.on("removechatbar-send", (chatId) => {
console.log("remove chat bar for this id", chatId);
socket.to(chatId).emit("removechatbar-recieve", chatId);
});

chat.users.forEach((user)=>{
if(user._id===newMessageRecieved.sender._id)return;
socket.on("new message", (newMessageRecieved) => {
var chat = newMessageRecieved.chat;

socket.in(user._id).emit('message recieved',newMessageRecieved);
})
})
if (!chat.users) return chat.users("users not defined");

chat.users.forEach((user) => {
if (user._id === newMessageRecieved.sender._id) return;

socket.in(user._id).emit("message recieved", newMessageRecieved);
});
});
});
Loading