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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164
  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 kotlinx.coroutines.*
  8. import kotlinx.coroutines.channels.map
  9. import java.util.concurrent.atomic.AtomicBoolean
  10. import java.util.logging.Level
  11. import java.util.logging.LogManager
  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 [joinMessage].
  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 idomatic 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) = caseMapping.areEquivalent(user.nickname, serverState.localNickname)
  63. }
  64. /**
  65. * Concrete implementation of an [IrcClient].
  66. *
  67. * @param server The server to connect to.
  68. * @param profile The user details to use when connecting.
  69. */
  70. // TODO: How should alternative nicknames work?
  71. // TODO: Should IRC Client take a pool of servers and rotate through, or make the caller do that?
  72. // TODO: Should there be a default profile?
  73. class IrcClientImpl(private val server: Server, private val profile: Profile) : IrcClient {
  74. internal var socketFactory: (String, Int, Boolean) -> LineBufferedSocket = ::KtorLineBufferedSocket
  75. override val serverState = ServerState(profile.initialNick)
  76. override val channelState = ChannelStateMap { caseMapping }
  77. override val userState = UserState { caseMapping }
  78. private val messageHandler = MessageHandler(messageProcessors.toList(), eventHandlers.toMutableList())
  79. private val parser = MessageParser()
  80. private var socket: LineBufferedSocket? = null
  81. private val scope = CoroutineScope(Dispatchers.IO)
  82. private val connecting = AtomicBoolean(false)
  83. private var connectionJob: Job? = null
  84. override fun send(message: String) {
  85. scope.launch {
  86. socket?.sendLine(message)
  87. }
  88. }
  89. override fun connect() {
  90. check(!connecting.getAndSet(true))
  91. connectionJob = scope.launch {
  92. with(socketFactory(server.host, server.port, server.tls)) {
  93. // TODO: Proper error handling - what if connect() fails?
  94. socket = this
  95. connect()
  96. messageHandler.emitEvent(this@IrcClientImpl, ServerConnected(currentTimeProvider()))
  97. sendLine("CAP LS 302") // TODO: Stick this in a builder
  98. server.password?.let { pass -> sendPassword(pass) }
  99. sendNickChange(profile.initialNick)
  100. // TODO: Send correct host
  101. sendUser(profile.userName, "localhost", server.host, profile.realName)
  102. messageHandler.processMessages(this@IrcClientImpl, readLines(scope).map { parser.parse(it) })
  103. }
  104. }
  105. }
  106. override fun disconnect() {
  107. socket?.disconnect()
  108. }
  109. suspend fun join() {
  110. connectionJob?.join()
  111. }
  112. override fun onEvent(handler: (IrcEvent) -> Unit) {
  113. messageHandler.handlers.add(object : EventHandler {
  114. override fun processEvent(client: IrcClient, event: IrcEvent) {
  115. handler(event)
  116. }
  117. })
  118. }
  119. }
  120. internal fun main() {
  121. val rootLogger = LogManager.getLogManager().getLogger("")
  122. rootLogger.level = Level.FINEST
  123. for (h in rootLogger.handlers) {
  124. h.level = Level.FINEST
  125. }
  126. runBlocking {
  127. with(IrcClientImpl(Server("testnet.inspircd.org", 6667), Profile("KtIrc", "Kotlin!", "kotlin"))) {
  128. onEvent { event ->
  129. when (event) {
  130. is ServerWelcome -> sendJoin("#ktirc")
  131. is MessageReceived ->
  132. if (event.message == "!test")
  133. reply(event, "Test successful!")
  134. }
  135. }
  136. connect()
  137. join()
  138. }
  139. }
  140. }