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

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