mirror of
https://github.com/dalbodeule/chibot-chzzk-bot.git
synced 2025-08-11 06:41:14 +00:00
Compare commits
31 Commits
101db7d20c
...
main
Author | SHA1 | Date | |
---|---|---|---|
|
eccbc94269 | ||
|
77eecaca34 | ||
|
08576cb35a | ||
|
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 | ||
|
d92ad1cc51 | ||
|
8d54d21620 |
@@ -1,16 +1,14 @@
|
||||
package space.mori.chzzk_bot.chatbot.chzzk
|
||||
|
||||
import com.google.gson.Gson
|
||||
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 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
|
||||
@@ -21,15 +19,16 @@ 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.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 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>()
|
||||
@@ -39,10 +38,11 @@ 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 = Connector.client.fetchLoggedUser().userId
|
||||
UserService.getAllUsers().map {
|
||||
if(!it.isDisabled)
|
||||
try {
|
||||
@@ -53,8 +53,8 @@ object ChzzkHandler {
|
||||
}
|
||||
|
||||
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) {
|
||||
@@ -113,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) {
|
||||
@@ -141,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)
|
||||
}
|
||||
@@ -197,6 +197,7 @@ object ChzzkHandler {
|
||||
}
|
||||
}
|
||||
|
||||
@OptIn(DelicateCoroutinesApi::class)
|
||||
class UserHandler(
|
||||
val channel: ChzzkChannel,
|
||||
val logger: Logger,
|
||||
@@ -204,8 +205,9 @@ class UserHandler(
|
||||
var streamStartTime: LocalDateTime?,
|
||||
) {
|
||||
var messageHandler: MessageHandler
|
||||
lateinit var client: ChzzkClient
|
||||
lateinit var listener: ChzzkUserSession
|
||||
var client: ChzzkClient
|
||||
var listener: ChzzkUserSession
|
||||
var chatChannelId: String?
|
||||
|
||||
private val dispatcher: CoroutinesEventBus by inject(CoroutinesEventBus::class.java)
|
||||
private var _isActive: Boolean
|
||||
@@ -220,20 +222,47 @@ class UserHandler(
|
||||
if(user?.accessToken == null || user.refreshToken == null) {
|
||||
throw RuntimeException("AccessToken or RefreshToken is not valid.")
|
||||
}
|
||||
|
||||
val tokens = ChzzkClient.refreshAccessToken(user.refreshToken!!)
|
||||
|
||||
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)
|
||||
|
||||
client.loginAsync().join()
|
||||
listener = ChzzkSessionBuilder(client).buildUserSession()
|
||||
|
||||
UserService.setTokens(user, tokens.first, tokens.second)
|
||||
|
||||
listener.createAndConnectAsync().join()
|
||||
messageHandler = MessageHandler(this@UserHandler)
|
||||
|
||||
listener.on(SessionChatMessageEvent::class.java) {
|
||||
messageHandler.handle(it.message, user)
|
||||
}
|
||||
messageHandler = MessageHandler(this@UserHandler)
|
||||
|
||||
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() {
|
||||
@@ -252,7 +281,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.")
|
||||
@@ -260,9 +289,9 @@ class UserHandler(
|
||||
reloadUser(UserService.getUser(user.id.value)!!)
|
||||
|
||||
logger.info("ChzzkChat connecting... ${channel.channelName} - ${channel.channelId}")
|
||||
listener.subscribeAsync(ChzzkSessionSubscriptionType.CHAT)
|
||||
listener.subscribeAsync(ChzzkSessionSubscriptionType.CHAT).join()
|
||||
|
||||
streamStartTime = status.content?.openDate?.let { convertChzzkDateToLocalDateTime(it) }
|
||||
streamStartTime = LocalDateTime.now()
|
||||
|
||||
if(!_isActive) {
|
||||
_isActive = true
|
||||
@@ -321,7 +350,21 @@ 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))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@@ -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
|
||||
}
|
||||
|
||||
|
||||
}
|
@@ -88,7 +88,7 @@ class MessageHandler(
|
||||
}
|
||||
|
||||
private fun manageAddCommand(msg: SessionChatMessage, user: User) {
|
||||
if (msg.profile.badges.size == 0) {
|
||||
if (msg.profile.badges.none { it.imageUrl.contains("manager") }) {
|
||||
handler.sendChat("매니저만 명령어를 추가할 수 있습니다.")
|
||||
return
|
||||
}
|
||||
@@ -109,7 +109,7 @@ class MessageHandler(
|
||||
}
|
||||
|
||||
private fun manageUpdateCommand(msg: SessionChatMessage, user: User) {
|
||||
if (msg.profile.badges.size == 0) {
|
||||
if (msg.profile.badges.none { it.imageUrl.contains("manager") }) {
|
||||
handler.sendChat("매니저만 명령어를 추가할 수 있습니다.")
|
||||
return
|
||||
}
|
||||
@@ -131,7 +131,7 @@ class MessageHandler(
|
||||
}
|
||||
|
||||
private fun manageRemoveCommand(msg: SessionChatMessage, user: User) {
|
||||
if (msg.profile.badges.size == 0) {
|
||||
if (msg.profile.badges.none { it.imageUrl.contains("manager") }) {
|
||||
handler.sendChat("매니저만 명령어를 삭제할 수 있습니다.")
|
||||
return
|
||||
}
|
||||
@@ -148,7 +148,7 @@ class MessageHandler(
|
||||
}
|
||||
|
||||
private fun timerCommand(msg: SessionChatMessage, user: User) {
|
||||
if (msg.profile.badges.size == 0) {
|
||||
if (msg.profile.badges.none { it.imageUrl.contains("manager") }) {
|
||||
handler.sendChat("매니저만 이 명령어를 사용할 수 있습니다.")
|
||||
return
|
||||
}
|
||||
@@ -227,7 +227,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") }) {
|
||||
handler.sendChat("매니저만 이 명령어를 사용할 수 있습니다.")
|
||||
return
|
||||
}
|
||||
@@ -298,7 +298,7 @@ class MessageHandler(
|
||||
}
|
||||
|
||||
private fun songStartCommand(msg: SessionChatMessage, user: User) {
|
||||
if (msg.profile?.badges?.size == 0) {
|
||||
if (msg.profile.badges.none { it.imageUrl.contains("manager") }) {
|
||||
handler.sendChat("매니저만 이 명령어를 사용할 수 있습니다.")
|
||||
return
|
||||
}
|
||||
@@ -353,15 +353,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) {
|
||||
|
@@ -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,9 +1,12 @@
|
||||
package space.mori.chzzk_bot.chatbot.utils
|
||||
|
||||
import com.google.gson.Gson
|
||||
import okhttp3.MediaType
|
||||
import okhttp3.MediaType.Companion.toMediaType
|
||||
import okhttp3.OkHttpClient
|
||||
import okhttp3.Request
|
||||
import okhttp3.RequestBody.Companion.toRequestBody
|
||||
import space.mori.chzzk_bot.chatbot.chzzk.dotenv
|
||||
import space.mori.chzzk_bot.common.utils.client
|
||||
import xyz.r2turntrue.chzzk4j.ChzzkClient
|
||||
import java.io.IOException
|
||||
@@ -36,9 +39,9 @@ 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 ->
|
||||
|
@@ -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
|
||||
}
|
@@ -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
|
||||
}
|
||||
|
@@ -22,12 +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 java.math.BigInteger
|
||||
import java.security.SecureRandom
|
||||
import java.time.Duration
|
||||
import kotlin.getValue
|
||||
import kotlin.time.toKotlinDuration
|
||||
|
||||
val dotenv = dotenv {
|
||||
@@ -81,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") {
|
||||
@@ -175,7 +181,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 +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,
|
||||
@@ -199,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,
|
||||
|
@@ -37,6 +37,7 @@ 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) {
|
||||
@@ -88,22 +89,42 @@ 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 {
|
||||
@@ -121,45 +142,58 @@ fun Routing.wsSongRoutes() {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
is Frame.Ping -> send(Frame.Pong(frame.data))
|
||||
else -> {}
|
||||
}
|
||||
}
|
||||
} catch (e: ClosedReceiveChannelException) {
|
||||
logger.error("Error in WebSocket: ${e.message}")
|
||||
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(
|
||||
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,
|
||||
|
@@ -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