Skip to content

Commit

Permalink
rename Device field and refactor webSocket
Browse files Browse the repository at this point in the history
  • Loading branch information
saroar committed Mar 10, 2023
1 parent 82cd5f4 commit 42046af
Show file tree
Hide file tree
Showing 9 changed files with 36 additions and 30 deletions.
2 changes: 1 addition & 1 deletion Package.resolved
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
"location" : "https://github.com/AddaMeSPB/AddaSharedModels.git",
"state" : {
"branch" : "CleanUpBackEndModel",
"revision" : "ef66e0258c22da72e3d70a0c5dde1b78525689c0"
"revision" : "33ae1cc978578fe674521569522530254aa9baea"
}
},
{
Expand Down
8 changes: 4 additions & 4 deletions Sources/App/AppExtensions/Application+Environment.swift
Original file line number Diff line number Diff line change
Expand Up @@ -26,28 +26,28 @@ extension Application {
fatalError("\(#line) No MongoDB connection string is available in .env.development")
}
connectionString = mongoURL
print("\(#line) mongoURL: \(connectionString)")
self.logger.info("\(#line) mongoURL: \(connectionString)")

case .staging:
guard let mongoURL = Environment.get("MONGO_DB_\(environmentNameUppercased)_URL") else {
fatalError("\(#line) No MongoDB connection string is available in .env.development")
}
connectionString = mongoURL
print("\(#line) mongoURL: \(connectionString)")
self.logger.info("\(#line) mongoURL: \(connectionString)")

case .testing:
guard let mongoURL = Environment.get("MONGO_DB_\(environmentNameUppercased)_URL") else {
fatalError("\(#line) No MongoDB connection string is available in .env.development")
}
connectionString = mongoURL
print("\(#line) mongoURL: \(connectionString)")
self.logger.info("\(#line) mongoURL: \(connectionString)")

default:
guard let mongoURL = Environment.get("MONGO_DB_\(environmentNameUppercased)_URL") else {
fatalError("No MongoDB connection string is available in .env.development")
}
connectionString = mongoURL
print("\(#line) mongoURL: \(connectionString)")
self.logger.info("\(#line) mongoURL: \(connectionString)")
}
}

Expand Down
4 changes: 2 additions & 2 deletions Sources/App/AppExtensions/JWTMiddleware.swift
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ public final class JWTMiddleware: AsyncMiddleware {
} catch let JWTError.claimVerificationFailure(name: name, reason: reason) {
throw JWTError.claimVerificationFailure(name: name, reason: reason)
} catch let error {
debugPrint("\(self) \(#line) \(#file) \(error)")
req.logger.info("\(self) \(#line) \(#file) \(error)")
if req.accessToken == "" {
return try await next.respond(to: req)
}
Expand All @@ -60,7 +60,7 @@ public final class JWTMiddleware: AsyncMiddleware {
return try await next.respond(to: req)

} else {
req.application.logger.notice("Unauthorized missing token \(req.url.path) \(String(describing: req.body.string))")
req.logger.error("Unauthorized missing token \(req.url.path) \(String(describing: req.body.string))")
return Response(status: .unauthorized, body: .init(string: "Missing authorization bearer header"))
}
}
Expand Down
10 changes: 5 additions & 5 deletions Sources/App/Models/DeviceModel.swift
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ public final class DeviceModel: Model {
name: String,
model: String? = nil,
osVersion: String? = nil,
token: String,
pushToken: String,
voipToken: String,
userId: UserModel.IDValue? = nil
) {
Expand All @@ -26,7 +26,7 @@ public final class DeviceModel: Model {
self.name = name
self.model = model
self.osVersion = osVersion
self.token = token
self.pushToken = pushToken
self.voipToken = voipToken
self.$user.id = userId
}
Expand All @@ -37,7 +37,7 @@ public final class DeviceModel: Model {
@Field(key: "name") public var name: String
@OptionalField(key: "model") public var model: String?
@OptionalField(key: "osVersion") public var osVersion: String?
@Field(key: "token") public var token: String
@Field(key: "pushToken") public var pushToken: String
@Field(key: "voipToken") public var voipToken: String

@OptionalParent(key: "ownerId") public var user: UserModel?
Expand All @@ -60,7 +60,7 @@ extension DeviceModel {
name: name,
model: model,
osVersion: osVersion,
token: token,
pushToken: pushToken,
voipToken: voipToken,
createdAt: createdAt,
updatedAt: updatedAt,
Expand All @@ -74,7 +74,7 @@ extension DeviceModel {
self.name = input.name
self.model = input.model
self.osVersion = input.osVersion
self.token = input.token
self.pushToken = input.pushToken
self.voipToken = input.voipToken
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ public func devicesHandler(
var currentUserID: ObjectId? = nil
var newInput = DeviceInOutPut.init(
name: input.name,
token: input.token,
pushToken: input.pushToken,
voipToken: input.voipToken
)

Expand All @@ -45,13 +45,13 @@ public func devicesHandler(
name: newInput.name,
model: newInput.model,
osVersion: newInput.osVersion,
token: newInput.token,
pushToken: newInput.pushToken,
voipToken: newInput.voipToken,
userId: currentUserID
)

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

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -38,11 +38,9 @@ public func conversationsHandler(
throw Abort(.notFound, reason: "Cant find member user by phoneNumber: \(content.opponentPhoneNumber) or current user and member user cant be same")
}

guard let opponentUserId = opponentUser.id
else {
throw Abort(.notFound, reason: "Cant find opponentUserId")
}
debugPrint("opponentUserId \(opponentUserId)")
guard let opponentUserId = opponentUser.id else {
throw Abort(.notFound, reason: "Cant find opponentUserId")
}

let userConversation = try await UserConversationModel.query(on: request.db)
.filter(\.$member.$id == currentUserID)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ public func eventsHandler(
// The equatorial radius of the Earth is
// approximately 3,963.2 miles or 6,378.1 kilometers.

debugPrint(page)
request.logger.info("\(page)")
let maxDistanceInMiles = Double(page.distance)

let events = request.mongoDB[HangoutEventModel.schema]
Expand Down
2 changes: 1 addition & 1 deletion Sources/App/Webbsockets/ChatClient.swift
Original file line number Diff line number Diff line change
Expand Up @@ -116,7 +116,7 @@ actor WebsocketClients {
title: conversation.title,
subtitle: msgItem.messageBody
),
to: device.token
to: device.pushToken
).get()

}
Expand Down
24 changes: 16 additions & 8 deletions Sources/App/Webbsockets/ChatHandle.swift
Original file line number Diff line number Diff line change
Expand Up @@ -34,12 +34,12 @@ actor WebsocketHandle {

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

let string = String(data: data, encoding: .utf8)
print(#line, string as Any)
req.logger.info("\(#function) \(#line) \(string as Any)")

guard let chatOutGoingEvent = ChatOutGoingEvent.decode(data: data) else {

Expand All @@ -50,20 +50,27 @@ actor WebsocketHandle {
return
}

let user = req.payload.user
guard let userID = user.id else {
req.logger.error("Cant found user from req.payload")
return
}

switch chatOutGoingEvent {
case .connect(let user):
let userID = user.id
case .connect:

Task {
await wsClients.join(id: userID, on: ws)
}
req.logger.info("web socker connect for user \(user.email ?? user.fullName ?? "")")
case .disconnect(let user):
let userID = user.id

case .disconnect:

Task {
await wsClients.leave(id: userID)
}
req.logger.info("web socker remove for user \(user.email ?? user.fullName ?? "")")

case .message(let msg):

Task {
Expand All @@ -77,10 +84,11 @@ actor WebsocketHandle {
}

req.logger.info("conversation conversation: \(lastMessage)")

case .notice(let msg):
print(#line, msg)
req.logger.info("error: \(msg)")
case .error(let error):
req.logger.info("error: \(error.localizedDescription)")
req.logger.error("error: \(error.localizedDescription)")
}
}
}
Expand Down

0 comments on commit 42046af

Please sign in to comment.