This commit is contained in:
SathishKannaa-HexrFactory
2025-01-22 16:59:14 +05:30
commit a28398259c
42 changed files with 2313 additions and 0 deletions

35
src/api-server/Dockerfile Normal file
View File

@@ -0,0 +1,35 @@
ARG NODE_VERSION=lts
FROM node:${NODE_VERSION}-alpine AS development
# Use production node environment by default.
ENV NODE_ENV development
WORKDIR /usr/src/app
RUN npm install -g npm
COPY package.json /usr/src/app/package.json
# COPY package-lock.json /usr/src/app/package-lock.json
RUN npm install
# Run the application as a non-root user.
USER root
# Copy the rest of the source files into the image.
COPY . .
# Expose the port that the application listens on.
EXPOSE 3503
# Run the application.
CMD ["npm", "run", "start:api"]

View File

@@ -0,0 +1,11 @@
import express from 'express';
import { camera } from '../controller/camera/camera-Controlle';
const router = express.Router();
router.post('/setCamera',camera.createCamera)
router.get('/getCamera/:organization/:userId',camera.getCamera)
router.get('/activeCameras/:organization',camera.onlineActiveDatas)
export default router;

View File

@@ -0,0 +1,9 @@
import express from 'express';
import { environment } from '../controller/environments/environments-controller';
const router = express.Router();
router.post('/setEvironments',environment.setEnvironment)
router.get('/findEnvironments/:organization/:userId',environment.getEnvironment)
export default router;

View File

@@ -0,0 +1,10 @@
import express from 'express';
import { floorItems } from '../controller/assets/flooritem-Controller';
const router = express.Router();
router.post('/setfloorItems',floorItems.setFloorItems)
router.get('/findfloorItems/:organization',floorItems.getFloorItems)
router.delete('/deletefloorItem',floorItems.deleteFloorItems)
export default router;

View File

@@ -0,0 +1,14 @@
import express from 'express';
import { lines } from '../controller/lines/line-Controller';
const router = express.Router();
router.post('/setLine',lines.setLines)
router.post('/updatePoint',lines.updateLines)
router.get('/findLines/:organization',lines.getLines)
router.delete('/deleteLine',lines.deleteLineItems)
router.delete('/deletePoint',lines.deleteLinPoiteItems)
router.post('/deleteLayer',lines.deleteLayer)
export default router;

View File

@@ -0,0 +1,11 @@
import express from 'express';
import { share } from '../controller/share/share-Controller';
const router = express.Router();
router.post('/shareUser',share.shareUser)
router.get('/findshareUsers',share.findshareUser)
export default router;

View File

@@ -0,0 +1,10 @@
import express from 'express';
import { user } from '../controller/user-Controller';
const router = express.Router();
router.post('/signup',user.signup)
router.post('/login',user.login)
export default router;

View File

@@ -0,0 +1,11 @@
import express from 'express';
import { wallItems } from '../controller/assets/wallitem-Controller';
const router = express.Router();
router.post('/setWallItems',wallItems.setWallItems)
router.get('/findWallItems/:organization',wallItems.getWallItems)
router.delete('/deleteWallItem',wallItems.deleteWallItems)
export default router;

31
src/api-server/app.ts Normal file
View File

@@ -0,0 +1,31 @@
import express from 'express';
import cors from 'cors';
import connectDB from '../shared/connect/mongoose';
import dotenv from 'dotenv';
import cameraRoutes from './Routes/camera-Routes'
import environmentsRoutes from './Routes/environments-Routes'
import linesRoutes from './Routes/lines-Routes'
import flooritemRoutes from './Routes/flooritem-Routes'
import WallitemRoutes from './Routes/wallItems-Routes'
import userRoutes from './Routes/user-Routes'
import shareRoutes from './Routes/share-Routes'
const app = express();
app.use(cors());
app.use(express.json());
dotenv.config();
app.get('/', (req, res) => {
res.send('Hello, I am Major-Dwinzo API!');
});
// connectDB();
app.get('/health',(req,res)=>{
res.status(200).json({ message: 'Server is running' });
})
app.use('/api/v1', cameraRoutes);
app.use('/api/v1', environmentsRoutes);
app.use('/api/v1', linesRoutes);
app.use('/api/v1', flooritemRoutes);
app.use('/api/v1', WallitemRoutes);
app.use('/api/v1', userRoutes);
app.use('/api/v1', shareRoutes);
export default app;

View File

@@ -0,0 +1,68 @@
import { Request, Response } from "express";
import floorItemsModel from "../../../shared/model/assets/flooritems-Model";
export class floorItems {
static async setFloorItems(req: Request, res: Response) {
try {
const { modeluuid, modelname, position, modelfileID,rotation,isLocked,isVisible,organization } = req.body
const findvalue = await floorItemsModel(organization).findOne({ modeluuid: modeluuid,modelname:modelname })
if (findvalue) {
const updatevalue = await floorItemsModel(organization).findOneAndUpdate(
{ modeluuid: modeluuid,modelname:modelname }, { position: position, rotation: rotation,isVisible:isVisible,isLocked:isLocked }, { new: true });
res.status(201).json(updatevalue);
} else {
const newValue = await floorItemsModel(organization).create({ modeluuid, modelfileID,modelname, position, rotation,isLocked,isVisible, });
res.status(201).json(newValue);
}
// Send response with the created document
} catch (error) {
console.error('Error creating flooritems:', error);
res.status(500).json({ message: "Failed to create flooritems" });
}
}
static async getFloorItems(req: Request, res: Response) {
try {
const { organization } = req.params;
// console.log('req.params: ', req.params);
const findValue = await floorItemsModel(organization).find()
if (!findValue) {
res.status(200).json("floorItems not found");
} else {
res.status(201).json(findValue);
}
} catch (error) {
console.error('Error get flooritems:', error);
res.status(500).json({ error: "Failed to get flooritems" });
}
}
static async deleteFloorItems(req: Request, res: Response) {
try {
const { modeluuid,modelname,organization } = req.body;
const findValue = await floorItemsModel(organization).findOneAndDelete({modeluuid:modeluuid,modelname:modelname})
if (!findValue) {
res.status(200).json("user not found");
} else {
res.status(201).json(findValue);
}
} catch (error) {
console.error('Error get flooritems:', error);
res.status(500).json({ error: "Failed to get flooritems" });
}
}
}

View File

@@ -0,0 +1,80 @@
import { Request, Response } from "express";
import wallItenmModel from "../../../shared/model/assets/wallitems-Model";
export class wallItems {
static async setWallItems(req: Request, res: Response) {
try {
const { modeluuid, modelname, position, type, csgposition,csgscale,quaternion,scale,organization } = req.body
const findvalue = await wallItenmModel(organization).findOne({ modeluuid: modeluuid})
if (findvalue) {
const updatevalue = await wallItenmModel(organization).findOneAndUpdate(
{ modeluuid: modeluuid },
{
modelname,
position,
type,
csgposition,
csgscale,
quaternion,
scale,
},
{ new: true } // Return the updated document
);
res.status(201).json(updatevalue);
} else {
const newValue = await wallItenmModel(organization).create({ modeluuid,modelname, position, type, csgposition,csgscale,quaternion,scale });
res.status(201).json(newValue);
}
// Send response with the created document
} catch (error) {
console.error('Error creating wallitems:', error);
res.status(500).json({ message: "Failed to create wallitems" });
}
}
static async getWallItems(req: Request, res: Response) {
try {
const { organization } = req.params;
const findValue = await wallItenmModel
(organization).find()
if (!findValue) {
res.status(200).json("wallitems not found");
} else {
res.status(201).json(findValue);
}
} catch (error) {
console.error('Error get wallitems:', error);
res.status(500).json({ error: "Failed to get wallitems" });
}
}
static async deleteWallItems(req: Request, res: Response) {
try {
const { modeluuid,modelname,organization } = req.body;
const findValue = await wallItenmModel
(organization).findOneAndDelete({modeluuid:modeluuid,modelname:modelname})
if (!findValue) {
res.status(200).json("user not found");
} else {
res.status(201).json(findValue);
}
} catch (error) {
console.error('Error get wallitems:', error);
res.status(500).json({ error: "Failed to get wallitems" });
}
}
}

View File

@@ -0,0 +1,89 @@
import { Request, Response } from "express";
import cameraModel from "../../../shared/model/camera/camera-Model";
import userModel from "../../../shared/model/user-Model";
export class camera {
static async createCamera(req: Request, res: Response) {
try {
const { userId, position, target, rotation,organization } = req.body
const findCamera = await cameraModel(organization).findOne({ userId: userId })
if (findCamera) {
const updateCamera = await cameraModel(organization).findOneAndUpdate(
{ userId: userId }, { position: position, target: target,rotation:rotation }, { new: true });
res.status(201).json(updateCamera);
} else {
const newCamera = await cameraModel(organization).create({ userId, position, target,rotation });
res.status(201).json(newCamera);
}
// Send response with the created document
} catch (error) {
console.error('Error creating camera:', error);
res.status(500).json({message:"Failed to create camera"});
}
}
static async getCamera(req: Request, res: Response) {
try {
const { userId, organization } = req.params;
// if (!userId) {
// res.status(201).json("User data is insufficient");
// }
const findCamera = await cameraModel(organization).findOne({ userId: userId })
if (!findCamera) {
res.status(200).json("user not found");
} else {
res.status(201).json(findCamera);
}
} catch (error) {
console.error('Error get camera:', error);
res.status(500).json({ error: "Failed to get camera" });
}
}
static async onlineActiveDatas(req: Request, res: Response) {
const {organization } = req.params;
try {
const findactiveUsers = await userModel(organization).find({activeStatus:"online"})
const cameraDataPromises = findactiveUsers.map(async (activeUser) => {
const cameraData = await cameraModel(organization)
.findOne({ userId: activeUser._id })
.select("position target rotation -_id");
if (cameraData) {
return {
position: cameraData.position,
target: cameraData.target,
rotation:cameraData.rotation,
userData: {
_id: activeUser._id,
userName: activeUser.userName,
email: activeUser.email,
activeStatus: activeUser.activeStatus,
},
};
}
// Return null if no camera data is found for the user
return null;
});
const cameraDatas = (await Promise.all(cameraDataPromises)).filter((singledata:any) => singledata !== null);
res.status(200).send({ cameraDatas });
} catch (error:any) {
res.status(500).send(error);
}
}
}

View File

@@ -0,0 +1,50 @@
import { Request, Response } from "express";
import environmentModel from "../../../shared/model/environments/environments-Model";
export class environment {
static async setEnvironment(req: Request, res: Response) {
try {
const { userId,roofVisibility,wallVisibility, organization } = req.body
const findvalue = await environmentModel(organization).findOne({ userId: userId })
if (findvalue) {
const updatevalue = await environmentModel(organization).findOneAndUpdate(
{ userId: userId }, { roofVisibility:roofVisibility,wallVisibility:wallVisibility }, { new: true });
res.status(201).json(updatevalue);
} else {
const newValue = await environmentModel(organization).create({ userId, roofVisibility, wallVisibility });
res.status(201).json(newValue);
}
// Send response with the created document
} catch (error) {
console.error('Error creating environments:', error);
res.status(500).json({message:"Failed to create environments"});
}
}
static async getEnvironment(req: Request, res: Response) {
try {
const { userId, organization } = req.params;
const findValue = await environmentModel(organization).findOne({ userId: userId })
if (!findValue) {
res.status(200).json("user not found");
} else {
res.status(201).json(findValue);
}
} catch (error) {
console.error('Error get environments:', error);
res.status(500).json({ error: "Failed to get environments" });
}
}
}

View File

@@ -0,0 +1,125 @@
import { Request, Response } from "express";
import lineModel from "../../../shared/model/lines/lines-Model";
export class lines {
static async setLines(req: Request, res: Response) {
try {
const {organization,layer,line,type}=req.body
const newLine = await lineModel(organization).create({ layer,line,type });
res.status(201).json(newLine);
// Send response with the created document
} catch (error) {
console.error('Error creating Lines:', error);
res.status(500).json({message:"Failed to create Lines"});
}
}
static async updateLines(req: Request, res: Response) {
try {
const {organization,uuid,position,}=req.body
// const findLine = await lineModel(organization).find({ 'line.uuid': uuid });
// Update the position of the line matching the uuid
const updateResult = await lineModel(organization).updateMany(
{ 'line.uuid': uuid }, // Filter: Find the line with the given uuid
{ $set: { 'line.$.position': position } } // Update the position and type
);
res.status(201).json(updateResult);
// Send response with the created document
} catch (error) {
console.error('Error creating Lines:', error);
res.status(500).json({message:"Failed to create Lines"});
}
}
static async getLines(req: Request, res: Response) {
try {
const { organization } = req.params;
const findValue = await lineModel(organization).find()
if (!findValue) {
res.status(200).json("user not found");
} else {
res.status(201).json(findValue);
}
} catch (error) {
console.error('Error get Lines:', error);
res.status(500).json({ error: "Failed to get Lines" });
}
}
static async deleteLineItems(req: Request, res: Response) {
try {
const {organization,layer,line,type}=req.body
const inputUuids = line.map((item: any) => item.uuid);
// const findValue = await lineModel(organization).findOneAndDelete({
// line: { $elemMatch: { uuid: { $in: inputUuids } } },
// });
const findValue = await lineModel(organization).findOneAndDelete({
"line.uuid": { $all: inputUuids } // Ensure all UUIDs are present in the `line` key
});
if (!findValue) {
res.status(200).json("data not found");
} else {
res.status(201).json(findValue);
}
} catch (error) {
console.error('Error delete Lines:', error);
res.status(500).json({ error: "Failed to delete Lines" });
}
}
static async deleteLinPoiteItems(req: Request, res: Response) {
try {
const {organization,layer,uuid,type}=req.body
const findValue = await lineModel(organization).deleteMany({ 'line.uuid': uuid })
if (!findValue) {
res.status(200).json("data not found");
} else {
res.status(201).json(findValue);
}
} catch (error) {
console.error('Error delete Lines:', error);
res.status(500).json({ error: "Failed to delete Lines" });
}
}
static async deleteLayer(req: Request, res: Response) {
try {
const {organization,layer}=req.body
// Fetch the documents with the specified layer value
const findValue = await lineModel(organization).find({ layer: layer });
if (!findValue) {
res.status(200).json("data not found");
} else {
await lineModel(organization).deleteMany({ layer: layer });
// console.log(`Documents with layer ${layer} have been deleted.`);
// Update documents with layer greater than -1
const updateResult = await lineModel(organization).updateMany(
{ layer: { $gt:layer} },
{ $inc: { layer: -1 } } // Example operation: decrementing layer by 1
);
res.status(201).json(updateResult);
}
} catch (error) {
console.error('Error delete Lines:', error);
res.status(500).json({ error: "Failed to delete Lines" });
}
}
}

View File

@@ -0,0 +1,43 @@
import { Request, Response } from "express";
import userModel from "../../../shared/model/user-Model";
export class share {
static async shareUser(req: Request, res: Response) {
try {
const { email, isShare, organization } = req.body
const findValue = await userModel(organization).findOneAndUpdate({email:email},{isShare:isShare},{new:true})
res.status(201).json({message:"scene shared successfully",data:findValue});
if (!findValue) {
res.status(404).json({message:"Not found"})
}
// Send response with the created document
} catch (error) {
console.error('Error creating Share:', error);
res.status(500).json({message:"Failed to create Share"});
}
}
static async findshareUser(req: Request, res: Response) {
try {
const organization = req.query.organization as string;
const findValue = await userModel(organization).find({}).select("isShare email userName -_id")
// console.log('findValue: ', findValue);
res.status(201).json({message:"scene shared datas",data:findValue});
if (!findValue) {
res.status(404).json({message:"Not found"})
}
// Send response with the created document
} catch (error) {
console.error('Error Share:', error);
res.status(500).json({message:"Failed to Share datas "});
}
}
}

View File

@@ -0,0 +1,103 @@
import { Request, Response } from "express";
import { Server } from 'http';
import userModel from "../../shared/model/user-Model";
import { isSharedArrayBuffer } from "util/types";
const {hashGenerate,hashValidator} = require("../../shared/security/Hasing.ts")
// import {hashGenerate} from '../security/Hasing'
let serverAlive = true;
export class user {
static async signup(req: Request, res: Response) {
try {
let role;
const { userName, email, password,organization,profilePicture } = req.body;
const caseChange = email.toLowerCase();
const emailcheck = await userModel(organization).findOne({ email: caseChange });
if (emailcheck!==null) {
res.json({
message:"User already exists"
});
} else {
const hashpassword=await hashGenerate(password)
const userCount = await userModel(organization).countDocuments({});
role = userCount === 0 ? "Admin" : "User";
const isShare = role === "Admin" ? "true" : "false";
const newuser = await userModel(organization).create({
userName: userName,
email: caseChange,
isShare:isShare,
password: hashpassword,
role:role,
profilePicture:profilePicture
});
newuser.save();
res.status(200).json({
message:"New User created"
});
}
} catch (error:any) {
res.status(500).send(error);
}
}
static async login(req: Request, res: Response) {
try {
let role;
const { email, password,organization } = req.body;
// console.log(' req.body: ', req.body);
const existingMail = await userModel(organization).findOne({
email:email
});
if (existingMail === null || !existingMail) {
res.status(404).json({ message: "User Not Found!!! Kindly signup..." });
} else {
const hashedpassword= existingMail.password
const checkpassword = await hashValidator(
password,
hashedpassword
)
// console.log('checkpassword: ', checkpassword);
if (checkpassword) {
// const tokenValidation=await tokenGenerator(existingMail.email)
res.status(200).send({
message: "login successfull",
email: existingMail.email,
name: existingMail.userName,
userId: existingMail._id,
isShare:existingMail.isShare,
// token:tokenValidation
});
} else {
res.status(404).json({message:"email & password is invalid...Check the credentials"})
}
}
} catch (error:any) {
res.status(500).send(error);
}
}
// static async checkserverHealth(server:Server,organization: string){
// try {
// if (server.listening) {
// console.log('Server is running');
// serverAlive = true;
// // Update all users to online status
// } else {
// // await userModel(organization).updateMany({}, { activeStatus: "offline" }); // Replace `activeStatus` with your actual field
// throw new Error('Server is not running');
// }
// } catch (error:any) {
// console.error('Server health check failed:', error.message);
// serverAlive = false;
// // Update all users to offline status
// // await userModel(organization).updateMany({}, { activeStatus: "offline" });
// }
// }
}
// export const startHealthCheck = (server: Server, organization: string) => {
// setInterval(() => user.checkserverHealth(server, organization), 5000);
// };

19
src/api-server/main.ts Normal file
View File

@@ -0,0 +1,19 @@
import app from './app';
import http from 'http';
// import { startHealthCheck } from './controller/user-Controller';
const server = http.createServer(app);
const organization = process.env.ORGANIZATION_NAME || 'defaultOrganization'; // Replace with your logic
if (!organization) {
throw new Error('ORGANIZATION_NAME is not defined in the environment');
}
const PORT = process.env.API_PORT
server.listen(PORT, () => {
console.log(`API-Server running on port ${PORT}`);
// startHealthCheck(server, organization);
});

View File

@@ -0,0 +1,47 @@
import mongoose, { Schema, Connection, Model } from "mongoose";
interface ConnectionCache {
[key: string]: Connection;
}
const connections: ConnectionCache = {};
const MainModel = <T>(
db: string,
modelName: string,
schema: Schema<T>,
collectionName: string
): Model<T> => {
const db1_url = `${process.env.MONGO_URI}${db}`;
// Check if the connection already exists
if (connections[db]) {
return connections[db].model<T>(modelName, schema, collectionName);
}
try {
const db1 = mongoose.createConnection(db1_url, {
maxPoolSize: 50,
});
// Cache the connection
connections[db] = db1;
// Log connection success or handle errors
db1.on("connected", () => {
console.log(`Connected to MongoDB database: ${db}`);
});
db1.on("error", (err) => {
console.error(`MongoDB connection error for database ${db}:`, err.message);
});
return db1.model<T>(modelName, schema, collectionName);
} catch (error) {
console.error("Database connection error:", (error as Error).message);
throw error;
}
};
export default MainModel;

View File

@@ -0,0 +1,57 @@
import mongoose, { Document, Schema } from 'mongoose';
import MainModel from '../../connect/mongoose';
// Interface for TypeScript with PascalCase
export interface floorItenms extends Document {
modeluuid: string;
modelfileID: string;
modelname: string
isLocked:boolean
isVisible:boolean
position: []
rotation: {
x: number;
y: number;
z: number;
};
}
// Define the Mongoose Schema
const floorItemsSchema: Schema = new Schema({
modeluuid: { type: String },
modelfileID: { type: String },
modelname: { type: String },
position: { type: Array},
isLocked:{type:Boolean},
isVisible:{type:Boolean},
rotation: {
x: { type: Number, required: true },
y: { type: Number, required: true },
z: { type: Number, required: true }
}
});
// Model for MongoDB collection
// const cameraModel = model<Camera>("Camera", cameraSchema);
// export default cameraModel;
// const floorItemsModel = (db: string) => {
// const mongoUrl = process.env.MONGO_URI || '';
// if (!mongoUrl) {
// throw new Error('MONGO_URI environment variable is not set');
// }
// // Connect to the database
// const dbConnection = mongoose.createConnection(mongoUrl, {
// dbName: db, // Specify the database name here
// serverSelectionTimeoutMS: 30000,
// });
// return dbConnection.model<floorItenms>('floorItenms', floorItenmsSchema,`floorItenms`);
// }
// export default floorItemsModel;
const floorItemsModel = (db:string) => {
return MainModel(db, "floorItems", floorItemsSchema, "floorItems")
};
export default floorItemsModel;

View File

@@ -0,0 +1,46 @@
import mongoose, { Document, Schema } from 'mongoose';
import MainModel from '../../connect/mongoose';
// Interface for TypeScript with PascalCase
export interface wallitems extends Document {
modeluuid: string;
modelname: string
type: string
csgposition: []
csgscale: []
position: []
quaternion: []
scale: []
}
// Define the Mongoose Schema
const wallItemsSchema: Schema = new Schema({
modeluuid: { type: String,unique:true },
modelname: { type: String},
type: { type: String },
csgposition: { type: Array},
csgscale: { type: Array,},
position: { type: Array },
quaternion: { type: Array},
scale: { type: Array}
});
// const wallItenmModel = (db: string) => {
// const mongoUrl = process.env.MONGO_URI || '';
// if (!mongoUrl) {
// throw new Error('MONGO_URI environment variable is not set');
// }
// // Connect to the database
// const dbConnection = mongoose.createConnection(mongoUrl, {
// dbName: db, // Specify the database name here
// serverSelectionTimeoutMS: 30000,
// });
// return dbConnection.model<wallitenms>('wallitenms', wallItenmsSchema, `wallitenms`);
// }
// export default wallItenmModel;
const wallItenmModel = (db:string) => {
return MainModel(db, "wallitems", wallItemsSchema, "wallitems")
};
export default wallItenmModel;

View File

@@ -0,0 +1,87 @@
import mongoose, { Document, Schema } from 'mongoose';
import MainModel from '../../connect/mongoose';
// Interface for TypeScript with PascalCase
export interface Camera extends Document {
userId: string;
position: {
x: number;
y: number;
z: number;
}
target: {
x: { type: Number, required: true },
y: { type: Number, required: true },
z: { type: Number, required: true }
}
rotation: {
x: { type: Number, required: true },
y: { type: Number, required: true },
z: { type: Number, required: true }
}
}
// Define the Mongoose Schema
const cameraSchema: Schema = new Schema({
userId: { type: String, unique: true },
position: {
x: { type: Number, required: true },
y: { type: Number, required: true },
z: { type: Number, required: true }
},
target: {
x: { type: Number, required: true },
y: { type: Number, required: true },
z: { type: Number, required: true }
},
rotation: {
x: { type: Number, required: true },
y: { type: Number, required: true },
z: { type: Number, required: true }
}
});
// Model for MongoDB collection
// const cameraModel = model<Camera>("Camera", cameraSchema);
// export default cameraModel;
// const cameraModel = (db: string) => {
// const mongoUrl = process.env.MONGO_URI || '';
// if (!mongoUrl) {
// throw new Error('MONGO_URI environment variable is not set');
// }
// // Connect to the database
// const dbConnection = mongoose.createConnection(mongoUrl, {
// dbName: db, // Specify the database name here
// serverSelectionTimeoutMS: 30000,
// });
// return dbConnection.model<Camera>('Camera', cameraSchema,`Camera`);
// }
// export default cameraModel;
// const cameraModel = (db: string) => {
// const mongoUrl = process.env.MONGO_URI || '';
// if (!mongoUrl) {
// throw new Error('MONGO_URI environment variable is not set');
// }
// const dbConnection = mongoose.createConnection(mongoUrl, {
// dbName: db,
// serverSelectionTimeoutMS: 60000, // Increased timeout
// });
// dbConnection.on('error', (err) => {
// console.error(`MongoDB connection error for database ${db}:`, err);
// });
// dbConnection.once('open', () => {
// console.log(`Connected to MongoDB database: ${db}`);
// });
// return dbConnection.model<Camera>('Camera', cameraSchema, 'Camera');
// };
// export default cameraModel
const cameraModel = (db:string) => {
return MainModel(db, "Camera", cameraSchema, "Camera")
};
export default cameraModel;

View File

@@ -0,0 +1,38 @@
import mongoose, { Document, Schema } from 'mongoose';
import MainModel from '../../connect/mongoose';
// Interface for TypeScript with PascalCase
export interface environment extends Document {
userId: string;
roofVisibility:boolean
wallVisibility:boolean
}
// Define the Mongoose Schema
const environmentSchema: Schema = new Schema({
userId: { type: String, unique: true },
roofVisibility: { type: Boolean ,default:false},
wallVisibility: { type: Boolean ,default:false},
});
// Model for MongoDB collection
// const cameraModel = model<Camera>("Camera", cameraSchema);
// export default cameraModel;
// const environmentModel = (db: string) => {
// const mongoUrl = process.env.MONGO_URI || '';
// if (!mongoUrl) {
// throw new Error('MONGO_URI environment variable is not set');
// }
// // Connect to the database
// const dbConnection = mongoose.createConnection(mongoUrl, {
// dbName: db, // Specify the database name here
// serverSelectionTimeoutMS: 30000,
// });
// return dbConnection.model<environment>('environments', environmentSchema,`environments`);
// }
// export default environmentModel;
const environmentModel = (db:string) => {
return MainModel(db, "environments", environmentSchema, "environments")
};
export default environmentModel;

View File

@@ -0,0 +1,43 @@
import mongoose, { Document, Schema } from "mongoose";
import MainModel from "../../connect/mongoose";
const positionSchema = new mongoose.Schema({
x: { type: Number, }, // Optional position fields
y: { type: Number, },
z: { type: Number},
});
// Define a schema for the individual line
const Vector3 = new mongoose.Schema({
position: { type: positionSchema, required: false }, // Optional position
uuid: { type: String, required: false }, // Optional uuid
});
// Define the main schema
const LineSchema = new mongoose.Schema({
layer: { type: Number, required: true }, // Layer is mandatory
line: { type: [Vector3], required: true }, // Array of line objects
type: { type: String, required: false }, // Optional type
});
// Database connection and model creation
// const lineModel = (db: string) => {
// const mongoUrl = process.env.MONGO_URI || "";
// if (!mongoUrl) {
// throw new Error("MONGO_URI environment variable is not set");
// }
// // Connect to the database
// const dbConnection = mongoose.createConnection(mongoUrl, {
// dbName: db, // Specify the database name here
// serverSelectionTimeoutMS: 30000,
// });
// // Return the model
// return dbConnection.model("lines", LineSchema, "lines");
// };
// export default lineModel;
const lineModel = (db:string) => {
return MainModel(db, "lines", LineSchema, "lines")
};
export default lineModel;

View File

@@ -0,0 +1,69 @@
import mongoose, { Document, Schema } from "mongoose";
import MainModel from "../connect/mongoose";
export interface User extends Document {
userName: String;
email: String;
password: String;
role: String;
profilePicture: String;
isShare:Boolean,
activeStatus:string
}
const signupschema: Schema = new Schema({
userName: {
type: String,
required: true,
},
email: {
type: String,
unique: true,
required: true,
},
password: {
type: String,
min: 8,
required: true,
},
role: {
type: String,
default: "User",
enum: ["User", "Admin", "Project Manager", "Manager", "Owner"],
},
profilePicture: {
type: String,
// default: "default-profile-picture.jpg"
},
isShare:{
type:Boolean,
default:false
},
activeStatus:{
type:String,
enum: ["online", "offline"],
default: "offline"
}
});
// const userModel = (db: string) => {
// const mongoUrl = process.env.MONGO_URI || "";
// if (!mongoUrl) {
// throw new Error("MONGO_URI environment variable is not set");
// }
// // Connect to the database
// const dbConnection = mongoose.createConnection(mongoUrl, {
// dbName: db, // Specify the database name here
// serverSelectionTimeoutMS: 30000,
// });
// // Return the model
// return dbConnection.model("Users", signupschema, "Users");
// };
// export default userModel;
const userModel = (db:string) => {
return MainModel(db, "Users", signupschema, "Users")
};
export default userModel;

View File

@@ -0,0 +1,24 @@
const bcrypt = require("bcryptjs");
const saltRounds = 10;
const hashGenerate = async (Password:String) => {
try {
const salt = await bcrypt.genSalt(saltRounds);
const hash = await bcrypt.hash(Password, salt);
return hash;
} catch (error) {
return error;
}
};
const hashValidator = async (password:String, hashedPassword:String) => {
try {
const result = await bcrypt.compare(password, hashedPassword);
return result;
} catch (error) {
return false;
}
};
module.exports.hashGenerate = hashGenerate;
module.exports.hashValidator = hashValidator;

View File

@@ -0,0 +1,38 @@
import { Request, Response, NextFunction } from 'express';
import * as Jwt from 'jsonwebtoken'; // Correct way to import jsonwebtoken
// Define a new interface extending Request
interface AuthenticatedRequest extends Request {
user?: {
email: string;
// Add more fields as needed based on your JWT payload
};
}
const tokenGenerator = (email: string) => {
const token = Jwt.sign({ email: email }, "Milestone", {
expiresIn: "3hours",
});
return token;
};
const tokenValidator = (req: AuthenticatedRequest, res: Response, next: NextFunction): void => {
const token: string | undefined = req.headers.token as string | undefined;
if (!token) {
res.status(403).json({
msg: "No token present",
});
return; // Make sure to return after sending a response
}
try {
const decoded = Jwt.verify(token,"Milestone") as { email: string }; // adjust if your JWT payload has more fields
req.user = decoded;
next();
} catch (err) {
res.status(401).json({
msg: "Invalid Token",
});
}
};
export { tokenValidator,tokenGenerator };

View File

@@ -0,0 +1,35 @@
ARG NODE_VERSION=lts
FROM node:${NODE_VERSION}-alpine AS development
# Use production node environment by default.
ENV NODE_ENV development
WORKDIR /usr/src/app
RUN npm install -g npm
COPY package.json /usr/src/app/package.json
# COPY package-lock.json /usr/src/app/package-lock.json
RUN npm install
# Run the application as a non-root user.
USER root
# Copy the rest of the source files into the image.
COPY . .
# Expose the port that the application listens on.
EXPOSE 1059
# Run the application.
CMD ["npm", "run", "start:socket"]

View File

@@ -0,0 +1,22 @@
import express from "express"
import { Response, Request } from "express";
import http from "http";
import dotenv from "dotenv"; // Import dotenv
dotenv.config();
import { initSocketServer } from "./socket/socketManager";
const app = express();
const PORT = process.env.SOCKET_PORT;
const server = http.createServer(app);
app.get('/', (req: Request, res: Response) => {
res.send('Hello, I am Major-Dwinzo RealTime!');
});
initSocketServer(server);
server.listen(PORT, () => {
console.log(`socket-Server is running on http://localhost:${PORT}`);
});

View File

@@ -0,0 +1,53 @@
import { Request, Response } from "express";
import floorItemsModel from "../../../shared/model/assets/flooritems-Model";
export const setFloorItems = async (data: any) => {
try {
const { modelfileID,modeluuid, modelname, position, rotation,isLocked,isVisible, organization } = data
const findvalue = await floorItemsModel(organization).findOne({ modeluuid: modeluuid, modelname: modelname })
if (findvalue) {
const updatevalue = await floorItemsModel(organization).findOneAndUpdate(
{ modeluuid: modeluuid, modelname: modelname }, { position: position, rotation: rotation ,isVisible:isVisible,isLocked:isLocked}, { new: true });
return { success: true, message: 'flooritems updated', data: updatevalue,organization:organization }
} else {
const newValue = await floorItemsModel(organization).create({ modeluuid, modelname, modelfileID,position, rotation,isLocked,isVisible });
return { success: true, message: 'flooritem created', data: newValue,organization:organization }
}
// Send response with the created document
} catch (error) {
console.error('Error creating flooritems:', error);
return { success: false, message: 'Error creating or updating camera', error }
}
}
export const deleteFloorItems = async (data: any)=>{
try {
const { modeluuid,modelname,organization } = data;
const findValue = await floorItemsModel(organization).findOneAndDelete({modeluuid:modeluuid,modelname:modelname})
if (!findValue) {
return { success: false, message: 'model not found',organization:organization }
} else {
return { success: true, message: 'flooritem deleted', data: findValue,organization:organization }
}
} catch (error) {
console.error('Error get flooritems:', error);
return { success: false, message: 'Failed to delete flooritems', error }
}
}

View File

@@ -0,0 +1,60 @@
import { Request, Response } from "express";
import wallItenmModel from "../../../shared/model/assets/wallitems-Model";
export const setWallItems = async (data: any) => {
try {
const { modeluuid, modelname, position, type, csgposition, csgscale, quaternion, scale, organization } = data
const findvalue = await wallItenmModel(organization).findOne({ modeluuid: modeluuid })
if (findvalue) {
const updatevalue = await wallItenmModel(organization).findOneAndUpdate(
{ modeluuid: modeluuid },
{
modelname,
position,
type,
csgposition,
csgscale,
quaternion,
scale,
},
{ new: true } // Return the updated document
);
return { success: true, message: 'wallIitem updated', data: updatevalue, organization: organization }
} else {
const newValue = await wallItenmModel(organization).create({ modeluuid, modelname, position, type, csgposition, csgscale, quaternion, scale });
return { success: true, message: 'wallIitem created', data: newValue, organization: organization }
}
// Send response with the created document
} catch (error) {
console.error('Error creating wallIitem:', error);
return { success: false, message: 'Error creating or updating camera', error }
}
}
export const deleteWallItems = async (data: any) => {
try {
const { modeluuid, modelname, organization } = data;
const findValue = await wallItenmModel(organization).findOneAndDelete({ modeluuid: modeluuid, modelname: modelname })
if (!findValue) {
return { success: false, message: 'model not found', organization: organization }
} else {
return { success: true, message: 'wallitem deleted', data: findValue, organization: organization }
}
} catch (error) {
console.error('Error get wallitem:', error);
return { success: false, message: 'Failed to delete wallitem', error }
}
}

View File

@@ -0,0 +1,31 @@
import { Request, Response } from "express";
import { Socket } from "socket.io";
import cameraModel from "../../../shared/model/camera/camera-Model";
export const createCamera = async (data: any,) => {
try {
const { userId, position, target, organization,rotation } = data
const findCamera = await cameraModel(organization).findOne({ userId: userId })
if (findCamera) {
const updateCamera = await cameraModel(organization).findOneAndUpdate(
{ userId: userId }, { position: position, target: target,rotation:rotation }, { new: true });
// io.emit('cameraUpdateResponse', { success: true, message: 'Camera updated', data: updateCamera });
return { success: true, message: 'Camera updated', data: updateCamera,organization:organization}
}
else {
const newCamera = await cameraModel(organization).create({ userId, position, target,rotation })
return { success: false, message: 'Camera created' ,data:newCamera,organization:organization}
}
// Send response with the created document
} catch (error) {
console.error('Error creating camera:', error);
return { success: false, message: 'Error creating or updating camera', error, }
}
}

View File

@@ -0,0 +1,33 @@
import { Request, Response } from "express";
import environmentModel from "../../../shared/model/environments/environments-Model";
export const setEnvironment = async (data: any,) => {
try {
const { userId,roofVisibility,wallVisibility,shadowVisibility, organization } = data
const findvalue = await environmentModel(organization).findOne({ userId: userId })
if (findvalue) {
const updatevalue = await environmentModel(organization).findOneAndUpdate(
{ userId: userId }, { roofVisibility:roofVisibility,wallVisibility:wallVisibility,shadowVisibility:shadowVisibility }, { new: true });
// res.status(201).json(updatevalue);
return { success: true, message: 'evironments updated', data: updatevalue,organization:organization }
} else {
const newValue = await environmentModel(organization).create({ userId, roofVisibility, wallVisibility,shadowVisibility });
return { success: true, message: 'evironments created', data: newValue,organization:organization }
// res.status(201).json(newValue);
}
// Send response with the created document
} catch (error) {
console.error('Error creating evironments:', error);
return { success: false, message: 'Error creating or updating evironments', error }
}
}

View File

@@ -0,0 +1,100 @@
import { Request, Response } from "express";
import lineModel from "../../../shared/model/lines/lines-Model";
export const createLineItems = async (data: any)=>{
try {
const {organization,layer,line,type}=data
const newLine = await lineModel(organization).create({ layer,line,type });
return { success: true, message: 'line create', data: newLine,organization:organization }
// Send response with the created document
} catch (error) {
return { success: false, message: 'Error create line', error }
}
}
export const updateLineItems = async (data: any)=>{
try {
const {organization,uuid,position,}=data
// const findLine = await lineModel(organization).find({ 'line.uuid': uuid });
// Update the position of the line matching the uuid
const updateResult = await lineModel(organization).updateMany(
{ 'line.uuid': uuid }, // Filter: Find the line with the given uuid
{ $set: { 'line.$.position': position } } // Update the position and type
);
return { success: true, message: 'line updated', data: {uuid:uuid,position:position},organization:organization }
// Send response with the created document
} catch (error) {
console.error('Error creating Lines:', error);
return { success: false, message: 'Error updating line', error }
}
}
export const deleteLineItems = async (data: any)=>{
try {
const {organization,line}=data
const inputUuids = line.map((item: any) => item.uuid);
// const findValue = await lineModel(organization).findOneAndDelete({
// line: { $elemMatch: { uuid: { $in: inputUuids } } },
// });
const findValue = await lineModel(organization).findOneAndDelete({
"line.uuid": { $all: inputUuids } // Ensure all UUIDs are present in the `line` key
});
if (!findValue) {
return { success: false, message: 'line not found',organization:organization }
} else {
return { success: true, message: 'line deleted', data: findValue,organization:organization }
}
} catch (error) {
console.error('Error delete Lines:', error);
return { success: false, message: 'Failed to delete line', error }
}
}
export const deleteLayer = async (data: any)=>{
try {
const {organization,layer}=data
const findValue = await lineModel(organization).find({ layer: layer });
if (!findValue) {
return { success: false, message: 'layer not found' }
} else {
await lineModel(organization).deleteMany({ layer: layer });
// Update documents with layer greater than -1
const updateResult = await lineModel(organization).updateMany(
{ layer: { $gt:layer} },
{ $inc: { layer: -1 } } // Example operation: decrementing layer by 1
);
return { success: true, message: 'layer deleted', data: layer,organization:organization }
}
} catch (error) {
console.error('Error delete layer:', error);
return { success: false, message: 'Failed to delete layer', error }
}
}
export const deleteLinPoiteItems = async (data: any)=>{
try {
const {organization,uuid}=data
const findValue = await lineModel(organization).deleteMany({ 'line.uuid': uuid })
if (!findValue) {
return { success: false, message: 'line not found',organization:organization }
} else {
return { success: true, message: 'point deleted', data: uuid ,organization:organization}
}
} catch (error) {
console.error('Error delete Lines:', error);
return { success: false, message: 'Failed to delete point', error }
}
}

View File

@@ -0,0 +1,97 @@
import cameraModel from "../../../shared/model/camera/camera-Model"
import userModel from "../../../shared/model/user-Model"
export const activeUsers = async (data: any) => {
try {
if (data && data.email) {
const email = data.email
const organization = email.split("@")[1].split(".")[0]
const findUser = await userModel(organization).findOne({email})
if (findUser) {
const updateActiveStatus = await userModel(organization).findOneAndUpdate({email:findUser.email},{activeStatus:"online"},{new:true})
if (updateActiveStatus) {
const cameraDatas=await cameraModel(organization).findOne({userId:updateActiveStatus._id})
.select("position target rotation -_id");
if (cameraDatas) {
const result = {
position: cameraDatas.position,
target: cameraDatas.target,
rotation: cameraDatas.rotation,
userData: {
_id: updateActiveStatus._id,
userName: updateActiveStatus.userName,
email: updateActiveStatus.email,
},
};
return { success: true, message: 'user connect ', data: result,organization:organization }
// return result;
}
}
}
}else {
console.error('Invalid data or missing email:', data);
// Handle the error or return a default value
// Example: Return an error response if the email is invalid
return { success: false, message: 'Email is missing or invalid', }
// return res.status(400).send({ message: 'Email is missing or invalid' });
}
// // return [];
} catch (error) {
return { success: false, message:error}
}
}
export const activeUserOffline = async (data: any) => {
try {
const email = data.email
const organization = email.split("@")[1].split(".")[0]
const findUsers = await userModel(organization).findOne({email})
// console.log('findUsers: ', findUsers);
if (findUsers) {
const updateActiveStatus = await userModel(organization).findOneAndUpdate({email:email},{activeStatus:"offline"},{new:true})
// console.log('updateActiveStatus: ',updateActiveStatus);
if (updateActiveStatus) {
const cameraDatas=await cameraModel(organization).findOne({userId:updateActiveStatus._id})
.select("position target rotation -_id");
// console.log('cameraDatas: ', cameraDatas);
if (cameraDatas) {
const result = {
position: cameraDatas.position,
target: cameraDatas.target,
rotation: cameraDatas.rotation,
userData: {
_id: updateActiveStatus._id,
userName: updateActiveStatus.userName,
email: updateActiveStatus.email,
},
};
// console.log("Formatted Result:", result);
// return result;
return { success: true, message: 'user disconnect', data: result,organization:organization }
}
}
}
// // return [];
} catch (error) {
return { success: false, message: error}
}
}

View File

@@ -0,0 +1,45 @@
export const EVENTS = {
connection: "connection",
disconnect:"disconnect",
//userActiveStatus
userConnect:"userConnectRespones",
userDisConnect:"userDisConnectRespones",
// Room management events
joinRoom: 'joinRoom',
createroom: "createRoom", // When a client joins a room
leaveRoom: 'leaveRoom', // When a client leaves a room
roomCreated: 'roomCreated', // When a new room is created
roomDeleted: 'roomDeleted', // When a room is deleted
// Camera //response
setCamera: 'v1:Camera:set',
cameraCreateResponse: "cameraCreateResponse", // Response for camera creation
cameraUpdateResponse: "cameraUpdateResponse", // Response for camera update
cameraError: "cameraError",
//Environment
setenvironment: "v1:Environment:set",
EnvironmentUpdateResponse: "EnvironmentUpdateResponse",
//FloorItems
setFloorItems: "v1:FloorItems:set",
FloorItemsUpdateResponse: "FloorItemsUpdateResponse",
deleteFloorItems: "v1:FloorItems:delete",
FloorItemsDeleteResponse: "FloorItemsDeleteResponse",
floorItemError: "floorItemError",
//WALLItems
setWallItems: "v1:wallItems:set",
wallItemsUpdateResponse: "wallItemsUpdateResponse",
deleteWallItems: "v1:wallItems:delete",
wallItemsDeleteResponse: "wallItemsDeleteResponse",
wallItemError: "wallItemError",
//Lines
createLine:"v1:Line:create",
createLineResponse:"Line:response:create",
updateLine:"v1:Line:update",
updateLineResponse:"Line:response:update",
deleteLine:"v1:Line:delete",
deleteLineResponse:"Line:response:delete",
deletePoint:"v1:Line:delete:point",
deletePointResponse:"Line:response:delete:point",
deleteLineLayer:"v1:Line:delete:layer",
deleteLineLayerResponse:"Line:response:delete:layer",
}

View File

@@ -0,0 +1,421 @@
import { Server, Socket } from 'socket.io';
import { EVENTS } from './events';
import { createCamera } from '../services/camera/camera-Controller';
import { setEnvironment } from '../services/environments/environments-controller';
import { deleteFloorItems, setFloorItems } from '../services/assets/flooritem-Controller';
import { deleteWallItems, setWallItems } from '../services/assets/wallitem-Controller';
import { deleteLineItems, deleteLinPoiteItems, updateLineItems ,createLineItems, deleteLayer} from '../services/lines/line-Controller';
import { activeUserOffline, activeUsers } from '../services/users/user-controller';
const cameraHandleEvent =async (event: string, socket: Socket, data: any,io:any) => {
switch (event) {
case EVENTS.setCamera:
const result = await createCamera(data,);
// console.log('result: ', result);
if (result.success) {
// console.log('result.success: ', result.success);
// if (result.message === 'Camera updated') {
// Emit update response
io.emit(EVENTS.cameraUpdateResponse, {
success: true,
message: result.message,
data: result.data,
socketId: socket.id,
organization:result.organization
});
} else if (result.message === 'Camera created') {
// Emit create response
io.emit(EVENTS.cameraCreateResponse, {
success: true,
message: result.message,
data: result.data,
socketId: socket.id,
organization:result.organization
});
// }
} else {
// Emit error response
socket.emit(EVENTS.cameraError, {
success: false,
message: result.message,
error: result.error,
socketId: socket.id,
organization:result.organization
});
}
break;
// case EVENTS.updataControlle_iot:
// updateControlle(data);
break;
// case EVENTS.deleteControlle_iot:
// deleteControlle(data);
break;
default:
// console.error(`Unhandled event type: ${event}`);
}
}
const EnvironmentHandleEvent =async (event: string, socket: Socket, data: any,io:any) => {
switch (event) {
case EVENTS.setenvironment:
const result = await setEnvironment(data,);
// console.log('result: ', result);
if (result.success) {
// if (result.message === 'Camera updated') {
// Emit update response
io.emit(EVENTS.EnvironmentUpdateResponse, {
success: true,
message: result.message,
data: result.data,
socketId: socket.id,
organization:result.organization
});
// } else if (result.message === 'evironments created') {
// // Emit create response
// io.emit(EVENTS.cameraCreateResponse, {
// success: true,
// message: result.message,
// data: result.data,
// });
// }
} else {
// Emit error response
socket.emit(EVENTS.cameraError, {
success: false,
message: result.message,
error: result.error,
socketId: socket.id,
organization:result.organization
});
}
break;
// case EVENTS.updataControlle_iot:
// updateControlle(data);
break;
// case EVENTS.deleteControlle_iot:
// deleteControlle(data);
break;
default:
// console.error(`Unhandled event type: ${event}`);
}
}
const floorItemsHandleEvent =async (event: string, socket: Socket, data: any,io:any) => {
switch (event) {
case EVENTS.setFloorItems:{
const result = await setFloorItems(data);
// console.log('result: ', result);
if (result.success) {
io.emit(EVENTS.FloorItemsUpdateResponse, {
success: true || false,
message: result.message,
data: result.data,
socketId: socket.id,
organization:result.organization
});
} else {
// Emit error response
socket.emit(EVENTS.floorItemError, {
success: false,
message: result.message,
error: result.error,
socketId: socket.id,
organization:result.organization
});
}
break;}
case EVENTS.deleteFloorItems:{
const result = await deleteFloorItems(data);
// console.log('result: ', result);
if (result.success) {
io.emit(EVENTS.FloorItemsDeleteResponse, {
success: true || false,
message: result.message,
data: result.data,
socketId: socket.id,
organization:result.organization
});
} else {
// Emit error response
socket.emit(EVENTS.floorItemError, {
success: false,
message: result.message,
error: result.error,
socketId: socket.id,
organization:result.organization
});
}
break;}
default:
// console.error(`Unhandled event type: ${event}`);
}
}
const wallItemsHandleEvent =async (event: string, socket: Socket, data: any,io:any) => {
switch (event) {
case EVENTS.setWallItems:{
const result = await setWallItems(data);
// console.log('result: ', result);
if (result.success) {
io.emit(EVENTS.wallItemsUpdateResponse, {
success: true,
message: result.message,
data: result.data,
socketId: socket.id,
organization:result.organization
});
} else {
// Emit error response
socket.emit(EVENTS.wallItemError, {
success: false,
message: result.message,
error: result.error,
});
}
break;
}
case EVENTS.deleteWallItems:{
const result = await deleteWallItems(data);
// console.log('result: ', result);
if (result.success) {
io.emit(EVENTS.wallItemsDeleteResponse, {
success: true || false,
message: result.message,
data: result.data,
socketId: socket.id,
organization:result.organization
});
} else {
// Emit error response
socket.emit(EVENTS.wallItemError, {
success: false,
message: result.message,
error: result.error,
});
}
break;
}
default:
// console.error(`Unhandled event type: ${event}`);
}
}
const lineHandleEvent =async (event: string, socket: Socket, data: any,io:any) => {
switch (event) {
case EVENTS.createLine:{
const result = await createLineItems(data);
// console.log('result: ', result);
if (result.success) {
io.emit(EVENTS.createLineResponse, {
success: true || false,
message: result.message,
data: result.data,
socketId: socket.id,
organization:result.organization
});
} else {
// Emit error response
// socket.emit(EVENTS.wallItemError, {
// success: false,
// message: result.message,
// error: result.error,
// });
}
break;
}
case EVENTS.updateLine: {
const result = await updateLineItems(data);
// console.log('result: ', result);
if (result.success) {
io.emit(EVENTS.updateLineResponse, {
success: true || false,
message: result.message,
data: result.data,
socketId: socket.id,
organization: result.organization
});
}
break;
}
case EVENTS.deleteLine:{
const result = await deleteLineItems(data);
// console.log('result: ', result);
if (result.success) {
io.emit(EVENTS.deleteLineResponse, {
success: true || false,
message: result.message,
data: result.data,
socketId: socket.id,
organization:result.organization
});
} else {
// Emit error response
// socket.emit(EVENTS.wallItemError, {
// success: false,
// message: result.message,
// error: result.error,
// });
}
break;
}
case EVENTS.deletePoint:{
const result = await deleteLinPoiteItems(data);
// console.log('result: ', result);
if (result.success) {
io.emit(EVENTS.deletePointResponse, {
success: true || false,
message: result.message,
data: result.data,
socketId: socket.id,
organization:result.organization
});
} else {
// Emit error response
// socket.emit(EVENTS.wallItemError, {
// success: false,
// message: result.message,
// error: result.error,
// });
}
break;
}
case EVENTS.deleteLineLayer:{
const result = await deleteLayer(data);
// console.log('result: ', result);
if (result.success) {
io.emit(EVENTS.deleteLineLayerResponse, {
success: true || false,
message: result.message,
data: result.data,
socketId: socket.id,
organization:result.organization
});
} else {
// Emit error response
// socket.emit(EVENTS.wallItemError, {
// success: false,
// message: result.message,
// error: result.error,
// });
}
break;
}
default:
// console.error(`Unhandled event type: ${event}`);
}
}
const userStatus =async (event: string, socket: Socket, data: any,io:any) => {
switch (event) {
case EVENTS.connection: {
// console.log('EVENTS.connection: ', EVENTS.connection);
// console.log('event: ', event);
const result = await activeUsers(data);
if (result?.success) {
// console.log('result.success: ', result.success)
io.emit(EVENTS.userConnect, {
success: true || false,
message: result.message,
data: result.data,
socketId: socket.id,
organization:result.organization
});}
break;
}
case EVENTS.disconnect: {
// console.log('EVENTS.disconnect: ', EVENTS.connection);
// console.log('event: ', event);
const result = await activeUserOffline(data);
if (result?.success) {
// console.log('result.success: ', result.success)
io.emit(EVENTS.userDisConnect, {
success: true || false,
message: result.message,
data: result.data,
socketId: socket.id,
organization:result.organization
});}
break;
}
}
}
export const initSocketServer = (httpServer: any) => {
const io = new Server(httpServer, {
cors: {
origin: '*', // Allow CORS for all origins (adjust in production)
methods: ['GET', 'POST'],
},
});
// Listen for new connections
io.on(EVENTS.connection, (socket: Socket) => {
// console.log(`New client connected: ${socket.id}`);
// console.log(socket.handshake.auth);
userStatus(EVENTS.connection, socket, socket.handshake.auth,io);
// Handle all incoming events with the handleEvent function
socket.onAny((event: string, data: any,) => {
cameraHandleEvent(event, socket, data,io);
EnvironmentHandleEvent(event, socket, data,io);
floorItemsHandleEvent(event, socket, data,io);
wallItemsHandleEvent(event, socket, data,io);
lineHandleEvent(event, socket, data,io);
});
socket.on(EVENTS.disconnect, (reason: string) => {
// console.log(`Client disconnected: ${socket.id}, Reason: ${reason}`);
// console.log(socket.handshake.auth);
userStatus(EVENTS.disconnect, socket, socket.handshake.auth,io);
// Perform cleanup or other necessary actions
});
});
return io;
};