Compare commits

..

No commits in common. "77eecaca34bcd718365720094b25b47b905c7d2a" and "27810c0b7f482ed52defb79e6270e5b95d2638f5" have entirely different histories.

5 changed files with 19 additions and 113 deletions

View File

@ -11,7 +11,6 @@ import org.slf4j.Logger
import org.slf4j.LoggerFactory import org.slf4j.LoggerFactory
import space.mori.chzzk_bot.chatbot.chzzk.Connector.getChannel import space.mori.chzzk_bot.chatbot.chzzk.Connector.getChannel
import space.mori.chzzk_bot.chatbot.discord.Discord 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.events.*
import space.mori.chzzk_bot.common.models.User import space.mori.chzzk_bot.common.models.User
import space.mori.chzzk_bot.common.services.LiveStatusService import space.mori.chzzk_bot.common.services.LiveStatusService
@ -207,7 +206,6 @@ class UserHandler(
var messageHandler: MessageHandler var messageHandler: MessageHandler
var client: ChzzkClient var client: ChzzkClient
var listener: ChzzkUserSession var listener: ChzzkUserSession
var chatChannelId: String?
private val dispatcher: CoroutinesEventBus by inject(CoroutinesEventBus::class.java) private val dispatcher: CoroutinesEventBus by inject(CoroutinesEventBus::class.java)
private var _isActive: Boolean private var _isActive: Boolean
@ -223,17 +221,18 @@ class UserHandler(
throw RuntimeException("AccessToken or RefreshToken is not valid.") throw RuntimeException("AccessToken or RefreshToken is not valid.")
} }
try { try {
val tokens = user.refreshToken?.let { token -> Connector.client.refreshAccessToken(token) }
if(tokens == null) { client = Connector.getClient(user.accessToken!!, user.refreshToken!!)
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() client.loginAsync().join()
client.refreshTokenAsync().join()
UserService.setRefreshToken(user, client.loginResult.accessToken(), client.loginResult.refreshToken())
listener = ChzzkSessionBuilder(client).buildUserSession() listener = ChzzkSessionBuilder(client).buildUserSession()
listener.createAndConnectAsync().join() listener.createAndConnectAsync().join()
messageHandler = MessageHandler(this@UserHandler) messageHandler = MessageHandler(this@UserHandler)
listener.on(SessionChatMessageEvent::class.java) { listener.on(SessionChatMessageEvent::class.java) {

View File

@ -88,7 +88,7 @@ class MessageHandler(
} }
private fun manageAddCommand(msg: SessionChatMessage, user: User) { private fun manageAddCommand(msg: SessionChatMessage, user: User) {
if (msg.profile.badges.none { it.imageUrl.contains("manager") }) { if (msg.profile.badges.size == 0) {
handler.sendChat("매니저만 명령어를 추가할 수 있습니다.") handler.sendChat("매니저만 명령어를 추가할 수 있습니다.")
return return
} }
@ -109,7 +109,7 @@ class MessageHandler(
} }
private fun manageUpdateCommand(msg: SessionChatMessage, user: User) { private fun manageUpdateCommand(msg: SessionChatMessage, user: User) {
if (msg.profile.badges.none { it.imageUrl.contains("manager") }) { if (msg.profile.badges.size == 0) {
handler.sendChat("매니저만 명령어를 추가할 수 있습니다.") handler.sendChat("매니저만 명령어를 추가할 수 있습니다.")
return return
} }
@ -131,7 +131,7 @@ class MessageHandler(
} }
private fun manageRemoveCommand(msg: SessionChatMessage, user: User) { private fun manageRemoveCommand(msg: SessionChatMessage, user: User) {
if (msg.profile.badges.none { it.imageUrl.contains("manager") }) { if (msg.profile.badges.size == 0) {
handler.sendChat("매니저만 명령어를 삭제할 수 있습니다.") handler.sendChat("매니저만 명령어를 삭제할 수 있습니다.")
return return
} }
@ -148,7 +148,7 @@ class MessageHandler(
} }
private fun timerCommand(msg: SessionChatMessage, user: User) { private fun timerCommand(msg: SessionChatMessage, user: User) {
if (msg.profile.badges.none { it.imageUrl.contains("manager") }) { if (msg.profile.badges.size == 0) {
handler.sendChat("매니저만 이 명령어를 사용할 수 있습니다.") handler.sendChat("매니저만 이 명령어를 사용할 수 있습니다.")
return return
} }
@ -227,7 +227,7 @@ class MessageHandler(
val config = SongConfigService.getConfig(user) val config = SongConfigService.getConfig(user)
if(config.streamerOnly && msg.profile.badges.none { it.imageUrl.contains("manager") }) { if(config.streamerOnly && msg.profile.badges.size == 0) {
handler.sendChat("매니저만 이 명령어를 사용할 수 있습니다.") handler.sendChat("매니저만 이 명령어를 사용할 수 있습니다.")
return return
} }
@ -298,7 +298,7 @@ class MessageHandler(
} }
private fun songStartCommand(msg: SessionChatMessage, user: User) { private fun songStartCommand(msg: SessionChatMessage, user: User) {
if (msg.profile.badges.none { it.imageUrl.contains("manager") }) { if (msg.profile?.badges?.size == 0) {
handler.sendChat("매니저만 이 명령어를 사용할 수 있습니다.") handler.sendChat("매니저만 이 명령어를 사용할 수 있습니다.")
return return
} }
@ -353,15 +353,15 @@ class MessageHandler(
// Replace followPattern // Replace followPattern
result = followPattern.replace(result) { _ -> result = followPattern.replace(result) { _ ->
try { try {
val followingDate = handler.chatChannelId?.let { getFollowDate(it, msg.senderChannelId) } val followingDate = getFollowDate(channel.channelId, msg.senderChannelId)
?.content?.streamingProperty?.following?.followDate ?: LocalDateTime.now().minusDays(1).toString() .content?.streamingProperty?.following?.followDate
val period = followingDate.let { val period = followingDate?.let {
val formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss") val formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")
val pastDate = LocalDateTime.parse(it, formatter) val pastDate = LocalDateTime.parse(it, formatter)
val today = LocalDateTime.now() val today = LocalDateTime.now()
ChronoUnit.DAYS.between(pastDate, today) ChronoUnit.DAYS.between(pastDate, today)
} + 1 } ?: 0
period.toString() period.toString()
} catch (e: Exception) { } catch (e: Exception) {

View File

@ -1,58 +0,0 @@
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
val client = OkHttpClient.Builder()
.addNetworkInterceptor { chain ->
chain.proceed(
chain.request()
.newBuilder()
.header("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36")
.build()
)
}
.build()
val gson = Gson()
data class RefreshTokenResponse(
val accessToken: String,
val refreshToken: String,
val expiresIn: Int,
val tokenType: String = "Bearer",
val scope: String
)
fun ChzzkClient.refreshAccessToken(refreshToken: String): Pair<String, String> {
val url = "https://openapi.chzzk.naver.com/auth/v1/token"
val request = Request.Builder()
.url(url)
.header("Content-Type", "application/json")
.post(gson.toJson(mapOf(
"grantType" to "refresh_token",
"refreshToken" to refreshToken,
"clientId" to 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)
return Pair(data.accessToken, data.refreshToken)
} catch(e: Exception) {
throw e
}
}
}

View File

@ -52,20 +52,6 @@ data class NicknameColor(
val colorCode: String = "" val colorCode: 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 추가 // OkHttpClient에 Interceptor 추가
val client = OkHttpClient.Builder() val client = OkHttpClient.Builder()
.addNetworkInterceptor { chain -> .addNetworkInterceptor { chain ->
@ -98,24 +84,3 @@ fun getFollowDate(chatID: String, userId: String) : IData<IFollowContent?> {
} }
} }
} }
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 data = gson.fromJson(body, object: TypeToken<IData<LiveStatus?>>() {})
return data.content?.chatChannelId
} catch(e: Exception) {
throw e
}
}
}

View File

@ -181,7 +181,7 @@ val server = embeddedServer(Netty, port = 8080, ) {
clientSecret = dotenv["NAVER_CLIENT_SECRET"] clientSecret = dotenv["NAVER_CLIENT_SECRET"]
) )
val response = applicationHttpClient.post("https://openapi.chzzk.naver.com/auth/v1/token") { val response = applicationHttpClient.post("https://chzzk.naver.com/auth/v1/token") {
contentType(ContentType.Application.Json) contentType(ContentType.Application.Json)
setBody(tokenRequest) setBody(tokenRequest)
} }