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.

ISupportProcessor.kt 2.7KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. package com.dmdirc.ktirc.messages
  2. import com.dmdirc.ktirc.events.ServerFeaturesUpdated
  3. import com.dmdirc.ktirc.io.CaseMapping
  4. import com.dmdirc.ktirc.model.IrcMessage
  5. import com.dmdirc.ktirc.model.ModePrefixMapping
  6. import com.dmdirc.ktirc.model.ServerFeatureMap
  7. import com.dmdirc.ktirc.model.serverFeatures
  8. import com.dmdirc.ktirc.util.logger
  9. import kotlin.reflect.KClass
  10. internal class ISupportProcessor : MessageProcessor {
  11. private val log by logger()
  12. override val commands = arrayOf(RPL_ISUPPORT)
  13. override fun process(message: IrcMessage) = listOf(ServerFeaturesUpdated(message.time, ServerFeatureMap().apply {
  14. // Ignore the first (nickname) and last ("are supported by this server") params
  15. for (i in 1 until message.params.size - 1) {
  16. parseParam(message.params[i])
  17. }
  18. }))
  19. private fun ServerFeatureMap.parseParam(param: ByteArray) = when (param[0]) {
  20. '-'.toByte() -> resetFeature(param.sliceArray(1 until param.size))
  21. else -> when (val equals = param.indexOf('='.toByte())) {
  22. -1 -> enableFeatureWithDefault(param)
  23. else -> enableFeature(param.sliceArray(0 until equals), param.sliceArray(equals + 1 until param.size))
  24. }
  25. }
  26. private fun ServerFeatureMap.resetFeature(name: ByteArray) = name.asFeature()?.let {
  27. reset(it)
  28. log.finer { "Reset feature ${it::class}" }
  29. }
  30. @Suppress("UNCHECKED_CAST")
  31. private fun ServerFeatureMap.enableFeature(name: ByteArray, value: ByteArray) {
  32. name.asFeature()?.let { feature ->
  33. set(feature, value.cast(feature.type))
  34. log.finer { "Set feature ${feature::class} to ${String(value)}" }
  35. }
  36. }
  37. private fun ServerFeatureMap.enableFeatureWithDefault(name: ByteArray) {
  38. name.asFeature()?.let { feature ->
  39. when (feature.type) {
  40. Boolean::class -> set(feature, true)
  41. else -> TODO("not implemented")
  42. }
  43. }
  44. }
  45. private fun ByteArray.asFeature() = serverFeatures[String(this)]
  46. ?: run {
  47. log.warning { "Unknown feature in 005: ${String(this)}" }
  48. null
  49. }
  50. private fun ByteArray.cast(to: KClass<out Any>): Any = with (String(this)) {
  51. when (to) {
  52. Int::class -> toInt()
  53. String::class -> this
  54. CaseMapping::class -> CaseMapping.fromName(this)
  55. ModePrefixMapping::class -> indexOf(')').let { ModePrefixMapping(substring(1 until it), substring(it + 1)) }
  56. Array<String>::class -> split(',').toTypedArray()
  57. else -> TODO("not implemented")
  58. }
  59. }
  60. }