Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

IrcClient.kt 5.6KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170
  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. // TODO: What happens if sending fails?
  86. scope.launch {
  87. socket?.sendLine(message)
  88. }
  89. }
  90. override fun connect() {
  91. check(!connecting.getAndSet(true))
  92. connectionJob = scope.launch {
  93. with(socketFactory(server.host, server.port, server.tls)) {
  94. // TODO: Proper error handling - what if connect() fails?
  95. socket = this
  96. connect()
  97. emitEvent(ServerConnected(currentTimeProvider()))
  98. sendCapabilityList()
  99. sendPasswordIfPresent()
  100. sendNickChange(profile.initialNick)
  101. // TODO: Send correct host
  102. sendUser(profile.userName, "localhost", server.host, profile.realName)
  103. messageHandler.processMessages(this@IrcClientImpl, readLines(scope).map { parser.parse(it) })
  104. }
  105. }
  106. }
  107. override fun disconnect() {
  108. socket?.disconnect()
  109. }
  110. suspend fun join() {
  111. connectionJob?.join()
  112. }
  113. override fun onEvent(handler: (IrcEvent) -> Unit) {
  114. messageHandler.handlers.add(object : EventHandler {
  115. override fun processEvent(client: IrcClient, event: IrcEvent): List<IrcEvent> {
  116. handler(event)
  117. return emptyList()
  118. }
  119. })
  120. }
  121. private fun emitEvent(event: IrcEvent) = messageHandler.emitEvent(this, event)
  122. private fun sendPasswordIfPresent() = server.password?.let(this::sendPassword)
  123. }
  124. internal fun main() {
  125. val rootLogger = LogManager.getLogManager().getLogger("")
  126. rootLogger.level = Level.FINEST
  127. for (h in rootLogger.handlers) {
  128. h.level = Level.FINEST
  129. }
  130. runBlocking {
  131. with(IrcClientImpl(Server("testnet.inspircd.org", 6667), Profile("KtIrc", "Kotlin!", "kotlin"))) {
  132. onEvent { event ->
  133. when (event) {
  134. is ServerWelcome -> sendJoin("#ktirc")
  135. is MessageReceived ->
  136. if (event.message == "!test")
  137. reply(event, "Test successful!")
  138. }
  139. }
  140. connect()
  141. join()
  142. }
  143. }
  144. }