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.

ServerState.kt 7.6KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193
  1. package com.dmdirc.ktirc.model
  2. import com.dmdirc.ktirc.SaslConfig
  3. import com.dmdirc.ktirc.events.IrcEvent
  4. import com.dmdirc.ktirc.io.CaseMapping
  5. import com.dmdirc.ktirc.util.logger
  6. import kotlin.reflect.KClass
  7. /**
  8. * Contains the current state of a single IRC server.
  9. */
  10. class ServerState internal constructor(
  11. private val initialNickname: String,
  12. private val initialServerName: String,
  13. saslConfig: SaslConfig? = null) {
  14. private val log by logger()
  15. /** Whether we've received the 'Welcome to IRC' (001) message. */
  16. internal var receivedWelcome = false
  17. /** The current status of the server. */
  18. var status = ServerStatus.Disconnected
  19. internal set
  20. /**
  21. * What we believe our current nickname to be on the server.
  22. *
  23. * Initially this will be the nickname provided in the config. It will be updated to the actual nickname
  24. * in use when connecting. Once you have received a [com.dmdirc.ktirc.events.ServerWelcome] event you can
  25. * rely on this value being current.
  26. * */
  27. var localNickname: String = initialNickname
  28. internal set
  29. /**
  30. * The name of the server we are connected to.
  31. *
  32. * Initially this will be the hostname or IP address provided in the config. It will be updated to the server's
  33. * self-reported hostname when connecting. Once you have received a [com.dmdirc.ktirc.events.ServerWelcome] event
  34. * you can rely on this value being current.
  35. */
  36. var serverName: String = initialServerName
  37. internal set
  38. /** The features that the server has declared it supports (from the 005 header). */
  39. val features = ServerFeatureMap()
  40. /** The capabilities we have negotiated with the server (from IRCv3). */
  41. val capabilities = CapabilitiesState()
  42. /** The current state of SASL authentication. */
  43. internal val sasl = SaslState(saslConfig)
  44. /**
  45. * Convenience accessor for the [ServerFeature.ModePrefixes] feature, which will always have a value.
  46. */
  47. val channelModePrefixes
  48. get() = features[ServerFeature.ModePrefixes] ?: throw IllegalStateException("lost mode prefixes")
  49. /**
  50. * Convenience accessor for the [ServerFeature.ChannelTypes] feature, which will always have a value.
  51. */
  52. val channelTypes
  53. get() = features[ServerFeature.ChannelTypes] ?: throw IllegalStateException("lost channel types")
  54. /**
  55. * Batches that are currently in progress.
  56. */
  57. internal val batches = mutableMapOf<String, Batch>()
  58. /**
  59. * Determines if the given mode is one applied to a user of a channel, such as 'o' for operator.
  60. */
  61. fun isChannelUserMode(mode: Char) = channelModePrefixes.isMode(mode)
  62. /**
  63. * Determines what type of channel mode the given character is, based on the server features.
  64. *
  65. * If the mode isn't found, or the server hasn't provided modes, it is presumed to be [ChannelModeType.NoParameter].
  66. */
  67. fun channelModeType(mode: Char): ChannelModeType {
  68. features[ServerFeature.ChannelModes]?.forEachIndexed { index, modes ->
  69. if (mode in modes) {
  70. return ChannelModeType.values()[index]
  71. }
  72. }
  73. log.warning { "Unknown channel mode $mode, assuming it's boolean" }
  74. return ChannelModeType.NoParameter
  75. }
  76. internal fun reset() {
  77. receivedWelcome = false
  78. status = ServerStatus.Disconnected
  79. localNickname = initialNickname
  80. serverName = initialServerName
  81. features.clear()
  82. capabilities.reset()
  83. sasl.reset()
  84. batches.clear()
  85. }
  86. }
  87. /**
  88. * Maps known features onto their values, enforcing type safety.
  89. */
  90. class ServerFeatureMap {
  91. private val features = HashMap<ServerFeature<*>, Any?>()
  92. /**
  93. * Gets the value, or the default value, of the given feature.
  94. */
  95. @Suppress("UNCHECKED_CAST")
  96. operator fun <T : Any> get(feature: ServerFeature<T>) = features.getOrDefault(feature, feature.default) as? T? ?: feature.default
  97. internal operator fun set(feature: ServerFeature<*>, value: Any) {
  98. require(feature.type.isInstance(value)) {
  99. "Value given for feature ${feature::class} must be type ${feature.type} but was ${value::class}"
  100. }
  101. features[feature] = value
  102. }
  103. internal fun setAll(featureMap: ServerFeatureMap) = featureMap.features.forEach { feature, value -> features[feature] = value }
  104. internal fun reset(feature: ServerFeature<*>) = features.put(feature, null)
  105. internal fun clear() = features.clear()
  106. internal fun isEmpty() = features.isEmpty()
  107. }
  108. /**
  109. * Stores the mapping of mode prefixes received from the server.
  110. */
  111. data class ModePrefixMapping(val modes: String, val prefixes: String) {
  112. /** Determines whether the given character is a mode prefix (e.g. "@", "+"). */
  113. fun isPrefix(char: Char) = prefixes.contains(char)
  114. /** Determines whether the given character is a channel user mode (e.g. "o", "v"). */
  115. fun isMode(char: Char) = modes.contains(char)
  116. /** Gets the mode corresponding to the given prefix (e.g. "@" -> "o"). */
  117. fun getMode(prefix: Char) = modes[prefixes.indexOf(prefix)]
  118. /** Gets the modes corresponding to the given prefixes (e.g. "@+" -> "ov"). */
  119. fun getModes(prefixes: String) = String(prefixes.map(this::getMode).toCharArray())
  120. }
  121. /**
  122. * Describes a server feature determined from the 005 response.
  123. */
  124. sealed class ServerFeature<T : Any>(val name: String, val type: KClass<T>, val default: T? = null) {
  125. /** The network the server says it belongs to. */
  126. object Network : ServerFeature<String>("NETWORK", String::class)
  127. /** The case mapping the server uses, defaulting to RFC. */
  128. object ServerCaseMapping : ServerFeature<CaseMapping>("CASEMAPPING", CaseMapping::class, CaseMapping.Rfc)
  129. /** The mode prefixes the server uses, defaulting to ov/@+. */
  130. object ModePrefixes : ServerFeature<ModePrefixMapping>("PREFIX", ModePrefixMapping::class, ModePrefixMapping("ov", "@+"))
  131. /** The maximum number of channels a client may join. */
  132. object MaximumChannels : ServerFeature<Int>("MAXCHANNELS", Int::class) // TODO: CHANLIMIT also exists
  133. /** The modes supported in channels. */
  134. object ChannelModes : ServerFeature<Array<String>>("CHANMODES", Array<String>::class)
  135. /** The types of channels supported. */
  136. object ChannelTypes : ServerFeature<String>("CHANTYPES", String::class, "#&")
  137. /** The maximum length of a channel name, defaulting to 200. */
  138. object MaximumChannelNameLength : ServerFeature<Int>("CHANNELLEN", Int::class, 200)
  139. /** Whether or not the server supports extended who. */
  140. object WhoxSupport : ServerFeature<Boolean>("WHOX", Boolean::class, false)
  141. }
  142. /**
  143. * Enumeration of the possible states of a server.
  144. */
  145. enum class ServerStatus {
  146. /** The server is not connected. */
  147. Disconnected,
  148. /** We are attempting to connect to the server. It is not yet ready for use. */
  149. Connecting,
  150. /** We are logging in, dealing with capabilities, etc. The server is not yet ready for use. */
  151. Negotiating,
  152. /** We are connected and commands can be sent. */
  153. Ready,
  154. }
  155. /**
  156. * Represents an in-progress batch.
  157. */
  158. internal data class Batch(val type: String, val arguments: List<String>, val parent: String? = null, val events: MutableList<IrcEvent> = mutableListOf())
  159. internal val serverFeatures: Map<String, ServerFeature<*>> by lazy {
  160. ServerFeature::class.nestedClasses.map { it.objectInstance as ServerFeature<*> }.associateBy { it.name }
  161. }