mirror of
https://github.com/dalbodeule/chibot-chzzk-bot.git
synced 2025-08-10 22:31:13 +00:00
Compare commits
56 Commits
d92ad1cc51
...
debug
Author | SHA1 | Date | |
---|---|---|---|
|
f27c0da775 | ||
|
c528448b5e | ||
|
db78bf3ff6 | ||
|
d7d4228063 | ||
|
b1432c662f | ||
|
19fcc15fe1 | ||
|
b497c690af | ||
|
866fe19cb9 | ||
|
e21641da7b | ||
|
66df771cb7 | ||
|
9e3a79a613 | ||
|
945d3fd5e4 | ||
|
af9c3a2cf5 | ||
|
bd31039f2b | ||
|
c5c115f6e6 | ||
|
5683edaa5e | ||
|
c86f0b2ab3 | ||
|
27cfbd9087 | ||
|
9ce07a025a | ||
|
073b50b9cd | ||
|
f37dd2c59a | ||
|
864ba3748d | ||
|
593b98b7fb | ||
|
95676e9b39 | ||
|
722b5972d9 | ||
|
a88f994ccd | ||
|
49541f7289 | ||
|
ba9fb052cd | ||
|
51232ad593 | ||
|
77eecaca34 | ||
|
90230c4691 | ||
|
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 |
41
README.md
41
README.md
@@ -1,6 +1,6 @@
|
||||
# nabot_chzzk_bot
|
||||
# chibot_chzzk_bot
|
||||
|
||||
[](https://discord.gg/up8ANZegmy) [](https://teamcity.mori.space/project/NabotChzzkBot) [](https://hub.docker.com/repository/docker/dalbodeule/chzzkbot/general)
|
||||
[](https://discord.gg/up8ANZegmy) [](https://teamcity.mori.space/project/NabotChzzkBot)
|
||||
|
||||
## Chzzk Chatbot with [JDA5](https://github.com/discord-jda/JDA), [chzzk4j](https://github.com/R2turnTrue/chzzk4j)
|
||||
|
||||
@@ -17,17 +17,6 @@
|
||||
- [x] \<daily_counter:counter_name>
|
||||
- [x] \<days:yyyy-mm-dd>
|
||||
|
||||
### 관리 명령어 (on Discord)
|
||||
- [x] /hook token: \[디스코드 연동 페이지에서 받은 Token]
|
||||
- [x] /alert channel: \[디스코드 Channel ID] content: \[알림 내용]
|
||||
- [x] /add label: \[명령어] content: \[내용]
|
||||
- [ ] /list
|
||||
- [x] /update label: \[명령어] content: \[내용]
|
||||
- [x] /delete label: \[명령어]
|
||||
### 매니저 명령어 (on Discord)
|
||||
- [x] /addmanager user: \[Discord user]
|
||||
- [x] /listmanager
|
||||
- [x] /removemanager user: \[Discord user]
|
||||
### 관리 명령어 (on Chzzk chat)
|
||||
- [x] !명령어추가 \[명령어] \[내용]
|
||||
- [x] !명령어수정 \[명령어] \[내용]
|
||||
@@ -42,32 +31,6 @@
|
||||
- [ ] !노래삭제 \[번호]
|
||||
- [ ] !노래설정 \[내용] \[켜기/끄기]
|
||||
|
||||
### Envs
|
||||
- DISCORD_TOKEN
|
||||
- DB_URL
|
||||
- DB_USER
|
||||
- DB_PASS
|
||||
- RUN_AGENT = `false`
|
||||
- NID_AUT
|
||||
- NID_SES
|
||||
|
||||
### 사용 예시
|
||||
- 팔로우
|
||||
- `/add label: !팔로우 content: <name>님은 오늘로 <following>일째 팔로우네요!`
|
||||
- 출첵
|
||||
- `/add label: !출첵 content: <name>님의 <daily_counter:attendance>번째 출석! fail_content: <name>님은 오늘 이미 출석했어요! <daily_counter:attendance>번 했네요?`
|
||||
- `/add label: ? content: <name>님이 <counter:hook>개째 갈고리 수집`
|
||||
- ㄱㅇㅇ
|
||||
- `/add label: ㄱㅇㅇ content: <counter:cute>번째 ㄱㅇㅇ`
|
||||
- `/add label: ㄱㅇㅇ content: 나누 귀여움 +<counter:cute>`
|
||||
- 풉
|
||||
- `/add label: 풉 content: <counter:poop>번째 비웃음?`
|
||||
- `/add label: 풉키풉키 content: <counter:poop>번째 비웃음?`
|
||||
- 바보
|
||||
- `/add label: 바보 content: 나 바보 아니다?`
|
||||
- `/add label: 바보 content: <counter:fool> 번째 바보? 나 바보 아니다?`
|
||||
- 첫방송
|
||||
- `/add label: 첫방송 content: 24년 7월 23일부터 <days:2024-07-23>일 째 방송중!`
|
||||
|
||||
## 사용 기술스택
|
||||
- [Exposed](https://github.com/JetBrains/Exposed)
|
||||
|
@@ -29,6 +29,7 @@ repositories {
|
||||
dependencies {
|
||||
// https://mvnrepository.com/artifact/ch.qos.logback/logback-classic
|
||||
implementation("ch.qos.logback:logback-classic:1.5.13")
|
||||
implementation("com.github.loki4j:loki-logback-appender:2.0.0")
|
||||
|
||||
// https://mvnrepository.com/artifact/org.jetbrains.kotlinx/kotlinx-coroutines-core
|
||||
implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.9.0")
|
||||
|
@@ -1,35 +1,34 @@
|
||||
package space.mori.chzzk_bot.chatbot.chzzk
|
||||
|
||||
import com.google.gson.Gson
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.delay
|
||||
import kotlinx.coroutines.*
|
||||
import kotlinx.coroutines.future.await
|
||||
import kotlinx.coroutines.launch
|
||||
import okhttp3.OkHttpClient
|
||||
import org.koin.java.KoinJavaComponent.inject
|
||||
import org.slf4j.Logger
|
||||
import org.slf4j.LoggerFactory
|
||||
import space.mori.chzzk_bot.chatbot.chzzk.Connector.client as ChzzkClient
|
||||
import space.mori.chzzk_bot.chatbot.chzzk.Connector.getChannel
|
||||
import space.mori.chzzk_bot.chatbot.discord.Discord
|
||||
import space.mori.chzzk_bot.chatbot.utils.refreshAccessToken
|
||||
import space.mori.chzzk_bot.common.events.*
|
||||
import space.mori.chzzk_bot.common.metrics.Metrics
|
||||
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 space.mori.chzzk_bot.common.utils.getChzzkChannelId
|
||||
import space.mori.chzzk_bot.common.utils.getUptime
|
||||
import xyz.r2turntrue.chzzk4j.ChzzkClient
|
||||
import xyz.r2turntrue.chzzk4j.auth.ChzzkSimpleUserLoginAdapter
|
||||
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 java.lang.Exception
|
||||
import xyz.r2turntrue.chzzk4j.types.channel.live.ChzzkLiveDetail
|
||||
import java.lang.Runnable
|
||||
import java.lang.Thread
|
||||
import java.net.SocketTimeoutException
|
||||
import java.nio.charset.Charset
|
||||
import java.time.LocalDateTime
|
||||
import java.util.concurrent.ConcurrentHashMap
|
||||
|
||||
object ChzzkHandler {
|
||||
private val handlers = mutableListOf<UserHandler>()
|
||||
@@ -38,23 +37,27 @@ object ChzzkHandler {
|
||||
@Volatile private var running: Boolean = false
|
||||
private val dispatcher: CoroutinesEventBus by inject(CoroutinesEventBus::class.java)
|
||||
|
||||
private val lastRunMap = ConcurrentHashMap<String, Long>()
|
||||
private val requiredWait = 300_000L
|
||||
|
||||
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 = Connector.client.fetchLoggedUser().userId
|
||||
UserService.getAllUsers().map {
|
||||
if(!it.isDisabled)
|
||||
try {
|
||||
Connector.getChannel(it.token)?.let { token -> addUser(token, it) }
|
||||
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.channel.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) {
|
||||
@@ -83,8 +86,10 @@ object ChzzkHandler {
|
||||
}
|
||||
|
||||
fun disable() {
|
||||
handlers.forEach { handler ->
|
||||
handler.disable()
|
||||
CoroutineScope(Dispatchers.Default).launch {
|
||||
handlers.forEach { handler ->
|
||||
handler.disable()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -113,20 +118,21 @@ 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()}")
|
||||
logger.info("Thread 1 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) {
|
||||
logger.info("Thread 1 Exception: ${it.channel.channelName} / ${e.stackTraceToString()}")
|
||||
} finally {
|
||||
lastRunMap[it.channel.channelId] = System.currentTimeMillis()
|
||||
Thread.sleep(5000)
|
||||
}
|
||||
}
|
||||
@@ -135,21 +141,30 @@ object ChzzkHandler {
|
||||
}
|
||||
|
||||
val threadRunner2 = Runnable {
|
||||
logger.info("Thread 2 started!")
|
||||
logger.info("Thread 2 started!")
|
||||
while (running) {
|
||||
handlers.forEach {
|
||||
if (!running) return@forEach
|
||||
try {
|
||||
val streamInfo = getStreamInfo(it.channel.channelId)
|
||||
if (streamInfo.content?.status == "OPEN" && !it.isActive) {
|
||||
val now = System.currentTimeMillis()
|
||||
val lastRun = lastRunMap[it.channel.channelId] ?: 0L
|
||||
val waitedTime = now - lastRun
|
||||
|
||||
if(waitedTime < requiredWait) {
|
||||
val sleepTime = requiredWait - waitedTime
|
||||
logger.info("Thread 2 Sleep: ${it.channel.channelName} / ${sleepTime}ms")
|
||||
Thread.sleep(sleepTime)
|
||||
}
|
||||
|
||||
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()}")
|
||||
logger.info("Thread 2 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()}")
|
||||
} catch (e: Exception) {
|
||||
@@ -197,15 +212,18 @@ object ChzzkHandler {
|
||||
}
|
||||
}
|
||||
|
||||
@OptIn(DelicateCoroutinesApi::class)
|
||||
class UserHandler(
|
||||
val channel: ChzzkChannel,
|
||||
val logger: Logger,
|
||||
private var user: User,
|
||||
var streamStartTime: LocalDateTime?,
|
||||
val chatLogger: Logger = LoggerFactory.getLogger("${channel.channelName}-chat"),
|
||||
) {
|
||||
var messageHandler: MessageHandler
|
||||
lateinit var client: ChzzkClient
|
||||
lateinit var listener: ChzzkUserSession
|
||||
lateinit var chatChannelId: String
|
||||
var listener: ChzzkUserSession? = null
|
||||
lateinit var messageHandler: MessageHandler
|
||||
|
||||
private val dispatcher: CoroutinesEventBus by inject(CoroutinesEventBus::class.java)
|
||||
private var _isActive: Boolean
|
||||
@@ -214,30 +232,55 @@ class UserHandler(
|
||||
LiveStatusService.updateOrCreate(user, value)
|
||||
}
|
||||
|
||||
init {
|
||||
private suspend fun connect() {
|
||||
val user = UserService.getUser(channel.channelId)
|
||||
|
||||
if(user?.accessToken == null || user.refreshToken == null) {
|
||||
throw RuntimeException("AccessToken or RefreshToken is not valid.")
|
||||
}
|
||||
|
||||
val tokens = ChzzkClient.refreshAccessToken(user.refreshToken!!)
|
||||
|
||||
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) ?: throw RuntimeException("Chat Channel ID is not found.")
|
||||
|
||||
client.loginAsync().await()
|
||||
listener = ChzzkSessionBuilder(client).buildUserSession()
|
||||
|
||||
UserService.setRefreshToken(user, tokens.first, tokens.second)
|
||||
delay(5000L)
|
||||
|
||||
listener.createAndConnectAsync().join()
|
||||
|
||||
listener.on(SessionChatMessageEvent::class.java) {
|
||||
messageHandler = MessageHandler(this@UserHandler)
|
||||
logger.info("${user.username} message handler init.")
|
||||
listener?.on(SessionChatMessageEvent::class.java) {
|
||||
messageHandler.handle(it.message, user)
|
||||
}
|
||||
messageHandler = MessageHandler(this@UserHandler)
|
||||
logger.info("${user.username} is connected.")
|
||||
|
||||
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
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
internal fun disable() {
|
||||
listener.disconnectAsync().join()
|
||||
internal suspend fun disable() {
|
||||
listener?.unsubscribeAsync(ChzzkSessionSubscriptionType.CHAT)?.await()
|
||||
listener?.disconnectAsync()?.await()
|
||||
|
||||
_isActive = false
|
||||
}
|
||||
|
||||
@@ -252,17 +295,21 @@ 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 {
|
||||
if(listener == null)
|
||||
connect()
|
||||
|
||||
listener!!.createAndConnectAsync()?.await()
|
||||
listener!!.subscribeAsync(ChzzkSessionSubscriptionType.CHAT)?.await()
|
||||
logger.info("${user.username} is live.")
|
||||
|
||||
reloadUser(UserService.getUser(user.id.value)!!)
|
||||
|
||||
logger.info("ChzzkChat connecting... ${channel.channelName} - ${channel.channelId}")
|
||||
listener.subscribeAsync(ChzzkSessionSubscriptionType.CHAT)
|
||||
|
||||
streamStartTime = status.content?.openDate?.let { convertChzzkDateToLocalDateTime(it) }
|
||||
streamStartTime = LocalDateTime.now()
|
||||
Metrics.increaseStreaming()
|
||||
|
||||
if(!_isActive) {
|
||||
_isActive = true
|
||||
@@ -296,8 +343,10 @@ class UserHandler(
|
||||
} else {
|
||||
logger.info("${user.username} is offline.")
|
||||
streamStartTime = null
|
||||
listener.disconnectAsync().join()
|
||||
listener?.unsubscribeAsync(ChzzkSessionSubscriptionType.CHAT)?.join()
|
||||
listener?.disconnectAsync()?.join()
|
||||
_isActive = false
|
||||
Metrics.decreaseStreaming()
|
||||
|
||||
CoroutineScope(Dispatchers.Default).launch {
|
||||
val events = listOf(
|
||||
@@ -321,7 +370,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) {
|
||||
client.sendChatToLoggedInChannel(msg)
|
||||
GlobalScope.launch {
|
||||
delay(100L)
|
||||
client.sendChatToLoggedInChannel(msg.limitUtf8Length(100))
|
||||
chatLogger.info("[SEND]${channel.channelName}: ${msg.limitUtf8Length(100)}{${msg.length} / 100}")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@@ -1,28 +1,56 @@
|
||||
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 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.ChzzkOauthLoginAdapter
|
||||
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 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? = client.fetchChannel(channelId)
|
||||
fun getLive(channelId: String): ChzzkLiveDetail? = client.fetchLiveDetail(channelId)
|
||||
|
||||
init {
|
||||
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 {
|
||||
@@ -33,4 +61,6 @@ object Connector {
|
||||
|
||||
return client
|
||||
}
|
||||
|
||||
|
||||
}
|
@@ -11,10 +11,8 @@ import space.mori.chzzk_bot.common.services.*
|
||||
import space.mori.chzzk_bot.common.utils.getFollowDate
|
||||
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 xyz.r2turntrue.chzzk4j.types.channel.live.ChzzkLiveSettings
|
||||
import java.time.LocalDateTime
|
||||
import java.time.format.DateTimeFormatter
|
||||
import java.time.temporal.ChronoUnit
|
||||
@@ -33,17 +31,20 @@ class MessageHandler(
|
||||
|
||||
private val channel = handler.channel
|
||||
private val logger = handler.logger
|
||||
private val chatLogger = handler.chatLogger
|
||||
private val listener = handler.listener
|
||||
|
||||
private val dispatcher: CoroutinesEventBus by inject(CoroutinesEventBus::class.java)
|
||||
|
||||
init {
|
||||
reloadCommand()
|
||||
dispatcher.subscribe(SongEvent::class) {
|
||||
if(it.type == SongType.STREAM_OFF) {
|
||||
val user = UserService.getUser(channel.channelId)
|
||||
if(! user?.let { usr -> SongListService.getSong(usr) }.isNullOrEmpty()) {
|
||||
SongListService.deleteUser(user)
|
||||
CoroutineScope(Dispatchers.Default).launch {
|
||||
dispatcher.subscribe(SongEvent::class) {
|
||||
if(it.type == SongType.STREAM_OFF) {
|
||||
val user = UserService.getUser(channel.channelId)
|
||||
if(! user?.let { usr -> SongListService.getSong(usr) }.isNullOrEmpty()) {
|
||||
SongListService.deleteUser(user)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -62,6 +63,8 @@ class MessageHandler(
|
||||
"!신청곡" to this::songAddCommand,
|
||||
"!노래목록" to this::songListCommand,
|
||||
"!노래시작" to this::songStartCommand,
|
||||
"!카테고리" to this::categoryChangeCommand,
|
||||
"!방제" to this::titleChangeCommand,
|
||||
)
|
||||
|
||||
manageCommands.forEach { (commandName, command) ->
|
||||
@@ -84,11 +87,11 @@ class MessageHandler(
|
||||
}
|
||||
|
||||
private fun commandListCommand(msg: SessionChatMessage, user: User) {
|
||||
handler.sendChat("리스트는 여기입니다. https://nabot.mori.space/commands/${user.token}")
|
||||
handler.sendChat("리스트는 여기입니다. https://chibot.mori.space/commands/${user.token}")
|
||||
}
|
||||
|
||||
private fun manageAddCommand(msg: SessionChatMessage, user: User) {
|
||||
if (msg.profile.badges.size == 0) {
|
||||
if (msg.profile.badges.none { it.isModerator() }) {
|
||||
handler.sendChat("매니저만 명령어를 추가할 수 있습니다.")
|
||||
return
|
||||
}
|
||||
@@ -109,7 +112,7 @@ class MessageHandler(
|
||||
}
|
||||
|
||||
private fun manageUpdateCommand(msg: SessionChatMessage, user: User) {
|
||||
if (msg.profile.badges.size == 0) {
|
||||
if (msg.profile.badges.none { it.isModerator() }) {
|
||||
handler.sendChat("매니저만 명령어를 추가할 수 있습니다.")
|
||||
return
|
||||
}
|
||||
@@ -131,7 +134,7 @@ class MessageHandler(
|
||||
}
|
||||
|
||||
private fun manageRemoveCommand(msg: SessionChatMessage, user: User) {
|
||||
if (msg.profile.badges.size == 0) {
|
||||
if (msg.profile.badges.none { it.isModerator() }) {
|
||||
handler.sendChat("매니저만 명령어를 삭제할 수 있습니다.")
|
||||
return
|
||||
}
|
||||
@@ -148,7 +151,7 @@ class MessageHandler(
|
||||
}
|
||||
|
||||
private fun timerCommand(msg: SessionChatMessage, user: User) {
|
||||
if (msg.profile.badges.size == 0) {
|
||||
if (msg.profile.badges.none { it.isModerator() }) {
|
||||
handler.sendChat("매니저만 이 명령어를 사용할 수 있습니다.")
|
||||
return
|
||||
}
|
||||
@@ -227,7 +230,7 @@ class MessageHandler(
|
||||
|
||||
val config = SongConfigService.getConfig(user)
|
||||
|
||||
if(config.streamerOnly && msg.profile.badges.size == 0) {
|
||||
if(config.streamerOnly && msg.profile.badges.none { it.imageUrl.contains("manager") || it.imageUrl.contains("streamer") }) {
|
||||
handler.sendChat("매니저만 이 명령어를 사용할 수 있습니다.")
|
||||
return
|
||||
}
|
||||
@@ -294,11 +297,11 @@ class MessageHandler(
|
||||
return
|
||||
}
|
||||
|
||||
handler.sendChat("리스트는 여기입니다. https://nabot.mori.space/songs/${user.token}")
|
||||
handler.sendChat("리스트는 여기입니다. https://chibot.mori.space/songs/${user.token}")
|
||||
}
|
||||
|
||||
private fun songStartCommand(msg: SessionChatMessage, user: User) {
|
||||
if (msg.profile?.badges?.size == 0) {
|
||||
if (msg.profile.badges.none { it.isModerator() }) {
|
||||
handler.sendChat("매니저만 이 명령어를 사용할 수 있습니다.")
|
||||
return
|
||||
}
|
||||
@@ -307,7 +310,7 @@ class MessageHandler(
|
||||
if(user.discord != null) {
|
||||
bot.retrieveUserById(user.discord!!).queue { discordUser ->
|
||||
discordUser?.openPrivateChannel()?.queue { channel ->
|
||||
channel.sendMessage("여기로 접속해주세요! ||https://nabot.mori.space/songlist||.")
|
||||
channel.sendMessage("여기로 접속해주세요! ||https://chibot.mori.space/songlist||.")
|
||||
.queue()
|
||||
}
|
||||
}
|
||||
@@ -316,9 +319,61 @@ class MessageHandler(
|
||||
}
|
||||
}
|
||||
|
||||
private fun categoryChangeCommand(msg: SessionChatMessage, user: User) {
|
||||
if (msg.profile.badges.none { it.isModerator() }) {
|
||||
handler.sendChat("매니저만 이 명령어를 사용할 수 있습니다.")
|
||||
return
|
||||
}
|
||||
|
||||
val parts = msg.content.split(" ", limit = 2)
|
||||
if(parts.size <= 1) {
|
||||
handler.sendChat("카테고리가 없습니다.")
|
||||
return
|
||||
}
|
||||
val category = parts[1].let {
|
||||
return@let when(it) {
|
||||
"저챗", "토크", "JustChatting", "Just Chatting", "" -> "talk"
|
||||
else -> it
|
||||
}
|
||||
}
|
||||
handler.sendChat("$category 카테고리로 수정을 시도해볼게요!")
|
||||
handler.client.searchCategories(category).handle { result, _ ->
|
||||
if(result.size == 0) {
|
||||
handler.sendChat("$category 카테고리는 없습니다.")
|
||||
return@handle
|
||||
}
|
||||
val settings = ChzzkLiveSettings()
|
||||
settings.category = result.first {
|
||||
it.categoryValue == category
|
||||
} ?: result[0]
|
||||
|
||||
handler.client.modifyLiveSettings(settings)
|
||||
handler.sendChat("$category 로 수정했어요!")
|
||||
}
|
||||
}
|
||||
|
||||
private fun titleChangeCommand(msg: SessionChatMessage, user: User) {
|
||||
if (msg.profile.badges.none { it.isModerator() }) {
|
||||
handler.sendChat("매니저만 이 명령어를 사용할 수 있습니다.")
|
||||
return
|
||||
}
|
||||
|
||||
val parts = msg.content.split(" ", limit = 2)
|
||||
if(parts.size <= 1) {
|
||||
handler.sendChat("입력된 방송 제목이 없습니다.")
|
||||
return
|
||||
}
|
||||
val title = parts[1]
|
||||
val settings = ChzzkLiveSettings()
|
||||
settings.defaultLiveTitle = title
|
||||
|
||||
handler.client.modifyLiveSettings(settings)
|
||||
handler.sendChat("$title 로 수정했어요!")
|
||||
}
|
||||
|
||||
internal fun handle(msg: SessionChatMessage, user: User) {
|
||||
if(msg.senderChannelId == ChzzkHandler.botUid) return
|
||||
|
||||
chatLogger.info("[RECV]${channel.channelName}: ${msg.content}{${msg.content.length} / 100}")
|
||||
val commandKey = msg.content.split(' ')[0]
|
||||
commands[commandKey.lowercase()]?.let { it(msg, user) }
|
||||
}
|
||||
@@ -353,15 +408,15 @@ class MessageHandler(
|
||||
// Replace followPattern
|
||||
result = followPattern.replace(result) { _ ->
|
||||
try {
|
||||
val followingDate = getFollowDate(channel.channelId, msg.senderChannelId)
|
||||
.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) {
|
||||
@@ -398,3 +453,7 @@ class MessageHandler(
|
||||
return result
|
||||
}
|
||||
}
|
||||
|
||||
fun SessionChatMessage.Profile.Badge.isManager() = imageUrl.contains("manager")
|
||||
fun SessionChatMessage.Profile.Badge.isStreamer() = imageUrl.contains("streamer")
|
||||
fun SessionChatMessage.Profile.Badge.isModerator() = isManager() || isStreamer()
|
@@ -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()
|
||||
|
@@ -1,24 +1,15 @@
|
||||
package space.mori.chzzk_bot.chatbot.utils
|
||||
|
||||
import com.google.gson.Gson
|
||||
import okhttp3.OkHttpClient
|
||||
import com.google.gson.reflect.TypeToken
|
||||
import okhttp3.MediaType.Companion.toMediaType
|
||||
import okhttp3.Request
|
||||
import okhttp3.RequestBody.Companion.toRequestBody
|
||||
import space.mori.chzzk_bot.chatbot.chzzk.dotenv
|
||||
import space.mori.chzzk_bot.common.utils.IData
|
||||
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,
|
||||
@@ -36,18 +27,18 @@ fun ChzzkClient.refreshAccessToken(refreshToken: String): Pair<String, String> {
|
||||
.post(gson.toJson(mapOf(
|
||||
"grantType" to "refresh_token",
|
||||
"refreshToken" to refreshToken,
|
||||
"clientId" to this.apiClientId,
|
||||
"clientSecret" to this.apiSecret
|
||||
)).toRequestBody())
|
||||
"clientId" to dotenv["NAVER_CLIENT_ID"],
|
||||
"clientSecret" to dotenv["NAVER_CLIENT_SECRET"]
|
||||
)).toRequestBody("application/json; charset=utf-8".toMediaType()))
|
||||
.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)
|
||||
val data = gson.fromJson(body, object: TypeToken<IData<RefreshTokenResponse>>() {})
|
||||
|
||||
return Pair(data.accessToken, data.refreshToken)
|
||||
return Pair(data.content.accessToken, data.content.refreshToken)
|
||||
} catch(e: Exception) {
|
||||
throw e
|
||||
}
|
||||
|
@@ -37,6 +37,11 @@ dependencies {
|
||||
// https://mvnrepository.com/artifact/com.google.code.gson/gson
|
||||
implementation("com.google.code.gson:gson:2.11.0")
|
||||
|
||||
api("io.micrometer:micrometer-registry-prometheus:1.15.1")
|
||||
|
||||
// https://mvnrepository.com/artifact/io.insert-koin/koin-core
|
||||
api("io.insert-koin:koin-core:4.0.0")
|
||||
|
||||
testImplementation(kotlin("test"))
|
||||
}
|
||||
|
||||
|
@@ -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
|
||||
}
|
@@ -0,0 +1,43 @@
|
||||
package space.mori.chzzk_bot.common.metrics
|
||||
|
||||
import io.micrometer.core.instrument.Gauge
|
||||
import io.micrometer.prometheusmetrics.PrometheusConfig
|
||||
import io.micrometer.prometheusmetrics.PrometheusMeterRegistry
|
||||
import space.mori.chzzk_bot.common.services.UserService
|
||||
|
||||
object Metrics {
|
||||
val registry = PrometheusMeterRegistry(PrometheusConfig.DEFAULT)
|
||||
|
||||
var streamer = 0.0
|
||||
val streamerGauge: Gauge = Gauge.builder("streamer_gauge", this) { streamer }
|
||||
.description("Current All Streamer Count")
|
||||
.register(registry)
|
||||
|
||||
var activeStreamer = 0.0
|
||||
val activateGauge: Gauge = Gauge.builder("active_streamer_gauge", this) { activeStreamer }
|
||||
.description("Current Active Streamer Count")
|
||||
.register(registry)
|
||||
|
||||
var streaming: Double = 0.0
|
||||
val streamingGauge: Gauge = Gauge.builder("streaming_gauge", this) { streaming }
|
||||
.description("Current Streaming Streamer Count")
|
||||
.register(registry)
|
||||
|
||||
fun refreshStreamerMetrics() {
|
||||
val streamers = UserService.getAllUsers()
|
||||
|
||||
streamer = streamers.size.toDouble()
|
||||
activeStreamer = streamers.filter { !it.isDisabled }.size.toDouble()
|
||||
}
|
||||
|
||||
fun increaseStreaming(inc: Int = 1) {
|
||||
streaming += inc
|
||||
}
|
||||
fun decreaseStreaming(dec: Int = 1) {
|
||||
streaming -= dec
|
||||
}
|
||||
|
||||
init {
|
||||
refreshStreamerMetrics()
|
||||
}
|
||||
}
|
@@ -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,40 +99,23 @@ 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
|
||||
return data.content?.chatChannelId
|
||||
} 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
|
||||
} catch(e: Exception) {
|
||||
throw e
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
@@ -12,6 +12,7 @@ import space.mori.chzzk_bot.chatbot.discord.Discord
|
||||
import space.mori.chzzk_bot.chatbot.chzzk.Connector as ChzzkConnector
|
||||
import space.mori.chzzk_bot.common.Connector
|
||||
import space.mori.chzzk_bot.common.events.CoroutinesEventBus
|
||||
import space.mori.chzzk_bot.common.metrics.Metrics
|
||||
import space.mori.chzzk_bot.webserver.start
|
||||
import space.mori.chzzk_bot.webserver.stop
|
||||
import java.util.concurrent.TimeUnit
|
||||
@@ -25,6 +26,7 @@ val logger: Logger = LoggerFactory.getLogger("main")
|
||||
fun main(args: Array<String>) {
|
||||
val dispatcher = module {
|
||||
single { CoroutinesEventBus() }
|
||||
single { Metrics.registry }
|
||||
}
|
||||
startKoin {
|
||||
modules(dispatcher)
|
||||
|
@@ -1,5 +1,5 @@
|
||||
<configuration>
|
||||
|
||||
<property name="lokiUrl" value="${LOKI_ENDPOINT}"/>
|
||||
<!-- 콘솔에 출력하는 기본 로그 설정 -->
|
||||
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
|
||||
<filter class="ch.qos.logback.classic.filter.ThresholdFilter">
|
||||
@@ -10,6 +10,15 @@
|
||||
</encoder>
|
||||
</appender>
|
||||
|
||||
<appender name="LOKI" class="com.github.loki4j.logback.Loki4jAppender">
|
||||
<http>
|
||||
<url>${lokiUrl}</url>
|
||||
</http>
|
||||
<labels>
|
||||
app = chibot-chzzk-bot
|
||||
</labels>
|
||||
</appender>
|
||||
|
||||
<!-- HikariCP 로그 레벨 설정 -->
|
||||
<logger name="com.zaxxer.hikari" level="INFO" />
|
||||
<logger name="o.m.jdbc.client.impl.StandardClient" level="INFO" />
|
||||
@@ -31,5 +40,8 @@
|
||||
<root level="DEBUG">
|
||||
<appender-ref ref="STDOUT" />
|
||||
</root>
|
||||
<root level="INFO">
|
||||
<appender-ref ref="LOKI" />
|
||||
</root>
|
||||
|
||||
</configuration>
|
@@ -34,16 +34,16 @@ dependencies {
|
||||
// https://mvnrepository.com/artifact/org.jetbrains.kotlin/kotlin-reflect
|
||||
implementation("org.jetbrains.kotlin:kotlin-reflect:2.0.21")
|
||||
|
||||
// https://mvnrepository.com/artifact/io.insert-koin/koin-core
|
||||
implementation("io.insert-koin:koin-core:4.0.0")
|
||||
|
||||
// https://mvnrepository.com/artifact/ch.qos.logback/logback-classic
|
||||
implementation("ch.qos.logback:logback-classic:1.5.12")
|
||||
|
||||
// https://mvnrepository.com/artifact/io.github.cdimascio/dotenv-kotlin
|
||||
implementation("io.github.cdimascio:dotenv-kotlin:6.4.2")
|
||||
|
||||
implementation("io.ktor:ktor-server-metrics-micrometer:$ktorVersion")
|
||||
|
||||
implementation(project(":common"))
|
||||
implementation("io.ktor:ktor-server-metrics-micrometer:3.1.3")
|
||||
|
||||
testImplementation(kotlin("test"))
|
||||
}
|
||||
|
@@ -11,6 +11,7 @@ import io.ktor.serialization.kotlinx.json.*
|
||||
import io.ktor.server.application.*
|
||||
import io.ktor.server.auth.*
|
||||
import io.ktor.server.engine.*
|
||||
import io.ktor.server.metrics.micrometer.MicrometerMetrics
|
||||
import io.ktor.server.netty.*
|
||||
import io.ktor.server.plugins.contentnegotiation.*
|
||||
import io.ktor.server.plugins.cors.routing.*
|
||||
@@ -19,15 +20,26 @@ import io.ktor.server.response.*
|
||||
import io.ktor.server.routing.*
|
||||
import io.ktor.server.sessions.*
|
||||
import io.ktor.server.websocket.*
|
||||
import io.micrometer.core.instrument.binder.jvm.JvmGcMetrics
|
||||
import io.micrometer.core.instrument.binder.jvm.JvmMemoryMetrics
|
||||
import io.micrometer.core.instrument.binder.system.ProcessorMetrics
|
||||
import io.micrometer.prometheusmetrics.PrometheusConfig
|
||||
import io.micrometer.prometheusmetrics.PrometheusMeterRegistry
|
||||
import kotlinx.coroutines.delay
|
||||
import kotlinx.serialization.Serializable
|
||||
import kotlinx.serialization.json.Json
|
||||
import org.koin.core.context.startKoin
|
||||
import org.koin.dsl.module
|
||||
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 java.math.BigInteger
|
||||
import java.security.SecureRandom
|
||||
import java.time.Duration
|
||||
import kotlin.getValue
|
||||
import kotlin.time.toKotlinDuration
|
||||
|
||||
val dotenv = dotenv {
|
||||
@@ -81,6 +93,8 @@ val server = embeddedServer(Netty, port = 8080, ) {
|
||||
}
|
||||
}
|
||||
routing {
|
||||
val dispatcher: CoroutinesEventBus by inject(CoroutinesEventBus::class.java)
|
||||
|
||||
route("/auth") {
|
||||
// discord login
|
||||
authenticate("auth-oauth-discord") {
|
||||
@@ -175,7 +189,7 @@ val server = embeddedServer(Netty, port = 8080, ) {
|
||||
clientSecret = dotenv["NAVER_CLIENT_SECRET"]
|
||||
)
|
||||
|
||||
val response = applicationHttpClient.post("https://chzzk.naver.com/auth/v1/token") {
|
||||
val response = applicationHttpClient.post("https://openapi.chzzk.naver.com/auth/v1/token") {
|
||||
contentType(ContentType.Application.Json)
|
||||
setBody(tokenRequest)
|
||||
}
|
||||
@@ -191,7 +205,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,
|
||||
@@ -199,7 +218,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) {
|
||||
@@ -211,11 +236,22 @@ val server = embeddedServer(Netty, port = 8080, ) {
|
||||
// common: logout
|
||||
get("/logout") {
|
||||
call.sessions.clear<UserSession>()
|
||||
call.response.status(HttpStatusCode.OK)
|
||||
return@get
|
||||
call.respondRedirect(getFrontendURL(""))
|
||||
}
|
||||
}
|
||||
|
||||
val appMicrometerRegistry: PrometheusMeterRegistry by inject(PrometheusMeterRegistry::class.java)
|
||||
|
||||
install(MicrometerMetrics) {
|
||||
registry = appMicrometerRegistry
|
||||
|
||||
meterBinders = listOf(
|
||||
JvmMemoryMetrics(),
|
||||
JvmGcMetrics(),
|
||||
ProcessorMetrics()
|
||||
)
|
||||
}
|
||||
|
||||
apiRoutes()
|
||||
apiSongRoutes()
|
||||
apiCommandRoutes()
|
||||
@@ -226,6 +262,8 @@ val server = embeddedServer(Netty, port = 8080, ) {
|
||||
wsSongRoutes()
|
||||
wsSongListRoutes()
|
||||
|
||||
metricRoutes()
|
||||
|
||||
swaggerUI("swagger-ui/index.html", "openapi/documentation.yaml") {
|
||||
options {
|
||||
version = "1.2.0"
|
||||
@@ -427,4 +465,4 @@ suspend fun getChzzkUser(accessToken: String): ChzzkApi<ChzzkMeApi> {
|
||||
|
||||
fun generateSecureRandomState(): String {
|
||||
return BigInteger(130, SecureRandom()).toString(32)
|
||||
}
|
||||
}
|
||||
|
@@ -1,6 +1,7 @@
|
||||
package space.mori.chzzk_bot.webserver.routes
|
||||
|
||||
import io.ktor.http.*
|
||||
import io.ktor.server.request.receive
|
||||
import io.ktor.server.response.*
|
||||
import io.ktor.server.routing.*
|
||||
import io.ktor.server.sessions.*
|
||||
@@ -11,7 +12,11 @@ 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
|
||||
import space.mori.chzzk_bot.common.metrics.Metrics
|
||||
|
||||
@Serializable
|
||||
data class GetUserDTO(
|
||||
@@ -36,6 +41,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 =
|
||||
@@ -50,21 +69,21 @@ fun Routing.apiRoutes() {
|
||||
|
||||
route("/user/{uid}") {
|
||||
get {
|
||||
val uid = call.parameters["uid"]
|
||||
val uid = call.parameters["uid"]
|
||||
if(uid == null) {
|
||||
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 +101,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 +110,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 +128,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,
|
||||
@@ -129,4 +148,50 @@ fun Routing.apiRoutes() {
|
||||
call.respond(HttpStatusCode.OK, returnUsers)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
route("/settings") {
|
||||
get {
|
||||
val session = call.sessions.get<UserSession>()
|
||||
if(session == null) {
|
||||
call.respondText("No session found", status = HttpStatusCode.Unauthorized)
|
||||
return@get
|
||||
}
|
||||
val user = UserService.getUser(session.id)
|
||||
if(user == null) {
|
||||
call.respondText("No user found", status = HttpStatusCode.NotFound)
|
||||
return@get
|
||||
}
|
||||
|
||||
call.respond(HttpStatusCode.OK, IUserSettingsDTO(
|
||||
user.isDisabled,
|
||||
user.isDisableStartupMsg
|
||||
))
|
||||
}
|
||||
|
||||
post {
|
||||
val session = call.sessions.get<UserSession>()
|
||||
val body: IUserSettingsDTO = call.receive()
|
||||
if(session == null) {
|
||||
call.respondText("No session found", status = HttpStatusCode.Unauthorized)
|
||||
return@post
|
||||
}
|
||||
val user = UserService.getUser(session.id)
|
||||
if(user == null) {
|
||||
call.respondText("No user found", status = HttpStatusCode.NotFound)
|
||||
return@post
|
||||
}
|
||||
|
||||
UserService.setIsDisabled(user, body.isBotDisabled)
|
||||
UserService.setIsStartupDisabled(user, body.isBotMsgDisabled)
|
||||
|
||||
Metrics.refreshStreamerMetrics()
|
||||
|
||||
call.respond(HttpStatusCode.OK, body)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
data class IUserSettingsDTO(
|
||||
val isBotDisabled: Boolean,
|
||||
val isBotMsgDisabled: Boolean
|
||||
)
|
@@ -0,0 +1,36 @@
|
||||
package space.mori.chzzk_bot.webserver.routes
|
||||
|
||||
import io.ktor.server.application.ApplicationStopped
|
||||
import io.ktor.server.response.respondText
|
||||
import io.ktor.server.routing.Routing
|
||||
import io.ktor.server.routing.get
|
||||
import io.micrometer.prometheusmetrics.PrometheusMeterRegistry
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.SupervisorJob
|
||||
import kotlinx.coroutines.cancel
|
||||
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.metrics.Metrics
|
||||
import kotlin.getValue
|
||||
|
||||
|
||||
val metricScope = CoroutineScope(SupervisorJob() + Dispatchers.Default)
|
||||
fun Routing.metricRoutes() {
|
||||
environment.monitor.subscribe(ApplicationStopped) {
|
||||
metricScope.cancel()
|
||||
}
|
||||
|
||||
val dispatcher: CoroutinesEventBus by inject(CoroutinesEventBus::class.java)
|
||||
val registry: PrometheusMeterRegistry by inject(PrometheusMeterRegistry::class.java)
|
||||
|
||||
dispatcher.subscribe(UserRegisterEvent::class) {
|
||||
Metrics.refreshStreamerMetrics()
|
||||
}
|
||||
|
||||
get("/metrics") {
|
||||
call.respondText(registry.scrape())
|
||||
}
|
||||
|
||||
}
|
@@ -37,9 +37,10 @@ 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) {
|
||||
if (sessions[uid]?.isEmpty() == true) {
|
||||
sessions.remove(uid)
|
||||
}
|
||||
}
|
||||
@@ -88,78 +89,111 @@ 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
|
||||
}
|
||||
addSession(uid, this)
|
||||
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) {
|
||||
is Frame.Text -> {
|
||||
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)
|
||||
}
|
||||
}
|
||||
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
|
||||
}
|
||||
is Frame.Ping -> send(Frame.Pong(frame.data))
|
||||
else -> {}
|
||||
}
|
||||
}
|
||||
} catch(e: ClosedReceiveChannelException) {
|
||||
logger.error("Error in WebSocket: ${e.message}")
|
||||
} finally {
|
||||
removeSession(uid, this)
|
||||
ackMap[uid]?.remove(this)
|
||||
|
||||
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) {
|
||||
is Frame.Text -> {
|
||||
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 -> {}
|
||||
}
|
||||
}
|
||||
} 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)
|
||||
}
|
||||
}
|
||||
|
||||
dispatcher.subscribe(SongEvent::class) {
|
||||
logger.debug("SongEvent: {} / {} {}", it.uid, it.type, it.current?.name)
|
||||
songScope.launch {
|
||||
broadcastMessage(it.uid, SongResponse(
|
||||
it.type.value,
|
||||
it.uid,
|
||||
it.reqUid,
|
||||
it.current?.toSerializable(),
|
||||
it.next?.toSerializable(),
|
||||
it.delUrl
|
||||
))
|
||||
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) {
|
||||
if (it.type == TimerType.STREAM_OFF) {
|
||||
songScope.launch {
|
||||
broadcastMessage(it.uid, SongResponse(
|
||||
it.type.value,
|
||||
it.uid,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
))
|
||||
broadcastMessage(
|
||||
it.uid, SongResponse(
|
||||
it.type.value,
|
||||
it.uid,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
)
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Serializable
|
||||
data class SerializableYoutubeVideo(
|
||||
val url: 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