mirror of
https://github.com/dalbodeule/chibot-chzzk-bot.git
synced 2025-08-11 06:41:14 +00:00
Compare commits
43 Commits
8a429172cf
...
develop
Author | SHA1 | Date | |
---|---|---|---|
|
b2f449bf65 | ||
|
5e3a350e15 | ||
|
8a0a507e5b | ||
|
1c4b818a85 | ||
|
83b5eaf345 | ||
|
b0be81df20 | ||
|
a99f3b342a | ||
|
a9d3ad436b | ||
|
53757476a7 | ||
|
27810c0b7f | ||
|
7257100adc | ||
|
f29370a31f | ||
|
2c0c887ba1 | ||
|
5223cbe2b2 | ||
|
11f9895198 | ||
|
a18b83fcc8 | ||
|
30d5edc5fe | ||
|
0709b8f526 | ||
|
1465716e72 | ||
|
d0292e0aa6 | ||
|
b2ffd18126 | ||
|
5fa04a6725 | ||
|
f65c446bed | ||
|
729a88a2b3 | ||
|
a896269087 | ||
|
d92ad1cc51 | ||
|
8d54d21620 | ||
|
101db7d20c | ||
|
3c3b9a79a2 | ||
|
61a5f985c1 | ||
|
aa95976005 | ||
|
c5a98943c0 | ||
|
8230762053 | ||
|
d07cdb6ae8 | ||
|
9c15c8f10d | ||
|
5a7f78ff3e | ||
|
7a84a9e437 | ||
|
02cede87f8 | ||
|
17d8065a34 | ||
|
0e8462eaf1 | ||
|
83cb68b63f | ||
|
c2bb653ee1 | ||
|
8ab1dc585e |
@@ -28,7 +28,7 @@ repositories {
|
||||
|
||||
dependencies {
|
||||
// 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
|
||||
implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.9.0")
|
||||
|
@@ -16,10 +16,10 @@ dependencies {
|
||||
}
|
||||
|
||||
// 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
|
||||
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
|
||||
implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.9.0")
|
||||
|
@@ -1,29 +1,34 @@
|
||||
package space.mori.chzzk_bot.chatbot.chzzk
|
||||
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.DelicateCoroutinesApi
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.GlobalScope
|
||||
import kotlinx.coroutines.delay
|
||||
import kotlinx.coroutines.future.await
|
||||
import kotlinx.coroutines.launch
|
||||
import org.koin.java.KoinJavaComponent.inject
|
||||
import org.slf4j.Logger
|
||||
import org.slf4j.LoggerFactory
|
||||
import space.mori.chzzk_bot.chatbot.chzzk.Connector.chzzk
|
||||
import space.mori.chzzk_bot.chatbot.chzzk.Connector.getChannel
|
||||
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.models.User
|
||||
import space.mori.chzzk_bot.common.services.LiveStatusService
|
||||
import space.mori.chzzk_bot.common.services.TimerConfigService
|
||||
import space.mori.chzzk_bot.common.services.UserService
|
||||
import space.mori.chzzk_bot.common.utils.*
|
||||
import xyz.r2turntrue.chzzk4j.chat.ChatEventListener
|
||||
import xyz.r2turntrue.chzzk4j.chat.ChatMessage
|
||||
import xyz.r2turntrue.chzzk4j.chat.ChzzkChat
|
||||
import xyz.r2turntrue.chzzk4j.ChzzkClient
|
||||
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.live.ChzzkLiveDetail
|
||||
import java.lang.Exception
|
||||
import java.net.SocketTimeoutException
|
||||
import java.time.LocalDateTime
|
||||
import java.nio.charset.Charset
|
||||
|
||||
object ChzzkHandler {
|
||||
private val handlers = mutableListOf<UserHandler>()
|
||||
@@ -33,19 +38,23 @@ object ChzzkHandler {
|
||||
private val dispatcher: CoroutinesEventBus by inject(CoroutinesEventBus::class.java)
|
||||
|
||||
fun addUser(chzzkChannel: ChzzkChannel, user: User) {
|
||||
handlers.add(UserHandler(chzzkChannel, logger, user, streamStartTime = null))
|
||||
handlers.add(UserHandler(chzzkChannel, logger, user, streamStartTime = LocalDateTime.now()))
|
||||
}
|
||||
|
||||
fun enable() {
|
||||
botUid = chzzk.loggedUser.userId
|
||||
botUid = Connector.client.fetchLoggedUser().userId
|
||||
UserService.getAllUsers().map {
|
||||
if(!it.isDisabled)
|
||||
chzzk.getChannel(it.token)?.let { token -> addUser(token, it) }
|
||||
try {
|
||||
Connector.getChannel(it.token)?.let { token -> addUser(token, it) }
|
||||
} catch(e: Exception) {
|
||||
logger.info("Exception: ${it.token}(${it.username}) not found. ${e.stackTraceToString()}")
|
||||
}
|
||||
}
|
||||
|
||||
handlers.forEach { handler ->
|
||||
val streamInfo = getStreamInfo(handler.listener.channelId)
|
||||
if (streamInfo.content?.status == "OPEN") handler.isActive(true, streamInfo)
|
||||
val streamInfo = Connector.getLive(handler.channel.channelId)
|
||||
if (streamInfo?.isOnline == true) handler.isActive(true, streamInfo)
|
||||
}
|
||||
|
||||
dispatcher.subscribe(UserRegisterEvent::class) {
|
||||
@@ -104,15 +113,15 @@ object ChzzkHandler {
|
||||
handlers.forEach {
|
||||
if (!running) return@forEach
|
||||
try {
|
||||
val streamInfo = getStreamInfo(it.channel.channelId)
|
||||
if (streamInfo.content?.status == "OPEN" && !it.isActive) {
|
||||
val streamInfo = Connector.getLive(it.channel.channelId)
|
||||
if (streamInfo?.isOnline == true && !it.isActive) {
|
||||
try {
|
||||
it.isActive(true, streamInfo)
|
||||
} catch(e: Exception) {
|
||||
logger.info("Exception: ${e.stackTraceToString()}")
|
||||
}
|
||||
}
|
||||
if (streamInfo.content?.status == "CLOSE" && it.isActive) it.isActive(false, streamInfo)
|
||||
if (streamInfo?.isOnline == false && it.isActive) it.isActive(false, streamInfo)
|
||||
} catch (e: SocketTimeoutException) {
|
||||
logger.info("Thread 1 Timeout: ${it.channel.channelName} / ${e.stackTraceToString()}")
|
||||
} catch (e: Exception) {
|
||||
@@ -132,19 +141,19 @@ object ChzzkHandler {
|
||||
handlers.forEach {
|
||||
if (!running) return@forEach
|
||||
try {
|
||||
val streamInfo = getStreamInfo(it.channel.channelId)
|
||||
if (streamInfo.content?.status == "OPEN" && !it.isActive) {
|
||||
val streamInfo = Connector.getLive(it.channel.channelId)
|
||||
if (streamInfo?.isOnline == true && !it.isActive) {
|
||||
try {
|
||||
it.isActive(true, streamInfo)
|
||||
} catch(e: Exception) {
|
||||
logger.info("Exception: ${e.stackTraceToString()}")
|
||||
}
|
||||
}
|
||||
if (streamInfo.content?.status == "CLOSE" && it.isActive) it.isActive(false, streamInfo)
|
||||
if (streamInfo?.isOnline == false && it.isActive) it.isActive(false, streamInfo)
|
||||
} catch (e: SocketTimeoutException) {
|
||||
logger.info("Thread 2 Timeout: ${it.channel.channelName} / ${e.stackTraceToString()}")
|
||||
logger.info("Thread 1 Timeout: ${it.channel.channelName} / ${e.stackTraceToString()}")
|
||||
} catch (e: Exception) {
|
||||
logger.info("Thread 2 Exception: ${it.channel.channelName} / ${e.stackTraceToString()}")
|
||||
logger.info("Thread 1 Exception: ${it.channel.channelName} / ${e.stackTraceToString()}")
|
||||
} finally {
|
||||
Thread.sleep(5000)
|
||||
}
|
||||
@@ -188,6 +197,7 @@ object ChzzkHandler {
|
||||
}
|
||||
}
|
||||
|
||||
@OptIn(DelicateCoroutinesApi::class)
|
||||
class UserHandler(
|
||||
val channel: ChzzkChannel,
|
||||
val logger: Logger,
|
||||
@@ -195,7 +205,9 @@ class UserHandler(
|
||||
var streamStartTime: LocalDateTime?,
|
||||
) {
|
||||
var messageHandler: MessageHandler
|
||||
var listener: ChzzkChat
|
||||
var client: ChzzkClient
|
||||
var listener: ChzzkUserSession
|
||||
var chatChannelId: String?
|
||||
|
||||
private val dispatcher: CoroutinesEventBus by inject(CoroutinesEventBus::class.java)
|
||||
private var _isActive: Boolean
|
||||
@@ -205,35 +217,54 @@ class UserHandler(
|
||||
}
|
||||
|
||||
init {
|
||||
listener = chzzk.chat(channel.channelId)
|
||||
.withAutoReconnect(true)
|
||||
.withChatListener(object : ChatEventListener {
|
||||
override fun onConnect(chat: ChzzkChat, isReconnecting: Boolean) {
|
||||
logger.info("${channel.channelName} - ${channel.channelId} / reconnected: $isReconnecting")
|
||||
}
|
||||
val user = UserService.getUser(channel.channelId)
|
||||
|
||||
override fun onError(ex: Exception) {
|
||||
logger.info("ChzzkChat error. ${channel.channelName} - ${channel.channelId}")
|
||||
logger.info(ex.stackTraceToString())
|
||||
if(user?.accessToken == null || user.refreshToken == null) {
|
||||
throw RuntimeException("AccessToken or RefreshToken is not valid.")
|
||||
}
|
||||
try {
|
||||
val tokens = Connector.client.refreshAccessToken(user.refreshToken!!)
|
||||
client = Connector.getClient(tokens.first, tokens.second)
|
||||
UserService.setRefreshToken(user, tokens.first, tokens.second)
|
||||
chatChannelId = getChzzkChannelId(channel.channelId)
|
||||
|
||||
override fun onChat(msg: ChatMessage) {
|
||||
if(!_isActive) return
|
||||
messageHandler.handle(msg, user)
|
||||
}
|
||||
|
||||
override fun onConnectionClosed(code: Int, reason: String?, remote: Boolean, tryingToReconnect: Boolean) {
|
||||
logger.info("ChzzkChat closed. ${channel.channelName} - ${channel.channelId}")
|
||||
logger.info("Reason: $reason / $tryingToReconnect")
|
||||
}
|
||||
})
|
||||
.build()
|
||||
client.loginAsync().join()
|
||||
listener = ChzzkSessionBuilder(client).buildUserSession()
|
||||
listener.createAndConnectAsync().join()
|
||||
messageHandler = MessageHandler(this@UserHandler)
|
||||
|
||||
listener.on(SessionChatMessageEvent::class.java) {
|
||||
messageHandler.handle(it.message, user)
|
||||
}
|
||||
|
||||
GlobalScope.launch {
|
||||
val timer = TimerConfigService.getConfig(user)
|
||||
if (timer?.option == TimerType.UPTIME.value)
|
||||
dispatcher.post(
|
||||
TimerEvent(
|
||||
channel.channelId,
|
||||
TimerType.UPTIME,
|
||||
getUptime(streamStartTime!!)
|
||||
)
|
||||
)
|
||||
else dispatcher.post(
|
||||
TimerEvent(
|
||||
channel.channelId,
|
||||
TimerType.entries.firstOrNull { it.value == timer?.option } ?: TimerType.REMOVE,
|
||||
null
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
} catch(e: Exception) {
|
||||
logger.error("Exception(${user.username}): ${e.stackTraceToString()}")
|
||||
throw RuntimeException("Exception: ${e.stackTraceToString()}")
|
||||
}
|
||||
}
|
||||
|
||||
internal fun disable() {
|
||||
listener.closeAsync()
|
||||
listener.disconnectAsync().join()
|
||||
_isActive = false
|
||||
}
|
||||
|
||||
internal fun reloadCommand() {
|
||||
@@ -247,7 +278,7 @@ class UserHandler(
|
||||
internal val isActive: Boolean
|
||||
get() = _isActive
|
||||
|
||||
internal fun isActive(value: Boolean, status: IData<IStreamInfo?>) {
|
||||
internal fun isActive(value: Boolean, status: ChzzkLiveDetail) {
|
||||
if(value) {
|
||||
CoroutineScope(Dispatchers.Default).launch {
|
||||
logger.info("${user.username} is live.")
|
||||
@@ -255,9 +286,9 @@ class UserHandler(
|
||||
reloadUser(UserService.getUser(user.id.value)!!)
|
||||
|
||||
logger.info("ChzzkChat connecting... ${channel.channelName} - ${channel.channelId}")
|
||||
listener.connectAsync().await()
|
||||
listener.subscribeAsync(ChzzkSessionSubscriptionType.CHAT).join()
|
||||
|
||||
streamStartTime = status.content?.openDate?.let { convertChzzkDateToLocalDateTime(it) }
|
||||
streamStartTime = LocalDateTime.now()
|
||||
|
||||
if(!_isActive) {
|
||||
_isActive = true
|
||||
@@ -281,7 +312,7 @@ class UserHandler(
|
||||
delay(5000L)
|
||||
try {
|
||||
if(!user.isDisableStartupMsg)
|
||||
listener.sendChat("${user.username} 님! 오늘도 열심히 방송하세요!")
|
||||
sendChat("${user.username} 님! 오늘도 열심히 방송하세요!")
|
||||
Discord.sendDiscord(user, status)
|
||||
} catch(e: Exception) {
|
||||
logger.info("Stream on logic has some error: ${e.stackTraceToString()}")
|
||||
@@ -291,7 +322,7 @@ class UserHandler(
|
||||
} else {
|
||||
logger.info("${user.username} is offline.")
|
||||
streamStartTime = null
|
||||
listener.closeAsync()
|
||||
listener.disconnectAsync().join()
|
||||
_isActive = false
|
||||
|
||||
CoroutineScope(Dispatchers.Default).launch {
|
||||
@@ -315,4 +346,22 @@ class UserHandler(
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun String.limitUtf8Length(maxBytes: Int): String {
|
||||
val bytes = this.toByteArray(Charset.forName("UTF-8"))
|
||||
if (bytes.size <= maxBytes) return this
|
||||
var truncatedString = this
|
||||
while (truncatedString.toByteArray(Charset.forName("UTF-8")).size > maxBytes) {
|
||||
truncatedString = truncatedString.substring(0, truncatedString.length - 1)
|
||||
}
|
||||
return truncatedString
|
||||
}
|
||||
|
||||
@OptIn(DelicateCoroutinesApi::class)
|
||||
internal fun sendChat(msg: String) {
|
||||
GlobalScope.launch {
|
||||
delay(100L)
|
||||
client.sendChatToLoggedInChannel(msg.limitUtf8Length(100))
|
||||
}
|
||||
}
|
||||
}
|
@@ -1,24 +1,66 @@
|
||||
package space.mori.chzzk_bot.chatbot.chzzk
|
||||
|
||||
import io.github.cdimascio.dotenv.dotenv
|
||||
import kotlinx.coroutines.DelicateCoroutinesApi
|
||||
import kotlinx.coroutines.GlobalScope
|
||||
import kotlinx.coroutines.launch
|
||||
import org.koin.java.KoinJavaComponent.inject
|
||||
import org.slf4j.LoggerFactory
|
||||
import xyz.r2turntrue.chzzk4j.Chzzk
|
||||
import xyz.r2turntrue.chzzk4j.ChzzkBuilder
|
||||
import space.mori.chzzk_bot.common.events.ChzzkUserFindEvent
|
||||
import space.mori.chzzk_bot.common.events.ChzzkUserReceiveEvent
|
||||
import space.mori.chzzk_bot.common.events.CoroutinesEventBus
|
||||
import xyz.r2turntrue.chzzk4j.ChzzkClient
|
||||
import xyz.r2turntrue.chzzk4j.ChzzkClientBuilder
|
||||
import xyz.r2turntrue.chzzk4j.auth.ChzzkLegacyLoginAdapter
|
||||
import xyz.r2turntrue.chzzk4j.auth.ChzzkSimpleUserLoginAdapter
|
||||
import xyz.r2turntrue.chzzk4j.types.channel.ChzzkChannel
|
||||
import xyz.r2turntrue.chzzk4j.types.channel.live.ChzzkLiveDetail
|
||||
import kotlin.getValue
|
||||
|
||||
val dotenv = dotenv {
|
||||
ignoreIfMissing = true
|
||||
}
|
||||
|
||||
@OptIn(DelicateCoroutinesApi::class)
|
||||
object Connector {
|
||||
val chzzk: Chzzk = ChzzkBuilder()
|
||||
.withAuthorization(dotenv["NID_AUT"], dotenv["NID_SES"])
|
||||
val adapter = ChzzkLegacyLoginAdapter(dotenv["NID_AUT"], dotenv["NID_SES"])
|
||||
val client: ChzzkClient = ChzzkClientBuilder(dotenv["NAVER_CLIENT_ID"], dotenv["NAVER_CLIENT_SECRET"])
|
||||
.withLoginAdapter(adapter)
|
||||
.build()
|
||||
private val logger = LoggerFactory.getLogger(this::class.java)
|
||||
private val dispatcher: CoroutinesEventBus by inject(CoroutinesEventBus::class.java)
|
||||
|
||||
fun getChannel(channelId: String): ChzzkChannel? = chzzk.getChannel(channelId)
|
||||
fun getChannel(channelId: String): ChzzkChannel? = client.fetchChannel(channelId)
|
||||
fun getLive(channelId: String): ChzzkLiveDetail? = client.fetchLiveDetail(channelId)
|
||||
|
||||
init {
|
||||
logger.info("chzzk logged: ${chzzk.isLoggedIn} / ${chzzk.loggedUser?.nickname ?: "----"}")
|
||||
logger.info("chzzk logged: ${client.isLoggedIn}")
|
||||
|
||||
client.loginAsync().join()
|
||||
|
||||
dispatcher.subscribe(ChzzkUserFindEvent::class) { event ->
|
||||
GlobalScope.launch {
|
||||
val user = getChannel(event.uid)
|
||||
|
||||
dispatcher.post(ChzzkUserReceiveEvent(
|
||||
find = user != null,
|
||||
uid = user?.channelId,
|
||||
nickname = user?.channelName,
|
||||
isStreamOn = user?.isBroadcasting,
|
||||
avatarUrl = user?.channelImageUrl
|
||||
))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
|
||||
|
||||
}
|
@@ -13,15 +13,16 @@ import space.mori.chzzk_bot.common.utils.getUptime
|
||||
import space.mori.chzzk_bot.common.utils.getYoutubeVideo
|
||||
import xyz.r2turntrue.chzzk4j.chat.ChatMessage
|
||||
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.format.DateTimeFormatter
|
||||
import java.time.temporal.ChronoUnit
|
||||
|
||||
|
||||
class MessageHandler(
|
||||
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 personalCounterPattern = Regex("<counter_personal:([^>]+)>")
|
||||
@@ -71,85 +72,90 @@ class MessageHandler(
|
||||
this.commands.put(it.command.lowercase()) { msg, user ->
|
||||
logger.debug("${channel.channelName} - ${it.command} - ${it.content}/${it.failContent}")
|
||||
|
||||
val result = replaceCounters(Pair(it.content, it.failContent), user, msg, listener, msg.profile?.nickname ?: "")
|
||||
listener.sendChat(result)
|
||||
val result = replaceCounters(
|
||||
Pair(it.content, it.failContent),
|
||||
user,
|
||||
msg,
|
||||
msg.profile?.nickname ?: ""
|
||||
)
|
||||
handler.sendChat(result)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun commandListCommand(msg: ChatMessage, user: User) {
|
||||
listener.sendChat("리스트는 여기입니다. https://nabot.mori.space/commands/${user.token}")
|
||||
private fun commandListCommand(msg: SessionChatMessage, user: User) {
|
||||
handler.sendChat("리스트는 여기입니다. https://nabot.mori.space/commands/${user.token}")
|
||||
}
|
||||
|
||||
private fun manageAddCommand(msg: ChatMessage, user: User) {
|
||||
if (msg.profile?.userRoleCode == "common_user") {
|
||||
listener.sendChat("매니저만 명령어를 추가할 수 있습니다.")
|
||||
private fun manageAddCommand(msg: SessionChatMessage, user: User) {
|
||||
if (msg.profile.badges.none { it.imageUrl.contains("manager") }) {
|
||||
handler.sendChat("매니저만 명령어를 추가할 수 있습니다.")
|
||||
return
|
||||
}
|
||||
|
||||
val parts = msg.content.split(" ", limit = 3)
|
||||
if (parts.size < 3) {
|
||||
listener.sendChat("명령어 추가 형식은 '!명령어추가 명령어 내용'입니다.")
|
||||
handler.sendChat("명령어 추가 형식은 '!명령어추가 명령어 내용'입니다.")
|
||||
return
|
||||
}
|
||||
if (commands.containsKey(parts[1])) {
|
||||
listener.sendChat("${parts[1]} 명령어는 이미 있는 명령어입니다.")
|
||||
handler.sendChat("${parts[1]} 명령어는 이미 있는 명령어입니다.")
|
||||
return
|
||||
}
|
||||
val command = parts[1]
|
||||
val content = parts[2]
|
||||
CommandService.saveCommand(user, command, content, "")
|
||||
listener.sendChat("명령어 '$command' 추가되었습니다.")
|
||||
handler.sendChat("명령어 '$command' 추가되었습니다.")
|
||||
}
|
||||
|
||||
private fun manageUpdateCommand(msg: ChatMessage, user: User) {
|
||||
if (msg.profile?.userRoleCode == "common_user") {
|
||||
listener.sendChat("매니저만 명령어를 추가할 수 있습니다.")
|
||||
private fun manageUpdateCommand(msg: SessionChatMessage, user: User) {
|
||||
if (msg.profile.badges.none { it.imageUrl.contains("manager") }) {
|
||||
handler.sendChat("매니저만 명령어를 추가할 수 있습니다.")
|
||||
return
|
||||
}
|
||||
|
||||
val parts = msg.content.split(" ", limit = 3)
|
||||
if (parts.size < 3) {
|
||||
listener.sendChat("명령어 수정 형식은 '!명령어수정 명령어 내용'입니다.")
|
||||
handler.sendChat("명령어 수정 형식은 '!명령어수정 명령어 내용'입니다.")
|
||||
return
|
||||
}
|
||||
if (!commands.containsKey(parts[1])) {
|
||||
listener.sendChat("${parts[1]} 명령어는 없는 명령어입니다.")
|
||||
handler.sendChat("${parts[1]} 명령어는 없는 명령어입니다.")
|
||||
return
|
||||
}
|
||||
val command = parts[1]
|
||||
val content = parts[2]
|
||||
CommandService.updateCommand(user, command, content, "")
|
||||
listener.sendChat("명령어 '$command' 수정되었습니다.")
|
||||
handler.sendChat("명령어 '$command' 수정되었습니다.")
|
||||
ChzzkHandler.reloadCommand(channel)
|
||||
}
|
||||
|
||||
private fun manageRemoveCommand(msg: ChatMessage, user: User) {
|
||||
if (msg.profile?.userRoleCode == "common_user") {
|
||||
listener.sendChat("매니저만 명령어를 삭제할 수 있습니다.")
|
||||
private fun manageRemoveCommand(msg: SessionChatMessage, user: User) {
|
||||
if (msg.profile.badges.none { it.imageUrl.contains("manager") }) {
|
||||
handler.sendChat("매니저만 명령어를 삭제할 수 있습니다.")
|
||||
return
|
||||
}
|
||||
|
||||
val parts = msg.content.split(" ", limit = 2)
|
||||
if (parts.size < 2) {
|
||||
listener.sendChat("명령어 삭제 형식은 '!명령어삭제 명령어'입니다.")
|
||||
handler.sendChat("명령어 삭제 형식은 '!명령어삭제 명령어'입니다.")
|
||||
return
|
||||
}
|
||||
val command = parts[1]
|
||||
CommandService.removeCommand(user, command)
|
||||
listener.sendChat("명령어 '$command' 삭제되었습니다.")
|
||||
handler.sendChat("명령어 '$command' 삭제되었습니다.")
|
||||
ChzzkHandler.reloadCommand(channel)
|
||||
}
|
||||
|
||||
private fun timerCommand(msg: ChatMessage, user: User) {
|
||||
if (msg.profile?.userRoleCode == "common_user") {
|
||||
listener.sendChat("매니저만 이 명령어를 사용할 수 있습니다.")
|
||||
private fun timerCommand(msg: SessionChatMessage, user: User) {
|
||||
if (msg.profile.badges.none { it.imageUrl.contains("manager") }) {
|
||||
handler.sendChat("매니저만 이 명령어를 사용할 수 있습니다.")
|
||||
return
|
||||
}
|
||||
|
||||
val parts = msg.content.split(" ", limit = 3)
|
||||
if (parts.size < 2) {
|
||||
listener.sendChat("타이머 명령어 형식을 잘 찾아봐주세요!")
|
||||
handler.sendChat("타이머 명령어 형식을 잘 찾아봐주세요!")
|
||||
return
|
||||
}
|
||||
|
||||
@@ -178,13 +184,13 @@ class MessageHandler(
|
||||
when (parts[2]) {
|
||||
"업타임" -> {
|
||||
TimerConfigService.saveOrUpdateConfig(user, TimerType.UPTIME)
|
||||
listener.sendChat("기본 타이머 설정이 업타임으로 바뀌었습니다.")
|
||||
handler.sendChat("기본 타이머 설정이 업타임으로 바뀌었습니다.")
|
||||
}
|
||||
"삭제" -> {
|
||||
TimerConfigService.saveOrUpdateConfig(user, TimerType.REMOVE)
|
||||
listener.sendChat("기본 타이머 설정이 삭제로 바뀌었습니다.")
|
||||
handler.sendChat("기본 타이머 설정이 삭제로 바뀌었습니다.")
|
||||
}
|
||||
else -> listener.sendChat("!타이머 설정 (업타임/삭제) 형식으로 써주세요!")
|
||||
else -> handler.sendChat("!타이머 설정 (업타임/삭제) 형식으로 써주세요!")
|
||||
}
|
||||
}
|
||||
else -> {
|
||||
@@ -198,9 +204,9 @@ class MessageHandler(
|
||||
dispatcher.post(TimerEvent(user.token, TimerType.TIMER, timestamp.toString()))
|
||||
}
|
||||
} catch (e: NumberFormatException) {
|
||||
listener.sendChat("!타이머/숫자 형식으로 적어주세요! 단위: 분")
|
||||
handler.sendChat("!타이머/숫자 형식으로 적어주세요! 단위: 분")
|
||||
} catch (e: Exception) {
|
||||
listener.sendChat("타이머 설정 중 오류가 발생했습니다.")
|
||||
handler.sendChat("타이머 설정 중 오류가 발생했습니다.")
|
||||
logger.error("Error processing timer command: ${e.message}", e)
|
||||
}
|
||||
}
|
||||
@@ -208,21 +214,21 @@ class MessageHandler(
|
||||
}
|
||||
|
||||
// songs
|
||||
private fun songAddCommand(msg: ChatMessage, user: User) {
|
||||
private fun songAddCommand(msg: SessionChatMessage, user: User) {
|
||||
if(SongConfigService.getConfig(user).disabled) {
|
||||
return
|
||||
}
|
||||
|
||||
val parts = msg.content.split(" ", limit = 2)
|
||||
if (parts.size < 2) {
|
||||
listener.sendChat("유튜브 URL을 입력해주세요!")
|
||||
handler.sendChat("유튜브 URL을 입력해주세요!")
|
||||
return
|
||||
}
|
||||
|
||||
val config = SongConfigService.getConfig(user)
|
||||
|
||||
if(config.streamerOnly && msg.profile?.userRoleCode == "common_user") {
|
||||
listener.sendChat("매니저만 이 명령어를 사용할 수 있습니다.")
|
||||
if(config.streamerOnly && msg.profile.badges.none { it.imageUrl.contains("manager") }) {
|
||||
handler.sendChat("매니저만 이 명령어를 사용할 수 있습니다.")
|
||||
return
|
||||
}
|
||||
|
||||
@@ -230,34 +236,34 @@ class MessageHandler(
|
||||
val songs = SongListService.getSong(user)
|
||||
|
||||
if(songs.size >= config.queueLimit) {
|
||||
listener.sendChat("더이상 노래를 신청할 수 없습니다. 잠시 뒤 다시 시도해주세요!")
|
||||
handler.sendChat("더이상 노래를 신청할 수 없습니다. 잠시 뒤 다시 시도해주세요!")
|
||||
return
|
||||
}
|
||||
if(songs.filter { it.uid == msg.userId }.size >= config.personalLimit) {
|
||||
listener.sendChat("더이상 노래를 신청할 수 없습니다. 잠시 뒤 다시 시도해주세요!")
|
||||
if(songs.filter { it.uid == msg.senderChannelId }.size >= config.personalLimit) {
|
||||
handler.sendChat("더이상 노래를 신청할 수 없습니다. 잠시 뒤 다시 시도해주세요!")
|
||||
return
|
||||
}
|
||||
|
||||
try {
|
||||
val video = getYoutubeVideo(url)
|
||||
if (video == null) {
|
||||
listener.sendChat("유튜브에서 찾을 수 없어요!")
|
||||
handler.sendChat("유튜브에서 찾을 수 없어요!")
|
||||
return
|
||||
}
|
||||
|
||||
if (songs.any { it.url == video.url }) {
|
||||
listener.sendChat("같은 노래가 이미 신청되어 있습니다.")
|
||||
handler.sendChat("같은 노래가 이미 신청되어 있습니다.")
|
||||
return
|
||||
}
|
||||
|
||||
if (video.length > 600) {
|
||||
listener.sendChat("10분이 넘는 노래는 신청할 수 없습니다.")
|
||||
handler.sendChat("10분이 넘는 노래는 신청할 수 없습니다.")
|
||||
return
|
||||
}
|
||||
|
||||
SongListService.saveSong(
|
||||
user,
|
||||
msg.userId,
|
||||
msg.senderChannelId,
|
||||
video.url,
|
||||
video.name,
|
||||
video.author,
|
||||
@@ -269,31 +275,31 @@ class MessageHandler(
|
||||
SongEvent(
|
||||
user.token,
|
||||
SongType.ADD,
|
||||
msg.userId,
|
||||
msg.senderChannelId,
|
||||
null,
|
||||
video,
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
listener.sendChat("노래가 추가되었습니다. ${video.name} - ${video.author}")
|
||||
handler.sendChat("노래가 추가되었습니다. ${video.name} - ${video.author}")
|
||||
} catch(e: Exception) {
|
||||
listener.sendChat("유튜브 영상 주소로 다시 신청해주세요!")
|
||||
handler.sendChat("유튜브 영상 주소로 다시 신청해주세요!")
|
||||
logger.info(e.stackTraceToString())
|
||||
}
|
||||
}
|
||||
|
||||
private fun songListCommand(msg: ChatMessage, user: User) {
|
||||
private fun songListCommand(msg: SessionChatMessage, user: User) {
|
||||
if(SongConfigService.getConfig(user).disabled) {
|
||||
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) {
|
||||
if (msg.profile?.userRoleCode == "common_user") {
|
||||
listener.sendChat("매니저만 이 명령어를 사용할 수 있습니다.")
|
||||
private fun songStartCommand(msg: SessionChatMessage, user: User) {
|
||||
if (msg.profile.badges.none { it.imageUrl.contains("manager") }) {
|
||||
handler.sendChat("매니저만 이 명령어를 사용할 수 있습니다.")
|
||||
return
|
||||
}
|
||||
|
||||
@@ -306,28 +312,28 @@ class MessageHandler(
|
||||
}
|
||||
}
|
||||
} else {
|
||||
listener.sendChat("나봇 홈페이지의 노래목록 페이지를 이용해주세요! 디스코드 연동을 하시면 DM으로 바로 전송됩니다.")
|
||||
handler.sendChat("나봇 홈페이지의 노래목록 페이지를 이용해주세요! 디스코드 연동을 하시면 DM으로 바로 전송됩니다.")
|
||||
}
|
||||
}
|
||||
|
||||
internal fun handle(msg: ChatMessage, user: User) {
|
||||
if(msg.userId == ChzzkHandler.botUid) return
|
||||
internal fun handle(msg: SessionChatMessage, user: User) {
|
||||
if(msg.senderChannelId == ChzzkHandler.botUid) return
|
||||
|
||||
val commandKey = msg.content.split(' ')[0]
|
||||
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 isFail = false
|
||||
|
||||
// Replace dailyCounterPattern
|
||||
result = dailyCounterPattern.replace(result) { matchResult ->
|
||||
val name = matchResult.groupValues[1]
|
||||
val dailyCounter = CounterService.getDailyCounterValue(name, msg.userId, user)
|
||||
val dailyCounter = CounterService.getDailyCounterValue(name, msg.senderChannelId, user)
|
||||
|
||||
if (dailyCounter.second) {
|
||||
CounterService.updateDailyCounterValue(name, msg.userId, 1, user).first.toString()
|
||||
CounterService.updateDailyCounterValue(name, msg.senderChannelId, 1, user).first.toString()
|
||||
} else {
|
||||
isFail = true
|
||||
dailyCounter.first.toString()
|
||||
@@ -339,7 +345,7 @@ class MessageHandler(
|
||||
result = chat.second
|
||||
result = dailyCounterPattern.replace(result) { matchResult ->
|
||||
val name = matchResult.groupValues[1]
|
||||
val dailyCounter = CounterService.getDailyCounterValue(name, msg.userId, user)
|
||||
val dailyCounter = CounterService.getDailyCounterValue(name, msg.senderChannelId, user)
|
||||
dailyCounter.first.toString()
|
||||
}
|
||||
}
|
||||
@@ -347,15 +353,15 @@ class MessageHandler(
|
||||
// Replace followPattern
|
||||
result = followPattern.replace(result) { _ ->
|
||||
try {
|
||||
val followingDate = getFollowDate(listener.chatId, msg.userId)
|
||||
.content?.streamingProperty?.following?.followDate
|
||||
val followingDate = handler.chatChannelId?.let { getFollowDate(it, msg.senderChannelId) }
|
||||
?.content?.streamingProperty?.following?.followDate ?: LocalDateTime.now().minusDays(1).toString()
|
||||
|
||||
val period = followingDate?.let {
|
||||
val period = followingDate.let {
|
||||
val formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")
|
||||
val pastDate = LocalDateTime.parse(it, formatter)
|
||||
val today = LocalDateTime.now()
|
||||
ChronoUnit.DAYS.between(pastDate, today)
|
||||
} ?: 0
|
||||
} + 1
|
||||
|
||||
period.toString()
|
||||
} catch (e: Exception) {
|
||||
@@ -383,7 +389,7 @@ class MessageHandler(
|
||||
// Replace personalCounterPattern
|
||||
result = personalCounterPattern.replace(result) { matchResult ->
|
||||
val name = matchResult.groupValues[1]
|
||||
CounterService.updatePersonalCounterValue(name, msg.userId, 1, user).toString()
|
||||
CounterService.updatePersonalCounterValue(name, msg.senderChannelId, 1, user).toString()
|
||||
}
|
||||
|
||||
// Replace namePattern
|
||||
@@ -391,5 +397,4 @@ class MessageHandler(
|
||||
|
||||
return result
|
||||
}
|
||||
|
||||
}
|
@@ -12,11 +12,12 @@ import net.dv8tion.jda.api.events.interaction.command.SlashCommandInteractionEve
|
||||
import net.dv8tion.jda.api.hooks.ListenerAdapter
|
||||
import net.dv8tion.jda.api.utils.messages.MessageCreateBuilder
|
||||
import org.slf4j.LoggerFactory
|
||||
import space.mori.chzzk_bot.common.utils.IData
|
||||
import space.mori.chzzk_bot.common.utils.IStreamInfo
|
||||
import space.mori.chzzk_bot.chatbot.discord.commands.*
|
||||
import space.mori.chzzk_bot.common.models.User
|
||||
import xyz.r2turntrue.chzzk4j.types.channel.live.ChzzkLiveDetail
|
||||
import xyz.r2turntrue.chzzk4j.types.channel.live.Resolution
|
||||
import java.time.Instant
|
||||
import kotlin.jvm.optionals.getOrNull
|
||||
|
||||
val dotenv = dotenv {
|
||||
ignoreIfMissing = true
|
||||
@@ -33,20 +34,26 @@ class Discord: ListenerAdapter() {
|
||||
return bot.getGuildById(guildId)?.getTextChannelById(channelId)
|
||||
}
|
||||
|
||||
fun sendDiscord(user: User, status: IData<IStreamInfo?>) {
|
||||
if(status.content == null) return
|
||||
fun sendDiscord(user: User, status: ChzzkLiveDetail) {
|
||||
if(user.liveAlertMessage != null && user.liveAlertGuild != null && user.liveAlertChannel != null) {
|
||||
val channel = getChannel(user.liveAlertGuild ?: 0, user.liveAlertChannel ?: 0)
|
||||
?: throw RuntimeException("${user.liveAlertChannel} is not valid.")
|
||||
|
||||
val embed = EmbedBuilder()
|
||||
embed.setTitle(status.content!!.liveTitle, "https://chzzk.naver.com/live/${user.token}")
|
||||
embed.setTitle(status.title, "https://chzzk.naver.com/live/${user.token}")
|
||||
embed.setDescription("${user.username} 님이 방송을 시작했습니다.")
|
||||
embed.setTimestamp(Instant.now())
|
||||
embed.setAuthor(user.username, "https://chzzk.naver.com/live/${user.token}", status.content!!.channel.channelImageUrl)
|
||||
embed.addField("카테고리", status.content!!.liveCategoryValue, true)
|
||||
embed.addField("태그", status.content!!.tags.joinToString(", "), true)
|
||||
embed.setImage(status.content!!.liveImageUrl.replace("{type}", "1080"))
|
||||
embed.setAuthor(user.username, "https://chzzk.naver.com/live/${user.token}")
|
||||
embed.addField("카테고리", status.liveCategoryValue, true)
|
||||
embed.addField("태그", status.tags.joinToString(", ") { it.trim() }, true)
|
||||
status.defaultThumbnailImageUrl.getOrNull()?.let { embed.setImage(it) }
|
||||
?: Resolution.entries.reversed().forEach {
|
||||
val thumbnail = status.getLiveImageUrl(it)
|
||||
if (thumbnail != null) {
|
||||
embed.setImage(thumbnail)
|
||||
return@forEach
|
||||
}
|
||||
}
|
||||
|
||||
channel.sendMessage(
|
||||
MessageCreateBuilder()
|
||||
|
@@ -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://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
|
||||
}
|
||||
}
|
||||
}
|
@@ -23,7 +23,7 @@ dependencies {
|
||||
api("com.zaxxer:HikariCP:6.1.0")
|
||||
|
||||
// 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
|
||||
implementation("org.mariadb.jdbc:mariadb-java-client:3.5.0")
|
||||
|
@@ -0,0 +1,7 @@
|
||||
package space.mori.chzzk_bot.common.events
|
||||
|
||||
data class ChzzkUserFindEvent(
|
||||
val uid: String
|
||||
): Event {
|
||||
val TAG = javaClass.simpleName
|
||||
}
|
@@ -0,0 +1,11 @@
|
||||
package space.mori.chzzk_bot.common.events
|
||||
|
||||
data class ChzzkUserReceiveEvent(
|
||||
val find: Boolean = true,
|
||||
val uid: String? = null,
|
||||
val nickname: String? = null,
|
||||
val isStreamOn: Boolean? = null,
|
||||
val avatarUrl: String? = null,
|
||||
): Event {
|
||||
val TAG = javaClass.simpleName
|
||||
}
|
@@ -5,7 +5,8 @@ enum class TimerType(var value: Int) {
|
||||
TIMER(1),
|
||||
REMOVE(2),
|
||||
|
||||
STREAM_OFF(50)
|
||||
STREAM_OFF(50),
|
||||
ACK(51)
|
||||
}
|
||||
|
||||
class TimerEvent(
|
||||
|
@@ -52,47 +52,18 @@ data class NicknameColor(
|
||||
val colorCode: String = ""
|
||||
)
|
||||
|
||||
// Stream info
|
||||
data class IStreamInfo(
|
||||
val liveId: Int = 0,
|
||||
val liveTitle: String = "",
|
||||
val status: String = "",
|
||||
val liveImageUrl: String = "",
|
||||
val defaultThumbnailImageUrl: String? = null,
|
||||
val concurrentUserCount: Int = 0,
|
||||
val accumulateCount: Int = 0,
|
||||
val openDate: String = "",
|
||||
val closeDate: String = "",
|
||||
val adult: Boolean = false,
|
||||
val clipActive: Boolean = false,
|
||||
val tags: List<String> = emptyList(),
|
||||
val chatChannelId: String = "",
|
||||
val categoryType: String = "",
|
||||
val liveCategory: String = "",
|
||||
val liveCategoryValue: String = "",
|
||||
val chatActive: Boolean = true,
|
||||
val chatAvailableGroup: String = "",
|
||||
val paidPromotion: Boolean = false,
|
||||
val chatAvailableCondition: String = "",
|
||||
val minFollowerMinute: Int = 0,
|
||||
val livePlaybackJson: String = "",
|
||||
val p2pQuality: List<Any> = emptyList(),
|
||||
val channel: Channel = Channel(),
|
||||
val livePollingStatusJson: String = "",
|
||||
val userAdultStatus: String? = null,
|
||||
val chatDonationRankingExposure: Boolean = true,
|
||||
val adParameter: AdParameter = AdParameter()
|
||||
)
|
||||
|
||||
data class Channel(
|
||||
val channelId: String = "",
|
||||
val channelName: String = "",
|
||||
val channelImageUrl: String = "",
|
||||
val verifiedMark: Boolean = false
|
||||
)
|
||||
|
||||
data class AdParameter(
|
||||
val tag: String = ""
|
||||
data class LiveStatus(
|
||||
val liveTitle: String,
|
||||
val status: String,
|
||||
val concurrentUserCount: Int,
|
||||
val accumulateCount: Int,
|
||||
val paidPromotion: Boolean,
|
||||
val adult: Boolean,
|
||||
val krOnlyViewing: Boolean,
|
||||
val openDate: String,
|
||||
val closeDate: String?,
|
||||
val clipActive: Boolean,
|
||||
val chatChannelId: String
|
||||
)
|
||||
|
||||
// OkHttpClient에 Interceptor 추가
|
||||
@@ -128,38 +99,21 @@ fun getFollowDate(chatID: String, userId: String) : IData<IFollowContent?> {
|
||||
}
|
||||
}
|
||||
|
||||
fun getStreamInfo(userId: String) : IData<IStreamInfo?> {
|
||||
val url = "https://api.chzzk.naver.com/service/v3/channels/${userId}/live-detail"
|
||||
fun getChzzkChannelId(channelId: String): String? {
|
||||
val url = "https://api.chzzk.naver.com/polling/v3/channels/$channelId/live-status?includePlayerRecommendContent=false"
|
||||
val request = Request.Builder()
|
||||
.url(url)
|
||||
.header("Content-Type", "application/json")
|
||||
.get()
|
||||
.build()
|
||||
|
||||
client.newCall(request).execute().use { response ->
|
||||
try {
|
||||
if(!response.isSuccessful) throw IOException("Unexpected code ${response.code}")
|
||||
val body = response.body?.string()
|
||||
val follow = gson.fromJson(body, object: TypeToken<IData<IStreamInfo?>>() {})
|
||||
val data = gson.fromJson(body, object: TypeToken<IData<LiveStatus?>>() {})
|
||||
|
||||
return follow
|
||||
} catch(e: Exception) {
|
||||
throw e
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun getUserInfo(userId: String): IData<Channel?> {
|
||||
val url = "https://api.chzzk.naver.com/service/v1/channels/${userId}"
|
||||
val request = Request.Builder()
|
||||
.url(url)
|
||||
.build()
|
||||
|
||||
client.newCall(request).execute().use { response ->
|
||||
try {
|
||||
if(!response.isSuccessful) throw IOException("Unexpected code ${response.code}")
|
||||
val body = response.body?.string()
|
||||
val channel = gson.fromJson(body, object: TypeToken<IData<Channel?>>() {})
|
||||
|
||||
return channel
|
||||
return data.content?.chatChannelId
|
||||
} catch(e: Exception) {
|
||||
throw e
|
||||
}
|
||||
|
@@ -10,7 +10,7 @@ repositories {
|
||||
mavenCentral()
|
||||
}
|
||||
|
||||
val ktorVersion = "3.0.1"
|
||||
val ktorVersion = "3.1.3"
|
||||
|
||||
dependencies {
|
||||
implementation("io.ktor:ktor-server-core:$ktorVersion")
|
||||
|
@@ -22,13 +22,16 @@ import io.ktor.server.websocket.*
|
||||
import kotlinx.coroutines.delay
|
||||
import kotlinx.serialization.Serializable
|
||||
import kotlinx.serialization.json.Json
|
||||
import org.koin.java.KoinJavaComponent.inject
|
||||
import space.mori.chzzk_bot.common.events.CoroutinesEventBus
|
||||
import space.mori.chzzk_bot.common.events.UserRegisterEvent
|
||||
import space.mori.chzzk_bot.common.services.UserService
|
||||
import space.mori.chzzk_bot.webserver.routes.*
|
||||
import space.mori.chzzk_bot.webserver.utils.DiscordRatelimits
|
||||
import wsSongListRoutes
|
||||
import java.math.BigInteger
|
||||
import java.security.SecureRandom
|
||||
import java.time.Duration
|
||||
import kotlin.getValue
|
||||
import kotlin.time.toKotlinDuration
|
||||
|
||||
val dotenv = dotenv {
|
||||
@@ -82,6 +85,8 @@ val server = embeddedServer(Netty, port = 8080, ) {
|
||||
}
|
||||
}
|
||||
routing {
|
||||
val dispatcher: CoroutinesEventBus by inject(CoroutinesEventBus::class.java)
|
||||
|
||||
route("/auth") {
|
||||
// discord login
|
||||
authenticate("auth-oauth-discord") {
|
||||
@@ -192,7 +197,12 @@ val server = embeddedServer(Netty, port = 8080, ) {
|
||||
val userInfo = getChzzkUser(tokenResponse.content.accessToken)
|
||||
|
||||
if(userInfo.content != null) {
|
||||
val user = UserService.getUser(userInfo.content.channelId)
|
||||
var user = UserService.getUser(userInfo.content.channelId)
|
||||
|
||||
if(user == null) {
|
||||
user = UserService.saveUser(userInfo.content.channelName , userInfo.content.channelId)
|
||||
}
|
||||
|
||||
call.sessions.set(
|
||||
UserSession(
|
||||
session.state,
|
||||
@@ -200,7 +210,13 @@ val server = embeddedServer(Netty, port = 8080, ) {
|
||||
listOf()
|
||||
)
|
||||
)
|
||||
user?.let { UserService.setRefreshToken(it, tokenResponse.content.accessToken, tokenResponse.content.refreshToken ?: "") }
|
||||
UserService.setRefreshToken(user,
|
||||
tokenResponse.content.accessToken,
|
||||
tokenResponse.content.refreshToken ?: ""
|
||||
)
|
||||
|
||||
dispatcher.post(UserRegisterEvent(user.token))
|
||||
|
||||
call.respondRedirect(getFrontendURL(""))
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
|
@@ -11,7 +11,10 @@ import space.mori.chzzk_bot.common.events.CoroutinesEventBus
|
||||
import space.mori.chzzk_bot.common.services.SongConfigService
|
||||
import space.mori.chzzk_bot.common.services.UserService
|
||||
import space.mori.chzzk_bot.webserver.UserSession
|
||||
import space.mori.chzzk_bot.webserver.utils.ChzzkUserCache
|
||||
import kotlinx.coroutines.CompletableDeferred
|
||||
import kotlinx.coroutines.withTimeoutOrNull
|
||||
import space.mori.chzzk_bot.common.events.ChzzkUserFindEvent
|
||||
import space.mori.chzzk_bot.common.events.ChzzkUserReceiveEvent
|
||||
|
||||
@Serializable
|
||||
data class GetUserDTO(
|
||||
@@ -36,6 +39,20 @@ data class GetSessionDTO(
|
||||
fun Routing.apiRoutes() {
|
||||
val dispatcher: CoroutinesEventBus by inject(CoroutinesEventBus::class.java)
|
||||
|
||||
suspend fun getChzzkUserWithId(uid: String): ChzzkUserReceiveEvent? {
|
||||
val completableDeferred = CompletableDeferred<ChzzkUserReceiveEvent>()
|
||||
dispatcher.subscribe(ChzzkUserReceiveEvent::class) { event ->
|
||||
if (event.uid == uid) {
|
||||
completableDeferred.complete(event)
|
||||
}
|
||||
}
|
||||
val user = withTimeoutOrNull(5000) {
|
||||
dispatcher.post(ChzzkUserFindEvent(uid))
|
||||
completableDeferred.await()
|
||||
}
|
||||
return user
|
||||
}
|
||||
|
||||
route("/") {
|
||||
get {
|
||||
call.respondText("Hello World!", status =
|
||||
@@ -55,16 +72,16 @@ fun Routing.apiRoutes() {
|
||||
call.respondText("Require UID", status = HttpStatusCode.NotFound)
|
||||
return@get
|
||||
}
|
||||
val user = ChzzkUserCache.getCachedUser(uid)
|
||||
if(user?.content == null) {
|
||||
val user = getChzzkUserWithId(uid)
|
||||
if (user?.find == false) {
|
||||
call.respondText("User not found", status = HttpStatusCode.NotFound)
|
||||
return@get
|
||||
} else {
|
||||
call.respond(HttpStatusCode.OK, GetUserDTO(
|
||||
user.content!!.channel.channelId,
|
||||
user.content!!.channel.channelName,
|
||||
user.content!!.status == "OPEN",
|
||||
user.content!!.channel.channelImageUrl
|
||||
user?.uid ?: "",
|
||||
user?.nickname ?: "",
|
||||
user?.isStreamOn ?: false,
|
||||
user?.avatarUrl ?: ""
|
||||
))
|
||||
}
|
||||
}
|
||||
@@ -82,7 +99,7 @@ fun Routing.apiRoutes() {
|
||||
user = UserService.saveUser("임시닉네임", session.id)
|
||||
}
|
||||
val songConfig = SongConfigService.getConfig(user)
|
||||
val status = ChzzkUserCache.getCachedUser(session.id)
|
||||
val status = getChzzkUserWithId(user.token)
|
||||
val returnUsers = mutableListOf<GetSessionDTO>()
|
||||
|
||||
if(status == null) {
|
||||
@@ -91,14 +108,14 @@ fun Routing.apiRoutes() {
|
||||
}
|
||||
|
||||
if (user.username == "임시닉네임") {
|
||||
status.content?.channel?.let { it1 -> UserService.updateUser(user, it1.channelId, it1.channelName) }
|
||||
status.let { stats -> UserService.updateUser(user, stats.uid ?: "", stats.nickname ?: "") }
|
||||
}
|
||||
|
||||
returnUsers.add(GetSessionDTO(
|
||||
status.content?.channel?.channelId ?: user.username,
|
||||
status.content?.channel?.channelName ?: user.token,
|
||||
status.content?.status == "OPEN",
|
||||
status.content?.channel?.channelImageUrl ?: "",
|
||||
status.uid ?: user.token,
|
||||
status.nickname ?: user.username,
|
||||
status.isStreamOn == true,
|
||||
status.avatarUrl ?: "",
|
||||
songConfig.queueLimit,
|
||||
songConfig.personalLimit,
|
||||
songConfig.streamerOnly,
|
||||
@@ -109,15 +126,15 @@ fun Routing.apiRoutes() {
|
||||
user.subordinates.toList()
|
||||
}
|
||||
returnUsers.addAll(subordinates.map {
|
||||
val subStatus = ChzzkUserCache.getCachedUser(it.token)
|
||||
return@map if (subStatus?.content == null) {
|
||||
val subStatus = getChzzkUserWithId(it.token)
|
||||
return@map if (subStatus == null) {
|
||||
null
|
||||
} else {
|
||||
GetSessionDTO(
|
||||
subStatus.content!!.channel.channelId,
|
||||
subStatus.content!!.channel.channelName,
|
||||
subStatus.content!!.status == "OPEN",
|
||||
subStatus.content!!.channel.channelImageUrl,
|
||||
subStatus.uid ?: "",
|
||||
subStatus.nickname ?: "",
|
||||
subStatus.isStreamOn == true,
|
||||
subStatus.avatarUrl ?: "",
|
||||
0,
|
||||
0,
|
||||
false,
|
||||
|
@@ -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.sessions.*
|
||||
import io.ktor.server.websocket.*
|
||||
import io.ktor.util.logging.Logger
|
||||
import io.ktor.websocket.*
|
||||
import io.ktor.websocket.Frame.*
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.*
|
||||
import kotlinx.coroutines.channels.ClosedReceiveChannelException
|
||||
import kotlinx.coroutines.delay
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.sync.Mutex
|
||||
import kotlinx.coroutines.sync.withLock
|
||||
import kotlinx.serialization.Serializable
|
||||
import kotlinx.serialization.json.Json
|
||||
import org.koin.java.KoinJavaComponent.inject
|
||||
import org.slf4j.Logger
|
||||
import org.slf4j.LoggerFactory
|
||||
import space.mori.chzzk_bot.common.events.*
|
||||
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.services.SongConfigService
|
||||
import space.mori.chzzk_bot.common.services.SongListService
|
||||
import space.mori.chzzk_bot.common.services.UserService
|
||||
import space.mori.chzzk_bot.common.utils.YoutubeVideo
|
||||
import space.mori.chzzk_bot.common.utils.getYoutubeVideo
|
||||
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 java.io.IOException
|
||||
import java.util.concurrent.ConcurrentHashMap
|
||||
|
||||
fun Routing.wsSongListRoutes() {
|
||||
val sessions = ConcurrentHashMap<String, WebSocketServerSession>()
|
||||
val status = ConcurrentHashMap<String, SongType>()
|
||||
val logger = LoggerFactory.getLogger("WSSongListRoutes")
|
||||
|
||||
val dispatcher: CoroutinesEventBus by inject(CoroutinesEventBus::class.java)
|
||||
val songListScope = CoroutineScope(SupervisorJob() + Dispatchers.Default)
|
||||
|
||||
fun addSession(uid: String, session: WebSocketServerSession) {
|
||||
if (sessions[uid] != null) {
|
||||
CoroutineScope(Dispatchers.Default).launch {
|
||||
sessions[uid]?.close(
|
||||
CloseReason(CloseReason.Codes.VIOLATED_POLICY, "Duplicated sessions.")
|
||||
)
|
||||
}
|
||||
}
|
||||
sessions[uid] = session
|
||||
}
|
||||
// Manage all active sessions
|
||||
val sessionHandlers = ConcurrentHashMap<String, SessionHandler>()
|
||||
|
||||
fun removeSession(uid: String) {
|
||||
sessions.remove(uid)
|
||||
// Handle application shutdown
|
||||
environment.monitor.subscribe(ApplicationStopped) {
|
||||
sessionHandlers.values.forEach {
|
||||
songListScope.launch {
|
||||
it.close(CloseReason(CloseReason.Codes.NORMAL, "Server shutting down"))
|
||||
}
|
||||
|
||||
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") {
|
||||
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) {
|
||||
close(CloseReason(CloseReason.Codes.CANNOT_ACCEPT, "Invalid SID"))
|
||||
return@webSocket
|
||||
@@ -117,102 +56,204 @@ fun Routing.wsSongListRoutes() {
|
||||
|
||||
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) {
|
||||
CoroutineScope(Dispatchers.Default).launch {
|
||||
sendSerialized(SongResponse(
|
||||
SongType.STREAM_OFF.value,
|
||||
uid,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
))
|
||||
}
|
||||
removeSession(uid)
|
||||
}
|
||||
val handler = SessionHandler(uid, this, dispatcher, logger)
|
||||
sessionHandlers[uid] = handler
|
||||
|
||||
// Initialize session
|
||||
handler.initialize()
|
||||
|
||||
// Listen for incoming frames
|
||||
try {
|
||||
for (frame in incoming) {
|
||||
when (frame) {
|
||||
is Text -> {
|
||||
if (frame.readText().trim() == "ping") {
|
||||
send("pong")
|
||||
} 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 -> ""
|
||||
is Frame.Text -> handler.handleTextFrame(frame.readText())
|
||||
is Frame.Ping -> send(Frame.Pong(frame.data))
|
||||
else -> Unit
|
||||
}
|
||||
}
|
||||
} 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 {
|
||||
removeSession(uid)
|
||||
sessionHandlers.remove(uid)
|
||||
handler.close(CloseReason(CloseReason.Codes.NORMAL, "Session ended"))
|
||||
}
|
||||
}
|
||||
|
||||
dispatcher.subscribe(SongEvent::class) {
|
||||
logger.debug("SongEvent: {} / {} {}", it.uid, it.type, it.current?.name)
|
||||
CoroutineScope(Dispatchers.Default).launch {
|
||||
val user = UserService.getUser(it.uid)
|
||||
if (user != null) {
|
||||
sendWithRetry(
|
||||
user.token, SongResponse(
|
||||
it.type.value,
|
||||
it.uid,
|
||||
it.reqUid,
|
||||
it.current?.toSerializable(),
|
||||
it.next?.toSerializable(),
|
||||
it.delUrl
|
||||
)
|
||||
)
|
||||
}
|
||||
// Subscribe to SongEvents
|
||||
dispatcher.subscribe(SongEvent::class) { event ->
|
||||
val handler = sessionHandlers[event.uid]
|
||||
songListScope.launch {
|
||||
handler?.sendSongResponse(event)
|
||||
}
|
||||
}
|
||||
|
||||
dispatcher.subscribe(TimerEvent::class) {
|
||||
if (it.type == TimerType.STREAM_OFF) {
|
||||
CoroutineScope(Dispatchers.Default).launch {
|
||||
val user = UserService.getUser(it.uid)
|
||||
if (user != null) {
|
||||
sendWithRetry(
|
||||
user.token, SongResponse(
|
||||
it.type.value,
|
||||
it.uid,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
)
|
||||
)
|
||||
}
|
||||
// Subscribe to TimerEvents
|
||||
dispatcher.subscribe(TimerEvent::class) { event ->
|
||||
if (event.type == TimerType.STREAM_OFF) {
|
||||
val handler = sessionHandlers[event.uid]
|
||||
songListScope.launch {
|
||||
handler?.sendTimerOff()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
suspend fun handleSongRequest(
|
||||
class SessionHandler(
|
||||
private val uid: String,
|
||||
private val session: WebSocketServerSession,
|
||||
private val dispatcher: CoroutinesEventBus,
|
||||
private val logger: Logger
|
||||
) {
|
||||
private val ackMap = ConcurrentHashMap<String, CompletableDeferred<Boolean>>()
|
||||
private val sessionMutex = Mutex()
|
||||
private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Default)
|
||||
|
||||
suspend fun initialize() {
|
||||
// Send initial status if needed,
|
||||
// For example, send STREAM_OFF if applicable
|
||||
// This can be extended based on your requirements
|
||||
}
|
||||
|
||||
suspend fun handleTextFrame(text: String) {
|
||||
if (text.trim() == "ping") {
|
||||
session.send("pong")
|
||||
return
|
||||
}
|
||||
|
||||
val data = try {
|
||||
Json.decodeFromString<SongRequest>(text)
|
||||
} catch (e: Exception) {
|
||||
logger.warn("Failed to decode SongRequest: ${e.message}")
|
||||
return
|
||||
}
|
||||
|
||||
when (data.type) {
|
||||
SongType.ACK.value -> handleAck(data.uid)
|
||||
else -> handleSongRequest(data)
|
||||
}
|
||||
}
|
||||
|
||||
private fun handleAck(requestUid: String) {
|
||||
ackMap[requestUid]?.complete(true)
|
||||
ackMap.remove(requestUid)
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private suspend fun handleAdd(
|
||||
data: SongRequest,
|
||||
user: User,
|
||||
dispatcher: CoroutinesEventBus,
|
||||
handler: SessionHandler,
|
||||
logger: Logger
|
||||
) {
|
||||
if (data.maxQueue != null && data.maxQueue > 0) SongConfigService.updateQueueLimit(user, data.maxQueue)
|
||||
if (data.maxUserLimit != null && data.maxUserLimit > 0) SongConfigService.updatePersonalLimit(user, data.maxUserLimit)
|
||||
if (data.isStreamerOnly != null) SongConfigService.updateStreamerOnly(user, data.isStreamerOnly)
|
||||
if (data.isDisabled != null) SongConfigService.updateDisabled(user, data.isDisabled)
|
||||
) {
|
||||
val url = data.url ?: return
|
||||
val youtubeVideo = getYoutubeVideo(url) ?: run {
|
||||
logger.warn("Failed to fetch YouTube video for URL: $url")
|
||||
return
|
||||
}
|
||||
|
||||
when (data.type) {
|
||||
SongType.ADD.value -> {
|
||||
data.url?.let { url ->
|
||||
try {
|
||||
val youtubeVideo = getYoutubeVideo(url)
|
||||
if (youtubeVideo != null) {
|
||||
CoroutineScope(Dispatchers.Default).launch {
|
||||
songMutex.withLock {
|
||||
SongListService.saveSong(
|
||||
user,
|
||||
user.token,
|
||||
@@ -222,81 +263,95 @@ suspend fun handleSongRequest(
|
||||
youtubeVideo.length,
|
||||
user.username
|
||||
)
|
||||
}
|
||||
|
||||
dispatcher.post(
|
||||
SongEvent(
|
||||
user.token,
|
||||
SongType.ADD,
|
||||
user.token,
|
||||
CurrentSong.getSong(user),
|
||||
youtubeVideo
|
||||
uid = user.token,
|
||||
type = SongType.ADD,
|
||||
reqUid = user.token,
|
||||
current = CurrentSong.getSong(user),
|
||||
next = youtubeVideo
|
||||
)
|
||||
)
|
||||
}
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
logger.debug("SongType.ADD Error: $uid $e")
|
||||
}
|
||||
}
|
||||
}
|
||||
SongType.REMOVE.value -> {
|
||||
data.url?.let { url ->
|
||||
|
||||
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)
|
||||
}
|
||||
}
|
||||
|
||||
dispatcher.post(
|
||||
SongEvent(
|
||||
user.token,
|
||||
SongType.REMOVE,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
url
|
||||
uid = user.token,
|
||||
type = SongType.REMOVE,
|
||||
delUrl = url,
|
||||
reqUid = null,
|
||||
current = null,
|
||||
next = null,
|
||||
)
|
||||
)
|
||||
}
|
||||
}
|
||||
SongType.NEXT.value -> {
|
||||
val songList = SongListService.getSong(user)
|
||||
|
||||
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)
|
||||
if (songList.isNotEmpty()) {
|
||||
song = songList[0]
|
||||
SongListService.deleteSong(user, song.uid, song.name)
|
||||
}
|
||||
}
|
||||
|
||||
song?.let {
|
||||
youtubeVideo = YoutubeVideo(
|
||||
song.url,
|
||||
song.name,
|
||||
song.author,
|
||||
song.time
|
||||
it.url,
|
||||
it.name,
|
||||
it.author,
|
||||
it.time
|
||||
)
|
||||
}
|
||||
|
||||
dispatcher.post(
|
||||
SongEvent(
|
||||
user.token,
|
||||
SongType.NEXT,
|
||||
song?.uid,
|
||||
youtubeVideo
|
||||
uid = user.token,
|
||||
type = SongType.NEXT,
|
||||
current = null,
|
||||
next = youtubeVideo,
|
||||
reqUid = null,
|
||||
delUrl = null
|
||||
)
|
||||
)
|
||||
|
||||
CurrentSong.setSong(user, youtubeVideo)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Serializable
|
||||
data class SongRequest(
|
||||
val type: Int,
|
||||
val uid: String,
|
||||
val url: String?,
|
||||
val maxQueue: Int?,
|
||||
val maxUserLimit: Int?,
|
||||
val isStreamerOnly: Boolean?,
|
||||
val remove: Int?,
|
||||
val isDisabled: Boolean?,
|
||||
val url: String? = null,
|
||||
val maxQueue: Int? = null,
|
||||
val maxUserLimit: Int? = null,
|
||||
val isStreamerOnly: Boolean? = null,
|
||||
val remove: Int? = null,
|
||||
val isDisabled: Boolean? = null
|
||||
)
|
||||
|
@@ -1,14 +1,20 @@
|
||||
package space.mori.chzzk_bot.webserver.routes
|
||||
|
||||
import io.ktor.server.application.ApplicationStopped
|
||||
import io.ktor.server.routing.*
|
||||
import io.ktor.server.websocket.*
|
||||
import io.ktor.websocket.*
|
||||
import kotlinx.coroutines.CompletableDeferred
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.SupervisorJob
|
||||
import kotlinx.coroutines.cancel
|
||||
import kotlinx.coroutines.channels.ClosedReceiveChannelException
|
||||
import kotlinx.coroutines.delay
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.withTimeoutOrNull
|
||||
import kotlinx.serialization.Serializable
|
||||
import kotlinx.serialization.json.Json
|
||||
import org.koin.java.KoinJavaComponent.inject
|
||||
import org.slf4j.LoggerFactory
|
||||
import space.mori.chzzk_bot.common.events.*
|
||||
@@ -17,10 +23,16 @@ import space.mori.chzzk_bot.common.utils.YoutubeVideo
|
||||
import java.util.concurrent.ConcurrentHashMap
|
||||
import java.util.concurrent.ConcurrentLinkedQueue
|
||||
|
||||
val songScope = CoroutineScope(SupervisorJob() + Dispatchers.Default)
|
||||
fun Routing.wsSongRoutes() {
|
||||
environment.monitor.subscribe(ApplicationStopped) {
|
||||
songScope.cancel()
|
||||
}
|
||||
val sessions = ConcurrentHashMap<String, ConcurrentLinkedQueue<WebSocketServerSession>>()
|
||||
val status = ConcurrentHashMap<String, SongType>()
|
||||
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) {
|
||||
sessions.computeIfAbsent(uid) { ConcurrentLinkedQueue() }.add(session)
|
||||
@@ -28,7 +40,7 @@ fun Routing.wsSongRoutes() {
|
||||
|
||||
fun removeSession(uid: String, session: WebSocketServerSession) {
|
||||
sessions[uid]?.remove(session)
|
||||
if(sessions[uid]?.isEmpty() == true) {
|
||||
if (sessions[uid]?.isEmpty() == true) {
|
||||
sessions.remove(uid)
|
||||
}
|
||||
}
|
||||
@@ -42,104 +54,141 @@ fun Routing.wsSongRoutes() {
|
||||
var attempt = 0
|
||||
while (attempt < maxRetries) {
|
||||
try {
|
||||
session.sendSerialized(message) // 메시지 전송 시도
|
||||
return true // 성공하면 true 반환
|
||||
session.sendSerialized(message)
|
||||
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) {
|
||||
attempt++
|
||||
logger.info("Failed to send message on attempt $attempt. Retrying in $delayMillis ms.")
|
||||
e.printStackTrace()
|
||||
delay(delayMillis) // 재시도 전 대기
|
||||
delay(delayMillis)
|
||||
}
|
||||
}
|
||||
return false // 재시도 실패 시 false 반환
|
||||
return false
|
||||
}
|
||||
|
||||
fun broadcastMessage(userId: String, message: SongResponse) {
|
||||
val userSessions = sessions[userId]
|
||||
|
||||
userSessions?.forEach { session ->
|
||||
CoroutineScope(Dispatchers.Default).launch {
|
||||
songScope.launch {
|
||||
val success = sendWithRetry(session, message)
|
||||
if (!success) {
|
||||
println("Removing session for user $userId due to repeated failures.")
|
||||
userSessions.remove(session) // 실패 시 세션 제거
|
||||
logger.info("Removing session for user $userId due to repeated failures.")
|
||||
removeSession(userId, session)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
webSocket("/song/{uid}") {
|
||||
logger.info("WebSocket connection attempt received")
|
||||
val uid = call.parameters["uid"]
|
||||
val user = uid?.let { UserService.getUser(it) }
|
||||
if (uid == null) {
|
||||
if (uid == null || user == null) {
|
||||
logger.warn("Invalid UID: $uid")
|
||||
close(CloseReason(CloseReason.Codes.CANNOT_ACCEPT, "Invalid UID"))
|
||||
return@webSocket
|
||||
}
|
||||
if (user == null) {
|
||||
close(CloseReason(CloseReason.Codes.CANNOT_ACCEPT, "Invalid UID"))
|
||||
return@webSocket
|
||||
}
|
||||
|
||||
try {
|
||||
addSession(uid, this)
|
||||
logger.info("WebSocket connection established for user: $uid")
|
||||
|
||||
if(status[uid] == SongType.STREAM_OFF) {
|
||||
CoroutineScope(Dispatchers.Default).launch {
|
||||
sendSerialized(SongResponse(
|
||||
// Start heartbeat
|
||||
val heartbeatJob = songScope.launch {
|
||||
while (true) {
|
||||
try {
|
||||
send(Frame.Ping(ByteArray(0)))
|
||||
delay(30000) // 30 seconds
|
||||
} catch (e: Exception) {
|
||||
logger.error("Heartbeat failed for user $uid", e)
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (status[uid] == SongType.STREAM_OFF) {
|
||||
songScope.launch {
|
||||
sendSerialized(
|
||||
SongResponse(
|
||||
SongType.STREAM_OFF.value,
|
||||
uid,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
))
|
||||
)
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
for (frame in incoming) {
|
||||
when(frame) {
|
||||
when (frame) {
|
||||
is Frame.Text -> {
|
||||
if(frame.readText().trim() == "ping") {
|
||||
val text = frame.readText().trim()
|
||||
if (text == "ping") {
|
||||
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))
|
||||
else -> {
|
||||
|
||||
else -> {}
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch(e: ClosedReceiveChannelException) {
|
||||
logger.error("Error in WebSocket: ${e.message}")
|
||||
} catch (e: ClosedReceiveChannelException) {
|
||||
logger.error("WebSocket connection closed for user $uid: ${e.message}")
|
||||
} catch (e: Exception) {
|
||||
logger.error("Unexpected error in WebSocket for user $uid", e)
|
||||
} finally {
|
||||
logger.info("Cleaning up WebSocket connection for user $uid")
|
||||
removeSession(uid, this)
|
||||
ackMap[uid]?.remove(this)
|
||||
heartbeatJob.cancel()
|
||||
}
|
||||
} catch(e: Exception) {
|
||||
logger.error("Unexpected error in WebSocket for user $uid", e)
|
||||
}
|
||||
}
|
||||
|
||||
val dispatcher: CoroutinesEventBus by inject(CoroutinesEventBus::class.java)
|
||||
|
||||
dispatcher.subscribe(SongEvent::class) {
|
||||
logger.debug("SongEvent: {} / {} {}", it.uid, it.type, it.current?.name)
|
||||
CoroutineScope(Dispatchers.Default).launch {
|
||||
broadcastMessage(it.uid, SongResponse(
|
||||
songScope.launch {
|
||||
broadcastMessage(
|
||||
it.uid, SongResponse(
|
||||
it.type.value,
|
||||
it.uid,
|
||||
it.reqUid,
|
||||
it.current?.toSerializable(),
|
||||
it.next?.toSerializable(),
|
||||
it.delUrl
|
||||
))
|
||||
)
|
||||
)
|
||||
}
|
||||
}
|
||||
dispatcher.subscribe(TimerEvent::class) {
|
||||
if(it.type == TimerType.STREAM_OFF) {
|
||||
CoroutineScope(Dispatchers.Default).launch {
|
||||
broadcastMessage(it.uid, SongResponse(
|
||||
if (it.type == TimerType.STREAM_OFF) {
|
||||
songScope.launch {
|
||||
broadcastMessage(
|
||||
it.uid, SongResponse(
|
||||
it.type.value,
|
||||
it.uid,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
))
|
||||
)
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -152,9 +201,7 @@ data class SerializableYoutubeVideo(
|
||||
val author: String,
|
||||
val length: Int
|
||||
)
|
||||
|
||||
fun YoutubeVideo.toSerializable() = SerializableYoutubeVideo(url, name, author, length)
|
||||
|
||||
@Serializable
|
||||
data class SongResponse(
|
||||
val type: Int,
|
||||
|
@@ -1,13 +1,20 @@
|
||||
package space.mori.chzzk_bot.webserver.routes
|
||||
|
||||
import io.ktor.server.application.ApplicationStopped
|
||||
import io.ktor.server.routing.*
|
||||
import io.ktor.server.websocket.*
|
||||
import io.ktor.websocket.*
|
||||
import kotlinx.coroutines.CompletableDeferred
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.SupervisorJob
|
||||
import kotlinx.coroutines.cancel
|
||||
import kotlinx.coroutines.channels.ClosedReceiveChannelException
|
||||
import kotlinx.coroutines.delay
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.withTimeoutOrNull
|
||||
import kotlinx.serialization.Serializable
|
||||
import kotlinx.serialization.json.Json
|
||||
import org.koin.java.KoinJavaComponent.inject
|
||||
import org.slf4j.LoggerFactory
|
||||
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.ConcurrentLinkedQueue
|
||||
|
||||
val timerScope = CoroutineScope(SupervisorJob() + Dispatchers.Default)
|
||||
fun Routing.wsTimerRoutes() {
|
||||
environment.monitor.subscribe(ApplicationStopped) {
|
||||
timerScope.cancel()
|
||||
}
|
||||
val sessions = ConcurrentHashMap<String, ConcurrentLinkedQueue<WebSocketServerSession>>()
|
||||
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) {
|
||||
sessions.computeIfAbsent(uid) { ConcurrentLinkedQueue() }.add(session)
|
||||
}
|
||||
|
||||
fun removeSession(uid: String, session: WebSocketServerSession) {
|
||||
sessions[uid]?.remove(session)
|
||||
if(sessions[uid]?.isEmpty() == true) {
|
||||
@@ -32,82 +44,132 @@ fun Routing.wsTimerRoutes() {
|
||||
}
|
||||
}
|
||||
|
||||
suspend fun sendWithRetry(
|
||||
session: WebSocketServerSession,
|
||||
message: TimerResponse,
|
||||
maxRetries: Int = 3,
|
||||
delayMillis: Long = 2000L
|
||||
): Boolean {
|
||||
var attempt = 0
|
||||
while (attempt < maxRetries) {
|
||||
try {
|
||||
session.sendSerialized(message)
|
||||
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) {
|
||||
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) {
|
||||
if (uid == null || user == null) {
|
||||
close(CloseReason(CloseReason.Codes.CANNOT_ACCEPT, "Invalid UID"))
|
||||
return@webSocket
|
||||
}
|
||||
if (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) {
|
||||
CoroutineScope(Dispatchers.Default).launch {
|
||||
sendSerialized(TimerResponse(TimerType.STREAM_OFF.value, null))
|
||||
if (timer?.type == TimerType.STREAM_OFF) {
|
||||
timerScope.launch {
|
||||
sendSerialized(TimerResponse(TimerType.STREAM_OFF.value, null, uid))
|
||||
}
|
||||
} else {
|
||||
CoroutineScope(Dispatchers.Default).launch {
|
||||
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
|
||||
null,
|
||||
uid
|
||||
)
|
||||
)
|
||||
} else {
|
||||
sendSerialized(
|
||||
TimerResponse(
|
||||
timer.type.value,
|
||||
timer.time
|
||||
timer.time,
|
||||
uid
|
||||
)
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
try {
|
||||
for (frame in incoming) {
|
||||
when(frame) {
|
||||
is Frame.Text -> {
|
||||
if(frame.readText().trim() == "ping") {
|
||||
val text = frame.readText().trim()
|
||||
if(text == "ping") {
|
||||
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))
|
||||
else -> {
|
||||
|
||||
}
|
||||
else -> {}
|
||||
}
|
||||
}
|
||||
} catch(e: ClosedReceiveChannelException) {
|
||||
logger.error("Error in WebSocket: ${e.message}")
|
||||
} finally {
|
||||
removeSession(uid, this)
|
||||
ackMap[uid]?.remove(this)
|
||||
}
|
||||
}
|
||||
|
||||
val dispatcher: CoroutinesEventBus by inject(CoroutinesEventBus::class.java)
|
||||
|
||||
dispatcher.subscribe(TimerEvent::class) {
|
||||
logger.debug("TimerEvent: {} / {}", it.uid, it.type)
|
||||
val user = UserService.getUser(it.uid)
|
||||
CurrentTimer.setTimer(user!!, it)
|
||||
CoroutineScope(Dispatchers.Default).launch {
|
||||
sessions[it.uid]?.forEach { ws ->
|
||||
ws.sendSerialized(TimerResponse(it.type.value, it.time ?: ""))
|
||||
}
|
||||
timerScope.launch {
|
||||
broadcastMessage(it.uid, TimerResponse(it.type.value, it.time ?: "", it.uid))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Serializable
|
||||
data class TimerResponse(
|
||||
val type: Int,
|
||||
val time: String?
|
||||
val time: String?,
|
||||
val uid: String
|
||||
)
|
||||
@Serializable
|
||||
data class TimerRequest(
|
||||
val type: Int,
|
||||
val uid: String
|
||||
)
|
@@ -1,50 +0,0 @@
|
||||
package space.mori.chzzk_bot.webserver.utils
|
||||
|
||||
import kotlinx.coroutines.sync.Mutex
|
||||
import kotlinx.coroutines.sync.withLock
|
||||
import org.slf4j.LoggerFactory
|
||||
import space.mori.chzzk_bot.common.utils.IData
|
||||
import space.mori.chzzk_bot.common.utils.IStreamInfo
|
||||
import space.mori.chzzk_bot.common.utils.getStreamInfo
|
||||
import space.mori.chzzk_bot.common.utils.getUserInfo
|
||||
import java.time.Instant
|
||||
import java.util.concurrent.ConcurrentHashMap
|
||||
|
||||
object ChzzkUserCache {
|
||||
private val cache = ConcurrentHashMap<String, CachedUser>()
|
||||
private const val EXP_SECONDS = 600L
|
||||
private val mutex = Mutex()
|
||||
private val logger = LoggerFactory.getLogger(this::class.java)
|
||||
|
||||
suspend fun getCachedUser(id: String): IData<IStreamInfo?>? {
|
||||
val now = Instant.now()
|
||||
var user = cache[id]
|
||||
|
||||
if(user == null || user.timestamp.plusSeconds(EXP_SECONDS).isBefore(now)) {
|
||||
mutex.withLock {
|
||||
if(user == null || user.timestamp.plusSeconds(EXP_SECONDS)?.isBefore(now) != false) {
|
||||
var findUser = getStreamInfo(id)
|
||||
if(findUser.content == null) {
|
||||
val userInfo = getUserInfo(id)
|
||||
|
||||
if(userInfo.content == null) return null
|
||||
|
||||
findUser = IData(200, null, IStreamInfo(
|
||||
channel = userInfo.content!!
|
||||
))
|
||||
}
|
||||
|
||||
user = CachedUser(findUser)
|
||||
user.let { cache[id] = user }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return cache[id]?.user
|
||||
}
|
||||
}
|
||||
|
||||
data class CachedUser(
|
||||
val user: IData<IStreamInfo?>,
|
||||
val timestamp: Instant = Instant.now(),
|
||||
)
|
Reference in New Issue
Block a user