Skip to content

Commit

Permalink
Refactor WebSocket
Browse files Browse the repository at this point in the history
  • Loading branch information
saroar committed Mar 8, 2023
1 parent 81f8cf0 commit 82cd5f4
Show file tree
Hide file tree
Showing 12 changed files with 230 additions and 273 deletions.
1 change: 0 additions & 1 deletion Sources/App/Controllers/AuthController.swift

This file was deleted.

15 changes: 8 additions & 7 deletions Sources/App/Controllers/ChatController.swift
Original file line number Diff line number Diff line change
Expand Up @@ -11,17 +11,18 @@ import MongoKitten
import JWT
import AddaSharedModels

extension ChatController: RouteCollection {
extension WebsocketController: RouteCollection {
func boot(routes: RoutesBuilder) throws {
routes.webSocket(onUpgrade: self.webSocket)
}
}

struct ChatController {
let wsController: WebSocketController

func webSocket(_ req: Request, socket: WebSocket) {
self.wsController.connect(socket, req: req)
struct WebsocketController {
let wsController: WebsocketHandle

func webSocket(_ req: Request, ws: WebSocket) {
Task {
await self.wsController.connectionHandler(ws: ws, req: req)
}
}

}
148 changes: 74 additions & 74 deletions Sources/App/Controllers/WebSocketController.swift
Original file line number Diff line number Diff line change
Expand Up @@ -11,77 +11,77 @@ import MongoKitten
import AddaSharedModels
import NIOConcurrencyHelpers

class WebSocketController {
let lock: NIOLock
let db: Database
let logger: Logger
var chatClients: WebsocketClients

init(eventLoop: EventLoop, db: Database) {
self.lock = NIOLock()
self.db = db
self.logger = Logger(label: "WebSocketController")
self.chatClients = WebsocketClients(eventLoop: eventLoop)
}

func connect(_ ws: WebSocket, req: Request) {

ws.onPong { ws in
ws.onText { (ws, text) in
print(#line, text)
}
}

ws.onPong { ws in
ws.onText { (ws, text) in
print(#line, text)
}
}

ws.onText { [self] ws, text in
guard let data = text.data(using: .utf8) else {
logger.error( "Wrong encoding for received message")
return
}

let string = String(data: data, encoding: .utf8)
print(#line, string as Any)

let chatOutGoingEvent = ChatOutGoingEvent.decode(data: data)

switch chatOutGoingEvent {

// from client to server
case .connect(let user):
let userID = user.id
let client = ChatClient(id: userID, socket: ws)
chatClients.add(client)

// from client to server
case .disconnect(let user):
let userID = user.id
let client = ChatClient(id: userID, socket: ws)
chatClients.remove(client)

// from client to server & server to client
case .message(let msg):
print(#line, msg)
chatClients.send(msg, req: req)

// from server to client
case .conversation(let lastMessage):
print(#line, lastMessage)
chatClients.send(lastMessage, req: req)

case .notice(let msg):
print(#line, msg)

case .error(let error):
print(#line, error)
logger.error("(error)")
case .none:
print(#line, "decode error")
}
}
}
}
//class WebSocketController {
// let lock: NIOLock
// let db: Database
// let logger: Logger
// var chatClients: WebsocketClients
//
// init(eventLoop: EventLoop, db: Database) {
// self.lock = NIOLock()
// self.db = db
// self.logger = Logger(label: "WebSocketController")
// self.chatClients = WebsocketClients(eventLoop: eventLoop)
// }
//
// func connect(_ ws: WebSocket, req: Request) {
//
// ws.onPong { ws in
// ws.onText { (ws, text) in
// print(#line, text)
// }
// }
//
// ws.onPong { ws in
// ws.onText { (ws, text) in
// print(#line, text)
// }
// }
//
// ws.onText { [self] ws, text in
// guard let data = text.data(using: .utf8) else {
// logger.error( "Wrong encoding for received message")
// return
// }
//
// let string = String(data: data, encoding: .utf8)
// print(#line, string as Any)
//
// let chatOutGoingEvent = ChatOutGoingEvent.decode(data: data)
//
// switch chatOutGoingEvent {
//
// // from client to server
// case .connect(let user):
// let userID = user.id
// let client = ChatClient(id: userID, socket: ws)
// chatClients.add(client)
//
// // from client to server
// case .disconnect(let user):
// let userID = user.id
// let client = ChatClient(id: userID, socket: ws)
// chatClients.remove(client)
//
// // from client to server & server to client
// case .message(let msg):
// print(#line, msg)
// chatClients.send(msg, req: req)
//
// // from server to client
// case .conversation(let lastMessage):
// print(#line, lastMessage)
// chatClients.send(lastMessage, req: req)
//
// case .notice(let msg):
// print(#line, msg)
//
// case .error(let error):
// print(#line, error)
// logger.error("(error)")
// case .none:
// print(#line, "decode error")
// }
// }
// }
//}
Original file line number Diff line number Diff line change
Expand Up @@ -178,6 +178,7 @@ private func emailVerificationResponseForValidUser(
let refreshToken = try req.application.jwt.signers.sign(refreshPayload)

let access = RefreshTokenResponse(accessToken: accessToken, refreshToken: refreshToken)
req.payload = userPayload

try await VerificationCodeAttempt.query(on: req.db)
.filter(\.$id == input.attemptId)
Expand Down
19 changes: 14 additions & 5 deletions Sources/App/RouteHandlers/AuthEngineHandlers/DeviceHandler.swift
Original file line number Diff line number Diff line change
Expand Up @@ -26,31 +26,40 @@ public func devicesHandler(
token: input.token,
voipToken: input.voipToken
)

/// we need it becz we add url for not login users
if let token = request.accessToken {
do {
request.payload = try request.jwt.verify(Array(token.utf8), as: Payload.self)
}
}

if request.loggedIn {
currentUserID = request.payload.user.id
newInput.ownerId = request.payload.user.id
}
newInput.ownerId = currentUserID

let data = DeviceModel(
identifierForVendor: newInput.identifierForVendor,
name: newInput.name,
model: newInput.model,
osVersion: newInput.osVersion,
token: newInput.token,
voipToken: newInput.voipToken,
userId: currentUserID
)
let device = try await DeviceModel.query(on: request.db)

guard let device = try await DeviceModel.query(on: request.db)
.filter(\.$token == input.token)
.first()
.get()
guard let device = device else {

else {
try await data.save(on: request.db).get()
return data.res
}

try await device.update(newInput)
try await device.update(on: request.db)
return device.res
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -289,16 +289,20 @@ public func userHandler(
.get()

return user.response

case let .devices(devicesRoute):
return try await devicesHandler(request: request, route: devicesRoute)

case let .attachments(attachmentsRoute):
return try await attachmentsHandler(request: request, route: attachmentsRoute)

case let .conversations(conversationsRoute):
return try await conversationsHandler(
request: request,
usersId: usersId,
route: conversationsRoute
)

case .events(_):
return Response(status: .badRequest)
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ public func usersHandler(
switch route {
case .user(id: let id, route: let userRoute):
return try await userHandler(request: request, usersId: id, route: userRoute)

case .update(input: let input):
if request.loggedIn == false { throw Abort(.unauthorized) }
guard let currentUserID = request.payload.user.id else {
Expand Down
Loading

0 comments on commit 82cd5f4

Please sign in to comment.