Skip to content

Commit

Permalink
Merge branch 'ws'
Browse files Browse the repository at this point in the history
  • Loading branch information
root14 committed Aug 12, 2024
2 parents de3db08 + 76eb71f commit 7aa1e3f
Show file tree
Hide file tree
Showing 12 changed files with 531 additions and 7 deletions.
337 changes: 336 additions & 1 deletion package-lock.json

Large diffs are not rendered by default.

9 changes: 8 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,8 @@
"devDependencies": {
"@types/express": "^4.17.21",
"@types/node": "^22.1.0",
"@types/uuid": "^10.0.0",
"@types/ws": "^8.5.12",
"nodemon": "^3.1.4",
"prisma": "^5.18.0",
"ts-node": "^10.9.2",
Expand All @@ -31,6 +33,11 @@
"dotenv": "^16.4.5",
"express": "^4.19.2",
"jsonwebtoken": "^9.0.2",
"mongodb": "^6.8.0"
"mongodb": "^6.8.0",
"redis": "^4.7.0",
"uuid": "^10.0.0",
"websocket": "^1.0.35",
"websocket-ts": "^2.1.5",
"ws": "^8.18.0"
}
}
1 change: 0 additions & 1 deletion src/controller/auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,6 @@ const register = async (req: Request, res: Response) => {
} else {
res.status(500).json({ error: err })
}

})
}
})
Expand Down
58 changes: 58 additions & 0 deletions src/controller/wscontroller.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
import { v4 as uuid, v4 } from "uuid"
import WebSocket from "ws";

import { jwtValidate } from "../util/jwtValidate"
import { randomMatch } from "../matchFinder";

const wsPort = process.env.WS_PORT || 3003

const wsServer = new WebSocket.Server({ port: wsPort as number }, () => {
console.log(`ws Server is running on http://localhost:${wsPort}`)
})

const handleWs = () => {
wsServer.on("connection", async (connection, request) => {
console.log(`Client connected`)

if (!jwtValidate(request.headers.authorization || "")) {
//cannot validate jwt
console.log("cannot validate jwt for a user")
connection.send("cannot validate your jwt")
connection.close()
return
}

connection.on("error", (error: Error) => {
console.log("Connection Error: " + error.message)
})

connection.on("close", () => {
console.log("Client connection closed");
})

connection.on("message", async (message: string) => {
const { userId } = JSON.parse(message)
let findedUser = await randomMatch(userId)


/** await setInterval(async () => {
randomMatch(userId).then((result) => {
console.log(`result is ${result}`)
if (result instanceof String) {
findedUser = result
}
})
}, 5000) */


console.log(`finded user is ${findedUser}`)
})
})

wsServer.on("error", (error: Error) => {
console.log("WebSocket server error: " + error.message)
})
}

export default handleWs
22 changes: 22 additions & 0 deletions src/data/redisConnector.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import { createClient } from 'redis'

const redisClient = createClient({
password: process.env.REDIS_PASS,
socket: {
host: process.env.REDIS_URL,
port: 19908
}
})

redisClient.on('error', err => console.log('Redis Client Error', err))

async function connectRedis() {
try {
await redisClient.connect()
console.log("connected to redis")
} catch (error) {
console.log(error)
}
}

export { connectRedis, redisClient }
26 changes: 26 additions & 0 deletions src/matchFinder.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import { redisClient } from "./data/redisConnector"

async function randomMatch(userId: string) {
const cardinality = await redisClient.sCard('user-pool')
await redisClient.expire(`user-pool${userId}`, 3600)
let poolUser

if (cardinality < 1) {
//if no user in pool, add user
await redisClient.sAdd('user-pool', userId)
} else {
//if someone waiting in pool, match
poolUser = await redisClient.sPop('user-pool')
}

return poolUser
}

function locationBasedMatch(userId: string) { }

export {
locationBasedMatch, randomMatch
}



16 changes: 16 additions & 0 deletions src/public/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
<!DOCTYPE html>
<html lang="tr">

<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>preview</title>
</head>

<body>
<video class="video-player" id="user-1" autoplay playsinline ></video>
<video class="video-player" id="user-2" autoplay playsinline ></video>
<script src="./index.js"></script>
</body>

</html>
9 changes: 9 additions & 0 deletions src/public/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@

let localStream
let remoteStream

let init = async () => {
localStream = await navigator.mediaDevices.getUserMedia({ video: true, audio: true })
document.getElementById('user-1').srcObject = localStream
}
init()
11 changes: 11 additions & 0 deletions src/public/main.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
#videos {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 2em;
}

.video-player {
background-color: black;
width: 100%;
height: 300px;
}
20 changes: 16 additions & 4 deletions src/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,17 +4,17 @@ import dotenv from "dotenv"
import authRoute from "./route/auth"
import verifyJWT from "./middleware/jwtVerify"

import { connectRedis } from "./data/redisConnector"
import handleWs from "./controller/wscontroller"
import path from "path"

dotenv.config()

const app = express()
export const prisma = new PrismaClient()

const port = process.env.PORT || 3001

app.get('/', (req, res) => {
res.send('hello')
})

app.listen(port, () => {
console.log(`Server is running on http://localhost:${port}`)
})
Expand All @@ -23,8 +23,20 @@ async function main() {
app.use(express.json())
app.use(express.urlencoded({ extended: true }))

connectRedis()
handleWs()

app.use("/api/v1/auth", authRoute)
//app.use("/api/v1", verifyJWT, )

// Public klasöründen statik dosyaları sunma
app.use(express.static(path.join(__dirname, 'public')))

app.use("/api/v1/auth", authRoute)

app.get('/hey', (req: Request, res: Response) => {
res.sendFile(path.join(__dirname, 'public', 'index.html'))
})
}

main()
Expand Down
12 changes: 12 additions & 0 deletions src/util/finderStates.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
/**
* @constant ERR -> on error
* @constant RAND_FAIL -> across yourself
* @constant NOT_ENOUGH_USER -> when there are not enough people in the pool
*/

enum FinderStates {
ERR = "0",
RAND_FAIL = "1",
NOTE_NOUGH_USER = "2"
}
export default FinderStates
17 changes: 17 additions & 0 deletions src/util/jwtValidate.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import jwt, { JwtPayload } from 'jsonwebtoken';

function jwtValidate(token: string) {
let result = false
jwt.verify(token, process.env.JWT_SECRET_KEY as string, (error, decoded) => {
if (error) {
result = false
} else {
result = true;
}
});
return result
}



export { jwtValidate }

0 comments on commit 7aa1e3f

Please sign in to comment.