IO-2935-Add-Enhanced-Websocket-Provider - Add another web socket provider, front end wiring, vite wiring (proxy and secure vite), bumped deps
Signed-off-by: Dave Richer <dave@imexsystems.ca>
This commit is contained in:
20
certs/cert.pem
Normal file
20
certs/cert.pem
Normal file
@@ -0,0 +1,20 @@
|
||||
-----BEGIN CERTIFICATE-----
|
||||
MIIDWzCCAkOgAwIBAgIUD/QBSAXy/AlJ/cS4DaPWJLpChxgwDQYJKoZIhvcNAQEL
|
||||
BQAwPTELMAkGA1UEBhMCQ0ExCzAJBgNVBAgMAk9OMSEwHwYDVQQKDBhJbnRlcm5l
|
||||
dCBXaWRnaXRzIFB0eSBMdGQwHhcNMjQwOTA5MTU0MjA1WhcNMjUwOTA5MTU0MjA1
|
||||
WjA9MQswCQYDVQQGEwJDQTELMAkGA1UECAwCT04xITAfBgNVBAoMGEludGVybmV0
|
||||
IFdpZGdpdHMgUHR5IEx0ZDCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEB
|
||||
AKSd0l7NJCNBwvtPU+dVPQkteg0AfC3sGqRnZMQteCRVa2oIgC4NoF3A9BK/yHbF
|
||||
ZF25OnXTck5vzc8yb3v73ndfTD9ASKNoiaZE84/GFBsxqlKR8cs0qVwzuAsdijMv
|
||||
vlMPNlMRyE1Rb7nR6HXGkPXNyxgMko03NXPkvIje9zRudm0Lf8L4q/hPyPkS7Mrm
|
||||
/uQfAAJe+xFcupkEX2XY7r0x1C+z6E8lA1UcuhK3SHdW7CWYqp1vU5/dnnUiXwCa
|
||||
GiC6Y1bCJB0pDAVISzy3JUDdINZdiqGR+y8ho3pstChf2mp/76s3N9eG9KA/qaFK
|
||||
BrGk2PvCoZ8/Aj1aMsRYFHECAwEAAaNTMFEwHQYDVR0OBBYEFDLJ2fbWP4VUJgOp
|
||||
PSs+NGHcVgRmMB8GA1UdIwQYMBaAFDLJ2fbWP4VUJgOpPSs+NGHcVgRmMA8GA1Ud
|
||||
EwEB/wQFMAMBAf8wDQYJKoZIhvcNAQELBQADggEBABfv5ut/y03atq0NMB0jeDY4
|
||||
AvW4ukk0k1svyqxFZCw9o7m2lHb/IjmVrZG1Sj4JWrrSv0s02ccb26/t6vazNa5L
|
||||
Powe3eyfHgfjTZJmgs8hyeMwKS0wWk/SPuu9JDhIJakiquqD+UVBGkHpP+XYvhDv
|
||||
vhS2XRlW+aEjpUmr1oCyyrc6WbzrYRNadqEsn/AxwcMyUbht3Ugjkg+OpidcTIQp
|
||||
5lv63waKo6I1vQofzBQ3L7JYsKo8kC0vAP7wkLxvzBii335uZJzzpFYFVOyVNezi
|
||||
dJdazPbRYbXz4LjltdEn/SNfRuKX8ZRiN2OSo7OfSrZaMTS87SfCSFJGgQM8Yrk=
|
||||
-----END CERTIFICATE-----
|
||||
28
certs/key.pem
Normal file
28
certs/key.pem
Normal file
@@ -0,0 +1,28 @@
|
||||
-----BEGIN PRIVATE KEY-----
|
||||
MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQCkndJezSQjQcL7
|
||||
T1PnVT0JLXoNAHwt7BqkZ2TELXgkVWtqCIAuDaBdwPQSv8h2xWRduTp103JOb83P
|
||||
Mm97+953X0w/QEijaImmRPOPxhQbMapSkfHLNKlcM7gLHYozL75TDzZTEchNUW+5
|
||||
0eh1xpD1zcsYDJKNNzVz5LyI3vc0bnZtC3/C+Kv4T8j5EuzK5v7kHwACXvsRXLqZ
|
||||
BF9l2O69MdQvs+hPJQNVHLoSt0h3VuwlmKqdb1Of3Z51Il8AmhogumNWwiQdKQwF
|
||||
SEs8tyVA3SDWXYqhkfsvIaN6bLQoX9pqf++rNzfXhvSgP6mhSgaxpNj7wqGfPwI9
|
||||
WjLEWBRxAgMBAAECggEAUNpHYlLFxh9dokujPUMreF+Cy/IKDBAkQc2au5RNpyLh
|
||||
YDIOqw/8TTAhcTgLQPLQygvZP9f8E7RsVLFD+pSJ/v2qmIJ9au1Edor1Sg+S/oxV
|
||||
SLrwFMunx2aLpcH7iAqSI3+cQg7A3+D4zD7iOz6tIl3Su9wo+v073tFhHKTOrEwv
|
||||
Qgr9Jf3viIiKV1ym+uQEVQndocfsj46FnFpXTQ2qs7kAF6FgAOLDGfQQwzkiqEBD
|
||||
NsqsDmbYIx6foZL+DEz1ZVO2M5B+xxpbNK82KwuQilVpimW8ui4LZHCe+RIFzt9+
|
||||
BK6KGlLpSEwTFliivI3nahy18JzskZsfyah0CPZlQQKBgQDVv+A0qIPGvOP3Sx+9
|
||||
HyeQCV23SkvvSvw8p8pMB0gvwv63YdJ7N/rJzBGS6YUHFWWZZgEeTgkJ6VJvoe0r
|
||||
8JL1el9uSUa7f0eayjmFBOGuzpktNVdIn2Tg7A9MWA4JqPNNC69RMOh86ewGD4J3
|
||||
a8Hz2a1bHxAmy/AZt2ukypY6eQKBgQDFJ7kqeOPkRBz9WbALRgVIXo8YWf5di0sQ
|
||||
r0HC03GAISHQ725A2IFBPHJWeqj0jaMiIZD0y+Obgp7KAskrJaLfsd7Ug775kFfw
|
||||
oUI9UAl6kRuPKvm3BaVAm46SQm+56VsgxTi73YN0NUp75THHZgAJjepF9zSpVJxq
|
||||
VY9DjEGruQKBgQCQCpGIatcCol/tUg69X7VFd0pULhkl1J5OMbQ9r9qRdRI5eg5h
|
||||
QsQaIQ7mtb8TmvOwf/DY/zVQHI+U8sXlCmW+TwzoQTENQSR7xzMj1LpRFqBaustr
|
||||
AR72A537kItFLzll/i3SxOam5uxK2UDOQSuerF4KPdCglGXkrpo3nt3F4QKBgQCa
|
||||
RArPAOjQo7tLQfJN3+wiRFsTYtd1uphx5bA/EdOtvj8HjVFnzADXWsTchf3N3UXY
|
||||
XwtdgGwIMpys1KEz8a8P+c2x26SDAj7NOmDqOMYx8Xju/WGHpBM6Cn30U6e4gK+d
|
||||
ZLSPyzQgqdIuP5hDvbwpvbGiLVw3Ys1BJtGCuSxpgQJ/eHnRiuSi5Zq5jGg+GpA+
|
||||
FEEc9NCy772rR+4uzEOqyIwqewffqzSuVWuIsY/8MP3fh+NDxl/mU6cB5QVeD54Z
|
||||
JZUKwmpM26muiM6WvVnM4ExPdSGA2+l4pZjby/KKd6F/w0tgZ1jb9Pb2/0vN3qVA
|
||||
Y4U4XNTMt2fxUACqiL4SHA==
|
||||
-----END PRIVATE KEY-----
|
||||
@@ -8,7 +8,7 @@ VITE_APP_CLOUDINARY_API_KEY=957865933348715
|
||||
VITE_APP_CLOUDINARY_THUMB_TRANSFORMATIONS=c_fill,h_250,w_250
|
||||
VITE_APP_FIREBASE_PUBLIC_VAPID_KEY='BG3tzU7L2BXlGZ_3VLK4PNaRceoEXEnmHfxcVbRMF5o5g05ejslhVPki9kBM9cBBT-08Ad9kN3HSpS6JmrWD6h4'
|
||||
VITE_APP_STRIPE_PUBLIC_KEY=pk_test_51GqB4TJl3nQjrZ0wCQWAxAhlNF8jKe0tipIa6ExBaxwJGitwvFsIZUEua4dUzaMIAuXp4qwYHXx7lgjyQSwP0Pe900vzm38C7g
|
||||
VITE_APP_AXIOS_BASE_API_URL=http://localhost:4000
|
||||
VITE_APP_AXIOS_BASE_API_URL=/api/
|
||||
VITE_APP_REPORTS_SERVER_URL=https://reports3.test.imex.online
|
||||
VITE_APP_SPLIT_API=ts615lqgnmk84thn72uk18uu5pgce6e0l4rc
|
||||
VITE_APP_INSTANCE=IMEX
|
||||
|
||||
@@ -8,7 +8,7 @@ VITE_APP_CLOUDINARY_API_KEY=957865933348715
|
||||
VITE_APP_CLOUDINARY_THUMB_TRANSFORMATIONS=c_fill,h_250,w_250
|
||||
VITE_APP_FIREBASE_PUBLIC_VAPID_KEY='BG3tzU7L2BXlGZ_3VLK4PNaRceoEXEnmHfxcVbRMF5o5g05ejslhVPki9kBM9cBBT-08Ad9kN3HSpS6JmrWD6h4'
|
||||
VITE_APP_STRIPE_PUBLIC_KEY=pk_test_51GqB4TJl3nQjrZ0wCQWAxAhlNF8jKe0tipIa6ExBaxwJGitwvFsIZUEua4dUzaMIAuXp4qwYHXx7lgjyQSwP0Pe900vzm38C7g
|
||||
VITE_APP_AXIOS_BASE_API_URL=http://localhost:4000
|
||||
VITE_APP_AXIOS_BASE_API_URL=/api/
|
||||
VITE_APP_REPORTS_SERVER_URL=https://reports3.test.imex.online
|
||||
VITE_APP_SPLIT_API=ts615lqgnmk84thn72uk18uu5pgce6e0l4rc
|
||||
VITE_APP_INSTANCE=PROMANAGER
|
||||
|
||||
@@ -9,7 +9,7 @@ VITE_APP_CLOUDINARY_API_KEY=957865933348715
|
||||
VITE_APP_CLOUDINARY_THUMB_TRANSFORMATIONS=c_fill,h_250,w_250
|
||||
VITE_APP_FIREBASE_PUBLIC_VAPID_KEY='BP1B7ZTYpn-KMt6nOxlld6aS8Skt3Q7ZLEqP0hAvGHxG4UojPYiXZ6kPlzZkUC5jH-EcWXomTLtmadAIxurfcHo'
|
||||
VITE_APP_STRIPE_PUBLIC_KEY=pk_test_51GqB4TJl3nQjrZ0wCQWAxAhlNF8jKe0tipIa6ExBaxwJGitwvFsIZUEua4dUzaMIAuXp4qwYHXx7lgjyQSwP0Pe900vzm38C7g
|
||||
VITE_APP_AXIOS_BASE_API_URL=http://localhost:4000
|
||||
VITE_APP_AXIOS_BASE_API_URL=/api/
|
||||
VITE_APP_REPORTS_SERVER_URL=https://reports3.test.imex.online
|
||||
VITE_APP_SPLIT_API=ts615lqgnmk84thn72uk18uu5pgce6e0l4rc
|
||||
VITE_APP_COUNTRY=USA
|
||||
|
||||
1
client/.gitignore
vendored
1
client/.gitignore
vendored
@@ -1,3 +1,4 @@
|
||||
|
||||
# Sentry Config File
|
||||
.sentryclirc
|
||||
/dev-dist
|
||||
|
||||
@@ -12,6 +12,6 @@ module.exports = defineConfig({
|
||||
setupNodeEvents(on, config) {
|
||||
return require("./cypress/plugins/index.js")(on, config);
|
||||
},
|
||||
baseUrl: "http://localhost:3000"
|
||||
baseUrl: "https://localhost:3000"
|
||||
}
|
||||
});
|
||||
|
||||
2127
client/package-lock.json
generated
2127
client/package-lock.json
generated
File diff suppressed because it is too large
Load Diff
@@ -8,38 +8,38 @@
|
||||
"private": true,
|
||||
"proxy": "http://localhost:4000",
|
||||
"dependencies": {
|
||||
"@ant-design/pro-layout": "^7.19.12",
|
||||
"@apollo/client": "^3.11.4",
|
||||
"@emotion/is-prop-valid": "^1.3.0",
|
||||
"@fingerprintjs/fingerprintjs": "^4.4.3",
|
||||
"@ant-design/pro-layout": "^7.20.2",
|
||||
"@apollo/client": "^3.11.8",
|
||||
"@emotion/is-prop-valid": "^1.3.1",
|
||||
"@fingerprintjs/fingerprintjs": "^4.5.0",
|
||||
"@jsreport/browser-client": "^3.1.0",
|
||||
"@reduxjs/toolkit": "^2.2.7",
|
||||
"@sentry/cli": "^2.33.1",
|
||||
"@sentry/cli": "^2.36.2",
|
||||
"@sentry/react": "^7.114.0",
|
||||
"@splitsoftware/splitio-react": "^1.12.1",
|
||||
"@splitsoftware/splitio-react": "^1.13.0",
|
||||
"@tanem/react-nprogress": "^5.0.51",
|
||||
"@vitejs/plugin-react": "^4.3.1",
|
||||
"antd": "^5.20.1",
|
||||
"antd": "^5.21.0",
|
||||
"apollo-link-logger": "^2.0.1",
|
||||
"apollo-link-sentry": "^3.3.0",
|
||||
"autosize": "^6.0.1",
|
||||
"axios": "^1.7.4",
|
||||
"axios": "^1.7.7",
|
||||
"classnames": "^2.5.1",
|
||||
"css-box-model": "^1.2.1",
|
||||
"dayjs": "^1.11.12",
|
||||
"dayjs": "^1.11.13",
|
||||
"dayjs-business-days2": "^1.2.2",
|
||||
"dinero.js": "^1.9.1",
|
||||
"dotenv": "^16.4.5",
|
||||
"env-cmd": "^10.1.0",
|
||||
"exifr": "^7.1.3",
|
||||
"firebase": "^10.12.5",
|
||||
"firebase": "^10.13.2",
|
||||
"graphql": "^16.9.0",
|
||||
"i18next": "^23.12.3",
|
||||
"i18next": "^23.15.1",
|
||||
"i18next-browser-languagedetector": "^8.0.0",
|
||||
"immutability-helper": "^3.1.1",
|
||||
"libphonenumber-js": "^1.11.5",
|
||||
"libphonenumber-js": "^1.11.9",
|
||||
"logrocket": "^8.1.2",
|
||||
"markerjs2": "^2.32.1",
|
||||
"markerjs2": "^2.32.2",
|
||||
"memoize-one": "^6.0.0",
|
||||
"normalize-url": "^8.0.1",
|
||||
"object-hash": "^3.0.0",
|
||||
@@ -47,7 +47,7 @@
|
||||
"query-string": "^9.1.0",
|
||||
"raf-schd": "^4.0.3",
|
||||
"react": "^18.3.1",
|
||||
"react-big-calendar": "^1.13.2",
|
||||
"react-big-calendar": "^1.14.1",
|
||||
"react-color": "^2.19.3",
|
||||
"react-cookie": "^7.2.0",
|
||||
"react-dom": "^18.3.1",
|
||||
@@ -58,15 +58,15 @@
|
||||
"react-icons": "^5.3.0",
|
||||
"react-image-lightbox": "^5.1.4",
|
||||
"react-markdown": "^9.0.1",
|
||||
"react-number-format": "^5.4.0",
|
||||
"react-number-format": "^5.4.2",
|
||||
"react-popopo": "^2.1.9",
|
||||
"react-product-fruits": "^2.2.6",
|
||||
"react-product-fruits": "^2.2.61",
|
||||
"react-redux": "^9.1.2",
|
||||
"react-resizable": "^3.0.5",
|
||||
"react-router-dom": "^6.26.0",
|
||||
"react-router-dom": "^6.26.2",
|
||||
"react-sticky": "^6.0.3",
|
||||
"react-virtualized": "^9.22.5",
|
||||
"react-virtuoso": "^4.10.1",
|
||||
"react-virtuoso": "^4.10.4",
|
||||
"recharts": "^2.12.7",
|
||||
"redux": "^5.0.1",
|
||||
"redux-actions": "^3.0.3",
|
||||
@@ -74,12 +74,12 @@
|
||||
"redux-saga": "^1.3.0",
|
||||
"redux-state-sync": "^3.1.4",
|
||||
"reselect": "^5.1.1",
|
||||
"sass": "^1.77.8",
|
||||
"socket.io-client": "^4.7.5",
|
||||
"styled-components": "^6.1.12",
|
||||
"sass": "^1.79.3",
|
||||
"socket.io-client": "^4.8.0",
|
||||
"styled-components": "^6.1.13",
|
||||
"subscriptions-transport-ws": "^0.11.0",
|
||||
"use-memo-one": "^1.1.3",
|
||||
"userpilot": "^1.3.5",
|
||||
"userpilot": "^1.3.6",
|
||||
"vite-plugin-ejs": "^1.7.0",
|
||||
"web-vitals": "^3.5.2"
|
||||
},
|
||||
@@ -91,6 +91,9 @@
|
||||
"start:imex": "dotenvx run --env-file=.env.development.imex -- vite",
|
||||
"start:rome": "dotenvx run --env-file=.env.development.rome -- vite",
|
||||
"start:promanager": "dotenvx run --env-file=.env.development.promanager -- vite",
|
||||
"preview:imex": "dotenvx run --env-file=.env.development.imex -- vite preview",
|
||||
"preview:rome": "dotenvx run --env-file=.env.development.rome -- vite preview",
|
||||
"preview:promanager": "dotenvx run --env-file=.env.development.promanager -- vite preview",
|
||||
"build:test:imex": "env-cmd -f .env.test.imex npm run build",
|
||||
"build:test:rome": "env-cmd -f .env.test.rome npm run build",
|
||||
"build:test:promanager": "env-cmd -f .env.test.promanager npm run build",
|
||||
@@ -131,29 +134,29 @@
|
||||
"devDependencies": {
|
||||
"@babel/plugin-proposal-private-property-in-object": "^7.21.11",
|
||||
"@babel/preset-react": "^7.24.7",
|
||||
"@dotenvx/dotenvx": "^1.7.0",
|
||||
"@dotenvx/dotenvx": "^1.14.1",
|
||||
"@emotion/babel-plugin": "^11.12.0",
|
||||
"@emotion/react": "^11.13.0",
|
||||
"@sentry/webpack-plugin": "^2.22.2",
|
||||
"@emotion/react": "^11.13.3",
|
||||
"@sentry/webpack-plugin": "^2.22.4",
|
||||
"@testing-library/cypress": "^10.0.2",
|
||||
"browserslist": "^4.23.3",
|
||||
"browserslist-to-esbuild": "^2.1.1",
|
||||
"chalk": "^5.3.0",
|
||||
"cross-env": "^7.0.3",
|
||||
"cypress": "^13.13.3",
|
||||
"cypress": "^13.14.2",
|
||||
"eslint": "^8.57.0",
|
||||
"eslint-config-react-app": "^7.0.1",
|
||||
"eslint-plugin-cypress": "^2.15.1",
|
||||
"memfs": "^4.11.1",
|
||||
"memfs": "^4.12.0",
|
||||
"os-browserify": "^0.3.0",
|
||||
"react-error-overlay": "6.0.11",
|
||||
"redux-logger": "^3.0.6",
|
||||
"source-map-explorer": "^2.5.3",
|
||||
"vite": "^5.4.0",
|
||||
"vite": "^5.4.7",
|
||||
"vite-plugin-babel": "^1.2.0",
|
||||
"vite-plugin-eslint": "^1.8.1",
|
||||
"vite-plugin-legacy": "^2.1.0",
|
||||
"vite-plugin-node-polyfills": "^0.22.0",
|
||||
"vite-plugin-pwa": "^0.20.1",
|
||||
"vite-plugin-pwa": "^0.20.5",
|
||||
"vite-plugin-style-import": "^2.0.0",
|
||||
"workbox-window": "^7.1.0"
|
||||
}
|
||||
|
||||
@@ -21,6 +21,7 @@ import "./App.styles.scss";
|
||||
import Eula from "../components/eula/eula.component";
|
||||
import InstanceRenderMgr from "../utils/instanceRenderMgr";
|
||||
import ProductFruitsWrapper from "./ProductFruitsWrapper.jsx";
|
||||
import { SocketProvider } from "../contexts/SocketIO/socketContext.jsx";
|
||||
|
||||
const ResetPassword = lazy(() => import("../pages/reset-password/reset-password.component"));
|
||||
const ManagePage = lazy(() => import("../pages/manage/manage.page.container"));
|
||||
@@ -201,7 +202,9 @@ export function App({ bodyshop, checkUserSession, currentUser, online, setOnline
|
||||
path="/manage/*"
|
||||
element={
|
||||
<ErrorBoundary>
|
||||
<PrivateRoute isAuthorized={currentUser.authorized} />
|
||||
<SocketProvider bodyshop={bodyshop}>
|
||||
<PrivateRoute isAuthorized={currentUser.authorized} />
|
||||
</SocketProvider>
|
||||
</ErrorBoundary>
|
||||
}
|
||||
>
|
||||
@@ -211,7 +214,9 @@ export function App({ bodyshop, checkUserSession, currentUser, online, setOnline
|
||||
path="/tech/*"
|
||||
element={
|
||||
<ErrorBoundary>
|
||||
<PrivateRoute isAuthorized={currentUser.authorized} />
|
||||
<SocketProvider bodyshop={bodyshop}>
|
||||
<PrivateRoute isAuthorized={currentUser.authorized} />
|
||||
</SocketProvider>
|
||||
</ErrorBoundary>
|
||||
}
|
||||
>
|
||||
|
||||
13
client/src/contexts/SocketIO/socketContext.jsx
Normal file
13
client/src/contexts/SocketIO/socketContext.jsx
Normal file
@@ -0,0 +1,13 @@
|
||||
import React, { createContext } from "react";
|
||||
import useSocket from "./useSocket"; // Import the custom hook
|
||||
|
||||
// Create the SocketContext
|
||||
const SocketContext = createContext(null);
|
||||
|
||||
export const SocketProvider = ({ children, bodyshop }) => {
|
||||
const { socket, clientId } = useSocket(bodyshop);
|
||||
|
||||
return <SocketContext.Provider value={{ socket, clientId }}> {children}</SocketContext.Provider>;
|
||||
};
|
||||
|
||||
export default SocketContext;
|
||||
71
client/src/contexts/SocketIO/useSocket.js
Normal file
71
client/src/contexts/SocketIO/useSocket.js
Normal file
@@ -0,0 +1,71 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import SocketIO from "socket.io-client";
|
||||
import { auth } from "../../firebase/firebase.utils";
|
||||
|
||||
const useSocket = (bodyshop) => {
|
||||
const [socket, setSocket] = useState(null);
|
||||
const [clientId, setClientId] = useState(null); // State to store unique identifier
|
||||
|
||||
useEffect(() => {
|
||||
if (bodyshop && bodyshop.id) {
|
||||
const endpoint = import.meta.env.PROD ? import.meta.env.VITE_APP_AXIOS_BASE_API_URL : "https://localhost:3000";
|
||||
|
||||
const socketInstance = SocketIO(endpoint, {
|
||||
path: "/wss", // Ensure this matches the Vite proxy and backend path
|
||||
withCredentials: true,
|
||||
auth: async (callback) => {
|
||||
const token = auth.currentUser && (await auth.currentUser.getIdToken());
|
||||
callback({ token });
|
||||
},
|
||||
reconnectionAttempts: Infinity, // Try reconnecting forever
|
||||
reconnectionDelay: 2000, // How long to wait between reconnection attempts
|
||||
reconnectionDelayMax: 10000 // Maximum delay between attempts
|
||||
});
|
||||
|
||||
setSocket(socketInstance);
|
||||
|
||||
const handleBodyshopMessage = (message) => {
|
||||
console.log(`Received message for bodyshop ${bodyshop.id}:`, message);
|
||||
};
|
||||
|
||||
const handleConnect = () => {
|
||||
console.log("Socket connected:", socketInstance.id);
|
||||
socketInstance.emit("join-bodyshop-room", bodyshop.id);
|
||||
setClientId(socketInstance.id);
|
||||
};
|
||||
|
||||
const handleReconnect = (attempt) => {
|
||||
console.log(`Socket reconnected after ${attempt} attempts`);
|
||||
};
|
||||
|
||||
const handleConnectionError = (err) => {
|
||||
console.error("Socket connection error:", err);
|
||||
};
|
||||
|
||||
const handleDisconnect = () => {
|
||||
console.log("Socket disconnected");
|
||||
};
|
||||
|
||||
socketInstance.on("connect", handleConnect);
|
||||
socketInstance.on("reconnect", handleReconnect);
|
||||
socketInstance.on("connect_error", handleConnectionError);
|
||||
socketInstance.on("disconnect", handleDisconnect);
|
||||
socketInstance.on("bodyshop-message", handleBodyshopMessage);
|
||||
|
||||
return () => {
|
||||
socketInstance.emit("leave-bodyshop-room", bodyshop.id);
|
||||
socketInstance.off("connect", handleConnect);
|
||||
socketInstance.off("reconnect", handleReconnect);
|
||||
socketInstance.off("connect_error", handleConnectionError);
|
||||
socketInstance.off("disconnect", handleDisconnect);
|
||||
socketInstance.off("bodyshop-message", handleBodyshopMessage);
|
||||
socketInstance.disconnect();
|
||||
};
|
||||
}
|
||||
}, [bodyshop]);
|
||||
|
||||
// Return both socket and clientId
|
||||
return { socket, clientId };
|
||||
};
|
||||
|
||||
export default useSocket;
|
||||
@@ -24,7 +24,7 @@ const mapDispatchToProps = (dispatch) => ({
|
||||
export default connect(mapStateToProps, mapDispatchToProps)(DmsContainer);
|
||||
|
||||
export const socket = SocketIO(
|
||||
import.meta.env.PROD ? import.meta.env.VITE_APP_AXIOS_BASE_API_URL : window.location.origin,
|
||||
import.meta.env.PROD ? import.meta.env.VITE_APP_AXIOS_BASE_API_URL : "https://localhost:3000",
|
||||
{
|
||||
path: "/ws",
|
||||
withCredentials: true,
|
||||
|
||||
@@ -34,7 +34,7 @@ const mapDispatchToProps = (dispatch) => ({
|
||||
export default connect(mapStateToProps, mapDispatchToProps)(DmsContainer);
|
||||
|
||||
export const socket = SocketIO(
|
||||
import.meta.env.PROD ? import.meta.env.VITE_APP_AXIOS_BASE_API_URL : "http://localhost:4000", // for dev testing,
|
||||
import.meta.env.PROD ? import.meta.env.VITE_APP_AXIOS_BASE_API_URL : "http://localhost:3000", // for dev testing,
|
||||
{
|
||||
path: "/ws",
|
||||
withCredentials: true,
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { FloatButton, Layout, Spin } from "antd";
|
||||
// import preval from "preval.macro";
|
||||
import React, { lazy, Suspense, useEffect, useState } from "react";
|
||||
import React, { lazy, Suspense, useContext, useEffect, useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { connect } from "react-redux";
|
||||
import { Link, Route, Routes } from "react-router-dom";
|
||||
@@ -19,6 +19,7 @@ import PartnerPingComponent from "../../components/partner-ping/partner-ping.com
|
||||
import PrintCenterModalContainer from "../../components/print-center-modal/print-center-modal.container";
|
||||
import ShopSubStatusComponent from "../../components/shop-sub-status/shop-sub-status.component";
|
||||
import { requestForToken } from "../../firebase/firebase.utils";
|
||||
import SocketContext from "../../contexts/SocketIO/socketContext.jsx";
|
||||
import { selectBodyshop, selectInstanceConflict } from "../../redux/user/user.selectors";
|
||||
|
||||
import UpdateAlert from "../../components/update-alert/update-alert.component";
|
||||
@@ -110,6 +111,7 @@ const mapDispatchToProps = (dispatch) => ({});
|
||||
export function Manage({ conflict, bodyshop }) {
|
||||
const { t } = useTranslation();
|
||||
const [chatVisible] = useState(false);
|
||||
const { socket, clientId } = useContext(SocketContext);
|
||||
|
||||
useEffect(() => {
|
||||
const widgetId = InstanceRenderManager({
|
||||
@@ -129,6 +131,7 @@ export function Manage({ conflict, bodyshop }) {
|
||||
promanager: t("titles.promanager")
|
||||
});
|
||||
}, [t]);
|
||||
|
||||
const AppRouteTable = (
|
||||
<Suspense
|
||||
fallback={
|
||||
@@ -569,6 +572,13 @@ export function Manage({ conflict, bodyshop }) {
|
||||
else if (bodyshop && bodyshop.sub_status !== "active") PageContent = <ShopSubStatusComponent />;
|
||||
else PageContent = AppRouteTable;
|
||||
|
||||
const broadcastMessage = () => {
|
||||
if (socket && bodyshop && bodyshop.id) {
|
||||
console.log(`Broadcasting message to bodyshop ${bodyshop.id}:`);
|
||||
socket.emit("broadcast-to-bodyshop", bodyshop.id, `Hello from ${clientId}`);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
{import.meta.env.PROD && <ChatAffixContainer bodyshop={bodyshop} chatVisible={chatVisible} />}
|
||||
@@ -603,6 +613,8 @@ export function Manage({ conflict, bodyshop }) {
|
||||
</div>
|
||||
<div id="noticeable-widget" style={{ marginLeft: "1rem" }} />
|
||||
</div>
|
||||
<button onClick={broadcastMessage}>Broadcast Message</button>
|
||||
|
||||
<Link to="/disclaimer" target="_blank" style={{ color: "#ccc" }}>
|
||||
Disclaimer & Notices
|
||||
</Link>
|
||||
|
||||
@@ -2,9 +2,9 @@ import axios from "axios";
|
||||
import { auth } from "../firebase/firebase.utils";
|
||||
import InstanceRenderManager from "./instanceRenderMgr";
|
||||
|
||||
axios.defaults.baseURL =
|
||||
import.meta.env.VITE_APP_AXIOS_BASE_API_URL ||
|
||||
(import.meta.env.MODE === "production" ? "https://api.imex.online/" : "http://localhost:4000/");
|
||||
axios.defaults.baseURL = import.meta.env.DEV
|
||||
? "/api/"
|
||||
: import.meta.env.VITE_APP_AXIOS_BASE_API_URL || "https://api.imex.online/";
|
||||
|
||||
export const axiosAuthInterceptorId = axios.interceptors.request.use(
|
||||
async (config) => {
|
||||
|
||||
@@ -3,16 +3,21 @@ import { promises as fsPromises } from "fs";
|
||||
import { createRequire } from "module";
|
||||
import * as path from "path";
|
||||
import * as url from "url";
|
||||
import { defineConfig } from "vite";
|
||||
import { createLogger, defineConfig } from "vite";
|
||||
import { ViteEjsPlugin } from "vite-plugin-ejs";
|
||||
import eslint from "vite-plugin-eslint";
|
||||
import { VitePWA } from "vite-plugin-pwa";
|
||||
import InstanceRenderManager from "./src/utils/instanceRenderMgr";
|
||||
import chalk from "chalk";
|
||||
|
||||
process.env.VITE_APP_GIT_SHA_DATE = new Date().toLocaleString("en-US", {
|
||||
timeZone: "America/Los_Angeles"
|
||||
});
|
||||
|
||||
const getFormattedTimestamp = () =>
|
||||
new Date().toLocaleTimeString("en-US", { hour12: true }).replace("AM", "a.m.").replace("PM", "p.m.");
|
||||
|
||||
/** This is a hack around react-virtualized, should be removed when switching to react-virtuoso */
|
||||
const WRONG_CODE = `import { bpfrpt_proptype_WindowScroller } from "../WindowScroller.js";`;
|
||||
|
||||
function reactVirtualizedFix() {
|
||||
@@ -32,6 +37,11 @@ function reactVirtualizedFix() {
|
||||
}
|
||||
};
|
||||
}
|
||||
/** End of hack */
|
||||
|
||||
export const logger = createLogger("info", {
|
||||
allowClearScreen: false
|
||||
});
|
||||
|
||||
export default defineConfig({
|
||||
base: "/",
|
||||
@@ -99,7 +109,6 @@ export default defineConfig({
|
||||
reactVirtualizedFix(),
|
||||
react(),
|
||||
eslint()
|
||||
// CompressionPlugin(), //Cloudfront already compresses assets, so not needed.
|
||||
],
|
||||
define: {
|
||||
APP_VERSION: JSON.stringify(process.env.npm_package_version)
|
||||
@@ -107,7 +116,69 @@ export default defineConfig({
|
||||
server: {
|
||||
host: true,
|
||||
port: 3000,
|
||||
open: true
|
||||
open: true,
|
||||
proxy: {
|
||||
"/ws": {
|
||||
target: "ws://localhost:4000",
|
||||
rewriteWsOrigin: true,
|
||||
secure: false,
|
||||
ws: true
|
||||
},
|
||||
"/wss": {
|
||||
target: "ws://localhost:4000",
|
||||
rewriteWsOrigin: true,
|
||||
secure: false,
|
||||
ws: true
|
||||
},
|
||||
"/api": {
|
||||
target: "http://localhost:4000",
|
||||
changeOrigin: true,
|
||||
secure: false,
|
||||
ws: false,
|
||||
rewrite: (path) => {
|
||||
const replacedValue = path.replace(/^\/api/, "");
|
||||
logger.info(
|
||||
`${chalk.grey.bold(getFormattedTimestamp())} ${chalk.cyan.bold("[vite]")} ${chalk.green.bold("[API]")} ${chalk.blue(replacedValue)}`
|
||||
);
|
||||
return replacedValue;
|
||||
}
|
||||
}
|
||||
},
|
||||
https: {
|
||||
key: await fsPromises.readFile("../certs/key.pem"),
|
||||
cert: await fsPromises.readFile("../certs/cert.pem"),
|
||||
allowHTTP1: false // Force HTTP/2
|
||||
}
|
||||
},
|
||||
preview: {
|
||||
port: 6000,
|
||||
host: true,
|
||||
open: true,
|
||||
https: {
|
||||
key: await fsPromises.readFile("../certs/key.pem"),
|
||||
cert: await fsPromises.readFile("../certs/cert.pem"),
|
||||
allowHTTP1: false // Force HTTP/2
|
||||
},
|
||||
proxy: {
|
||||
"/ws": {
|
||||
target: "ws://localhost:4000",
|
||||
rewriteWsOrigin: true,
|
||||
secure: false,
|
||||
ws: true
|
||||
},
|
||||
"/wss": {
|
||||
target: "ws://localhost:4000",
|
||||
rewriteWsOrigin: true,
|
||||
secure: false,
|
||||
ws: true
|
||||
},
|
||||
"/api": {
|
||||
target: "http://localhost:4000",
|
||||
changeOrigin: true,
|
||||
secure: false,
|
||||
ws: false
|
||||
}
|
||||
}
|
||||
},
|
||||
build: {
|
||||
rollupOptions: {
|
||||
@@ -121,11 +192,30 @@ export default defineConfig({
|
||||
}
|
||||
},
|
||||
optimizeDeps: {
|
||||
include: ["react", "react-dom", "antd", "@apollo/client", "@reduxjs/toolkit", "axios"],
|
||||
include: [
|
||||
"react",
|
||||
"react-dom",
|
||||
"antd",
|
||||
"@apollo/client",
|
||||
"@reduxjs/toolkit",
|
||||
"axios",
|
||||
"react-router-dom",
|
||||
"dayjs",
|
||||
"redux",
|
||||
"react-redux"
|
||||
],
|
||||
esbuildOptions: {
|
||||
loader: {
|
||||
".js": "jsx"
|
||||
}
|
||||
}
|
||||
},
|
||||
css: {
|
||||
preprocessorOptions: {
|
||||
scss: {
|
||||
api: "modern-compiler",
|
||||
quietDeps: true // Quite Deprecation Warnings, should be disabled occasionally before major upgrades
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
Must set the environment variables using:
|
||||
|
||||
firebase functions:config:set auth.graphql_endpoint="https://db.dev.bodyshop.app/v1/graphql"
|
||||
firebase functions:config:set auth.graphql_endpoint="https://db.dev.imex.online/v1/graphql"
|
||||
auth.hasura_secret_admin_key="Dev-BodyShopApp!"
|
||||
|
||||
1570
package-lock.json
generated
1570
package-lock.json
generated
File diff suppressed because it is too large
Load Diff
35
package.json
35
package.json
@@ -19,26 +19,27 @@
|
||||
"makeitpretty": "prettier --write \"**/*.{css,js,json,jsx,scss}\""
|
||||
},
|
||||
"dependencies": {
|
||||
"@aws-sdk/client-secrets-manager": "^3.629.0",
|
||||
"@aws-sdk/client-ses": "^3.629.0",
|
||||
"@aws-sdk/credential-provider-node": "^3.629.0",
|
||||
"@opensearch-project/opensearch": "^2.11.0",
|
||||
"aws4": "^1.13.1",
|
||||
"axios": "^1.7.4",
|
||||
"@aws-sdk/client-secrets-manager": "^3.654.0",
|
||||
"@aws-sdk/client-ses": "^3.654.0",
|
||||
"@aws-sdk/credential-provider-node": "^3.654.0",
|
||||
"@opensearch-project/opensearch": "^2.12.0",
|
||||
"@socket.io/redis-adapter": "^8.3.0",
|
||||
"aws4": "^1.13.2",
|
||||
"axios": "^1.7.7",
|
||||
"better-queue": "^3.8.12",
|
||||
"bluebird": "^3.7.2",
|
||||
"body-parser": "^1.20.2",
|
||||
"body-parser": "^1.20.3",
|
||||
"canvas": "^2.11.2",
|
||||
"chart.js": "^4.4.3",
|
||||
"cloudinary": "^2.4.0",
|
||||
"chart.js": "^4.4.4",
|
||||
"cloudinary": "^2.5.0",
|
||||
"compression": "^1.7.4",
|
||||
"cookie-parser": "^1.4.6",
|
||||
"cors": "2.8.5",
|
||||
"csrf": "^3.1.0",
|
||||
"dinero.js": "^1.9.1",
|
||||
"dotenv": "^16.4.5",
|
||||
"express": "^4.19.2",
|
||||
"firebase-admin": "^12.3.1",
|
||||
"express": "^4.21.0",
|
||||
"firebase-admin": "^12.5.0",
|
||||
"graphql": "^16.9.0",
|
||||
"graphql-request": "^6.1.0",
|
||||
"graylog2": "^0.2.1",
|
||||
@@ -49,14 +50,16 @@
|
||||
"moment": "^2.30.1",
|
||||
"moment-timezone": "^0.5.45",
|
||||
"multer": "^1.4.5-lts.1",
|
||||
"node-mailjet": "^6.0.5",
|
||||
"node-mailjet": "^6.0.6",
|
||||
"node-persist": "^4.0.3",
|
||||
"nodemailer": "^6.9.14",
|
||||
"phone": "^3.1.49",
|
||||
"nodemailer": "^6.9.15",
|
||||
"phone": "^3.1.50",
|
||||
"recursive-diff": "^1.0.9",
|
||||
"redis": "^4.7.0",
|
||||
"rimraf": "^6.0.1",
|
||||
"soap": "^1.1.1",
|
||||
"socket.io": "^4.7.5",
|
||||
"soap": "^1.1.4",
|
||||
"socket.io": "^4.8.0",
|
||||
"socket.io-adapter": "^2.5.5",
|
||||
"ssh2-sftp-client": "^10.0.3",
|
||||
"twilio": "^4.23.0",
|
||||
"uuid": "^10.0.0",
|
||||
|
||||
402
server.js
402
server.js
@@ -1,4 +1,3 @@
|
||||
// Import core modules
|
||||
const express = require("express");
|
||||
const cors = require("cors");
|
||||
const bodyParser = require("body-parser");
|
||||
@@ -7,104 +6,339 @@ const compression = require("compression");
|
||||
const cookieParser = require("cookie-parser");
|
||||
const http = require("http");
|
||||
const { Server } = require("socket.io");
|
||||
const { createClient } = require("redis");
|
||||
const { createAdapter } = require("@socket.io/redis-adapter");
|
||||
const logger = require("./server/utils/logger");
|
||||
const { redisSocketEvents } = require("./server/web-sockets/redisSocketEvents");
|
||||
|
||||
// Load environment variables
|
||||
require("dotenv").config({
|
||||
path: path.resolve(process.cwd(), `.env.${process.env.NODE_ENV || "development"}`)
|
||||
});
|
||||
|
||||
// Import custom utilities and handlers
|
||||
const logger = require("./server/utils/logger");
|
||||
/**
|
||||
* CORS Origin for Socket.IO
|
||||
* @type {string[][]}
|
||||
*/
|
||||
const SOCKETIO_CORS_ORIGIN = [
|
||||
"https://test.imex.online",
|
||||
"https://www.test.imex.online",
|
||||
"http://localhost:3000",
|
||||
"https://imex.online",
|
||||
"https://www.imex.online",
|
||||
"https://romeonline.io",
|
||||
"https://www.romeonline.io",
|
||||
"https://beta.test.romeonline.io",
|
||||
"https://www.beta.test.romeonline.io",
|
||||
"https://beta.romeonline.io",
|
||||
"https://www.beta.romeonline.io",
|
||||
"https://beta.test.imex.online",
|
||||
"https://www.beta.test.imex.online",
|
||||
"https://beta.imex.online",
|
||||
"https://www.beta.imex.online",
|
||||
"https://www.test.promanager.web-est.com",
|
||||
"https://test.promanager.web-est.com",
|
||||
"https://www.promanager.web-est.com",
|
||||
"https://www.promanager.web-est.com",
|
||||
"https://old.imex.online",
|
||||
"https://www.old.imex.online"
|
||||
];
|
||||
|
||||
// Express app and server setup
|
||||
const app = express();
|
||||
const port = process.env.PORT || 5000;
|
||||
const server = http.createServer(app);
|
||||
const io = new Server(server, {
|
||||
path: "/ws",
|
||||
cors: {
|
||||
origin: [
|
||||
"https://test.imex.online",
|
||||
"https://www.test.imex.online",
|
||||
"http://localhost:3000",
|
||||
"https://imex.online",
|
||||
"https://www.imex.online",
|
||||
"https://romeonline.io", //Added in all RO and PM routes to simplyify setup.
|
||||
"https://www.romeonline.io",
|
||||
"https://beta.test.romeonline.io",
|
||||
"https://www.beta.test.romeonline.io",
|
||||
"https://beta.romeonline.io",
|
||||
"https://www.beta.romeonline.io",
|
||||
"https://beta.test.imex.online",
|
||||
"https://www.beta.test.imex.online",
|
||||
"https://beta.imex.online",
|
||||
"https://www.beta.imex.online",
|
||||
"https://www.test.promanager.web-est.com",
|
||||
"https://test.promanager.web-est.com",
|
||||
"https://www.promanager.web-est.com",
|
||||
"https://www.promanager.web-est.com"
|
||||
],
|
||||
methods: ["GET", "POST"],
|
||||
credentials: true,
|
||||
exposedHeaders: ["set-cookie"]
|
||||
/**
|
||||
* Middleware for Express app
|
||||
* @param app
|
||||
*/
|
||||
const applyMiddleware = (app) => {
|
||||
app.use(compression());
|
||||
app.use(cookieParser());
|
||||
app.use(bodyParser.json({ limit: "50mb" }));
|
||||
app.use(bodyParser.urlencoded({ limit: "50mb", extended: true }));
|
||||
app.use(cors({ credentials: true, exposedHeaders: ["set-cookie"] }));
|
||||
|
||||
// Helper middleware
|
||||
app.use((req, res, next) => {
|
||||
req.logger = logger;
|
||||
next();
|
||||
});
|
||||
};
|
||||
|
||||
/**
|
||||
* Route groupings for Express app
|
||||
* @param app
|
||||
*/
|
||||
const applyRoutes = (app) => {
|
||||
app.use("/", require("./server/routes/miscellaneousRoutes"));
|
||||
app.use("/notifications", require("./server/routes/notificationsRoutes"));
|
||||
app.use("/render", require("./server/routes/renderRoutes"));
|
||||
app.use("/mixdata", require("./server/routes/mixDataRoutes"));
|
||||
app.use("/accounting", require("./server/routes/accountingRoutes"));
|
||||
app.use("/qbo", require("./server/routes/qboRoutes"));
|
||||
app.use("/media", require("./server/routes/mediaRoutes"));
|
||||
app.use("/sms", require("./server/routes/smsRoutes"));
|
||||
app.use("/job", require("./server/routes/jobRoutes"));
|
||||
app.use("/scheduling", require("./server/routes/schedulingRoutes"));
|
||||
app.use("/utils", require("./server/routes/utilRoutes"));
|
||||
app.use("/data", require("./server/routes/dataRoutes"));
|
||||
app.use("/adm", require("./server/routes/adminRoutes"));
|
||||
app.use("/tech", require("./server/routes/techRoutes"));
|
||||
app.use("/intellipay", require("./server/routes/intellipayRoutes"));
|
||||
app.use("/cdk", require("./server/routes/cdkRoutes"));
|
||||
app.use("/csi", require("./server/routes/csiRoutes"));
|
||||
app.use("/payroll", require("./server/routes/payrollRoutes"));
|
||||
|
||||
// Default route for forbidden access
|
||||
app.get("/", (req, res) => {
|
||||
res.status(200).send("Access Forbidden.");
|
||||
});
|
||||
};
|
||||
|
||||
/**
|
||||
* Apply Redis to the server
|
||||
* @param server
|
||||
* @param app
|
||||
*/
|
||||
const applySocketIO = async (server, app) => {
|
||||
// Redis client setup for Pub/Sub and Key-Value Store
|
||||
const pubClient = createClient({ url: process.env.REDIS_URL || "redis://localhost:6379" });
|
||||
const subClient = pubClient.duplicate();
|
||||
|
||||
pubClient.on("error", (err) => logger.log(`Redis pubClient error: ${err}`, "ERROR", "redis"));
|
||||
subClient.on("error", (err) => logger.log(`Redis subClient error: ${err}`, "ERROR", "redis"));
|
||||
|
||||
try {
|
||||
await Promise.all([pubClient.connect(), subClient.connect()]);
|
||||
logger.log(`[${process.env.NODE_ENV}] Connected to Redis`, "INFO", "redis", "api");
|
||||
} catch (redisError) {
|
||||
logger.log("Failed to connect to Redis", "ERROR", "redis", redisError);
|
||||
}
|
||||
});
|
||||
exports.io = io;
|
||||
|
||||
require("./server/web-sockets/web-socket");
|
||||
process.on("SIGINT", async () => {
|
||||
logger.log("Closing Redis connections...", "INFO", "redis", "api");
|
||||
await Promise.all([pubClient.disconnect(), subClient.disconnect()]);
|
||||
process.exit(0);
|
||||
});
|
||||
|
||||
// Middleware
|
||||
app.use(compression());
|
||||
app.use(cookieParser());
|
||||
app.use(bodyParser.json({ limit: "50mb" }));
|
||||
app.use(bodyParser.urlencoded({ limit: "50mb", extended: true }));
|
||||
app.use(cors({ credentials: true, exposedHeaders: ["set-cookie"] }));
|
||||
const ioRedis = new Server(server, {
|
||||
path: "/wss",
|
||||
adapter: createAdapter(pubClient, subClient),
|
||||
cors: {
|
||||
origin: SOCKETIO_CORS_ORIGIN,
|
||||
methods: ["GET", "POST"],
|
||||
credentials: true,
|
||||
exposedHeaders: ["set-cookie"]
|
||||
}
|
||||
});
|
||||
|
||||
// Helper middleware
|
||||
app.use((req, res, next) => {
|
||||
req.logger = logger;
|
||||
next();
|
||||
});
|
||||
const io = new Server(server, {
|
||||
path: "/ws",
|
||||
cors: {
|
||||
origin: SOCKETIO_CORS_ORIGIN,
|
||||
methods: ["GET", "POST"],
|
||||
credentials: true,
|
||||
exposedHeaders: ["set-cookie"]
|
||||
}
|
||||
});
|
||||
|
||||
// Route groupings
|
||||
app.use("/", require("./server/routes/miscellaneousRoutes"));
|
||||
app.use("/notifications", require("./server/routes/notificationsRoutes"));
|
||||
app.use("/render", require("./server/routes/renderRoutes"));
|
||||
app.use("/mixdata", require("./server/routes/mixDataRoutes"));
|
||||
app.use("/accounting", require("./server/routes/accountingRoutes"));
|
||||
app.use("/qbo", require("./server/routes/qboRoutes"));
|
||||
app.use("/media", require("./server/routes/mediaRoutes"));
|
||||
app.use("/sms", require("./server/routes/smsRoutes"));
|
||||
app.use("/job", require("./server/routes/jobRoutes"));
|
||||
app.use("/scheduling", require("./server/routes/schedulingRoutes"));
|
||||
app.use("/utils", require("./server/routes/utilRoutes"));
|
||||
app.use("/data", require("./server/routes/dataRoutes"));
|
||||
app.use("/adm", require("./server/routes/adminRoutes"));
|
||||
app.use("/tech", require("./server/routes/techRoutes"));
|
||||
app.use("/intellipay", require("./server/routes/intellipayRoutes"));
|
||||
app.use("/cdk", require("./server/routes/cdkRoutes"));
|
||||
app.use("/csi", require("./server/routes/csiRoutes"));
|
||||
app.use("/payroll", require("./server/routes/payrollRoutes"));
|
||||
app.use((req, res, next) => {
|
||||
Object.assign(req, {
|
||||
pubClient,
|
||||
io,
|
||||
ioRedis
|
||||
});
|
||||
|
||||
// Default route for forbidden access
|
||||
app.get("/", (req, res) => {
|
||||
res.status(200).send("Access Forbidden.");
|
||||
});
|
||||
next();
|
||||
});
|
||||
|
||||
Object.assign(module.exports, { io, pubClient, ioRedis });
|
||||
|
||||
return { pubClient, io, ioRedis };
|
||||
};
|
||||
|
||||
/**
|
||||
* Apply Redis helper functions
|
||||
* @param pubClient
|
||||
* @param app
|
||||
*/
|
||||
const applyRedisHelpers = (pubClient, app) => {
|
||||
// Store session data in Redis
|
||||
const setSessionData = async (socketId, key, value) => {
|
||||
await pubClient.hSet(`socket:${socketId}`, key, JSON.stringify(value)); // Use Redis pubClient
|
||||
};
|
||||
|
||||
// Retrieve session data from Redis
|
||||
const getSessionData = async (socketId, key) => {
|
||||
const data = await pubClient.hGet(`socket:${socketId}`, key);
|
||||
return data ? JSON.parse(data) : null;
|
||||
};
|
||||
|
||||
// Clear session data from Redis
|
||||
const clearSessionData = async (socketId) => {
|
||||
await pubClient.del(`socket:${socketId}`);
|
||||
};
|
||||
|
||||
// Store multiple session data in Redis
|
||||
const setMultipleSessionData = async (socketId, keyValues) => {
|
||||
// keyValues is expected to be an object { key1: value1, key2: value2, ... }
|
||||
const entries = Object.entries(keyValues).map(([key, value]) => [key, JSON.stringify(value)]);
|
||||
await pubClient.hSet(`socket:${socketId}`, ...entries.flat());
|
||||
};
|
||||
|
||||
// Retrieve multiple session data from Redis
|
||||
const getMultipleSessionData = async (socketId, keys) => {
|
||||
const data = await pubClient.hmGet(`socket:${socketId}`, keys);
|
||||
// Redis returns an object with null values for missing keys, so we parse the non-null ones
|
||||
return Object.fromEntries(keys.map((key, index) => [key, data[index] ? JSON.parse(data[index]) : null]));
|
||||
};
|
||||
|
||||
const setMultipleFromArraySessionData = async (socketId, keyValueArray) => {
|
||||
// Use Redis multi/pipeline to batch the commands
|
||||
const multi = pubClient.multi();
|
||||
|
||||
keyValueArray.forEach(([key, value]) => {
|
||||
multi.hSet(`socket:${socketId}`, key, JSON.stringify(value));
|
||||
});
|
||||
|
||||
await multi.exec(); // Execute all queued commands
|
||||
};
|
||||
|
||||
// Helper function to add an item to the end of the Redis list
|
||||
const addItemToEndOfList = async (socketId, key, newItem) => {
|
||||
try {
|
||||
await pubClient.rPush(`socket:${socketId}:${key}`, JSON.stringify(newItem));
|
||||
} catch (error) {
|
||||
console.error(`Error adding item to the end of the list for socket ${socketId}:`, error);
|
||||
}
|
||||
};
|
||||
|
||||
// Helper function to add an item to the beginning of the Redis list
|
||||
const addItemToBeginningOfList = async (socketId, key, newItem) => {
|
||||
try {
|
||||
await pubClient.lPush(`socket:${socketId}:${key}`, JSON.stringify(newItem));
|
||||
} catch (error) {
|
||||
console.error(`Error adding item to the beginning of the list for socket ${socketId}:`, error);
|
||||
}
|
||||
};
|
||||
|
||||
// Helper function to clear a list in Redis
|
||||
const clearList = async (socketId, key) => {
|
||||
try {
|
||||
await pubClient.del(`socket:${socketId}:${key}`);
|
||||
} catch (error) {
|
||||
console.error(`Error clearing list for socket ${socketId}:`, error);
|
||||
}
|
||||
};
|
||||
|
||||
const api = {
|
||||
setSessionData,
|
||||
getSessionData,
|
||||
clearSessionData,
|
||||
setMultipleSessionData,
|
||||
getMultipleSessionData,
|
||||
setMultipleFromArraySessionData,
|
||||
addItemToEndOfList,
|
||||
addItemToBeginningOfList,
|
||||
clearList
|
||||
};
|
||||
|
||||
Object.assign(module.exports, api);
|
||||
|
||||
app.use((req, res, next) => {
|
||||
req.sessionUtils = api;
|
||||
next();
|
||||
});
|
||||
|
||||
// // Demo to show how all the helper functions work
|
||||
// const demoSessionData = async () => {
|
||||
// const socketId = "testSocketId";
|
||||
//
|
||||
// // Store session data using setSessionData
|
||||
// await exports.setSessionData(socketId, "field1", "Hello, Redis!");
|
||||
//
|
||||
// // Retrieve session data using getSessionData
|
||||
// const field1Value = await exports.getSessionData(socketId, "field1");
|
||||
// console.log("Retrieved single field value:", field1Value);
|
||||
//
|
||||
// // Store multiple session data using setMultipleSessionData
|
||||
// await exports.setMultipleSessionData(socketId, { field2: "Second Value", field3: "Third Value" });
|
||||
//
|
||||
// // Retrieve multiple session data using getMultipleSessionData
|
||||
// const multipleFields = await exports.getMultipleSessionData(socketId, ["field2", "field3"]);
|
||||
// console.log("Retrieved multiple field values:", multipleFields);
|
||||
//
|
||||
// // Store multiple session data using setMultipleFromArraySessionData
|
||||
// await exports.setMultipleFromArraySessionData(socketId, [
|
||||
// ["field4", "Fourth Value"],
|
||||
// ["field5", "Fifth Value"]
|
||||
// ]);
|
||||
//
|
||||
// // Retrieve and log all fields
|
||||
// const allFields = await exports.getMultipleSessionData(socketId, [
|
||||
// "field1",
|
||||
// "field2",
|
||||
// "field3",
|
||||
// "field4",
|
||||
// "field5"
|
||||
// ]);
|
||||
// console.log("Retrieved all field values:", allFields);
|
||||
//
|
||||
// // Add item to the end of a Redis list
|
||||
// await exports.addItemToEndOfList(socketId, "logEvents", { event: "Log Event 1", timestamp: new Date() });
|
||||
// await exports.addItemToEndOfList(socketId, "logEvents", { event: "Log Event 2", timestamp: new Date() });
|
||||
//
|
||||
// // Add item to the beginning of a Redis list
|
||||
// await exports.addItemToBeginningOfList(socketId, "logEvents", { event: "First Log Event", timestamp: new Date() });
|
||||
//
|
||||
// // Retrieve the entire list (using lRange)
|
||||
// const logEvents = await pubClient.lRange(`socket:${socketId}:logEvents`, 0, -1);
|
||||
// console.log("Log Events List:", logEvents.map(JSON.parse));
|
||||
//
|
||||
// // **Add the new code below to test clearList**
|
||||
//
|
||||
// // Clear the list using clearList
|
||||
// await exports.clearList(socketId, "logEvents");
|
||||
// console.log("Log Events List cleared.");
|
||||
//
|
||||
// // Retrieve the list after clearing to confirm it's empty
|
||||
// const logEventsAfterClear = await pubClient.lRange(`socket:${socketId}:logEvents`, 0, -1);
|
||||
// console.log("Log Events List after clearing:", logEventsAfterClear); // Should be an empty array
|
||||
//
|
||||
// // Clear session data
|
||||
// await exports.clearSessionData(socketId);
|
||||
// console.log("Session data cleared.");
|
||||
// };
|
||||
//
|
||||
// if (process.env.NODE_ENV === "development") {
|
||||
// demoSessionData();
|
||||
// }
|
||||
};
|
||||
|
||||
/**
|
||||
* Main function to start the server
|
||||
* @returns {Promise<void>}
|
||||
*/
|
||||
const main = async () => {
|
||||
await server.listen(port);
|
||||
const app = express();
|
||||
const port = process.env.PORT || 5000;
|
||||
|
||||
const server = http.createServer(app);
|
||||
|
||||
const { pubClient, ioRedis } = await applySocketIO(server, app);
|
||||
applyRedisHelpers(pubClient, app);
|
||||
|
||||
// Legacy Socket Events
|
||||
require("./server/web-sockets/web-socket");
|
||||
|
||||
applyMiddleware(app);
|
||||
applyRoutes(app);
|
||||
redisSocketEvents(ioRedis);
|
||||
|
||||
try {
|
||||
await server.listen(port);
|
||||
logger.log(`[${process.env.NODE_ENV}] Server started on port ${port}`, "INFO", "api");
|
||||
} catch (error) {
|
||||
logger.log(`[${process.env.NODE_ENV}] Server failed to start on port ${port}`, "ERROR", "api", error);
|
||||
}
|
||||
};
|
||||
|
||||
// Start server
|
||||
main()
|
||||
.then(() => {
|
||||
logger.log(`[${process.env.NODE_ENV || "DEVELOPMENT"}] Server started on port ${port}`, "INFO", "api");
|
||||
})
|
||||
.catch((error) => {
|
||||
logger.log(
|
||||
`[${process.env.NODE_ENV || "DEVELOPMENT"}] Server failed to start on port ${port}`,
|
||||
"ERROR",
|
||||
"api",
|
||||
error
|
||||
);
|
||||
});
|
||||
main();
|
||||
|
||||
79
server/web-sockets/redisSocketEvents.js
Normal file
79
server/web-sockets/redisSocketEvents.js
Normal file
@@ -0,0 +1,79 @@
|
||||
const path = require("path");
|
||||
require("dotenv").config({
|
||||
path: path.resolve(process.cwd(), `.env.${process.env.NODE_ENV || "development"}`)
|
||||
});
|
||||
const logger = require("../utils/logger");
|
||||
const { admin } = require("../firebase/firebase-handler");
|
||||
|
||||
// Logging helper functions
|
||||
function createLogEvent(socket, level, message) {
|
||||
console.log(`[IOREDIS LOG EVENT] - ${socket.user.email} - ${socket.id} - ${message}`);
|
||||
logger.log("ioredis-log-event", level, socket.user.email, null, { wsmessage: message });
|
||||
}
|
||||
|
||||
const redisSocketEvents = (io) => {
|
||||
// Room management and broadcasting events
|
||||
function registerRoomAndBroadcastEvents(socket) {
|
||||
socket.on("join-bodyshop-room", async (bodyshopUUID) => {
|
||||
socket.join(bodyshopUUID);
|
||||
createLogEvent(socket, "DEBUG", `Client joined bodyshop room: ${bodyshopUUID}`);
|
||||
});
|
||||
|
||||
socket.on("leave-bodyshop-room", async (bodyshopUUID) => {
|
||||
socket.leave(bodyshopUUID);
|
||||
createLogEvent(socket, "DEBUG", `Client left bodyshop room: ${bodyshopUUID}`);
|
||||
});
|
||||
|
||||
socket.on("broadcast-to-bodyshop", async (bodyshopUUID, message) => {
|
||||
io.to(bodyshopUUID).emit("bodyshop-message", message);
|
||||
createLogEvent(socket, "INFO", `Broadcast message to bodyshop ${bodyshopUUID}`);
|
||||
});
|
||||
}
|
||||
|
||||
// Register all socket events for a given socket connection
|
||||
function registerSocketEvents(socket) {
|
||||
createLogEvent(socket, "DEBUG", `Connected and Authenticated.`);
|
||||
|
||||
// Register room and broadcasting events
|
||||
registerRoomAndBroadcastEvents(socket);
|
||||
|
||||
// Handle socket disconnection
|
||||
socket.on("disconnect", async () => {
|
||||
createLogEvent(socket, "DEBUG", `User disconnected.`);
|
||||
});
|
||||
}
|
||||
|
||||
const authMiddleware = (socket, next) => {
|
||||
try {
|
||||
if (socket.handshake.auth.token) {
|
||||
admin
|
||||
.auth()
|
||||
.verifyIdToken(socket.handshake.auth.token)
|
||||
.then((user) => {
|
||||
socket.user = user;
|
||||
next();
|
||||
})
|
||||
.catch((error) => {
|
||||
next(new Error("Authentication error", JSON.stringify(error)));
|
||||
});
|
||||
} else {
|
||||
next(new Error("Authentication error - no authorization token."));
|
||||
}
|
||||
} catch (error) {
|
||||
console.log("Uncaught connection error:::", error);
|
||||
logger.log("websocket-connection-error", "error", null, null, {
|
||||
token: socket.handshake.auth.token,
|
||||
...error
|
||||
});
|
||||
next(new Error(`Authentication error ${error}`));
|
||||
}
|
||||
};
|
||||
|
||||
// Socket.IO Middleware and Connection
|
||||
io.use(authMiddleware);
|
||||
io.on("connection", registerSocketEvents);
|
||||
};
|
||||
|
||||
module.exports = {
|
||||
redisSocketEvents
|
||||
};
|
||||
Reference in New Issue
Block a user