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.3KB

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