Compare commits

...

15 Commits

Author SHA1 Message Date
dalbodeule
101db7d20c
[refactor] chzzk4j update to 0.1.1 2025-05-13 21:31:17 +09:00
dalbodeule
3c3b9a79a2
debug chzzk login 4 2025-05-13 21:25:57 +09:00
dalbodeule
61a5f985c1
Refactor: replace songListScope with appropriate scopes
Replaced `songListScope` with `songScope` in `WSSongRoutes` and `timerScope` in `WSTimerRoutes` to better reflect their respective purposes. Improves code clarity and consistency in scope usage.
2025-04-24 17:48:11 +09:00
dalbodeule
aa95976005
Refactor WebSocket song list handling and improve session logic
Replaced individual WebSocket session management with `SessionHandler` to centralize and streamline logic. Improved code readability, reliability, and maintainability by reducing redundancy and encapsulating session and request handling in dedicated classes. Added retry mechanisms, acknowledgment handling, and better application shutdown handling.
2025-04-24 17:45:25 +09:00
dalbodeule
c5a98943c0
Refactor WebSocket ACK handling and improve message retries
Introduced `waitForAck` to centralize ACK handling logic and updated retry mechanism in `sendWithRetry` to improve reliability and readability. Cleaned up error handling in WebSocket session management and ensured proper cleanup of resources. These changes enhance maintainability and robustness of the WebSocket song list routes.
2025-04-24 17:08:12 +09:00
dalbodeule
8230762053
Refactor WebSocket handlers and add ACK-based message flow
Consolidated coroutine scopes into `songListScope` and `timerScope` for better management across WebSocket routes. Introduced ACK (acknowledgment) handling for reliable message delivery with retries and timeouts. Updated session handling for multiple WebSocket routes to improve code maintainability and consistency.
2025-04-24 16:56:49 +09:00
dalbodeule
d07cdb6ae8
Cancel route scope on application stop and simplify ACK handling.
Added a monitor to cancel the route scope when the application stops, ensuring proper resource cleanup. Removed the timeout logic in the ACK handling method, simplifying the flow while maintaining error handling.
2025-04-24 16:37:11 +09:00
dalbodeule
9c15c8f10d
Remove SongListWebSocketManager and simplify wsSongListRoutes
The SongListWebSocketManager class and its associated logic were removed to streamline the codebase. The wsSongListRoutes function was updated accordingly to no longer require the manager as a parameter.
2025-04-24 16:26:25 +09:00
dalbodeule
5a7f78ff3e
Refactor WebSocket route to use shared CoroutineScope
Introduced a shared `routeScope` with `SupervisorJob` for better coroutine management across WebSocket routes. This replaces ad-hoc CoroutineScope creation, preventing unnecessary scope overhead and supporting centralized cancellation. Mutexes were added for session and song-related operations to ensure thread safety.
2025-04-24 16:23:55 +09:00
dalbodeule
7a84a9e437
Configure SongListWebSocketManager in wsSongListRoutes.
This change adds a `SongListWebSocketManager` instance with a logger to the `wsSongListRoutes` setup. It improves manageability and ensures better logging for WebSocket interactions in the song list route.
2025-04-24 16:01:16 +09:00
dalbodeule
02cede87f8
Add SongListWebSocketManager and refactor WebSocket routes
Introduced SongListWebSocketManager for managing WebSocket sessions, including ping-pong handling and retry mechanisms. Refactored WSSongListRoutes to delegate session management and simplify logic by leveraging the new manager class.
2025-04-24 15:58:56 +09:00
dalbodeule
17d8065a34
Fix session cleanup in WebSocket routes
Add missing `finally` blocks to ensure session removal in WebSocket routes after exceptions. This prevents potential memory leaks and ensures proper resource cleanup.
2025-04-24 15:01:12 +09:00
dalbodeule
0e8462eaf1
Handle WebSocket session removal on channel closure
Add `removeSession` calls in WebSocket exception handling blocks to ensure proper session cleanup when a `ClosedReceiveChannelException` occurs. Prevents potential resource leaks and ensures consistency across WebSocket routes.
2025-04-24 14:56:00 +09:00
dalbodeule
83cb68b63f
**Remove redundant session cleanup in WebSocket error handlers**
Removed unnecessary `removeSession` calls from WebSocket `finally` blocks as they are either handled elsewhere or no longer needed. This simplifies the error handling flow and ensures consistency across WebSocket route implementations.
2025-04-24 14:51:28 +09:00
JinU Choi
c2bb653ee1
Merge pull request #124 from dalbodeule/develop
if account deleted?
2025-03-31 18:47:13 +09:00
15 changed files with 638 additions and 409 deletions

View File

@ -28,7 +28,7 @@ repositories {
dependencies { dependencies {
// https://mvnrepository.com/artifact/ch.qos.logback/logback-classic // https://mvnrepository.com/artifact/ch.qos.logback/logback-classic
implementation("ch.qos.logback:logback-classic:1.5.12") implementation("ch.qos.logback:logback-classic:1.5.13")
// https://mvnrepository.com/artifact/org.jetbrains.kotlinx/kotlinx-coroutines-core // https://mvnrepository.com/artifact/org.jetbrains.kotlinx/kotlinx-coroutines-core
implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.9.0") implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.9.0")

View File

@ -16,10 +16,10 @@ dependencies {
} }
// https://mvnrepository.com/artifact/io.github.R2turnTrue/chzzk4j // https://mvnrepository.com/artifact/io.github.R2turnTrue/chzzk4j
implementation("io.github.R2turnTrue:chzzk4j:0.0.12") implementation("io.github.R2turnTrue:chzzk4j:0.1.1")
// https://mvnrepository.com/artifact/ch.qos.logback/logback-classic // https://mvnrepository.com/artifact/ch.qos.logback/logback-classic
implementation("ch.qos.logback:logback-classic:1.5.12") implementation("ch.qos.logback:logback-classic:1.5.13")
// https://mvnrepository.com/artifact/org.jetbrains.kotlinx/kotlinx-coroutines-core // https://mvnrepository.com/artifact/org.jetbrains.kotlinx/kotlinx-coroutines-core
implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.9.0") implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.9.0")

View File

@ -1,25 +1,31 @@
package space.mori.chzzk_bot.chatbot.chzzk package space.mori.chzzk_bot.chatbot.chzzk
import com.google.gson.Gson
import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay import kotlinx.coroutines.delay
import kotlinx.coroutines.future.await import kotlinx.coroutines.future.await
import kotlinx.coroutines.launch import kotlinx.coroutines.launch
import okhttp3.OkHttpClient
import org.koin.java.KoinJavaComponent.inject import org.koin.java.KoinJavaComponent.inject
import org.slf4j.Logger import org.slf4j.Logger
import org.slf4j.LoggerFactory import org.slf4j.LoggerFactory
import space.mori.chzzk_bot.chatbot.chzzk.Connector.chzzk import space.mori.chzzk_bot.chatbot.chzzk.Connector.client as ChzzkClient
import space.mori.chzzk_bot.chatbot.chzzk.Connector.getChannel import space.mori.chzzk_bot.chatbot.chzzk.Connector.getChannel
import space.mori.chzzk_bot.chatbot.discord.Discord import space.mori.chzzk_bot.chatbot.discord.Discord
import space.mori.chzzk_bot.chatbot.utils.refreshAccessToken
import space.mori.chzzk_bot.common.events.* import space.mori.chzzk_bot.common.events.*
import space.mori.chzzk_bot.common.models.User import space.mori.chzzk_bot.common.models.User
import space.mori.chzzk_bot.common.services.LiveStatusService import space.mori.chzzk_bot.common.services.LiveStatusService
import space.mori.chzzk_bot.common.services.TimerConfigService import space.mori.chzzk_bot.common.services.TimerConfigService
import space.mori.chzzk_bot.common.services.UserService import space.mori.chzzk_bot.common.services.UserService
import space.mori.chzzk_bot.common.utils.* import space.mori.chzzk_bot.common.utils.*
import xyz.r2turntrue.chzzk4j.chat.ChatEventListener import xyz.r2turntrue.chzzk4j.ChzzkClient
import xyz.r2turntrue.chzzk4j.chat.ChatMessage import xyz.r2turntrue.chzzk4j.auth.ChzzkSimpleUserLoginAdapter
import xyz.r2turntrue.chzzk4j.chat.ChzzkChat import xyz.r2turntrue.chzzk4j.session.ChzzkSessionBuilder
import xyz.r2turntrue.chzzk4j.session.ChzzkSessionSubscriptionType
import xyz.r2turntrue.chzzk4j.session.ChzzkUserSession
import xyz.r2turntrue.chzzk4j.session.event.SessionChatMessageEvent
import xyz.r2turntrue.chzzk4j.types.channel.ChzzkChannel import xyz.r2turntrue.chzzk4j.types.channel.ChzzkChannel
import java.lang.Exception import java.lang.Exception
import java.net.SocketTimeoutException import java.net.SocketTimeoutException
@ -37,18 +43,17 @@ object ChzzkHandler {
} }
fun enable() { fun enable() {
botUid = chzzk.loggedUser.userId
UserService.getAllUsers().map { UserService.getAllUsers().map {
if(!it.isDisabled) if(!it.isDisabled)
try { try {
chzzk.getChannel(it.token)?.let { token -> addUser(token, it) } Connector.getChannel(it.token)?.let { token -> addUser(token, it) }
} catch(e: Exception) { } catch(e: Exception) {
logger.info("Exception: ${it.token}(${it.username}) not found. ${e.stackTraceToString()}") logger.info("Exception: ${it.token}(${it.username}) not found. ${e.stackTraceToString()}")
} }
} }
handlers.forEach { handler -> handlers.forEach { handler ->
val streamInfo = getStreamInfo(handler.listener.channelId) val streamInfo = getStreamInfo(handler.channel.channelId)
if (streamInfo.content?.status == "OPEN") handler.isActive(true, streamInfo) if (streamInfo.content?.status == "OPEN") handler.isActive(true, streamInfo)
} }
@ -199,7 +204,8 @@ class UserHandler(
var streamStartTime: LocalDateTime?, var streamStartTime: LocalDateTime?,
) { ) {
var messageHandler: MessageHandler var messageHandler: MessageHandler
var listener: ChzzkChat lateinit var client: ChzzkClient
lateinit var listener: ChzzkUserSession
private val dispatcher: CoroutinesEventBus by inject(CoroutinesEventBus::class.java) private val dispatcher: CoroutinesEventBus by inject(CoroutinesEventBus::class.java)
private var _isActive: Boolean private var _isActive: Boolean
@ -209,35 +215,30 @@ class UserHandler(
} }
init { init {
listener = chzzk.chat(channel.channelId) val user = UserService.getUser(channel.channelId)
.withAutoReconnect(true)
.withChatListener(object : ChatEventListener {
override fun onConnect(chat: ChzzkChat, isReconnecting: Boolean) {
logger.info("${channel.channelName} - ${channel.channelId} / reconnected: $isReconnecting")
}
override fun onError(ex: Exception) { if(user?.accessToken == null || user.refreshToken == null) {
logger.info("ChzzkChat error. ${channel.channelName} - ${channel.channelId}") throw RuntimeException("AccessToken or RefreshToken is not valid.")
logger.info(ex.stackTraceToString()) }
}
override fun onChat(msg: ChatMessage) { val tokens = ChzzkClient.refreshAccessToken(user.refreshToken!!)
if(!_isActive) return
messageHandler.handle(msg, user)
}
override fun onConnectionClosed(code: Int, reason: String?, remote: Boolean, tryingToReconnect: Boolean) { client = Connector.getClient(tokens.first, tokens.second)
logger.info("ChzzkChat closed. ${channel.channelName} - ${channel.channelId}") listener = ChzzkSessionBuilder(client).buildUserSession()
logger.info("Reason: $reason / $tryingToReconnect")
} UserService.setTokens(user, tokens.first, tokens.second)
})
.build() listener.createAndConnectAsync().join()
listener.on(SessionChatMessageEvent::class.java) {
messageHandler.handle(it.message, user)
}
messageHandler = MessageHandler(this@UserHandler) messageHandler = MessageHandler(this@UserHandler)
} }
internal fun disable() { internal fun disable() {
listener.closeAsync() listener.disconnectAsync().join()
_isActive = false
} }
internal fun reloadCommand() { internal fun reloadCommand() {
@ -259,7 +260,7 @@ class UserHandler(
reloadUser(UserService.getUser(user.id.value)!!) reloadUser(UserService.getUser(user.id.value)!!)
logger.info("ChzzkChat connecting... ${channel.channelName} - ${channel.channelId}") logger.info("ChzzkChat connecting... ${channel.channelName} - ${channel.channelId}")
listener.connectAsync().await() listener.subscribeAsync(ChzzkSessionSubscriptionType.CHAT)
streamStartTime = status.content?.openDate?.let { convertChzzkDateToLocalDateTime(it) } streamStartTime = status.content?.openDate?.let { convertChzzkDateToLocalDateTime(it) }
@ -285,7 +286,7 @@ class UserHandler(
delay(5000L) delay(5000L)
try { try {
if(!user.isDisableStartupMsg) if(!user.isDisableStartupMsg)
listener.sendChat("${user.username} 님! 오늘도 열심히 방송하세요!") sendChat("${user.username} 님! 오늘도 열심히 방송하세요!")
Discord.sendDiscord(user, status) Discord.sendDiscord(user, status)
} catch(e: Exception) { } catch(e: Exception) {
logger.info("Stream on logic has some error: ${e.stackTraceToString()}") logger.info("Stream on logic has some error: ${e.stackTraceToString()}")
@ -295,7 +296,7 @@ class UserHandler(
} else { } else {
logger.info("${user.username} is offline.") logger.info("${user.username} is offline.")
streamStartTime = null streamStartTime = null
listener.closeAsync() listener.disconnectAsync().join()
_isActive = false _isActive = false
CoroutineScope(Dispatchers.Default).launch { CoroutineScope(Dispatchers.Default).launch {
@ -319,4 +320,8 @@ class UserHandler(
} }
} }
} }
internal fun sendChat(msg: String) {
client.sendChatToLoggedInChannel(msg)
}
} }

View File

@ -2,8 +2,10 @@ package space.mori.chzzk_bot.chatbot.chzzk
import io.github.cdimascio.dotenv.dotenv import io.github.cdimascio.dotenv.dotenv
import org.slf4j.LoggerFactory import org.slf4j.LoggerFactory
import xyz.r2turntrue.chzzk4j.Chzzk import xyz.r2turntrue.chzzk4j.ChzzkClient
import xyz.r2turntrue.chzzk4j.ChzzkBuilder import xyz.r2turntrue.chzzk4j.ChzzkClientBuilder
import xyz.r2turntrue.chzzk4j.auth.ChzzkOauthLoginAdapter
import xyz.r2turntrue.chzzk4j.auth.ChzzkSimpleUserLoginAdapter
import xyz.r2turntrue.chzzk4j.types.channel.ChzzkChannel import xyz.r2turntrue.chzzk4j.types.channel.ChzzkChannel
val dotenv = dotenv { val dotenv = dotenv {
@ -11,14 +13,24 @@ val dotenv = dotenv {
} }
object Connector { object Connector {
val chzzk: Chzzk = ChzzkBuilder() val client: ChzzkClient = ChzzkClientBuilder(dotenv["NAVER_CLIENT_ID"], dotenv["NAVER_CLIENT_SECRET"])
.withAuthorization(dotenv["NID_AUT"], dotenv["NID_SES"])
.build() .build()
private val logger = LoggerFactory.getLogger(this::class.java) private val logger = LoggerFactory.getLogger(this::class.java)
fun getChannel(channelId: String): ChzzkChannel? = chzzk.getChannel(channelId) fun getChannel(channelId: String): ChzzkChannel? = client.fetchChannel(channelId)
init { init {
logger.info("chzzk logged: ${chzzk.isLoggedIn} / ${chzzk.loggedUser?.nickname ?: "----"}") logger.info("chzzk logged: ${client.isLoggedIn}")
client.loginAsync().join()
}
fun getClient(accessToken: String, refreshToken: String): ChzzkClient {
val adapter = ChzzkSimpleUserLoginAdapter(accessToken, refreshToken)
val client = ChzzkClientBuilder(dotenv["NAVER_CLIENT_ID"], dotenv["NAVER_CLIENT_SECRET"])
.withLoginAdapter(adapter)
.build()
return client
} }
} }

View File

@ -13,15 +13,16 @@ import space.mori.chzzk_bot.common.utils.getUptime
import space.mori.chzzk_bot.common.utils.getYoutubeVideo import space.mori.chzzk_bot.common.utils.getYoutubeVideo
import xyz.r2turntrue.chzzk4j.chat.ChatMessage import xyz.r2turntrue.chzzk4j.chat.ChatMessage
import xyz.r2turntrue.chzzk4j.chat.ChzzkChat import xyz.r2turntrue.chzzk4j.chat.ChzzkChat
import xyz.r2turntrue.chzzk4j.session.ChzzkUserSession
import xyz.r2turntrue.chzzk4j.session.message.SessionChatMessage
import java.time.LocalDateTime import java.time.LocalDateTime
import java.time.format.DateTimeFormatter import java.time.format.DateTimeFormatter
import java.time.temporal.ChronoUnit import java.time.temporal.ChronoUnit
class MessageHandler( class MessageHandler(
private val handler: UserHandler private val handler: UserHandler
) { ) {
private val commands = mutableMapOf<String, (msg: ChatMessage, user: User) -> Unit>() private val commands = mutableMapOf<String, (msg: SessionChatMessage, user: User) -> Unit>()
private val counterPattern = Regex("<counter:([^>]+)>") private val counterPattern = Regex("<counter:([^>]+)>")
private val personalCounterPattern = Regex("<counter_personal:([^>]+)>") private val personalCounterPattern = Regex("<counter_personal:([^>]+)>")
@ -71,85 +72,90 @@ class MessageHandler(
this.commands.put(it.command.lowercase()) { msg, user -> this.commands.put(it.command.lowercase()) { msg, user ->
logger.debug("${channel.channelName} - ${it.command} - ${it.content}/${it.failContent}") logger.debug("${channel.channelName} - ${it.command} - ${it.content}/${it.failContent}")
val result = replaceCounters(Pair(it.content, it.failContent), user, msg, listener, msg.profile?.nickname ?: "") val result = replaceCounters(
listener.sendChat(result) Pair(it.content, it.failContent),
user,
msg,
msg.profile?.nickname ?: ""
)
handler.sendChat(result)
} }
} }
} }
private fun commandListCommand(msg: ChatMessage, user: User) { private fun commandListCommand(msg: SessionChatMessage, user: User) {
listener.sendChat("리스트는 여기입니다. https://nabot.mori.space/commands/${user.token}") handler.sendChat("리스트는 여기입니다. https://nabot.mori.space/commands/${user.token}")
} }
private fun manageAddCommand(msg: ChatMessage, user: User) { private fun manageAddCommand(msg: SessionChatMessage, user: User) {
if (msg.profile?.userRoleCode == "common_user") { if (msg.profile.badges.size == 0) {
listener.sendChat("매니저만 명령어를 추가할 수 있습니다.") handler.sendChat("매니저만 명령어를 추가할 수 있습니다.")
return return
} }
val parts = msg.content.split(" ", limit = 3) val parts = msg.content.split(" ", limit = 3)
if (parts.size < 3) { if (parts.size < 3) {
listener.sendChat("명령어 추가 형식은 '!명령어추가 명령어 내용'입니다.") handler.sendChat("명령어 추가 형식은 '!명령어추가 명령어 내용'입니다.")
return return
} }
if (commands.containsKey(parts[1])) { if (commands.containsKey(parts[1])) {
listener.sendChat("${parts[1]} 명령어는 이미 있는 명령어입니다.") handler.sendChat("${parts[1]} 명령어는 이미 있는 명령어입니다.")
return return
} }
val command = parts[1] val command = parts[1]
val content = parts[2] val content = parts[2]
CommandService.saveCommand(user, command, content, "") CommandService.saveCommand(user, command, content, "")
listener.sendChat("명령어 '$command' 추가되었습니다.") handler.sendChat("명령어 '$command' 추가되었습니다.")
} }
private fun manageUpdateCommand(msg: ChatMessage, user: User) { private fun manageUpdateCommand(msg: SessionChatMessage, user: User) {
if (msg.profile?.userRoleCode == "common_user") { if (msg.profile.badges.size == 0) {
listener.sendChat("매니저만 명령어를 추가할 수 있습니다.") handler.sendChat("매니저만 명령어를 추가할 수 있습니다.")
return return
} }
val parts = msg.content.split(" ", limit = 3) val parts = msg.content.split(" ", limit = 3)
if (parts.size < 3) { if (parts.size < 3) {
listener.sendChat("명령어 수정 형식은 '!명령어수정 명령어 내용'입니다.") handler.sendChat("명령어 수정 형식은 '!명령어수정 명령어 내용'입니다.")
return return
} }
if (!commands.containsKey(parts[1])) { if (!commands.containsKey(parts[1])) {
listener.sendChat("${parts[1]} 명령어는 없는 명령어입니다.") handler.sendChat("${parts[1]} 명령어는 없는 명령어입니다.")
return return
} }
val command = parts[1] val command = parts[1]
val content = parts[2] val content = parts[2]
CommandService.updateCommand(user, command, content, "") CommandService.updateCommand(user, command, content, "")
listener.sendChat("명령어 '$command' 수정되었습니다.") handler.sendChat("명령어 '$command' 수정되었습니다.")
ChzzkHandler.reloadCommand(channel) ChzzkHandler.reloadCommand(channel)
} }
private fun manageRemoveCommand(msg: ChatMessage, user: User) { private fun manageRemoveCommand(msg: SessionChatMessage, user: User) {
if (msg.profile?.userRoleCode == "common_user") { if (msg.profile.badges.size == 0) {
listener.sendChat("매니저만 명령어를 삭제할 수 있습니다.") handler.sendChat("매니저만 명령어를 삭제할 수 있습니다.")
return return
} }
val parts = msg.content.split(" ", limit = 2) val parts = msg.content.split(" ", limit = 2)
if (parts.size < 2) { if (parts.size < 2) {
listener.sendChat("명령어 삭제 형식은 '!명령어삭제 명령어'입니다.") handler.sendChat("명령어 삭제 형식은 '!명령어삭제 명령어'입니다.")
return return
} }
val command = parts[1] val command = parts[1]
CommandService.removeCommand(user, command) CommandService.removeCommand(user, command)
listener.sendChat("명령어 '$command' 삭제되었습니다.") handler.sendChat("명령어 '$command' 삭제되었습니다.")
ChzzkHandler.reloadCommand(channel) ChzzkHandler.reloadCommand(channel)
} }
private fun timerCommand(msg: ChatMessage, user: User) { private fun timerCommand(msg: SessionChatMessage, user: User) {
if (msg.profile?.userRoleCode == "common_user") { if (msg.profile.badges.size == 0) {
listener.sendChat("매니저만 이 명령어를 사용할 수 있습니다.") handler.sendChat("매니저만 이 명령어를 사용할 수 있습니다.")
return return
} }
val parts = msg.content.split(" ", limit = 3) val parts = msg.content.split(" ", limit = 3)
if (parts.size < 2) { if (parts.size < 2) {
listener.sendChat("타이머 명령어 형식을 잘 찾아봐주세요!") handler.sendChat("타이머 명령어 형식을 잘 찾아봐주세요!")
return return
} }
@ -178,13 +184,13 @@ class MessageHandler(
when (parts[2]) { when (parts[2]) {
"업타임" -> { "업타임" -> {
TimerConfigService.saveOrUpdateConfig(user, TimerType.UPTIME) TimerConfigService.saveOrUpdateConfig(user, TimerType.UPTIME)
listener.sendChat("기본 타이머 설정이 업타임으로 바뀌었습니다.") handler.sendChat("기본 타이머 설정이 업타임으로 바뀌었습니다.")
} }
"삭제" -> { "삭제" -> {
TimerConfigService.saveOrUpdateConfig(user, TimerType.REMOVE) TimerConfigService.saveOrUpdateConfig(user, TimerType.REMOVE)
listener.sendChat("기본 타이머 설정이 삭제로 바뀌었습니다.") handler.sendChat("기본 타이머 설정이 삭제로 바뀌었습니다.")
} }
else -> listener.sendChat("!타이머 설정 (업타임/삭제) 형식으로 써주세요!") else -> handler.sendChat("!타이머 설정 (업타임/삭제) 형식으로 써주세요!")
} }
} }
else -> { else -> {
@ -198,9 +204,9 @@ class MessageHandler(
dispatcher.post(TimerEvent(user.token, TimerType.TIMER, timestamp.toString())) dispatcher.post(TimerEvent(user.token, TimerType.TIMER, timestamp.toString()))
} }
} catch (e: NumberFormatException) { } catch (e: NumberFormatException) {
listener.sendChat("!타이머/숫자 형식으로 적어주세요! 단위: 분") handler.sendChat("!타이머/숫자 형식으로 적어주세요! 단위: 분")
} catch (e: Exception) { } catch (e: Exception) {
listener.sendChat("타이머 설정 중 오류가 발생했습니다.") handler.sendChat("타이머 설정 중 오류가 발생했습니다.")
logger.error("Error processing timer command: ${e.message}", e) logger.error("Error processing timer command: ${e.message}", e)
} }
} }
@ -208,21 +214,21 @@ class MessageHandler(
} }
// songs // songs
private fun songAddCommand(msg: ChatMessage, user: User) { private fun songAddCommand(msg: SessionChatMessage, user: User) {
if(SongConfigService.getConfig(user).disabled) { if(SongConfigService.getConfig(user).disabled) {
return return
} }
val parts = msg.content.split(" ", limit = 2) val parts = msg.content.split(" ", limit = 2)
if (parts.size < 2) { if (parts.size < 2) {
listener.sendChat("유튜브 URL을 입력해주세요!") handler.sendChat("유튜브 URL을 입력해주세요!")
return return
} }
val config = SongConfigService.getConfig(user) val config = SongConfigService.getConfig(user)
if(config.streamerOnly && msg.profile?.userRoleCode == "common_user") { if(config.streamerOnly && msg.profile.badges.size == 0) {
listener.sendChat("매니저만 이 명령어를 사용할 수 있습니다.") handler.sendChat("매니저만 이 명령어를 사용할 수 있습니다.")
return return
} }
@ -230,34 +236,34 @@ class MessageHandler(
val songs = SongListService.getSong(user) val songs = SongListService.getSong(user)
if(songs.size >= config.queueLimit) { if(songs.size >= config.queueLimit) {
listener.sendChat("더이상 노래를 신청할 수 없습니다. 잠시 뒤 다시 시도해주세요!") handler.sendChat("더이상 노래를 신청할 수 없습니다. 잠시 뒤 다시 시도해주세요!")
return return
} }
if(songs.filter { it.uid == msg.userId }.size >= config.personalLimit) { if(songs.filter { it.uid == msg.senderChannelId }.size >= config.personalLimit) {
listener.sendChat("더이상 노래를 신청할 수 없습니다. 잠시 뒤 다시 시도해주세요!") handler.sendChat("더이상 노래를 신청할 수 없습니다. 잠시 뒤 다시 시도해주세요!")
return return
} }
try { try {
val video = getYoutubeVideo(url) val video = getYoutubeVideo(url)
if (video == null) { if (video == null) {
listener.sendChat("유튜브에서 찾을 수 없어요!") handler.sendChat("유튜브에서 찾을 수 없어요!")
return return
} }
if (songs.any { it.url == video.url }) { if (songs.any { it.url == video.url }) {
listener.sendChat("같은 노래가 이미 신청되어 있습니다.") handler.sendChat("같은 노래가 이미 신청되어 있습니다.")
return return
} }
if (video.length > 600) { if (video.length > 600) {
listener.sendChat("10분이 넘는 노래는 신청할 수 없습니다.") handler.sendChat("10분이 넘는 노래는 신청할 수 없습니다.")
return return
} }
SongListService.saveSong( SongListService.saveSong(
user, user,
msg.userId, msg.senderChannelId,
video.url, video.url,
video.name, video.name,
video.author, video.author,
@ -269,31 +275,31 @@ class MessageHandler(
SongEvent( SongEvent(
user.token, user.token,
SongType.ADD, SongType.ADD,
msg.userId, msg.senderChannelId,
null, null,
video, video,
) )
) )
} }
listener.sendChat("노래가 추가되었습니다. ${video.name} - ${video.author}") handler.sendChat("노래가 추가되었습니다. ${video.name} - ${video.author}")
} catch(e: Exception) { } catch(e: Exception) {
listener.sendChat("유튜브 영상 주소로 다시 신청해주세요!") handler.sendChat("유튜브 영상 주소로 다시 신청해주세요!")
logger.info(e.stackTraceToString()) logger.info(e.stackTraceToString())
} }
} }
private fun songListCommand(msg: ChatMessage, user: User) { private fun songListCommand(msg: SessionChatMessage, user: User) {
if(SongConfigService.getConfig(user).disabled) { if(SongConfigService.getConfig(user).disabled) {
return return
} }
listener.sendChat("리스트는 여기입니다. https://nabot.mori.space/songs/${user.token}") handler.sendChat("리스트는 여기입니다. https://nabot.mori.space/songs/${user.token}")
} }
private fun songStartCommand(msg: ChatMessage, user: User) { private fun songStartCommand(msg: SessionChatMessage, user: User) {
if (msg.profile?.userRoleCode == "common_user") { if (msg.profile?.badges?.size == 0) {
listener.sendChat("매니저만 이 명령어를 사용할 수 있습니다.") handler.sendChat("매니저만 이 명령어를 사용할 수 있습니다.")
return return
} }
@ -306,28 +312,28 @@ class MessageHandler(
} }
} }
} else { } else {
listener.sendChat("나봇 홈페이지의 노래목록 페이지를 이용해주세요! 디스코드 연동을 하시면 DM으로 바로 전송됩니다.") handler.sendChat("나봇 홈페이지의 노래목록 페이지를 이용해주세요! 디스코드 연동을 하시면 DM으로 바로 전송됩니다.")
} }
} }
internal fun handle(msg: ChatMessage, user: User) { internal fun handle(msg: SessionChatMessage, user: User) {
if(msg.userId == ChzzkHandler.botUid) return if(msg.senderChannelId == ChzzkHandler.botUid) return
val commandKey = msg.content.split(' ')[0] val commandKey = msg.content.split(' ')[0]
commands[commandKey.lowercase()]?.let { it(msg, user) } commands[commandKey.lowercase()]?.let { it(msg, user) }
} }
private fun replaceCounters(chat: Pair<String, String>, user: User, msg: ChatMessage, listener: ChzzkChat, userName: String): String { private fun replaceCounters(chat: Pair<String, String>, user: User, msg: SessionChatMessage, userName: String): String {
var result = chat.first var result = chat.first
var isFail = false var isFail = false
// Replace dailyCounterPattern // Replace dailyCounterPattern
result = dailyCounterPattern.replace(result) { matchResult -> result = dailyCounterPattern.replace(result) { matchResult ->
val name = matchResult.groupValues[1] val name = matchResult.groupValues[1]
val dailyCounter = CounterService.getDailyCounterValue(name, msg.userId, user) val dailyCounter = CounterService.getDailyCounterValue(name, msg.senderChannelId, user)
if (dailyCounter.second) { if (dailyCounter.second) {
CounterService.updateDailyCounterValue(name, msg.userId, 1, user).first.toString() CounterService.updateDailyCounterValue(name, msg.senderChannelId, 1, user).first.toString()
} else { } else {
isFail = true isFail = true
dailyCounter.first.toString() dailyCounter.first.toString()
@ -339,7 +345,7 @@ class MessageHandler(
result = chat.second result = chat.second
result = dailyCounterPattern.replace(result) { matchResult -> result = dailyCounterPattern.replace(result) { matchResult ->
val name = matchResult.groupValues[1] val name = matchResult.groupValues[1]
val dailyCounter = CounterService.getDailyCounterValue(name, msg.userId, user) val dailyCounter = CounterService.getDailyCounterValue(name, msg.senderChannelId, user)
dailyCounter.first.toString() dailyCounter.first.toString()
} }
} }
@ -347,7 +353,7 @@ class MessageHandler(
// Replace followPattern // Replace followPattern
result = followPattern.replace(result) { _ -> result = followPattern.replace(result) { _ ->
try { try {
val followingDate = getFollowDate(listener.chatId, msg.userId) val followingDate = getFollowDate(channel.channelId, msg.senderChannelId)
.content?.streamingProperty?.following?.followDate .content?.streamingProperty?.following?.followDate
val period = followingDate?.let { val period = followingDate?.let {
@ -383,7 +389,7 @@ class MessageHandler(
// Replace personalCounterPattern // Replace personalCounterPattern
result = personalCounterPattern.replace(result) { matchResult -> result = personalCounterPattern.replace(result) { matchResult ->
val name = matchResult.groupValues[1] val name = matchResult.groupValues[1]
CounterService.updatePersonalCounterValue(name, msg.userId, 1, user).toString() CounterService.updatePersonalCounterValue(name, msg.senderChannelId, 1, user).toString()
} }
// Replace namePattern // Replace namePattern
@ -391,5 +397,4 @@ class MessageHandler(
return result return result
} }
} }

View File

@ -0,0 +1,55 @@
package space.mori.chzzk_bot.chatbot.utils
import com.google.gson.Gson
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.RequestBody.Companion.toRequestBody
import space.mori.chzzk_bot.common.utils.client
import xyz.r2turntrue.chzzk4j.ChzzkClient
import java.io.IOException
val client = OkHttpClient.Builder()
.addNetworkInterceptor { chain ->
chain.proceed(
chain.request()
.newBuilder()
.header("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36")
.build()
)
}
.build()
val gson = Gson()
data class RefreshTokenResponse(
val accessToken: String,
val refreshToken: String,
val expiresIn: Int,
val tokenType: String = "Bearer",
val scope: String
)
fun ChzzkClient.refreshAccessToken(refreshToken: String): Pair<String, String> {
val url = "https://openapi.chzzk.naver.com/auth/v1/token"
val request = Request.Builder()
.url(url)
.header("Content-Type", "application/json")
.post(gson.toJson(mapOf(
"grantType" to "refresh_token",
"refreshToken" to refreshToken,
"clientId" to this.apiClientId,
"clientSecret" to this.apiSecret
)).toRequestBody())
.build()
client.newCall(request).execute().use { response ->
try {
if(!response.isSuccessful) throw IOException("Unexpected code ${response.code}")
val body = response.body?.string()
val data = gson.fromJson(body, RefreshTokenResponse::class.java)
return Pair(data.accessToken, data.refreshToken)
} catch(e: Exception) {
throw e
}
}
}

View File

@ -23,7 +23,7 @@ dependencies {
api("com.zaxxer:HikariCP:6.1.0") api("com.zaxxer:HikariCP:6.1.0")
// https://mvnrepository.com/artifact/ch.qos.logback/logback-classic // https://mvnrepository.com/artifact/ch.qos.logback/logback-classic
implementation("ch.qos.logback:logback-classic:1.5.12") implementation("ch.qos.logback:logback-classic:1.5.13")
// https://mvnrepository.com/artifact/org.mariadb.jdbc/mariadb-java-client // https://mvnrepository.com/artifact/org.mariadb.jdbc/mariadb-java-client
implementation("org.mariadb.jdbc:mariadb-java-client:3.5.0") implementation("org.mariadb.jdbc:mariadb-java-client:3.5.0")

View File

@ -5,7 +5,8 @@ enum class TimerType(var value: Int) {
TIMER(1), TIMER(1),
REMOVE(2), REMOVE(2),
STREAM_OFF(50) STREAM_OFF(50),
ACK(51)
} }
class TimerEvent( class TimerEvent(

View File

@ -15,6 +15,8 @@ object Users: IntIdTable("users") {
val liveAlertMessage = text("live_alert_message").nullable() val liveAlertMessage = text("live_alert_message").nullable()
val isDisableStartupMsg = bool("is_disable_startup_msg").default(false) val isDisableStartupMsg = bool("is_disable_startup_msg").default(false)
val isDisabled = bool("is_disabled").default(false) val isDisabled = bool("is_disabled").default(false)
val accessToken = varchar("access_token", 255).nullable()
val refreshToken = varchar("refresh_token", 255).nullable()
} }
class User(id: EntityID<Int>) : IntEntity(id) { class User(id: EntityID<Int>) : IntEntity(id) {
@ -29,6 +31,9 @@ class User(id: EntityID<Int>) : IntEntity(id) {
var isDisableStartupMsg by Users.isDisableStartupMsg var isDisableStartupMsg by Users.isDisableStartupMsg
var isDisabled by Users.isDisabled var isDisabled by Users.isDisabled
var accessToken by Users.accessToken
var refreshToken by Users.refreshToken
// 유저가 가진 매니저들 // 유저가 가진 매니저들
var managers by User.via(UserManagers.user, UserManagers.manager) var managers by User.via(UserManagers.user, UserManagers.manager)

View File

@ -97,4 +97,19 @@ object UserService {
user user
} }
} }
fun setAccessToken(user: User, accessToken: String): User {
return transaction {
user.accessToken = accessToken
user
}
}
fun setRefreshToken(user: User, accessToken: String, refreshToken: String): User {
return transaction {
user.accessToken = accessToken
user.refreshToken = refreshToken
user
}
}
} }

View File

@ -10,7 +10,7 @@ repositories {
mavenCentral() mavenCentral()
} }
val ktorVersion = "3.0.1" val ktorVersion = "3.1.3"
dependencies { dependencies {
implementation("io.ktor:ktor-server-core:$ktorVersion") implementation("io.ktor:ktor-server-core:$ktorVersion")

View File

@ -25,7 +25,6 @@ import kotlinx.serialization.json.Json
import space.mori.chzzk_bot.common.services.UserService import space.mori.chzzk_bot.common.services.UserService
import space.mori.chzzk_bot.webserver.routes.* import space.mori.chzzk_bot.webserver.routes.*
import space.mori.chzzk_bot.webserver.utils.DiscordRatelimits import space.mori.chzzk_bot.webserver.utils.DiscordRatelimits
import wsSongListRoutes
import java.math.BigInteger import java.math.BigInteger
import java.security.SecureRandom import java.security.SecureRandom
import java.time.Duration import java.time.Duration
@ -192,6 +191,7 @@ val server = embeddedServer(Netty, port = 8080, ) {
val userInfo = getChzzkUser(tokenResponse.content.accessToken) val userInfo = getChzzkUser(tokenResponse.content.accessToken)
if(userInfo.content != null) { if(userInfo.content != null) {
val user = UserService.getUser(userInfo.content.channelId)
call.sessions.set( call.sessions.set(
UserSession( UserSession(
session.state, session.state,
@ -199,6 +199,7 @@ val server = embeddedServer(Netty, port = 8080, ) {
listOf() listOf()
) )
) )
user?.let { UserService.setRefreshToken(it, tokenResponse.content.accessToken, tokenResponse.content.refreshToken ?: "") }
call.respondRedirect(getFrontendURL("")) call.respondRedirect(getFrontendURL(""))
} }
} catch (e: Exception) { } catch (e: Exception) {

View File

@ -1,115 +1,54 @@
package space.mori.chzzk_bot.webserver.routes
import io.ktor.client.plugins.websocket.WebSocketException
import io.ktor.server.application.*
import io.ktor.server.routing.* import io.ktor.server.routing.*
import io.ktor.server.sessions.* import io.ktor.server.sessions.*
import io.ktor.server.websocket.* import io.ktor.server.websocket.*
import io.ktor.util.logging.Logger
import io.ktor.websocket.* import io.ktor.websocket.*
import io.ktor.websocket.Frame.* import kotlinx.coroutines.*
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.channels.ClosedReceiveChannelException import kotlinx.coroutines.channels.ClosedReceiveChannelException
import kotlinx.coroutines.delay import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.launch import kotlinx.coroutines.sync.withLock
import kotlinx.serialization.Serializable import kotlinx.serialization.Serializable
import kotlinx.serialization.json.Json import kotlinx.serialization.json.Json
import org.koin.java.KoinJavaComponent.inject import org.koin.java.KoinJavaComponent.inject
import org.slf4j.Logger
import org.slf4j.LoggerFactory import org.slf4j.LoggerFactory
import space.mori.chzzk_bot.common.events.* import space.mori.chzzk_bot.common.events.*
import space.mori.chzzk_bot.common.models.SongList import space.mori.chzzk_bot.common.models.SongList
import space.mori.chzzk_bot.common.models.SongLists.uid
import space.mori.chzzk_bot.common.models.User import space.mori.chzzk_bot.common.models.User
import space.mori.chzzk_bot.common.services.SongConfigService
import space.mori.chzzk_bot.common.services.SongListService import space.mori.chzzk_bot.common.services.SongListService
import space.mori.chzzk_bot.common.services.UserService import space.mori.chzzk_bot.common.services.UserService
import space.mori.chzzk_bot.common.utils.YoutubeVideo import space.mori.chzzk_bot.common.utils.YoutubeVideo
import space.mori.chzzk_bot.common.utils.getYoutubeVideo import space.mori.chzzk_bot.common.utils.getYoutubeVideo
import space.mori.chzzk_bot.webserver.UserSession import space.mori.chzzk_bot.webserver.UserSession
import space.mori.chzzk_bot.webserver.routes.SongResponse
import space.mori.chzzk_bot.webserver.routes.toSerializable
import space.mori.chzzk_bot.webserver.utils.CurrentSong import space.mori.chzzk_bot.webserver.utils.CurrentSong
import java.io.IOException
import java.util.concurrent.ConcurrentHashMap import java.util.concurrent.ConcurrentHashMap
fun Routing.wsSongListRoutes() { fun Routing.wsSongListRoutes() {
val sessions = ConcurrentHashMap<String, WebSocketServerSession>()
val status = ConcurrentHashMap<String, SongType>()
val logger = LoggerFactory.getLogger("WSSongListRoutes") val logger = LoggerFactory.getLogger("WSSongListRoutes")
val dispatcher: CoroutinesEventBus by inject(CoroutinesEventBus::class.java) val dispatcher: CoroutinesEventBus by inject(CoroutinesEventBus::class.java)
val songListScope = CoroutineScope(SupervisorJob() + Dispatchers.Default)
fun addSession(uid: String, session: WebSocketServerSession) { // Manage all active sessions
if (sessions[uid] != null) { val sessionHandlers = ConcurrentHashMap<String, SessionHandler>()
CoroutineScope(Dispatchers.Default).launch {
sessions[uid]?.close( // Handle application shutdown
CloseReason(CloseReason.Codes.VIOLATED_POLICY, "Duplicated sessions.") environment.monitor.subscribe(ApplicationStopped) {
) sessionHandlers.values.forEach {
songListScope.launch {
it.close(CloseReason(CloseReason.Codes.NORMAL, "Server shutting down"))
} }
} }
sessions[uid] = session
}
fun removeSession(uid: String) {
sessions.remove(uid)
}
suspend fun waitForAck(ws: WebSocketServerSession, expectedType: Int): Boolean {
val timeout = 5000L // 5 seconds timeout
val startTime = System.currentTimeMillis()
while (System.currentTimeMillis() - startTime < timeout) {
for (frame in ws.incoming) {
if (frame is Text) {
val message = frame.readText()
if(message == "ping") {
return true
}
val data = Json.decodeFromString<SongRequest>(message)
if (data.type == SongType.ACK.value) {
return true // ACK received
}
}
}
delay(100) // Check every 100 ms
}
return false // Timeout
}
suspend fun sendWithRetry(uid: String, res: SongResponse, maxRetries: Int = 5, delayMillis: Long = 3000L) {
var attempt = 0
var sentSuccessfully = false
while (attempt < maxRetries && !sentSuccessfully) {
val ws = sessions[uid]
try {
if(ws == null) {
delay(delayMillis)
continue
}
// Attempt to send the message
ws.sendSerialized(res)
logger.debug("Message sent successfully to $uid on attempt $attempt")
// Wait for ACK
val ackReceived = waitForAck(ws, res.type)
if (ackReceived == true) {
sentSuccessfully = true
} else {
logger.warn("ACK not received for message to $uid on attempt $attempt.")
}
} catch (e: Exception) {
attempt++
logger.warn("Failed to send message to $uid on attempt $attempt. Retrying in $delayMillis ms.")
logger.warn(e.stackTraceToString())
} finally {
// Wait before retrying
delay(delayMillis)
}
}
if (!sentSuccessfully) {
logger.error("Failed to send message to $uid after $maxRetries attempts.")
}
} }
// WebSocket endpoint
webSocket("/songlist") { webSocket("/songlist") {
val session = call.sessions.get<UserSession>() val session = call.sessions.get<UserSession>()
val user = session?.id?.let { UserService.getUser(it) } val user: User? = session?.id?.let { UserService.getUser(it) }
if (user == null) { if (user == null) {
close(CloseReason(CloseReason.Codes.CANNOT_ACCEPT, "Invalid SID")) close(CloseReason(CloseReason.Codes.CANNOT_ACCEPT, "Invalid SID"))
return@webSocket return@webSocket
@ -117,175 +56,291 @@ fun Routing.wsSongListRoutes() {
val uid = user.token val uid = user.token
addSession(uid, this) // Ensure only one session per user
sessionHandlers[uid]?.close(CloseReason(CloseReason.Codes.VIOLATED_POLICY, "Another session is already active."))
if (status[uid] == SongType.STREAM_OFF) { val handler = SessionHandler(uid, this, dispatcher, logger)
CoroutineScope(Dispatchers.Default).launch { sessionHandlers[uid] = handler
sendSerialized(SongResponse(
SongType.STREAM_OFF.value,
uid,
null,
null,
null,
))
}
removeSession(uid)
}
// Initialize session
handler.initialize()
// Listen for incoming frames
try { try {
for (frame in incoming) { for (frame in incoming) {
when (frame) { when (frame) {
is Text -> { is Frame.Text -> handler.handleTextFrame(frame.readText())
if (frame.readText().trim() == "ping") { is Frame.Ping -> send(Frame.Pong(frame.data))
send("pong") else -> Unit
} else {
val data = frame.readText().let { Json.decodeFromString<SongRequest>(it) }
// Handle song requests
handleSongRequest(data, user, dispatcher, logger)
}
}
is Ping -> send(Pong(frame.data))
else -> ""
} }
} }
} catch (e: ClosedReceiveChannelException) { } catch (e: ClosedReceiveChannelException) {
logger.error("Error in WebSocket: ${e.message}") logger.info("Session closed: ${e.message}")
} catch (e: IOException) {
logger.error("IO error: ${e.message}")
} catch (e: Exception) {
logger.error("Unexpected error: ${e.message}")
} finally { } finally {
removeSession(uid) sessionHandlers.remove(uid)
handler.close(CloseReason(CloseReason.Codes.NORMAL, "Session ended"))
} }
} }
dispatcher.subscribe(SongEvent::class) { // Subscribe to SongEvents
logger.debug("SongEvent: {} / {} {}", it.uid, it.type, it.current?.name) dispatcher.subscribe(SongEvent::class) { event ->
CoroutineScope(Dispatchers.Default).launch { val handler = sessionHandlers[event.uid]
val user = UserService.getUser(it.uid) songListScope.launch {
if (user != null) { handler?.sendSongResponse(event)
sendWithRetry(
user.token, SongResponse(
it.type.value,
it.uid,
it.reqUid,
it.current?.toSerializable(),
it.next?.toSerializable(),
it.delUrl
)
)
}
} }
} }
dispatcher.subscribe(TimerEvent::class) { // Subscribe to TimerEvents
if (it.type == TimerType.STREAM_OFF) { dispatcher.subscribe(TimerEvent::class) { event ->
CoroutineScope(Dispatchers.Default).launch { if (event.type == TimerType.STREAM_OFF) {
val user = UserService.getUser(it.uid) val handler = sessionHandlers[event.uid]
if (user != null) { songListScope.launch {
sendWithRetry( handler?.sendTimerOff()
user.token, SongResponse(
it.type.value,
it.uid,
null,
null,
null,
)
)
}
} }
} }
} }
} }
suspend fun handleSongRequest( class SessionHandler(
data: SongRequest, private val uid: String,
user: User, private val session: WebSocketServerSession,
dispatcher: CoroutinesEventBus, private val dispatcher: CoroutinesEventBus,
logger: Logger private val logger: Logger
) { ) {
if (data.maxQueue != null && data.maxQueue > 0) SongConfigService.updateQueueLimit(user, data.maxQueue) private val ackMap = ConcurrentHashMap<String, CompletableDeferred<Boolean>>()
if (data.maxUserLimit != null && data.maxUserLimit > 0) SongConfigService.updatePersonalLimit(user, data.maxUserLimit) private val sessionMutex = Mutex()
if (data.isStreamerOnly != null) SongConfigService.updateStreamerOnly(user, data.isStreamerOnly) private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Default)
if (data.isDisabled != null) SongConfigService.updateDisabled(user, data.isDisabled)
when (data.type) { suspend fun initialize() {
SongType.ADD.value -> { // Send initial status if needed,
data.url?.let { url -> // For example, send STREAM_OFF if applicable
try { // This can be extended based on your requirements
val youtubeVideo = getYoutubeVideo(url) }
if (youtubeVideo != null) {
CoroutineScope(Dispatchers.Default).launch { suspend fun handleTextFrame(text: String) {
SongListService.saveSong( if (text.trim() == "ping") {
user, session.send("pong")
user.token, return
url, }
youtubeVideo.name,
youtubeVideo.author, val data = try {
youtubeVideo.length, Json.decodeFromString<SongRequest>(text)
user.username } catch (e: Exception) {
) logger.warn("Failed to decode SongRequest: ${e.message}")
dispatcher.post( return
SongEvent( }
user.token,
SongType.ADD, when (data.type) {
user.token, SongType.ACK.value -> handleAck(data.uid)
CurrentSong.getSong(user), else -> handleSongRequest(data)
youtubeVideo }
) }
)
} private fun handleAck(requestUid: String) {
} ackMap[requestUid]?.complete(true)
} catch (e: Exception) { ackMap.remove(requestUid)
logger.debug("SongType.ADD Error: $uid $e") }
private fun handleSongRequest(data: SongRequest) {
scope.launch {
SongRequestProcessor.process(data, uid, dispatcher, this@SessionHandler, logger)
}
}
suspend fun sendSongResponse(event: SongEvent) {
val response = SongResponse(
type = event.type.value,
uid = event.uid,
reqUid = event.reqUid,
current = event.current?.toSerializable(),
next = event.next?.toSerializable(),
delUrl = event.delUrl
)
sendWithRetry(response)
}
suspend fun sendTimerOff() {
val response = SongResponse(
type = TimerType.STREAM_OFF.value,
uid = uid,
reqUid = null,
current = null,
next = null,
delUrl = null
)
sendWithRetry(response)
}
private suspend fun sendWithRetry(res: SongResponse, maxRetries: Int = 5, delayMillis: Long = 3000L) {
var attempt = 0
while (attempt < maxRetries) {
try {
session.sendSerialized(res)
val ackDeferred = CompletableDeferred<Boolean>()
ackMap[res.uid] = ackDeferred
val ackReceived = withTimeoutOrNull(5000L) { ackDeferred.await() } ?: false
if (ackReceived) {
logger.debug("ACK received for message to $uid on attempt $attempt.")
return
} else {
logger.warn("ACK not received for message to $uid on attempt $attempt.")
} }
} catch (e: IOException) {
logger.warn("Failed to send message to $uid on attempt $attempt: ${e.message}")
if (e is WebSocketException) {
close(CloseReason(CloseReason.Codes.PROTOCOL_ERROR, "WebSocket error"))
return
}
} catch (e: CancellationException) {
throw e
} catch (e: Exception) {
logger.warn("Unexpected error while sending message to $uid on attempt $attempt: ${e.message}")
}
attempt++
delay(delayMillis)
}
logger.error("Failed to send message to $uid after $maxRetries attempts.")
}
suspend fun close(reason: CloseReason) {
try {
session.close(reason)
} catch (e: Exception) {
logger.warn("Error closing session: ${e.message}")
}
}
}
object SongRequestProcessor {
private val songMutex = Mutex()
suspend fun process(
data: SongRequest,
uid: String,
dispatcher: CoroutinesEventBus,
handler: SessionHandler,
logger: Logger
) {
val user = UserService.getUser(uid) ?: return
when (data.type) {
SongType.ADD.value -> handleAdd(data, user, dispatcher, handler, logger)
SongType.REMOVE.value -> handleRemove(data, user, dispatcher, logger)
SongType.NEXT.value -> handleNext(user, dispatcher, logger)
else -> {
// Handle other types if necessary
} }
} }
SongType.REMOVE.value -> { }
data.url?.let { url ->
val songs = SongListService.getSong(user) private suspend fun handleAdd(
val exactSong = songs.firstOrNull { it.url == url } data: SongRequest,
if (exactSong != null) { user: User,
SongListService.deleteSong(user, exactSong.uid, exactSong.name) dispatcher: CoroutinesEventBus,
} handler: SessionHandler,
dispatcher.post( logger: Logger
SongEvent( ) {
user.token, val url = data.url ?: return
SongType.REMOVE, val youtubeVideo = getYoutubeVideo(url) ?: run {
null, logger.warn("Failed to fetch YouTube video for URL: $url")
null, return
null, }
url
) songMutex.withLock {
) SongListService.saveSong(
user,
user.token,
url,
youtubeVideo.name,
youtubeVideo.author,
youtubeVideo.length,
user.username
)
}
dispatcher.post(
SongEvent(
uid = user.token,
type = SongType.ADD,
reqUid = user.token,
current = CurrentSong.getSong(user),
next = youtubeVideo
)
)
}
private suspend fun handleRemove(
data: SongRequest,
user: User,
dispatcher: CoroutinesEventBus,
logger: Logger
) {
val url = data.url ?: return
songMutex.withLock {
val songs = SongListService.getSong(user)
val exactSong = songs.firstOrNull { it.url == url }
if (exactSong != null) {
SongListService.deleteSong(user, exactSong.uid, exactSong.name)
} }
} }
SongType.NEXT.value -> {
dispatcher.post(
SongEvent(
uid = user.token,
type = SongType.REMOVE,
delUrl = url,
reqUid = null,
current = null,
next = null,
)
)
}
private suspend fun handleNext(
user: User,
dispatcher: CoroutinesEventBus,
logger: Logger
) {
var song: SongList? = null
var youtubeVideo: YoutubeVideo? = null
songMutex.withLock {
val songList = SongListService.getSong(user) val songList = SongListService.getSong(user)
var song: SongList? = null
var youtubeVideo: YoutubeVideo? = null
if (songList.isNotEmpty()) { if (songList.isNotEmpty()) {
song = songList[0] song = songList[0]
SongListService.deleteSong(user, song.uid, song.name) SongListService.deleteSong(user, song.uid, song.name)
} }
song?.let {
youtubeVideo = YoutubeVideo(
song.url,
song.name,
song.author,
song.time
)
}
dispatcher.post(
SongEvent(
user.token,
SongType.NEXT,
song?.uid,
youtubeVideo
)
)
CurrentSong.setSong(user, youtubeVideo)
} }
song?.let {
youtubeVideo = YoutubeVideo(
it.url,
it.name,
it.author,
it.time
)
}
dispatcher.post(
SongEvent(
uid = user.token,
type = SongType.NEXT,
current = null,
next = youtubeVideo,
reqUid = null,
delUrl = null
)
)
CurrentSong.setSong(user, youtubeVideo)
} }
} }
@ -293,10 +348,10 @@ suspend fun handleSongRequest(
data class SongRequest( data class SongRequest(
val type: Int, val type: Int,
val uid: String, val uid: String,
val url: String?, val url: String? = null,
val maxQueue: Int?, val maxQueue: Int? = null,
val maxUserLimit: Int?, val maxUserLimit: Int? = null,
val isStreamerOnly: Boolean?, val isStreamerOnly: Boolean? = null,
val remove: Int?, val remove: Int? = null,
val isDisabled: Boolean?, val isDisabled: Boolean? = null
) )

View File

@ -1,14 +1,20 @@
package space.mori.chzzk_bot.webserver.routes package space.mori.chzzk_bot.webserver.routes
import io.ktor.server.application.ApplicationStopped
import io.ktor.server.routing.* import io.ktor.server.routing.*
import io.ktor.server.websocket.* import io.ktor.server.websocket.*
import io.ktor.websocket.* import io.ktor.websocket.*
import kotlinx.coroutines.CompletableDeferred
import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.cancel
import kotlinx.coroutines.channels.ClosedReceiveChannelException import kotlinx.coroutines.channels.ClosedReceiveChannelException
import kotlinx.coroutines.delay import kotlinx.coroutines.delay
import kotlinx.coroutines.launch import kotlinx.coroutines.launch
import kotlinx.coroutines.withTimeoutOrNull
import kotlinx.serialization.Serializable import kotlinx.serialization.Serializable
import kotlinx.serialization.json.Json
import org.koin.java.KoinJavaComponent.inject import org.koin.java.KoinJavaComponent.inject
import org.slf4j.LoggerFactory import org.slf4j.LoggerFactory
import space.mori.chzzk_bot.common.events.* import space.mori.chzzk_bot.common.events.*
@ -17,15 +23,20 @@ import space.mori.chzzk_bot.common.utils.YoutubeVideo
import java.util.concurrent.ConcurrentHashMap import java.util.concurrent.ConcurrentHashMap
import java.util.concurrent.ConcurrentLinkedQueue import java.util.concurrent.ConcurrentLinkedQueue
val songScope = CoroutineScope(SupervisorJob() + Dispatchers.Default)
fun Routing.wsSongRoutes() { fun Routing.wsSongRoutes() {
environment.monitor.subscribe(ApplicationStopped) {
songScope.cancel()
}
val sessions = ConcurrentHashMap<String, ConcurrentLinkedQueue<WebSocketServerSession>>() val sessions = ConcurrentHashMap<String, ConcurrentLinkedQueue<WebSocketServerSession>>()
val status = ConcurrentHashMap<String, SongType>() val status = ConcurrentHashMap<String, SongType>()
val logger = LoggerFactory.getLogger("WSSongRoutes") val logger = LoggerFactory.getLogger("WSSongRoutes")
val dispatcher: CoroutinesEventBus by inject(CoroutinesEventBus::class.java)
val ackMap = ConcurrentHashMap<String, ConcurrentHashMap<WebSocketServerSession, CompletableDeferred<Boolean>>>()
fun addSession(uid: String, session: WebSocketServerSession) { fun addSession(uid: String, session: WebSocketServerSession) {
sessions.computeIfAbsent(uid) { ConcurrentLinkedQueue() }.add(session) sessions.computeIfAbsent(uid) { ConcurrentLinkedQueue() }.add(session)
} }
fun removeSession(uid: String, session: WebSocketServerSession) { fun removeSession(uid: String, session: WebSocketServerSession) {
sessions[uid]?.remove(session) sessions[uid]?.remove(session)
if(sessions[uid]?.isEmpty() == true) { if(sessions[uid]?.isEmpty() == true) {
@ -42,27 +53,35 @@ fun Routing.wsSongRoutes() {
var attempt = 0 var attempt = 0
while (attempt < maxRetries) { while (attempt < maxRetries) {
try { try {
session.sendSerialized(message) // 메시지 전송 시도 session.sendSerialized(message)
return true // 성공하면 true 반환 val ackDeferred = CompletableDeferred<Boolean>()
ackMap.computeIfAbsent(message.uid) { ConcurrentHashMap() }[session] = ackDeferred
val ackReceived = withTimeoutOrNull(delayMillis) { ackDeferred.await() } ?: false
if (ackReceived) {
ackMap[message.uid]?.remove(session)
return true
} else {
attempt++
logger.warn("ACK not received for message to ${message.uid} on attempt $attempt.")
}
} catch (e: Exception) { } catch (e: Exception) {
attempt++ attempt++
logger.info("Failed to send message on attempt $attempt. Retrying in $delayMillis ms.") logger.info("Failed to send message on attempt $attempt. Retrying in $delayMillis ms.")
e.printStackTrace() e.printStackTrace()
delay(delayMillis) // 재시도 전 대기 delay(delayMillis)
} }
} }
return false // 재시도 실패 시 false 반환 return false
} }
fun broadcastMessage(userId: String, message: SongResponse) { fun broadcastMessage(userId: String, message: SongResponse) {
val userSessions = sessions[userId] val userSessions = sessions[userId]
userSessions?.forEach { session -> userSessions?.forEach { session ->
CoroutineScope(Dispatchers.Default).launch { songScope.launch {
val success = sendWithRetry(session, message) val success = sendWithRetry(session, message)
if (!success) { if (!success) {
println("Removing session for user $userId due to repeated failures.") logger.info("Removing session for user $userId due to repeated failures.")
userSessions.remove(session) // 실패 시 세션 제거 removeSession(userId, session)
} }
} }
} }
@ -71,19 +90,13 @@ fun Routing.wsSongRoutes() {
webSocket("/song/{uid}") { webSocket("/song/{uid}") {
val uid = call.parameters["uid"] val uid = call.parameters["uid"]
val user = uid?.let { UserService.getUser(it) } val user = uid?.let { UserService.getUser(it) }
if (uid == null) { if (uid == null || user == null) {
close(CloseReason(CloseReason.Codes.CANNOT_ACCEPT, "Invalid UID")) close(CloseReason(CloseReason.Codes.CANNOT_ACCEPT, "Invalid UID"))
return@webSocket return@webSocket
} }
if (user == null) {
close(CloseReason(CloseReason.Codes.CANNOT_ACCEPT, "Invalid UID"))
return@webSocket
}
addSession(uid, this) addSession(uid, this)
if(status[uid] == SongType.STREAM_OFF) { if(status[uid] == SongType.STREAM_OFF) {
CoroutineScope(Dispatchers.Default).launch { songScope.launch {
sendSerialized(SongResponse( sendSerialized(SongResponse(
SongType.STREAM_OFF.value, SongType.STREAM_OFF.value,
uid, uid,
@ -93,33 +106,36 @@ fun Routing.wsSongRoutes() {
)) ))
} }
} }
try { try {
for (frame in incoming) { for (frame in incoming) {
when(frame) { when(frame) {
is Frame.Text -> { is Frame.Text -> {
if(frame.readText().trim() == "ping") { val text = frame.readText().trim()
if(text == "ping") {
send("pong") send("pong")
} else {
val data = Json.decodeFromString<SongRequest>(text)
if (data.type == SongType.ACK.value) {
ackMap[data.uid]?.get(this)?.complete(true)
ackMap[data.uid]?.remove(this)
}
} }
} }
is Frame.Ping -> send(Frame.Pong(frame.data)) is Frame.Ping -> send(Frame.Pong(frame.data))
else -> { else -> {}
}
} }
} }
} catch(e: ClosedReceiveChannelException) { } catch(e: ClosedReceiveChannelException) {
logger.error("Error in WebSocket: ${e.message}") logger.error("Error in WebSocket: ${e.message}")
} finally { } finally {
removeSession(uid, this) removeSession(uid, this)
ackMap[uid]?.remove(this)
} }
} }
val dispatcher: CoroutinesEventBus by inject(CoroutinesEventBus::class.java)
dispatcher.subscribe(SongEvent::class) { dispatcher.subscribe(SongEvent::class) {
logger.debug("SongEvent: {} / {} {}", it.uid, it.type, it.current?.name) logger.debug("SongEvent: {} / {} {}", it.uid, it.type, it.current?.name)
CoroutineScope(Dispatchers.Default).launch { songScope.launch {
broadcastMessage(it.uid, SongResponse( broadcastMessage(it.uid, SongResponse(
it.type.value, it.type.value,
it.uid, it.uid,
@ -132,7 +148,7 @@ fun Routing.wsSongRoutes() {
} }
dispatcher.subscribe(TimerEvent::class) { dispatcher.subscribe(TimerEvent::class) {
if(it.type == TimerType.STREAM_OFF) { if(it.type == TimerType.STREAM_OFF) {
CoroutineScope(Dispatchers.Default).launch { songScope.launch {
broadcastMessage(it.uid, SongResponse( broadcastMessage(it.uid, SongResponse(
it.type.value, it.type.value,
it.uid, it.uid,
@ -144,7 +160,6 @@ fun Routing.wsSongRoutes() {
} }
} }
} }
@Serializable @Serializable
data class SerializableYoutubeVideo( data class SerializableYoutubeVideo(
val url: String, val url: String,
@ -152,9 +167,7 @@ data class SerializableYoutubeVideo(
val author: String, val author: String,
val length: Int val length: Int
) )
fun YoutubeVideo.toSerializable() = SerializableYoutubeVideo(url, name, author, length) fun YoutubeVideo.toSerializable() = SerializableYoutubeVideo(url, name, author, length)
@Serializable @Serializable
data class SongResponse( data class SongResponse(
val type: Int, val type: Int,

View File

@ -1,13 +1,20 @@
package space.mori.chzzk_bot.webserver.routes package space.mori.chzzk_bot.webserver.routes
import io.ktor.server.application.ApplicationStopped
import io.ktor.server.routing.* import io.ktor.server.routing.*
import io.ktor.server.websocket.* import io.ktor.server.websocket.*
import io.ktor.websocket.* import io.ktor.websocket.*
import kotlinx.coroutines.CompletableDeferred
import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.cancel
import kotlinx.coroutines.channels.ClosedReceiveChannelException import kotlinx.coroutines.channels.ClosedReceiveChannelException
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch import kotlinx.coroutines.launch
import kotlinx.coroutines.withTimeoutOrNull
import kotlinx.serialization.Serializable import kotlinx.serialization.Serializable
import kotlinx.serialization.json.Json
import org.koin.java.KoinJavaComponent.inject import org.koin.java.KoinJavaComponent.inject
import org.slf4j.LoggerFactory import org.slf4j.LoggerFactory
import space.mori.chzzk_bot.common.events.* import space.mori.chzzk_bot.common.events.*
@ -17,14 +24,19 @@ import space.mori.chzzk_bot.webserver.utils.CurrentTimer
import java.util.concurrent.ConcurrentHashMap import java.util.concurrent.ConcurrentHashMap
import java.util.concurrent.ConcurrentLinkedQueue import java.util.concurrent.ConcurrentLinkedQueue
val timerScope = CoroutineScope(SupervisorJob() + Dispatchers.Default)
fun Routing.wsTimerRoutes() { fun Routing.wsTimerRoutes() {
environment.monitor.subscribe(ApplicationStopped) {
timerScope.cancel()
}
val sessions = ConcurrentHashMap<String, ConcurrentLinkedQueue<WebSocketServerSession>>() val sessions = ConcurrentHashMap<String, ConcurrentLinkedQueue<WebSocketServerSession>>()
val logger = LoggerFactory.getLogger("WSTimerRoutes") val logger = LoggerFactory.getLogger("WSTimerRoutes")
val dispatcher: CoroutinesEventBus by inject(CoroutinesEventBus::class.java)
val ackMap = ConcurrentHashMap<String, ConcurrentHashMap<WebSocketServerSession, CompletableDeferred<Boolean>>>()
fun addSession(uid: String, session: WebSocketServerSession) { fun addSession(uid: String, session: WebSocketServerSession) {
sessions.computeIfAbsent(uid) { ConcurrentLinkedQueue() }.add(session) sessions.computeIfAbsent(uid) { ConcurrentLinkedQueue() }.add(session)
} }
fun removeSession(uid: String, session: WebSocketServerSession) { fun removeSession(uid: String, session: WebSocketServerSession) {
sessions[uid]?.remove(session) sessions[uid]?.remove(session)
if(sessions[uid]?.isEmpty() == true) { if(sessions[uid]?.isEmpty() == true) {
@ -32,82 +44,132 @@ fun Routing.wsTimerRoutes() {
} }
} }
webSocket("/timer/{uid}") { suspend fun sendWithRetry(
val uid = call.parameters["uid"] session: WebSocketServerSession,
val user = uid?.let { UserService.getUser(it) } message: TimerResponse,
if (uid == null) { maxRetries: Int = 3,
close(CloseReason(CloseReason.Codes.CANNOT_ACCEPT, "Invalid UID")) delayMillis: Long = 2000L
return@webSocket ): Boolean {
} var attempt = 0
if (user == null) { while (attempt < maxRetries) {
close(CloseReason(CloseReason.Codes.CANNOT_ACCEPT, "Invalid UID")) try {
return@webSocket session.sendSerialized(message)
} val ackDeferred = CompletableDeferred<Boolean>()
ackMap.computeIfAbsent(message.uid) { ConcurrentHashMap() }[session] = ackDeferred
addSession(uid, this) val ackReceived = withTimeoutOrNull(delayMillis) { ackDeferred.await() } ?: false
val timer = CurrentTimer.getTimer(user) if (ackReceived) {
ackMap[message.uid]?.remove(session)
if(timer?.type == TimerType.STREAM_OFF) { return true
CoroutineScope(Dispatchers.Default).launch {
sendSerialized(TimerResponse(TimerType.STREAM_OFF.value, null))
}
} else {
CoroutineScope(Dispatchers.Default).launch {
if (timer == null) {
sendSerialized(
TimerResponse(
TimerConfigService.getConfig(user)?.option ?: TimerType.REMOVE.value,
null
)
)
} else { } else {
sendSerialized( attempt++
TimerResponse( logger.warn("ACK not received for message to ${message.uid} on attempt $attempt.")
timer.type.value, }
timer.time } catch (e: Exception) {
) attempt++
) logger.info("Failed to send message on attempt $attempt. Retrying in $delayMillis ms.")
e.printStackTrace()
delay(delayMillis)
}
}
return false
}
fun broadcastMessage(uid: String, message: TimerResponse) {
val userSessions = sessions[uid]
userSessions?.forEach { session ->
timerScope.launch {
val success = sendWithRetry(session, message.copy(uid = uid))
if (!success) {
logger.info("Removing session for user $uid due to repeated failures.")
removeSession(uid, session)
} }
} }
} }
}
webSocket("/timer/{uid}") {
val uid = call.parameters["uid"]
val user = uid?.let { UserService.getUser(it) }
if (uid == null || user == null) {
close(CloseReason(CloseReason.Codes.CANNOT_ACCEPT, "Invalid UID"))
return@webSocket
}
addSession(uid, this)
val timer = CurrentTimer.getTimer(user)
if (timer?.type == TimerType.STREAM_OFF) {
timerScope.launch {
sendSerialized(TimerResponse(TimerType.STREAM_OFF.value, null, uid))
}
} else {
timerScope.launch {
if(timer?.type == TimerType.STREAM_OFF) {
sendSerialized(TimerResponse(TimerType.STREAM_OFF.value, null, uid))
} else {
if (timer == null) {
sendSerialized(
TimerResponse(
TimerConfigService.getConfig(user)?.option ?: TimerType.REMOVE.value,
null,
uid
)
)
} else {
sendSerialized(
TimerResponse(
timer.type.value,
timer.time,
uid
)
)
}
}
}
}
try { try {
for (frame in incoming) { for (frame in incoming) {
when(frame) { when(frame) {
is Frame.Text -> { is Frame.Text -> {
if(frame.readText().trim() == "ping") { val text = frame.readText().trim()
if(text == "ping") {
send("pong") send("pong")
} else {
val data = Json.decodeFromString<TimerRequest>(text)
if (data.type == TimerType.ACK.value) {
ackMap[data.uid]?.get(this)?.complete(true)
ackMap[data.uid]?.remove(this)
}
} }
} }
is Frame.Ping -> send(Frame.Pong(frame.data)) is Frame.Ping -> send(Frame.Pong(frame.data))
else -> { else -> {}
}
} }
} }
} catch(e: ClosedReceiveChannelException) { } catch(e: ClosedReceiveChannelException) {
logger.error("Error in WebSocket: ${e.message}") logger.error("Error in WebSocket: ${e.message}")
} finally { } finally {
removeSession(uid, this) removeSession(uid, this)
ackMap[uid]?.remove(this)
} }
} }
val dispatcher: CoroutinesEventBus by inject(CoroutinesEventBus::class.java)
dispatcher.subscribe(TimerEvent::class) { dispatcher.subscribe(TimerEvent::class) {
logger.debug("TimerEvent: {} / {}", it.uid, it.type) logger.debug("TimerEvent: {} / {}", it.uid, it.type)
val user = UserService.getUser(it.uid) val user = UserService.getUser(it.uid)
CurrentTimer.setTimer(user!!, it) CurrentTimer.setTimer(user!!, it)
CoroutineScope(Dispatchers.Default).launch { timerScope.launch {
sessions[it.uid]?.forEach { ws -> broadcastMessage(it.uid, TimerResponse(it.type.value, it.time ?: "", it.uid))
ws.sendSerialized(TimerResponse(it.type.value, it.time ?: ""))
}
} }
} }
} }
@Serializable @Serializable
data class TimerResponse( data class TimerResponse(
val type: Int, val type: Int,
val time: String? val time: String?,
val uid: String
)
@Serializable
data class TimerRequest(
val type: Int,
val uid: String
) )