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 5.8KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140
  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.currentTimeProvider
  13. import com.dmdirc.ktirc.util.generateLabel
  14. import com.dmdirc.ktirc.util.logger
  15. import kotlinx.coroutines.*
  16. import kotlinx.coroutines.channels.Channel
  17. import kotlinx.coroutines.channels.map
  18. import java.time.Duration
  19. import java.util.concurrent.atomic.AtomicBoolean
  20. import java.util.logging.Level
  21. /**
  22. * Concrete implementation of an [IrcClient].
  23. */
  24. // TODO: How should alternative nicknames work?
  25. // TODO: Should IRC Client take a pool of servers and rotate through, or make the caller do that?
  26. internal class IrcClientImpl(private val config: IrcClientConfig) : ExperimentalIrcClient, CoroutineScope {
  27. private val log by logger()
  28. @ExperimentalCoroutinesApi
  29. override val coroutineContext = GlobalScope.newCoroutineContext(Dispatchers.IO)
  30. @ExperimentalCoroutinesApi
  31. internal var socketFactory: (CoroutineScope, String, Int, Boolean) -> LineBufferedSocket = ::LineBufferedSocketImpl
  32. internal var asyncTimeout = Duration.ofSeconds(20)
  33. override var behaviour = config.behaviour
  34. override val serverState = ServerState(config.profile.nickname, config.server.host, config.sasl)
  35. override val channelState = ChannelStateMap { caseMapping }
  36. override val userState = UserState { caseMapping }
  37. private val messageHandler = MessageHandler(messageProcessors, eventMutators, eventHandlers)
  38. private val messageBuilder = MessageBuilder()
  39. private val parser = MessageParser()
  40. private var socket: LineBufferedSocket? = null
  41. private val connecting = AtomicBoolean(false)
  42. override fun send(message: String) {
  43. socket?.sendChannel?.offer(message.toByteArray()) ?: log.warning { "No send channel for message: $message" }
  44. }
  45. override fun send(tags: Map<MessageTag, String>, command: String, vararg arguments: String) {
  46. maybeEchoMessage(command, arguments)
  47. socket?.sendChannel?.offer(messageBuilder.build(tags, command, arguments))
  48. ?: log.warning { "No send channel for command: $command" }
  49. }
  50. override fun sendAsync(tags: Map<MessageTag, String>, command: String, arguments: Array<String>, matcher: (IrcEvent) -> Boolean) = async {
  51. val label = generateLabel(this@IrcClientImpl)
  52. val channel = Channel<IrcEvent>(1)
  53. if (serverState.asyncResponseState.supportsLabeledResponses) {
  54. serverState.asyncResponseState.pendingResponses[label] = channel to { event -> event.metadata.label == label }
  55. send(tags + (MessageTag.Label to label), command, *arguments)
  56. } else {
  57. serverState.asyncResponseState.pendingResponses[label] = channel to matcher
  58. send(tags, command, *arguments)
  59. }
  60. withTimeoutOrNull(asyncTimeout.toMillis()) {
  61. channel.receive()
  62. }.also { serverState.asyncResponseState.pendingResponses.remove(label) }
  63. }
  64. override fun connect() {
  65. check(!connecting.getAndSet(true))
  66. @Suppress("EXPERIMENTAL_API_USAGE")
  67. with(socketFactory(this, config.server.host, config.server.port, config.server.useTls)) {
  68. socket = this
  69. emitEvent(ServerConnecting(EventMetadata(currentTimeProvider())))
  70. launch {
  71. try {
  72. connect()
  73. emitEvent(ServerConnected(EventMetadata(currentTimeProvider())))
  74. sendCapabilityList()
  75. sendPasswordIfPresent()
  76. sendNickChange(config.profile.nickname)
  77. sendUser(config.profile.username, config.profile.realName)
  78. messageHandler.processMessages(this@IrcClientImpl, receiveChannel.map { parser.parse(it) })
  79. } catch (ex: Exception) {
  80. log.log(Level.SEVERE, ex) { "Error connecting to ${config.server.host}:${config.server.port}" }
  81. emitEvent(ServerConnectionError(EventMetadata(currentTimeProvider()), ex.toConnectionError(), ex.localizedMessage))
  82. }
  83. reset()
  84. emitEvent(ServerDisconnected(EventMetadata(currentTimeProvider())))
  85. }
  86. }
  87. }
  88. override fun disconnect() {
  89. socket?.disconnect()
  90. }
  91. override fun onEvent(handler: (IrcEvent) -> Unit) = messageHandler.addEmitter(handler)
  92. private fun emitEvent(event: IrcEvent) = messageHandler.handleEvent(this, event)
  93. private fun sendPasswordIfPresent() = config.server.password?.let(this::sendPassword)
  94. private fun maybeEchoMessage(command: String, arguments: Array<out String>) {
  95. // TODO: Is this the best place to do it? It'd be nicer to actually build the message and
  96. // reflect the raw line back through all the processors etc.
  97. if (command == "PRIVMSG" && behaviour.alwaysEchoMessages && !serverState.capabilities.enabledCapabilities.contains(Capability.EchoMessages)) {
  98. emitEvent(MessageReceived(
  99. EventMetadata(currentTimeProvider()),
  100. userState[serverState.localNickname]?.details ?: User(serverState.localNickname),
  101. arguments[0],
  102. arguments[1]
  103. ))
  104. }
  105. }
  106. internal fun reset() {
  107. serverState.reset()
  108. channelState.clear()
  109. userState.reset()
  110. socket = null
  111. connecting.set(false)
  112. }
  113. }