Compare commits

..
11 Commits
11 changed files with 80 additions and 41 deletions
+1 -1
View File
@@ -6,7 +6,7 @@ plugins {
} }
group = "com.shr4pnel" group = "com.shr4pnel"
version = "0.1.0" version = "0.1.1"
val ktorVersion = "3.5.2" val ktorVersion = "3.5.2"
repositories { repositories {
@@ -6,14 +6,11 @@ import com.shr4pnel.ferretirc.irc.User
import com.shr4pnel.ferretirc.net.Connection import com.shr4pnel.ferretirc.net.Connection
import com.shr4pnel.ferretirc.net.messages.ClientMessage import com.shr4pnel.ferretirc.net.messages.ClientMessage
import com.shr4pnel.ferretirc.net.messages.ServerMessage import com.shr4pnel.ferretirc.net.messages.ServerMessage
import io.github.oshai.kotlinlogging.KotlinLogging
import io.github.oshai.kotlinlogging.KotlinLoggingConfiguration import io.github.oshai.kotlinlogging.KotlinLoggingConfiguration
import io.github.oshai.kotlinlogging.slf4j.logger
import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.cancel import kotlinx.coroutines.cancel
import org.slf4j.helpers.NOPLogger
class IrcClient( class IrcClient(
hostname: String, hostname: String,
@@ -30,8 +27,7 @@ class IrcClient(
lateinit var server: Server lateinit var server: Server
private set private set
lateinit var currentUser: User val user = User()
private set
@PublishedApi @PublishedApi
internal val connection = Connection(hostname, port, scope, enableLogging) internal val connection = Connection(hostname, port, scope, enableLogging)
@@ -52,6 +48,9 @@ class IrcClient(
} }
suspend fun join(channel: IRCChannel) = queueMessage(ClientMessage.Join(channel)) suspend fun join(channel: IRCChannel) = queueMessage(ClientMessage.Join(channel))
suspend fun quit(reason: String) = queueMessage(ClientMessage.Quit(reason))
suspend fun part(channels: List<String>) = queueMessage(ClientMessage.Part(channels))
suspend fun part(channel: String) = queueMessage(ClientMessage.Part(listOf(channel)))
/** /**
* Send a message to the IRC server writer * Send a message to the IRC server writer
@@ -108,19 +107,17 @@ class IrcClient(
realName: String? = null, realName: String? = null,
password: String? = null, password: String? = null,
) { ) {
currentUser = User(nick, "") // TODO TEMP USER ASSIGNMENT user.nick = nick // TODO TEMP USER ASSIGNMENT
val messages = val messages =
buildList { buildList {
if (!password.isNullOrEmpty()) add(ClientMessage.Pass(password)) if (!password.isNullOrEmpty()) add(ClientMessage.Pass(password))
add(ClientMessage.Cap.LS()) add(ClientMessage.Cap.LS())
add(ClientMessage.Nick(nick)) add(ClientMessage.Nick(nick))
if (!realName.isNullOrEmpty()) { if (!realName.isNullOrEmpty()) add(ClientMessage.User(nick, realName))
add(ClientMessage.User(nick, realName)) else add(ClientMessage.User(nick, nick))
} else {
add(ClientMessage.User(nick, nick))
}
add(ClientMessage.Cap.END()) add(ClientMessage.Cap.END())
}.toTypedArray() }.toTypedArray()
waitForNextMessageAfterAction<ServerMessage.Numeric.RPL_WELCOME> { queueMessages(*messages) } waitForNextMessageAfterAction<ServerMessage.Numeric.RPL_WELCOME> { queueMessages(*messages) }
} }
} }
@@ -6,6 +6,7 @@ import com.shr4pnel.ferretirc.net.messages.ServerMessage.Numeric
import io.github.oshai.kotlinlogging.KotlinLogging import io.github.oshai.kotlinlogging.KotlinLogging
import io.github.oshai.kotlinlogging.slf4j.logger import io.github.oshai.kotlinlogging.slf4j.logger
import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.TimeoutCancellationException
import kotlinx.coroutines.channels.Channel import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.SharedFlow import kotlinx.coroutines.flow.SharedFlow
@@ -114,20 +115,20 @@ class Server(
* @param T The type of ServerMessage to fetch * @param T The type of ServerMessage to fetch
* @return A set of messages of type T in the buffer that arrive before untilMessage appears * @return A set of messages of type T in the buffer that arrive before untilMessage appears
*/ */
suspend inline fun <reified T : ServerMessage, reified U : ServerMessage> fetchMessagesOfType( // suspend inline fun <reified T : ServerMessage, reified U : ServerMessage> fetchMessagesOfType(
timeoutMillis: Long = 5000, // timeoutMillis: Long = 5000,
noinline subscriptionMessage: suspend () -> Unit = {}, // noinline subscriptionMessage: suspend () -> Unit = {},
): List<T> { // ): List<T> {
val buffer = mutableListOf<T>() // val buffer = mutableListOf<T>()
withTimeoutOrNull(timeoutMillis) { // withTimeoutOrNull(timeoutMillis) {
msgBuffer // msgBuffer
.onSubscription { subscriptionMessage() } // .onSubscription { subscriptionMessage() }
.takeWhile { it !is U } // .takeWhile { it !is U }
.filterIsInstance<T>() // .filterIsInstance<T>()
.collect { buffer.add(it) } // .collect { buffer.add(it) }
} ?: logger.error { "Timed out while waiting to receive ${U::class}" } // } ?: logger.error { "Timed out while waiting to receive ${U::class}" }
return buffer.toList() // return buffer.toList()
} // }
fun fetchFeatures() { fun fetchFeatures() {
} }
@@ -137,12 +138,18 @@ class Server(
predicate: (T) -> Boolean = { true }, predicate: (T) -> Boolean = { true },
timeoutMillis: Long = 5000, timeoutMillis: Long = 5000,
onSubscribedLambda: suspend () -> Unit = {}, onSubscribedLambda: suspend () -> Unit = {},
): T = ): T {
withTimeout(timeoutMillis) { try {
return withTimeout(timeoutMillis) {
msgBuffer msgBuffer
.onSubscription { onSubscribedLambda() } .onSubscription { onSubscribedLambda() }
.filter { kClass.isInstance(it) } .filter { kClass.isInstance(it) }
.map { kClass.cast(it) } .map { kClass.cast(it) }
.first(predicate) .first(predicate)
} }
} catch (e: TimeoutCancellationException) {
logger.error {"Timed out while waiting to receive ${kClass.simpleName} message"}
throw e
}
}
} }
@@ -1,3 +1,5 @@
package com.shr4pnel.ferretirc.irc package com.shr4pnel.ferretirc.irc
class User(val nick: String, var mask: String?) class User(var nick: String? = null, var mask: String? = null) {
}
@@ -15,9 +15,9 @@ class Connection(
) { ) {
private val selectorManager = SelectorManager(Dispatchers.IO) private val selectorManager = SelectorManager(Dispatchers.IO)
private val socketBuilder = aSocket(selectorManager).tcp() private val socketBuilder = aSocket(selectorManager).tcp()
lateinit var socket: Socket lateinit var socket: Socket private set
lateinit var reader: MessageReader lateinit var reader: MessageReader private set
lateinit var writer: MessageWriter lateinit var writer: MessageWriter private set
suspend fun connect(): Server { suspend fun connect(): Server {
socket = socketBuilder.connect(hostname, port) socket = socketBuilder.connect(hostname, port)
@@ -61,6 +61,7 @@ class MessageParser(val incoming: Channel<String>, enableLogging: Boolean = fals
"CAP" -> Cap(getTrailingParameterString()) "CAP" -> Cap(getTrailingParameterString())
"PING" -> Ping(getTrailingParameterString()) "PING" -> Ping(getTrailingParameterString())
"ERROR" -> Error(getTrailingParameterString()) "ERROR" -> Error(getTrailingParameterString())
"PART" -> Part(getNonTrailingParameters())
else -> UNIMPLEMENTED("$command ${getTrailingParameterString()}") else -> UNIMPLEMENTED("$command ${getTrailingParameterString()}")
} }
} }
@@ -82,6 +83,7 @@ class MessageParser(val incoming: Channel<String>, enableLogging: Boolean = fals
TOPICWHOTIME(333), TOPICWHOTIME(333),
NAMREPLY(353), NAMREPLY(353),
ENDOFNAMES(366), ENDOFNAMES(366),
YOUREOPER(381),
NONE(0xbeef), ; NONE(0xbeef), ;
companion object { companion object {
@@ -112,6 +114,7 @@ class MessageParser(val incoming: Channel<String>, enableLogging: Boolean = fals
RPL.TOPICWHOTIME -> UNIMPLEMENTED(parameters.toString()) RPL.TOPICWHOTIME -> UNIMPLEMENTED(parameters.toString())
RPL.NAMREPLY -> UNIMPLEMENTED(parameters.toString()) RPL.NAMREPLY -> UNIMPLEMENTED(parameters.toString())
RPL.ENDOFNAMES -> RPL_ENDOFNAMES RPL.ENDOFNAMES -> RPL_ENDOFNAMES
RPL.YOUREOPER -> RPL_YOUREOPER
RPL.NONE -> UNIMPLEMENTED(parameters.toString()) RPL.NONE -> UNIMPLEMENTED(parameters.toString())
} }
} }
@@ -115,4 +115,21 @@ sealed class ClientMessage(val strName: String) {
override val trailing: String override val trailing: String
get() = token get() = token
} }
class Quit(val reason: String) : ClientMessage("QUIT") {
override val trailing: String
get() = reason
}
class Part(channels: kotlin.collections.List<String>) : ClientMessage("PART") {
val strChannels = listOf(channels.joinToString(","))
override val params: kotlin.collections.List<String>
get() = strChannels
}
class Stats(val query: Char) : ClientMessage("STATS") {
override val params: kotlin.collections.List<String>
get() = listOf(query.toString())
}
} }
@@ -13,6 +13,7 @@ sealed class ServerMessage {
data class Join(val target: String) : ServerMessage() data class Join(val target: String) : ServerMessage()
data class Ping(val token: String) : ServerMessage() data class Ping(val token: String) : ServerMessage()
data class Error(val message: String) : ServerMessage() data class Error(val message: String) : ServerMessage()
data class Part(val channels: List<String>) : ServerMessage()
sealed class Numeric(val number: Short) : ServerMessage() { sealed class Numeric(val number: Short) : ServerMessage() {
data class RPL_WELCOME(val message: String) : Numeric(1) data class RPL_WELCOME(val message: String) : Numeric(1)
@@ -27,5 +28,6 @@ sealed class ServerMessage {
data class RPL_TOPIC(val topic: String) : Numeric(332) data class RPL_TOPIC(val topic: String) : Numeric(332)
data class RPL_NAMREPLY(val message: String) : Numeric(353) data class RPL_NAMREPLY(val message: String) : Numeric(353)
data object RPL_ENDOFNAMES : Numeric(366) data object RPL_ENDOFNAMES : Numeric(366)
data object RPL_YOUREOPER : Numeric(381)
} }
} }
@@ -24,11 +24,11 @@ object Codes {
const val FG_START = ANSI.ESC_START + "38;5;" const val FG_START = ANSI.ESC_START + "38;5;"
const val FG_BOLD_START = ANSI.ESC_START + ANSI.BOLD + "38;5;" const val FG_BOLD_START = ANSI.ESC_START + ANSI.BOLD + "38;5;"
const val BG_START = ANSI.ESC_START + "48;5;" const val BG_START = ANSI.ESC_START + "48;5;"
const val RED = "9" const val RED = "196"
const val BLACK = "16" const val BLACK = "16"
const val BLUE = "26" const val BLUE = "26"
const val GREEN = "28" const val GREEN = "34"
const val ORANGE = "202" const val ORANGE = "208"
const val DIMMED_WHITE = "250" const val DIMMED_WHITE = "250"
const val WHITE = "255" const val WHITE = "255"
const val UNSET = "" const val UNSET = ""
@@ -52,7 +52,7 @@ class IrcClientTest {
fun shutdown() = fun shutdown() =
runBlocking { runBlocking {
logger.info { "Closing server." } logger.info { "Closing server." }
client.queueMessage(Message.Die()) client.quit("")
client.waitForNext<ServerMessage.Notice>() client.waitForNext<ServerMessage.Notice>()
processes.forEach { it.destroy() } processes.forEach { it.destroy() }
} }
@@ -0,0 +1,11 @@
package com.shr4pnel.ferretirc
import com.shr4pnel.ferretirc.net.messages.ClientMessage
import org.junit.jupiter.api.Test
class Sandbox {
@Test
fun doesPartUnderstandMultiChannel() {
val part = ClientMessage.Part(listOf("#Default", "#Secondary"))
}
}