-
Notifications
You must be signed in to change notification settings - Fork 11
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
557b2ca
commit 9ebf59d
Showing
20 changed files
with
418 additions
and
77 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,3 +1,3 @@ | ||
subprojects { | ||
version = "3.4.1-SNAPSHOT" | ||
version = "3.5.0-SNAPSHOT" | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -18,7 +18,6 @@ tasks { | |
freeCompilerArgs = freeCompilerArgs + "-Xcontext-receivers" | ||
} | ||
} | ||
|
||
} | ||
|
||
mikbotPlugin { | ||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
60 changes: 0 additions & 60 deletions
60
music/commands/src/main/kotlin/dev/schlaubi/mikmusic/commands/LycricsCommand.kt
This file was deleted.
Oops, something went wrong.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,37 @@ | ||
import dev.schlaubi.mikbot.gradle.GenerateDefaultTranslationBundleTask | ||
import java.util.* | ||
|
||
plugins { | ||
`mikbot-module` | ||
com.google.devtools.ksp | ||
dev.schlaubi.mikbot.`gradle-plugin` | ||
alias(libs.plugins.kotlinx.serialization) | ||
} | ||
|
||
dependencies { | ||
plugin(projects.music.player) | ||
plugin(projects.core.ktor) | ||
ktorDependency(libs.ktor.server.websockets) | ||
ktorDependency(libs.ktor.server.cors) | ||
} | ||
|
||
mikbotPlugin { | ||
pluginId = "music-lyrics" | ||
description = "Plugin providing lyrics for the music plugin" | ||
} | ||
|
||
fun DependencyHandlerScope.ktorDependency(dependency: ProviderConvertible<*>) = ktorDependency(dependency.asProvider()) | ||
fun DependencyHandlerScope.ktorDependency(dependency: Provider<*>) = implementation(dependency) { | ||
exclude(module = "ktor-server-core") | ||
} | ||
|
||
|
||
tasks { | ||
val generateDefaultResourceBundle by registering(GenerateDefaultTranslationBundleTask::class) { | ||
defaultLocale = Locale("en", "GB") | ||
} | ||
|
||
classes { | ||
dependsOn(generateDefaultResourceBundle) | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,165 @@ | ||
package dev.schlaubi.mikmusic.lyrics | ||
|
||
import com.kotlindiscord.kord.extensions.ExtensibleBot | ||
import com.kotlindiscord.kord.extensions.koin.KordExKoinComponent | ||
import dev.kord.cache.api.query | ||
import dev.kord.common.annotation.KordExperimental | ||
import dev.kord.common.annotation.KordUnsafe | ||
import dev.kord.common.entity.Snowflake | ||
import dev.kord.core.Kord | ||
import dev.kord.core.cache.data.VoiceStateData | ||
import dev.kord.core.event.user.VoiceStateUpdateEvent | ||
import dev.kord.core.on | ||
import dev.schlaubi.lavakord.audio.TrackEndEvent | ||
import dev.schlaubi.lavakord.audio.TrackStartEvent | ||
import dev.schlaubi.lavakord.audio.on | ||
import dev.schlaubi.lavakord.audio.player.Player | ||
import dev.schlaubi.lavakord.plugins.lyrics.rest.requestLyrics | ||
import dev.schlaubi.lyrics.protocol.TimedLyrics | ||
import dev.schlaubi.mikbot.plugin.api.config.Environment | ||
import dev.schlaubi.mikbot.util_plugins.ktor.api.KtorExtensionPoint | ||
import dev.schlaubi.mikmusic.core.MusicModule | ||
import dev.schlaubi.mikmusic.lyrics.events.Event | ||
import dev.schlaubi.mikmusic.lyrics.events.NextTrackEvent | ||
import dev.schlaubi.mikmusic.lyrics.events.PlayerStateUpdateEvent | ||
import dev.schlaubi.mikmusic.lyrics.events.PlayerStoppedEvent | ||
import dev.schlaubi.mikmusic.player.MusicPlayer | ||
import io.ktor.http.* | ||
import io.ktor.serialization.kotlinx.* | ||
import io.ktor.server.application.* | ||
import io.ktor.server.plugins.* | ||
import io.ktor.server.plugins.cors.routing.* | ||
import io.ktor.server.plugins.statuspages.* | ||
import io.ktor.server.request.* | ||
import io.ktor.server.response.* | ||
import io.ktor.server.routing.* | ||
import io.ktor.server.websocket.* | ||
import io.ktor.util.* | ||
import io.ktor.websocket.* | ||
import kotlinx.coroutines.* | ||
import kotlinx.datetime.Clock | ||
import kotlinx.serialization.json.Json | ||
import org.koin.core.component.inject | ||
import org.pf4j.Extension | ||
import kotlin.collections.set | ||
import kotlin.time.Duration.Companion.seconds | ||
import dev.schlaubi.mikbot.plugin.api.config.Config as BotConfig | ||
|
||
private val PLAYER = AttributeKey<MusicPlayer>("MUSIC_PLAYER") | ||
private val authKeys = mutableMapOf<String, Snowflake>() | ||
|
||
fun requestToken(userId: Snowflake): String { | ||
val key = generateNonce() | ||
authKeys[key] = userId | ||
return key | ||
} | ||
|
||
@Extension | ||
class APIServer : KtorExtensionPoint, KordExKoinComponent { | ||
|
||
private val bot by inject<ExtensibleBot>() | ||
private val musicModule by lazy { bot.findExtension<MusicModule>()!! } | ||
|
||
private val ApplicationCall.userId: Snowflake | ||
get() { | ||
val header = request.authorization() ?: parameters["api_key"] ?: unauthorized() | ||
return authKeys[header] ?: unauthorized() | ||
} | ||
|
||
@OptIn(KordUnsafe::class, KordExperimental::class) | ||
private suspend fun Snowflake.findPlayer(): MusicPlayer { | ||
val voiceState = bot.kordRef.findVoiceState(this) ?: notFound() | ||
val player = musicModule.getMusicPlayer(bot.kordRef.unsafe.guild(voiceState.guildId)) | ||
|
||
return player.takeIf { it.playingTrack != null } ?: notFound() | ||
} | ||
|
||
override fun Application.apply() { | ||
if (pluginOrNull(WebSockets) == null) { | ||
install(WebSockets) { | ||
contentConverter = KotlinxWebsocketSerializationConverter(Json) | ||
} | ||
} | ||
if (pluginOrNull(CORS) == null && BotConfig.ENVIRONMENT == Environment.DEVELOPMENT) { | ||
install(CORS) { | ||
allowMethod(HttpMethod.Options) | ||
allowMethod(HttpMethod.Put) | ||
allowMethod(HttpMethod.Delete) | ||
allowMethod(HttpMethod.Patch) | ||
allowHeader(HttpHeaders.Authorization) | ||
anyHost() | ||
} | ||
} | ||
|
||
routing { | ||
route("lyrics") { | ||
get("current") { | ||
val player = call.userId.findPlayer() | ||
|
||
call.respond(player.player.requestLyrics().takeIf { it is TimedLyrics } ?: notFound()) | ||
} | ||
|
||
route("events") { | ||
intercept(ApplicationCallPipeline.Plugins) { | ||
call.attributes.put(PLAYER, call.userId.findPlayer()) | ||
proceed() | ||
} | ||
|
||
webSocket { | ||
val player = call.attributes[PLAYER].player | ||
val listenerScope = this | ||
launch { | ||
var state = player.toState() | ||
while (isActive) { | ||
val newState = player.toState() | ||
if (newState != state && state.playing) { | ||
state = newState | ||
sendSerialized<Event>(newState) | ||
} | ||
|
||
delay(1.seconds) | ||
} | ||
} | ||
|
||
player.on<TrackEndEvent>(listenerScope) { | ||
if (!reason.mayStartNext) { | ||
sendSerialized<Event>(PlayerStoppedEvent) | ||
} | ||
} | ||
player.on<TrackStartEvent>(listenerScope) { | ||
sendSerialized<Event>(NextTrackEvent(player.position)) | ||
} | ||
bot.kordRef.on<VoiceStateUpdateEvent>(listenerScope) { | ||
if (state.userId == call.userId && state.channelId == null && old?.channelId != null) { | ||
close(CloseReason(CloseReason.Codes.VIOLATED_POLICY, "Left voice channel")) | ||
} | ||
} | ||
|
||
// Wait for connection to die or websocket getting closed otherwise | ||
awaitCancellation() | ||
} | ||
} | ||
} | ||
} | ||
} | ||
|
||
override fun StatusPagesConfig.apply() { | ||
exception<UnauthorizedException> { call, _ -> | ||
call.respond(HttpStatusCode.Unauthorized) | ||
} | ||
} | ||
} | ||
|
||
suspend fun Kord.findVoiceState(userId: Snowflake): VoiceStateData? { | ||
return cache.query<VoiceStateData> { | ||
VoiceStateData::channelId ne null | ||
VoiceStateData::userId eq userId | ||
}.singleOrNull() | ||
} | ||
|
||
private class UnauthorizedException : RuntimeException() | ||
|
||
private fun unauthorized(): Nothing = throw UnauthorizedException() | ||
private fun notFound(): Nothing = throw NotFoundException() | ||
|
||
private fun Player.toState() = PlayerStateUpdateEvent(!paused, position, Clock.System.now()) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,7 @@ | ||
package dev.schlaubi.mikmusic.lyrics | ||
|
||
import dev.schlaubi.mikbot.plugin.api.EnvironmentConfig | ||
|
||
object Config : EnvironmentConfig() { | ||
val LYRICS_WEB_URL by getEnv("http://localhost:3000") | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,34 @@ | ||
package dev.schlaubi.mikmusic.lyrics | ||
|
||
import com.kotlindiscord.kord.extensions.extensions.Extension | ||
import com.kotlindiscord.kord.extensions.extensions.ephemeralSlashCommand | ||
import dev.schlaubi.lavakord.plugins.lyrics.rest.requestLyrics | ||
import dev.schlaubi.lyrics.protocol.TimedLyrics | ||
import dev.schlaubi.mikbot.plugin.api.util.discordError | ||
import dev.schlaubi.mikmusic.checks.musicQuizAntiCheat | ||
import dev.schlaubi.mikmusic.util.musicModule | ||
|
||
suspend fun Extension.karaokeCommand() = ephemeralSlashCommand { | ||
name = "karaoke" | ||
description = "commands.karaoke.description" | ||
|
||
check { | ||
musicQuizAntiCheat(musicModule) | ||
} | ||
|
||
action { | ||
val player = with(musicModule) { player } | ||
|
||
val lyrics = runCatching { player.requestLyrics() }.getOrNull() | ||
|
||
if (lyrics !is TimedLyrics) { | ||
discordError(translate("commands.karaoke.not_available")) | ||
} | ||
|
||
val token = requestToken(user.id) | ||
|
||
respond { | ||
content = translate("commands.karaoke.success", arrayOf("${Config.LYRICS_WEB_URL}?apiKey=$token")) | ||
} | ||
} | ||
} |
Oops, something went wrong.