Skip to content

Commit

Permalink
moved idle phrases to database. add unified reload source command
Browse files Browse the repository at this point in the history
  • Loading branch information
rootofundefined committed Aug 15, 2020
1 parent 2902935 commit dce5d13
Show file tree
Hide file tree
Showing 11 changed files with 121 additions and 42 deletions.
2 changes: 1 addition & 1 deletion src/main/kotlin/EventListener.kt
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ object EventListener {
}
GlobalScope.launch {
UADAB.log.debug("Loading...")
ExternalSourceRegistry.sources.forEach {
ExternalSourceRegistry.sources.values.forEach {
launch {
it.startLoading()
}
Expand Down
2 changes: 1 addition & 1 deletion src/main/kotlin/UADAB.kt
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ object UADAB {
System.setProperty("org.slf4j.simpleLogger.logFile", "System.out") //Redirect slf4j-simple to System.out from System.err
cfg = ConfigUtils.loadConfig(Config::class.java, "config.json", JsonObject())
Database.connect(
"jdbc:mysql://${cfg.dbHost}:3306/${cfg.dbName}?useUnicode=yes&characterEncoding=UTF-8&autoReconnect=true&serverTimezone=UTC",
"jdbc:mysql://${cfg.dbHost}:3306/${cfg.dbName}?useUnicode=yes&characterEncoding=UTF-8&autoReconnect=true&serverTimezone=UTC&useSSL=false",
"com.mysql.jdbc.Driver",
cfg.dbLogin,
cfg.dbPass
Expand Down
16 changes: 0 additions & 16 deletions src/main/kotlin/commands/MusicCommands.kt
Original file line number Diff line number Diff line change
Expand Up @@ -325,22 +325,6 @@ object MusicCommands : ICommandList {
}
onDenied { musicDeny() }
}
command("reload") {
allowed to admin_or_interface
help = "Reload music context"
action {
val contextState = MusicHandler.isContextAvailable
MusicSource.reload()
MusicHandler.loadContext()
val newContextState = MusicHandler.isContextAvailable
replyCat {
color = if (newContextState) GREEN else RED
title = "Reloaded"
+"Context ${if (newContextState xor contextState) "is now" else "still"} ${if (newContextState) "available" else "not available"}"
}
}
onDenied { musicDeny() }
}
command("volume") {
allowed to assets
help = "Change volume"
Expand Down
51 changes: 49 additions & 2 deletions src/main/kotlin/commands/SystemCommands.kt
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,15 @@ import cmd.CommandCategory
import cmd.CommandListBuilder
import cmd.ICommandList
import dsl.Init
import dsl.editEmbedWithAttachments
import dsl.embed
import dsl.paginatedEmbed
import kotlinx.coroutines.async
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.withContext
import net.dv8tion.jda.core.Permission
import sources.ExternalSourceRegistry
import sources.get
import users.Classification
import users.Classification.Companion.ADMIN
import users.Classification.Companion.ANALOG_INTERFACE
Expand All @@ -15,6 +22,7 @@ import users.assets
import users.everyone
import java.awt.Color
import java.awt.Color.GREEN
import java.awt.Color.YELLOW
import kotlin.system.exitProcess

object SystemCommands : ICommandList {
Expand Down Expand Up @@ -103,6 +111,7 @@ object SystemCommands : ICommandList {
append field "text" to "Constant text. Like 'args' in here means that you have to type 'args' to get this message"
append field "i%name%" to "Number argument. Just some number, like 1, 12, or 6741"
append field "(%arg%)+" to "Arguments with + on the end can be repeated infinitely, use space as separator"
append field "(%arg%)*" to "Arguments with * can be optional or repeated infinitely, use space as separator"
append field "(%arg%)?" to "Arguments with ? are optional, you can just skip them"
append field "--some-flag" to "Flag argument. It's like constant text but with few features"
append field "-(-s)ome-flag" to "Flag with shortname. You can use '-s' instead of '--some-flag'"
Expand Down Expand Up @@ -178,7 +187,45 @@ object SystemCommands : ICommandList {
})
}
}
}

command("reload") {
allowed to assets
help = "Reload sources (such as music, colors, etc...)"
args = "(%source%)*"
val params by parser.leftoverDelegate()
action {
val sources = ExternalSourceRegistry.sources
if (params.isEmpty()) {
return@action replyCat {
title = "Sources"
color = GREEN
sources.keys.forEach { -"- $it" }
}
}

reply(embed {
title = "Reloading..."
color = YELLOW
}, success = {
it.channel.editEmbedWithAttachments(it.idLong, embed {
title = "Reload finished"
color = GREEN
runBlocking {
args.map {
async {
it to (sources[it]?.let { source ->
source.reload()
source.getAsync().getCompletionExceptionOrNull()?.let { e ->
"${e::class.simpleName}"
} ?: "Reloaded"
} ?: "Invalid name")
}
}.map { d -> d.await() }
}.forEach { (key, result) ->
append field key to result
}
}).queue()
})
}
}
}
}
9 changes: 9 additions & 0 deletions src/main/kotlin/dao/Tables.kt
Original file line number Diff line number Diff line change
@@ -1,10 +1,19 @@
package dao

import net.dv8tion.jda.core.entities.Game
import org.jetbrains.exposed.sql.Table

object DAOUsers : Table("users") {
val discordId = long("discord_id").primaryKey()
val name = varchar("name", 255)
val classification = varchar("classification", 255)
val ssn = integer("ssn")
}

object DAOPhrases : Table("idle_phrases") {
val type = enumerationByName("type",
Game.GameType.values().map { it.name.length }.max() ?: 9,
Game.GameType::class.java)
val phrase = text("phrase")
val weight = float("weight")
}
4 changes: 4 additions & 0 deletions src/main/kotlin/dsl/EmbedBuilder.kt
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,10 @@ open class BaseEmbedCreater {
text(this)
}

open operator fun String.unaryMinus() {
+"$this\n"
}

open fun field(init: Init<FieldBuilder>) {
setElement(::FieldBuilder, init)
}
Expand Down
1 change: 0 additions & 1 deletion src/main/kotlin/music/MusicHandler.kt
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@ import com.sedmelluq.discord.lavaplayer.track.AudioTrack
import commands.MusicCommands
import kotlinx.coroutines.runBlocking
import net.dv8tion.jda.core.entities.Guild
import org.omg.SendingContext.RunTime
import sources.MusicSource
import sources.get
import uadamusic.*
Expand Down
22 changes: 11 additions & 11 deletions src/main/kotlin/sources/ExternalSourceRegistry.kt
Original file line number Diff line number Diff line change
Expand Up @@ -2,24 +2,24 @@ package sources

object ExternalSourceRegistry {

private val mutableSources: MutableList<IExternalSource<*>> = mutableListOf()
val sources: List<IExternalSource<*>>
private val mutableSources: MutableMap<String, IExternalSource<*>> = mutableMapOf()
val sources: Map<String, IExternalSource<*>>
get() = mutableSources

init {
register(HttpCodeSource)
register(XkcdColorSource)
register(GameListSource)
register(MusicSource)
register(QuoterSource)
register("http", HttpCodeSource)
register("colors", XkcdColorSource)
register("phrases", GameListSource)
register("music", MusicSource)
register("quoter", QuoterSource)
}

fun register(s: IExternalSource<*>) {
mutableSources.add(s)
fun register(name: String, s: IExternalSource<*>) {
mutableSources[name] = s
}

fun unregister(s: IExternalSource<*>) {
mutableSources.remove(s)
fun unregister(name: String) {
mutableSources.remove(name)
}

}
20 changes: 10 additions & 10 deletions src/main/kotlin/sources/GameListSource.kt
Original file line number Diff line number Diff line change
@@ -1,20 +1,20 @@
package sources

import dao.DAOPhrases
import net.dv8tion.jda.core.entities.Game
import org.jetbrains.exposed.sql.selectAll
import org.jetbrains.exposed.sql.transactions.transaction
import utils.WeightedList
import utils.toWeightedList
import java.io.File


typealias GameList = List<Game>
typealias GameList = WeightedList<Game>

object GameListSource : BasicExternalSource<GameList>() {


override suspend fun load(): GameList = File("idlePhrases.txt").useLines { f ->
f.filter { it[0] != '#' }
.map { it.split(":", limit = 2) }
.map { (type, text) -> Game.of(Game.GameType.valueOf(type), text) }
.toList()
override suspend fun load(): GameList = transaction {
DAOPhrases.selectAll()
.map { it[DAOPhrases.weight] to Game.of(it[DAOPhrases.type], it[DAOPhrases.phrase]) }
.toWeightedList()
}


}
6 changes: 6 additions & 0 deletions src/main/kotlin/sources/MusicSource.kt
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package sources

import music.MusicHandler
import uadamusic.MusicContext
import java.nio.file.Paths

Expand All @@ -10,4 +11,9 @@ object MusicSource : BasicExternalSource<MusicContext>() {
return MusicContext(Paths.get(UADAB.cfg.musicDir))
}

override suspend fun reload() {
super.reload()
MusicHandler.loadContext()
}

}
30 changes: 30 additions & 0 deletions src/main/kotlin/utils/WeightedList.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
package utils

import kotlin.random.Random

class WeightedList<A> {

private val list = mutableListOf<Pair<Float, A>>()

constructor(iterable: Iterable<Pair<Float, A>>) {
addAll(iterable)
}

private val accumulatedWeight: Float
get() = list.lastOrNull()?.first ?: 0.0f

fun add(weight: Float, item: A) =
list.add(accumulatedWeight + weight to item)

fun addAll(iterable: Iterable<Pair<Float, A>>) {
iterable.forEach { (weight, item) -> add(weight, item) }
}

fun random(): A = (Random.nextDouble() * accumulatedWeight).let {
list.first { x -> x.first >= it }.second
}

}

fun <A> List<Pair<Float, A>>.toWeightedList(): WeightedList<A> =
WeightedList(this)

0 comments on commit dce5d13

Please sign in to comment.