spektacles/src/main/kotlin/moe/kageru/spektacles/Parser.kt

60 lines
1.8 KiB
Kotlin

package moe.kageru.spektacles
import arrow.core.Option
import arrow.core.toOption
import java.time.LocalDateTime
class ParsedLine(val time: LocalDateTime,
val user: Option<String>,
val userMode: UserMode,
val message: String,
val isSystemMessage: Boolean,
private val originalMessage: String
) {
override fun toString() = originalMessage
fun getMention(): Option<String> = mentionRegex.find(message).toOption().map { it.value.toLowerCase() }
companion object {
// 18 04 26 19:40:47 <kageru_> Hi
private val lineRegex = Regex("""(?<year>\d\d)\s(?<month>\d\d)\s(?<day>\d\d)\s(?<hour>\d\d):(?<minute>\d\d):(?<second>\d\d)\s(<(?<mode>[~&@%+])?(?<author>\w+)>\t)?(?<message>.*)""")
private val mentionRegex = Regex("(?<=@)\\w+")
fun parse(line: String): ParsedLine? = lineRegex
.matchEntire(line)
?.let {
ParsedLine(
LocalDateTime.of(
it.groups["year"]!!.value.toInt(),
it.groups["month"]!!.value.toInt(),
it.groups["day"]!!.value.toInt(),
it.groups["hour"]!!.value.toInt(),
it.groups["minute"]!!.value.toInt(),
it.groups["second"]!!.value.toInt()
),
it.groups["author"]?.value.toOption(),
it.groups["mode"]?.value?.let { UserMode.values().first { mode -> mode.icon == it } } ?: UserMode.NONE,
it.groups["message"]!!.value,
it.groups["author"] == null,
it.value
)
}
}
}
enum class UserMode(val icon: String) {
ADMIN("~"),
BOT("&"),
OP("@"),
HOP("%"),
VOICE("+"),
NONE("")
}
typealias ParsedLines = Sequence<ParsedLine>
fun Lines.parse(): ParsedLines {
return map { ParsedLine.parse(it) }
.filterNotNull()
}