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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151
  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 io.ktor.util.KtorExperimentalAPI
  8. import kotlinx.coroutines.*
  9. import kotlinx.coroutines.channels.map
  10. import java.util.concurrent.atomic.AtomicBoolean
  11. /**
  12. * Primary interface for interacting with KtIrc.
  13. */
  14. interface IrcClient {
  15. val serverState: ServerState
  16. val channelState: ChannelStateMap
  17. val userState: UserState
  18. val profile: Profile
  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. * Concrete implementation of an [IrcClient].
  70. *
  71. * @param server The server to connect to.
  72. * @param profile The user details to use when connecting.
  73. */
  74. // TODO: How should alternative nicknames work?
  75. // TODO: Should IRC Client take a pool of servers and rotate through, or make the caller do that?
  76. // TODO: Should there be a default profile?
  77. @KtorExperimentalAPI
  78. @ExperimentalCoroutinesApi
  79. class IrcClientImpl(private val server: Server, override val profile: Profile) : IrcClient, CoroutineScope {
  80. override val coroutineContext = GlobalScope.newCoroutineContext(Dispatchers.IO)
  81. internal var socketFactory: (CoroutineScope, String, Int, Boolean) -> LineBufferedSocket = ::KtorLineBufferedSocket
  82. override val serverState = ServerState(profile.initialNick, server.host)
  83. override val channelState = ChannelStateMap { caseMapping }
  84. override val userState = UserState { caseMapping }
  85. private val messageHandler = MessageHandler(messageProcessors.toList(), eventHandlers.toMutableList())
  86. private val parser = MessageParser()
  87. private var socket: LineBufferedSocket? = null
  88. private val connecting = AtomicBoolean(false)
  89. override fun send(message: String) {
  90. socket?.sendChannel?.offer(message.toByteArray())
  91. }
  92. override fun connect() {
  93. check(!connecting.getAndSet(true))
  94. with(socketFactory(this, server.host, server.port, server.tls)) {
  95. // TODO: Proper error handling - what if connect() fails?
  96. socket = this
  97. emitEvent(ServerConnecting(currentTimeProvider()))
  98. launch {
  99. connect()
  100. emitEvent(ServerConnected(currentTimeProvider()))
  101. sendCapabilityList()
  102. sendPasswordIfPresent()
  103. sendNickChange(profile.initialNick)
  104. // TODO: Send correct host
  105. sendUser(profile.userName, profile.realName)
  106. messageHandler.processMessages(this@IrcClientImpl, receiveChannel.map { parser.parse(it) })
  107. emitEvent(ServerDisconnected(currentTimeProvider()))
  108. }
  109. }
  110. }
  111. override fun disconnect() {
  112. socket?.disconnect()
  113. }
  114. override fun onEvent(handler: (IrcEvent) -> Unit) {
  115. messageHandler.handlers.add(object : EventHandler {
  116. override fun processEvent(client: IrcClient, event: IrcEvent): List<IrcEvent> {
  117. handler(event)
  118. return emptyList()
  119. }
  120. })
  121. }
  122. private fun emitEvent(event: IrcEvent) = messageHandler.emitEvent(this, event)
  123. private fun sendPasswordIfPresent() = server.password?.let(this::sendPassword)
  124. }