Compare commits

..

No commits in common. "27810c0b7f482ed52defb79e6270e5b95d2638f5" and "1465716e728746cea6ada77331048d3b6cc750d5" have entirely different histories.

4 changed files with 57 additions and 137 deletions

View File

@ -1,9 +1,7 @@
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.launch
import org.koin.java.KoinJavaComponent.inject
@ -23,11 +21,10 @@ 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 xyz.r2turntrue.chzzk4j.types.channel.live.ChzzkLiveStatus
import java.lang.Exception
import java.net.SocketTimeoutException
import java.time.LocalDateTime
import java.nio.charset.Charset
object ChzzkHandler {
private val handlers = mutableListOf<UserHandler>()
@ -37,7 +34,7 @@ object ChzzkHandler {
private val dispatcher: CoroutinesEventBus by inject(CoroutinesEventBus::class.java)
fun addUser(chzzkChannel: ChzzkChannel, user: User) {
handlers.add(UserHandler(chzzkChannel, logger, user, streamStartTime = LocalDateTime.now()))
handlers.add(UserHandler(chzzkChannel, logger, user, streamStartTime = null))
}
fun enable() {
@ -196,7 +193,6 @@ object ChzzkHandler {
}
}
@OptIn(DelicateCoroutinesApi::class)
class UserHandler(
val channel: ChzzkChannel,
val logger: Logger,
@ -238,26 +234,6 @@ class 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()}")
@ -280,7 +256,7 @@ class UserHandler(
internal val isActive: Boolean
get() = _isActive
internal fun isActive(value: Boolean, status: ChzzkLiveDetail) {
internal fun isActive(value: Boolean, status: ChzzkLiveStatus) {
if(value) {
CoroutineScope(Dispatchers.Default).launch {
logger.info("${user.username} is live.")
@ -288,7 +264,7 @@ class UserHandler(
reloadUser(UserService.getUser(user.id.value)!!)
logger.info("ChzzkChat connecting... ${channel.channelName} - ${channel.channelId}")
listener.subscribeAsync(ChzzkSessionSubscriptionType.CHAT).join()
listener.subscribeAsync(ChzzkSessionSubscriptionType.CHAT)
streamStartTime = LocalDateTime.now()
@ -349,21 +325,7 @@ 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))
}
client.sendChatToLoggedInChannel(msg)
}
}

View File

@ -14,7 +14,7 @@ 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 xyz.r2turntrue.chzzk4j.types.channel.live.ChzzkLiveStatus
import kotlin.getValue
val dotenv = dotenv {
@ -31,7 +31,7 @@ object Connector {
private val dispatcher: CoroutinesEventBus by inject(CoroutinesEventBus::class.java)
fun getChannel(channelId: String): ChzzkChannel? = client.fetchChannel(channelId)
fun getLive(channelId: String): ChzzkLiveDetail? = client.fetchLiveDetail(channelId)
fun getLive(channelId: String): ChzzkLiveStatus? = client.fetchLiveStatus(channelId)
init {
logger.info("chzzk logged: ${client.isLoggedIn}")

View File

@ -14,8 +14,7 @@ import net.dv8tion.jda.api.utils.messages.MessageCreateBuilder
import org.slf4j.LoggerFactory
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 xyz.r2turntrue.chzzk4j.types.channel.live.ChzzkLiveStatus
import java.time.Instant
import kotlin.jvm.optionals.getOrNull
@ -34,7 +33,7 @@ class Discord: ListenerAdapter() {
return bot.getGuildById(guildId)?.getTextChannelById(channelId)
}
fun sendDiscord(user: User, status: ChzzkLiveDetail) {
fun sendDiscord(user: User, status: ChzzkLiveStatus) {
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.")
@ -46,14 +45,7 @@ class Discord: ListenerAdapter() {
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
}
}
// embed.setImage(status.)
channel.sendMessage(
MessageCreateBuilder()

View File

@ -37,7 +37,6 @@ fun Routing.wsSongRoutes() {
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) {
@ -89,42 +88,22 @@ fun Routing.wsSongRoutes() {
}
webSocket("/song/{uid}") {
logger.info("WebSocket connection attempt received")
val uid = call.parameters["uid"]
val user = uid?.let { UserService.getUser(it) }
if (uid == null || user == null) {
logger.warn("Invalid UID: $uid")
close(CloseReason(CloseReason.Codes.CANNOT_ACCEPT, "Invalid UID"))
return@webSocket
}
try {
addSession(uid, this)
logger.info("WebSocket connection established for user: $uid")
// 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(
sendSerialized(SongResponse(
SongType.STREAM_OFF.value,
uid,
null,
null,
null,
)
)
))
}
}
try {
@ -142,58 +121,45 @@ fun Routing.wsSongRoutes() {
}
}
}
is Frame.Ping -> send(Frame.Pong(frame.data))
else -> {}
}
}
} 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)
logger.error("Error in WebSocket: ${e.message}")
} 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)
}
}
dispatcher.subscribe(SongEvent::class) {
logger.debug("SongEvent: {} / {} {}", it.uid, it.type, it.current?.name)
songScope.launch {
broadcastMessage(
it.uid, SongResponse(
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) {
songScope.launch {
broadcastMessage(
it.uid, SongResponse(
broadcastMessage(it.uid, SongResponse(
it.type.value,
it.uid,
null,
null,
null,
)
)
))
}
}
}
}
@Serializable
data class SerializableYoutubeVideo(
val url: String,