You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

IrcClient.kt 5.7KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170
  1. package com.dmdirc.ktirc
  2. import com.dmdirc.ktirc.events.*
  3. import com.dmdirc.ktirc.io.*
  4. import com.dmdirc.ktirc.messages.*
  5. import com.dmdirc.ktirc.model.*
  6. import com.dmdirc.ktirc.util.currentTimeProvider
  7. import com.dmdirc.ktirc.util.logger
  8. import io.ktor.util.KtorExperimentalAPI
  9. import kotlinx.coroutines.*
  10. import kotlinx.coroutines.channels.map
  11. import java.util.concurrent.atomic.AtomicBoolean
  12. /**
  13. * Primary interface for interacting with KtIrc.
  14. */
  15. interface IrcClient {
  16. val serverState: ServerState
  17. val channelState: ChannelStateMap
  18. val userState: UserState
  19. val caseMapping: CaseMapping
  20. get() = serverState.features[ServerFeature.ServerCaseMapping] ?: CaseMapping.Rfc
  21. /**
  22. * Begins a connection attempt to the IRC server.
  23. *
  24. * This method will return immediately, and the attempt to connect will be executed in a coroutine on the
  25. * IO scheduler. To check the status of the connection, monitor events using [onEvent].
  26. */
  27. fun connect()
  28. /**
  29. * Disconnect immediately from the IRC server, without sending a QUIT.
  30. */
  31. fun disconnect()
  32. /**
  33. * Sends the given raw line to the IRC server, followed by a carriage return and line feed.
  34. *
  35. * Standard IRC messages can be constructed using the methods in [com.dmdirc.ktirc.messages]
  36. * such as [sendJoin].
  37. *
  38. * @param message The line to be sent to the IRC server.
  39. */
  40. fun send(message: String)
  41. /**
  42. * Registers a new handler for all events on this connection.
  43. *
  44. * All events are subclasses of [IrcEvent]; the idiomatic way to handle them is using a `when` statement:
  45. *
  46. * ```
  47. * client.onEvent {
  48. * when(it) {
  49. * is MessageReceived -> println(it.message)
  50. * }
  51. * }
  52. * ```
  53. *
  54. * *Note*: at present handlers cannot be removed; they last the lifetime of the [IrcClient].
  55. *
  56. * @param handler The method to call when a new event occurs.
  57. */
  58. fun onEvent(handler: (IrcEvent) -> Unit)
  59. /**
  60. * Utility method to determine if the given user is the one we are connected to IRC as.
  61. */
  62. fun isLocalUser(user: User) = isLocalUser(user.nickname)
  63. /**
  64. * Utility method to determine if the given user is the one we are connected to IRC as.
  65. */
  66. fun isLocalUser(nickname: String) = caseMapping.areEquivalent(nickname, serverState.localNickname)
  67. }
  68. /**
  69. * Constructs a new [IrcClient] using a configuration DSL.
  70. *
  71. * See [IrcClientConfigBuilder] for details of all options
  72. */
  73. @IrcClientDsl
  74. @Suppress("FunctionName")
  75. fun IrcClient(block: IrcClientConfigBuilder.() -> Unit): IrcClient =
  76. IrcClientImpl(IrcClientConfigBuilder().apply(block).build())
  77. /**
  78. * Concrete implementation of an [IrcClient].
  79. */
  80. // TODO: How should alternative nicknames work?
  81. // TODO: Should IRC Client take a pool of servers and rotate through, or make the caller do that?
  82. // TODO: Should there be a default profile?
  83. internal class IrcClientImpl(private val config: IrcClientConfig) : IrcClient, CoroutineScope {
  84. private val log by logger()
  85. @ExperimentalCoroutinesApi
  86. override val coroutineContext = GlobalScope.newCoroutineContext(Dispatchers.IO)
  87. @ExperimentalCoroutinesApi
  88. @KtorExperimentalAPI
  89. internal var socketFactory: (CoroutineScope, String, Int, Boolean) -> LineBufferedSocket = ::KtorLineBufferedSocket
  90. override val serverState = ServerState(config.profile.nickname, config.server.host, config.sasl)
  91. override val channelState = ChannelStateMap { caseMapping }
  92. override val userState = UserState { caseMapping }
  93. private val messageHandler = MessageHandler(messageProcessors.toList(), eventHandlers.toMutableList())
  94. private val parser = MessageParser()
  95. private var socket: LineBufferedSocket? = null
  96. private val connecting = AtomicBoolean(false)
  97. override fun send(message: String) {
  98. socket?.sendChannel?.offer(message.toByteArray()) ?: log.warning { "No send channel for message: $message" }
  99. }
  100. override fun connect() {
  101. check(!connecting.getAndSet(true))
  102. @Suppress("EXPERIMENTAL_API_USAGE")
  103. with(socketFactory(this, config.server.host, config.server.port, config.server.useTls)) {
  104. // TODO: Proper error handling - what if connect() fails?
  105. socket = this
  106. emitEvent(ServerConnecting(currentTimeProvider()))
  107. launch {
  108. connect()
  109. emitEvent(ServerConnected(currentTimeProvider()))
  110. sendCapabilityList()
  111. sendPasswordIfPresent()
  112. sendNickChange(config.profile.nickname)
  113. sendUser(config.profile.username, config.profile.realName)
  114. messageHandler.processMessages(this@IrcClientImpl, receiveChannel.map { parser.parse(it) })
  115. reset()
  116. emitEvent(ServerDisconnected(currentTimeProvider()))
  117. }
  118. }
  119. }
  120. override fun disconnect() {
  121. socket?.disconnect()
  122. }
  123. override fun onEvent(handler: (IrcEvent) -> Unit) {
  124. messageHandler.handlers.add(object : EventHandler {
  125. override fun processEvent(client: IrcClient, event: IrcEvent): List<IrcEvent> {
  126. handler(event)
  127. return emptyList()
  128. }
  129. })
  130. }
  131. private fun emitEvent(event: IrcEvent) = messageHandler.emitEvent(this, event)
  132. private fun sendPasswordIfPresent() = config.server.password?.let(this::sendPassword)
  133. internal fun reset() {
  134. serverState.reset()
  135. channelState.clear()
  136. userState.reset()
  137. socket = null
  138. connecting.set(false)
  139. }
  140. }