Compare commits

..

No commits in common. "593b98b7fb055bf794b5dd44222093be9c9bdef2" and "ba9fb052cd6a552ed61d6e75d164e635b1651459" have entirely different histories.

View File

@ -1,7 +1,11 @@
package space.mori.chzzk_bot.chatbot.chzzk package space.mori.chzzk_bot.chatbot.chzzk
import kotlinx.coroutines.* import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.future.await 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 import org.koin.java.KoinJavaComponent.inject
import org.slf4j.Logger import org.slf4j.Logger
import org.slf4j.LoggerFactory import org.slf4j.LoggerFactory
@ -13,8 +17,7 @@ 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.getChzzkChannelId import space.mori.chzzk_bot.common.utils.*
import space.mori.chzzk_bot.common.utils.getUptime
import xyz.r2turntrue.chzzk4j.ChzzkClient import xyz.r2turntrue.chzzk4j.ChzzkClient
import xyz.r2turntrue.chzzk4j.session.ChzzkSessionBuilder import xyz.r2turntrue.chzzk4j.session.ChzzkSessionBuilder
import xyz.r2turntrue.chzzk4j.session.ChzzkSessionSubscriptionType import xyz.r2turntrue.chzzk4j.session.ChzzkSessionSubscriptionType
@ -22,11 +25,10 @@ import xyz.r2turntrue.chzzk4j.session.ChzzkUserSession
import xyz.r2turntrue.chzzk4j.session.event.SessionChatMessageEvent import xyz.r2turntrue.chzzk4j.session.event.SessionChatMessageEvent
import xyz.r2turntrue.chzzk4j.types.channel.ChzzkChannel import xyz.r2turntrue.chzzk4j.types.channel.ChzzkChannel
import xyz.r2turntrue.chzzk4j.types.channel.live.ChzzkLiveDetail import xyz.r2turntrue.chzzk4j.types.channel.live.ChzzkLiveDetail
import java.lang.Runnable import java.lang.Exception
import java.lang.Thread
import java.net.SocketTimeoutException import java.net.SocketTimeoutException
import java.nio.charset.Charset
import java.time.LocalDateTime import java.time.LocalDateTime
import java.nio.charset.Charset
object ChzzkHandler { object ChzzkHandler {
private val handlers = mutableListOf<UserHandler>() private val handlers = mutableListOf<UserHandler>()
@ -81,10 +83,8 @@ object ChzzkHandler {
} }
fun disable() { fun disable() {
CoroutineScope(Dispatchers.Default).launch { handlers.forEach { handler ->
handlers.forEach { handler -> handler.disable()
handler.disable()
}
} }
} }
@ -118,7 +118,7 @@ object ChzzkHandler {
try { try {
it.isActive(true, streamInfo) it.isActive(true, streamInfo)
} catch(e: Exception) { } catch(e: Exception) {
logger.info("Thread 1 Exception: ${e.stackTraceToString()}") logger.info("Exception: ${e.stackTraceToString()}")
} }
} }
if (streamInfo?.isOnline == false && it.isActive) it.isActive(false, streamInfo) if (streamInfo?.isOnline == false && it.isActive) it.isActive(false, streamInfo)
@ -146,14 +146,14 @@ object ChzzkHandler {
try { try {
it.isActive(true, streamInfo) it.isActive(true, streamInfo)
} catch(e: Exception) { } catch(e: Exception) {
logger.info("Thread 2 Exception: ${e.stackTraceToString()}") logger.info("Exception: ${e.stackTraceToString()}")
} }
} }
if (streamInfo?.isOnline == false && it.isActive) it.isActive(false, streamInfo) if (streamInfo?.isOnline == false && it.isActive) it.isActive(false, streamInfo)
} catch (e: SocketTimeoutException) { } 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) { } catch (e: Exception) {
logger.info("Thread 2 Exception: ${it.channel.channelName} / ${e.stackTraceToString()}") logger.info("Thread 1 Exception: ${it.channel.channelName} / ${e.stackTraceToString()}")
} finally { } finally {
Thread.sleep(5000) Thread.sleep(5000)
} }
@ -204,10 +204,10 @@ class UserHandler(
private var user: User, private var user: User,
var streamStartTime: LocalDateTime?, var streamStartTime: LocalDateTime?,
) { ) {
lateinit var messageHandler: MessageHandler var messageHandler: MessageHandler
lateinit var client: ChzzkClient var client: ChzzkClient
lateinit var listener: ChzzkUserSession var listener: ChzzkUserSession
lateinit var chatChannelId: String var chatChannelId: String?
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
@ -216,53 +216,57 @@ class UserHandler(
LiveStatusService.updateOrCreate(user, value) LiveStatusService.updateOrCreate(user, value)
} }
private suspend fun connect() { init {
val user = UserService.getUser(channel.channelId) val user = UserService.getUser(channel.channelId)
if(user?.accessToken == null || user.refreshToken == null) { if(user?.accessToken == null || user.refreshToken == null) {
throw RuntimeException("AccessToken or RefreshToken is not valid.") throw RuntimeException("AccessToken or RefreshToken is not valid.")
} }
try {
val tokens = user.refreshToken?.let { token -> Connector.client.refreshAccessToken(token)}
if(tokens == null) {
throw RuntimeException("AccessToken is not valid.")
}
client = Connector.getClient(tokens.first, tokens.second)
UserService.setRefreshToken(user, tokens.first, tokens.second)
chatChannelId = getChzzkChannelId(channel.channelId)
val tokens = user.refreshToken?.let { token -> Connector.client.refreshAccessToken(token)} client.loginAsync().join()
if(tokens == null) { listener = ChzzkSessionBuilder(client).buildUserSession()
throw RuntimeException("AccessToken is not valid.") listener.createAndConnectAsync().join()
} messageHandler = MessageHandler(this@UserHandler)
client = Connector.getClient(tokens.first, tokens.second)
UserService.setRefreshToken(user, tokens.first, tokens.second)
chatChannelId = getChzzkChannelId(channel.channelId) ?: throw RuntimeException("Chat Channel ID is not found.")
client.loginAsync().await() listener.on(SessionChatMessageEvent::class.java) {
listener = ChzzkSessionBuilder(client).buildUserSession() messageHandler.handle(it.message, user)
listener.createAndConnectAsync().await() }
delay(1000L) GlobalScope.launch {
val timer = TimerConfigService.getConfig(user)
listener.on(SessionChatMessageEvent::class.java) { if (timer?.option == TimerType.UPTIME.value)
messageHandler.handle(it.message, user) dispatcher.post(
} TimerEvent(
channel.channelId,
val timer = TimerConfigService.getConfig(user) TimerType.UPTIME,
if (timer?.option == TimerType.UPTIME.value) getUptime(streamStartTime!!)
dispatcher.post( )
TimerEvent( )
channel.channelId, else dispatcher.post(
TimerType.UPTIME, TimerEvent(
getUptime(streamStartTime!!) channel.channelId,
TimerType.entries.firstOrNull { it.value == timer?.option } ?: TimerType.REMOVE,
null
)
) )
) }
else dispatcher.post(
TimerEvent( } catch(e: Exception) {
channel.channelId, logger.error("Exception(${user.username}): ${e.stackTraceToString()}")
TimerType.entries.firstOrNull { it.value == timer?.option } ?: TimerType.REMOVE, throw RuntimeException("Exception: ${e.stackTraceToString()}")
null }
)
)
messageHandler = MessageHandler(this@UserHandler)
} }
internal suspend fun disable() { internal fun disable() {
listener.disconnectAsync().await() listener.disconnectAsync().join()
_isActive = false _isActive = false
} }
@ -280,8 +284,6 @@ class UserHandler(
internal fun isActive(value: Boolean, status: ChzzkLiveDetail) { internal fun isActive(value: Boolean, status: ChzzkLiveDetail) {
if(value) { if(value) {
CoroutineScope(Dispatchers.Default).launch { CoroutineScope(Dispatchers.Default).launch {
connect()
logger.info("${user.username} is live.") logger.info("${user.username} is live.")
reloadUser(UserService.getUser(user.id.value)!!) reloadUser(UserService.getUser(user.id.value)!!)