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.

IrcClientImpl.kt 7.1KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176
  1. package com.dmdirc.ktirc
  2. import com.dmdirc.ktirc.events.*
  3. import com.dmdirc.ktirc.events.handlers.eventHandlers
  4. import com.dmdirc.ktirc.events.mutators.eventMutators
  5. import com.dmdirc.ktirc.io.LineBufferedSocket
  6. import com.dmdirc.ktirc.io.LineBufferedSocketImpl
  7. import com.dmdirc.ktirc.io.MessageHandler
  8. import com.dmdirc.ktirc.io.MessageParser
  9. import com.dmdirc.ktirc.messages.*
  10. import com.dmdirc.ktirc.messages.processors.messageProcessors
  11. import com.dmdirc.ktirc.model.*
  12. import com.dmdirc.ktirc.util.RemoveIn
  13. import com.dmdirc.ktirc.util.currentTimeProvider
  14. import com.dmdirc.ktirc.util.generateLabel
  15. import com.dmdirc.ktirc.util.logger
  16. import kotlinx.coroutines.*
  17. import kotlinx.coroutines.channels.Channel
  18. import kotlinx.coroutines.channels.map
  19. import kotlinx.coroutines.sync.Mutex
  20. import java.net.Inet6Address
  21. import java.net.InetAddress
  22. import java.time.Duration
  23. import java.util.logging.Level
  24. /**
  25. * Concrete implementation of an [IrcClient].
  26. */
  27. internal class IrcClientImpl(private val config: IrcClientConfig) : ExperimentalIrcClient, CoroutineScope {
  28. private val log by logger()
  29. @ExperimentalCoroutinesApi
  30. override val coroutineContext = GlobalScope.newCoroutineContext(Dispatchers.IO)
  31. @ExperimentalCoroutinesApi
  32. internal var socketFactory: (CoroutineScope, String, String, Int, Boolean) -> LineBufferedSocket = ::LineBufferedSocketImpl
  33. internal var resolver: (String) -> Collection<ResolveResult> = { host ->
  34. InetAddress.getAllByName(host).map { ResolveResult(it.hostAddress, it is Inet6Address) }
  35. }
  36. internal var asyncTimeout = Duration.ofSeconds(20)
  37. override var behaviour = config.behaviour
  38. override val serverState = ServerState(config.profile.nickname, config.server.host, config.sasl)
  39. override val channelState = ChannelStateMap { caseMapping }
  40. override val localUser = User(config.profile.nickname)
  41. override val userState = UserState { caseMapping }.apply { this += localUser }
  42. private val messageHandler = MessageHandler(messageProcessors, eventMutators, eventHandlers)
  43. private val messageBuilder = MessageBuilder()
  44. private val parser = MessageParser()
  45. private var socket: LineBufferedSocket? = null
  46. private val connecting = Mutex(false)
  47. @Deprecated("Use structured send instead", ReplaceWith("send(command, arguments)"))
  48. @RemoveIn("2.0.0")
  49. override fun send(message: String) {
  50. socket?.sendChannel?.offer(message.toByteArray()) ?: log.warning { "No send channel for message: $message" }
  51. }
  52. override fun send(tags: Map<MessageTag, String>, command: String, vararg arguments: String) {
  53. maybeEchoMessage(command, arguments)
  54. socket?.sendChannel?.offer(messageBuilder.build(tags, command, arguments))
  55. ?: log.warning { "No send channel for command: $command" }
  56. }
  57. override fun sendAsync(tags: Map<MessageTag, String>, command: String, arguments: Array<String>, matcher: (IrcEvent) -> Boolean) = async {
  58. val label = generateLabel(this@IrcClientImpl)
  59. val channel = Channel<IrcEvent>(1)
  60. if (serverState.asyncResponseState.supportsLabeledResponses) {
  61. serverState.asyncResponseState.pendingResponses[label] = channel to { event -> event.metadata.label == label }
  62. send(tags + (MessageTag.Label to label), command, *arguments)
  63. } else {
  64. serverState.asyncResponseState.pendingResponses[label] = channel to matcher
  65. send(tags, command, *arguments)
  66. }
  67. withTimeoutOrNull(asyncTimeout.toMillis()) {
  68. channel.receive()
  69. }.also { serverState.asyncResponseState.pendingResponses.remove(label) }
  70. }
  71. override fun connect() {
  72. check(connecting.tryLock()) { "IrcClient is already connected to a server" }
  73. val ip: String
  74. try {
  75. ip = resolve(config.server.host)
  76. } catch (ex: Exception) {
  77. log.log(Level.SEVERE, ex) { "Error resolving ${config.server.host}" }
  78. emitEvent(ServerConnectionError(EventMetadata(currentTimeProvider()), ConnectionError.UnresolvableAddress, ex.localizedMessage))
  79. reset()
  80. return
  81. }
  82. @Suppress("EXPERIMENTAL_API_USAGE")
  83. with(socketFactory(this, config.server.host, ip, config.server.port, config.server.useTls)) {
  84. socket = this
  85. emitEvent(ServerConnecting(EventMetadata(currentTimeProvider())))
  86. launch {
  87. try {
  88. connect()
  89. emitEvent(ServerConnected(EventMetadata(currentTimeProvider())))
  90. sendCapabilityList()
  91. sendPasswordIfPresent()
  92. sendNickChange(config.profile.nickname)
  93. sendUser(config.profile.username, config.profile.realName)
  94. messageHandler.processMessages(this@IrcClientImpl, receiveChannel.map { parser.parse(it) })
  95. } catch (ex: Exception) {
  96. log.log(Level.SEVERE, ex) { "Error connecting to ${config.server.host}:${config.server.port}" }
  97. emitEvent(ServerConnectionError(EventMetadata(currentTimeProvider()), ex.toConnectionError(), ex.localizedMessage))
  98. }
  99. reset()
  100. emitEvent(ServerDisconnected(EventMetadata(currentTimeProvider())))
  101. }
  102. }
  103. }
  104. override fun disconnect() {
  105. runBlocking {
  106. socket?.disconnect()
  107. connecting.lock()
  108. connecting.unlock()
  109. }
  110. }
  111. override fun onEvent(handler: (IrcEvent) -> Unit) = messageHandler.addEmitter(handler)
  112. private fun emitEvent(event: IrcEvent) = messageHandler.handleEvent(this, event)
  113. private fun sendPasswordIfPresent() = config.server.password?.let(this::sendPassword)
  114. private fun maybeEchoMessage(command: String, arguments: Array<out String>) {
  115. // TODO: Is this the best place to do it? It'd be nicer to actually build the message and
  116. // reflect the raw line back through all the processors etc.
  117. if (command == "PRIVMSG" && behaviour.alwaysEchoMessages && !serverState.capabilities.enabledCapabilities.contains(Capability.EchoMessages)) {
  118. emitEvent(MessageReceived(
  119. EventMetadata(currentTimeProvider()),
  120. localUser,
  121. arguments[0],
  122. arguments[1]
  123. ))
  124. }
  125. }
  126. private fun resolve(host: String): String {
  127. val hosts = resolver(host)
  128. val preferredHosts = hosts.filter { it.isV6 == behaviour.preferIPv6 }
  129. return if (preferredHosts.isNotEmpty()) {
  130. preferredHosts.random().ip
  131. } else {
  132. hosts.random().ip
  133. }
  134. }
  135. internal fun reset() {
  136. serverState.reset()
  137. channelState.clear()
  138. userState.reset()
  139. localUser.reset(config.profile.nickname)
  140. userState += localUser
  141. socket = null
  142. connecting.tryLock()
  143. connecting.unlock()
  144. }
  145. }
  146. internal data class ResolveResult(val ip: String, val isV6: Boolean)