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

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