Skip to content

Commit

Permalink
Refactor/socket io event refactor (#195)
Browse files Browse the repository at this point in the history
* ♻️ 重構 WebSocketEvent

* 🐛 修正 Broadcast 行為

* fix: socket io event mapping

---------

Co-authored-by: KuoChe <[email protected]>
  • Loading branch information
frankvicky and kuoche1712003 authored Jan 14, 2024
1 parent 8a0948c commit 02a647d
Show file tree
Hide file tree
Showing 13 changed files with 99 additions and 99 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -24,8 +24,8 @@ class ChangePlayerReadinessUsecase(
room.changePlayerReadiness(player.id, readiness)
roomRepository.update(room)

val playerReadinessChangedEvent = room.changePlayerReadiness(readiness, player.id!!.value, player.nickname)
eventBus.broadcast(playerReadinessChangedEvent)
room.changePlayerReadiness(readiness, player.id.value, player.nickname)
.also { eventBus.broadcast(it) }
}
}

Expand All @@ -49,6 +49,6 @@ fun Room.changePlayerReadiness(
): PlayerReadinessChangedEvent {
val type = if (readiness) USER_READY else USER_NOT_READY
val user = User(playerId, nickname)
val data = Data(user, roomId!!.value)
val data = Data(user, roomId!!)
return PlayerReadinessChangedEvent(type, data)
}
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ import tw.waterballsa.gaas.application.repositories.RoomRepository
import tw.waterballsa.gaas.application.repositories.UserRepository
import tw.waterballsa.gaas.domain.Room
import tw.waterballsa.gaas.events.EndedGameEvent
import tw.waterballsa.gaas.events.EndedGameEvent.Data
import tw.waterballsa.gaas.events.enums.EventMessageType.GAME_ENDED
import javax.inject.Named

Expand All @@ -17,11 +16,12 @@ class EndGameUseCase(
) : AbstractRoomUseCase(roomRepository, userRepository) {
fun execute(request: Request) {
val room = findRoomById(request.roomId)
room.endGame()
roomRepository.update(room)

val endedGameEvent = room.endGameByGameService()
eventBus.broadcast(endedGameEvent)
with(room) {
endGame()
roomRepository.update(this)
endGameByGameService()
.also { eventBus.broadcast(it) }
}
}

data class Request(
Expand All @@ -30,7 +30,6 @@ class EndGameUseCase(
}

fun Room.endGameByGameService(): EndedGameEvent {
val type = GAME_ENDED
val data = Data(roomId!!.value)
return EndedGameEvent(type, data)
val data = EndedGameEvent.Data(roomId!!)
return EndedGameEvent(GAME_ENDED, data)
}
Original file line number Diff line number Diff line change
Expand Up @@ -32,8 +32,8 @@ class JoinRoomUsecase(
ensureThatPlayerNotJoinFullRoom()
joinPlayer(player)

val playerJoinedRoomEvent = room.joinRoomEvent(player.id.value, player.nickname)
eventBus.broadcast(playerJoinedRoomEvent)
joinRoomEvent(player.id.value, player.nickname)
.also { eventBus.broadcast(it) }
}
}

Expand Down Expand Up @@ -69,7 +69,7 @@ class JoinRoomUsecase(
nickname: String,
): PlayerJoinedRoomEvent {
val user = Player(playerId, nickname)
val data = Data(user, roomId!!.value)
val data = Data(user, roomId!!)
return PlayerJoinedRoomEvent(USER_JOINED, data)
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,8 +27,8 @@ class LeaveRoomUsecase(
else -> roomRepository.leaveRoom(room)
}

val playerLeavedRoomEvent = room.leaveRoomEvent(player.id.value, player.nickname)
eventBus.broadcast(playerLeavedRoomEvent)
room.leaveRoomEvent(player.id.value, player.nickname)
.also { eventBus.broadcast(it) }
}
}

Expand All @@ -37,7 +37,7 @@ class LeaveRoomUsecase(
nickname: String,
): PlayerLeavedRoomEvent {
val user = Player(playerId, nickname)
val data = Data(user, roomId!!.value)
val data = Data(user, roomId!!)
return PlayerLeavedRoomEvent(USER_LEFT, data)
}

Expand Down
Original file line number Diff line number Diff line change
@@ -1,12 +1,17 @@
package tw.waterballsa.gaas.events

import tw.waterballsa.gaas.domain.Room
import tw.waterballsa.gaas.events.enums.EventMessageType

data class EndedGameEvent(
val type: EventMessageType,
val data: Data,
) : DomainEvent() {
class EndedGameEvent(
type: EventMessageType,
val data: Data
) : RoomEvent(type) {
data class Data(
val roomId: String,
val roomId: Room.Id,
)

override fun getEventData(): Any = data

override fun getRoomId(): Room.Id = data.roomId
}
Original file line number Diff line number Diff line change
@@ -1,18 +1,23 @@
package tw.waterballsa.gaas.events

import tw.waterballsa.gaas.domain.Room
import tw.waterballsa.gaas.events.enums.EventMessageType

data class PlayerJoinedRoomEvent(
val type: EventMessageType,
val data: Data,
) : DomainEvent() {
class PlayerJoinedRoomEvent(
type: EventMessageType,
val data: Data
) : RoomEvent(type) {
data class Data(
val user: Player,
val roomId: String,
val roomId: Room.Id,
) {
data class Player(
val id: String,
val nickname: String,
)
}

override fun getEventData(): Any = data

override fun getRoomId(): Room.Id = data.roomId
}
Original file line number Diff line number Diff line change
@@ -1,18 +1,23 @@
package tw.waterballsa.gaas.events

import tw.waterballsa.gaas.domain.Room
import tw.waterballsa.gaas.events.enums.EventMessageType

data class PlayerLeavedRoomEvent(
val type: EventMessageType,
val data: Data,
) : DomainEvent() {
class PlayerLeavedRoomEvent(
type: EventMessageType,
val data: Data
) : RoomEvent(type) {
data class Data(
val user: Player,
val roomId: String,
val roomId: Room.Id,
) {
data class Player(
val id: String,
val nickname: String,
)
}

override fun getEventData(): Any = data

override fun getRoomId(): Room.Id = data.roomId
}
Original file line number Diff line number Diff line change
@@ -1,18 +1,23 @@
package tw.waterballsa.gaas.events

import tw.waterballsa.gaas.domain.Room
import tw.waterballsa.gaas.events.enums.EventMessageType

data class PlayerReadinessChangedEvent(
val type: EventMessageType,
val data: Data,
) : DomainEvent() {
class PlayerReadinessChangedEvent(
type: EventMessageType,
val data: Data
) : RoomEvent(type) {
data class Data(
val user: User,
val roomId: String,
val roomId: Room.Id,
) {
data class User(
val id: String,
val nickname: String,
)
}

override fun getEventData(): Any = data

override fun getRoomId(): Room.Id = data.roomId
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
package tw.waterballsa.gaas.events

import tw.waterballsa.gaas.domain.Room
import tw.waterballsa.gaas.events.enums.EventMessageType

abstract class RoomEvent(type: EventMessageType) : SocketIOResponseEvent(type) {
abstract fun getRoomId(): Room.Id
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
package tw.waterballsa.gaas.events

import tw.waterballsa.gaas.events.enums.EventMessageType

abstract class SocketIOResponseEvent(val type: EventMessageType) : DomainEvent() {
abstract fun getEventData(): Any
}
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,16 @@ package tw.waterballsa.gaas.events
import tw.waterballsa.gaas.domain.Room
import tw.waterballsa.gaas.events.enums.EventMessageType

data class StartedGameEvent(
val type: EventMessageType,
val data: Data,
) : DomainEvent() {

class StartedGameEvent(
type: EventMessageType,
val data: Data
) : RoomEvent(type) {
data class Data(
val gameUrl: String,
val roomId: Room.Id,
)

override fun getEventData(): Any = data

override fun getRoomId(): Room.Id = data.roomId
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,24 +2,16 @@ package tw.waterballsa.gaas.spring.configs.socketio

import com.corundumstudio.socketio.SocketIOClient
import com.corundumstudio.socketio.SocketIOServer
import com.corundumstudio.socketio.listener.DisconnectListener
import com.nimbusds.jose.shaded.json.JSONObject
import io.netty.handler.codec.http.HttpHeaderNames
import org.apache.catalina.manager.util.SessionUtils
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import org.springframework.security.oauth2.jwt.Jwt
import org.springframework.stereotype.Component
import org.springframework.web.context.request.RequestContextHolder
import tw.waterballsa.gaas.application.eventbus.EventBus
import tw.waterballsa.gaas.application.repositories.RoomRepository
import tw.waterballsa.gaas.application.repositories.UserRepository
import tw.waterballsa.gaas.application.usecases.GetRoomUsecase
import tw.waterballsa.gaas.domain.Room
import tw.waterballsa.gaas.events.ChatData
import tw.waterballsa.gaas.events.SocketioEvent
import tw.waterballsa.gaas.events.enums.EventMessageType
import javax.servlet.http.HttpServletRequest


@Component
Expand All @@ -38,14 +30,14 @@ class SocketIOEventHandler(
}


fun configureEventHandlers() {
private final fun configureEventHandlers() {

socketIOServer.addConnectListener { client ->
val token = client.handshakeData.httpHeaders.get(HttpHeaderNames.COOKIE)
val customHeader = client.handshakeData.getSingleUrlParam("Authorization")

if (client != null ) {
logger.info("有新用戶連結 , SessionId: {}", client.getSessionId())
logger.info("有新用戶連結 , SessionId: {}", client.sessionId)
val board = socketIOServer.broadcastOperations
logger.info("board clientId {}", board.clients)
}
Expand Down Expand Up @@ -85,26 +77,24 @@ class SocketIOEventHandler(
}


socketIOServer.addEventListener(SocketIOEventName.LEAVE_ROOM.eventName, SocketioEvent::class.java) {
client: SocketIOClient, socketioEvent: SocketioEvent, _ ->
socketIOServer.addEventListener(SocketIOEventName.LEAVE_ROOM.eventName, ChatData::class.java) {
client: SocketIOClient, socketioEvent: ChatData, _ ->
// ECHO
logger.info(" LEAVE_ROOM Received message: ${socketioEvent.data.target} from client: ${client.sessionId}")

client.leaveRoom(socketioEvent.data.target)
socketIOServer.removeNamespace(socketioEvent.data.target)
logger.info(" LEAVE_ROOM Received message: ${socketioEvent.target} from client: ${client.sessionId}")
client.leaveRoom(socketioEvent.target)
}


socketIOServer.addEventListener(SocketIOEventName.DISCONNECT.eventName, SocketioEvent::class.java) {
client: SocketIOClient, socketioEvent: SocketioEvent, _ ->
client: SocketIOClient, _: SocketioEvent, _ ->

client.disconnect()
logger.info(" client is leaven room with key disconnect")
}

socketIOServer.addDisconnectListener {
client: SocketIOClient ->
logger.info("Server disconnected on the server side")

logger.info("Server disconnected on the server side")
}
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,10 @@ import org.slf4j.Logger
import org.slf4j.LoggerFactory
import org.springframework.stereotype.Component
import tw.waterballsa.gaas.application.eventbus.EventBus
import tw.waterballsa.gaas.events.*
import tw.waterballsa.gaas.events.DomainEvent
import tw.waterballsa.gaas.events.RoomEvent
import tw.waterballsa.gaas.spring.controllers.viewmodel.SocketioViewModel


import kotlin.reflect.safeCast

@Component
class WebSocketEventBus(
Expand All @@ -17,40 +17,13 @@ class WebSocketEventBus(

private val logger: Logger = LoggerFactory.getLogger(WebSocketEventBus::class.java)


lateinit var viewModel: SocketioViewModel

// TODO broadcast the events!
override fun broadcast(events: Collection<DomainEvent>) {
for (event in events) {
if (event is PlayerJoinedRoomEvent) {
val data = event.data
val type = event.type

val roomId = "ROOM_${data.roomId}"
val room = socketIOServer.getRoomOperations(roomId)
room.sendEvent(type.eventName, data)
} else if(event is PlayerLeavedRoomEvent){
val data = event.data
val type = event.type
socketIOServer.broadcastOperations.sendEvent(type.toString(), data)
} else if(event is PlayerReadinessChangedEvent){
val data = event.data
val type = event.type
socketIOServer.broadcastOperations.sendEvent(type.toString(), data)
} else if(event is StartedGameEvent){
val data = event.data
val type = event.type
socketIOServer.broadcastOperations.sendEvent(type.toString(), data)
} else if(event is UserUpdatedEvent){
// val data = event.data
// val type = event.type
// socketIOServer.broadcastOperations.sendEvent(type.toString(), data)
events.asSequence()
.mapNotNull { RoomEvent::class.safeCast(it) }
.forEach {
socketIOServer.getRoomOperations("ROOM_${it.getRoomId().value}")
.sendEvent(it.type.eventName, it.getEventData())
}

}


}

}
}

0 comments on commit 02a647d

Please sign in to comment.