BookSourceDebugWebSocket.kt 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. package io.legato.kazusa.web.socket
  2. import fi.iki.elonen.NanoHTTPD
  3. import fi.iki.elonen.NanoWSD
  4. import io.legato.kazusa.R
  5. import io.legato.kazusa.data.appDb
  6. import io.legato.kazusa.model.Debug
  7. import io.legato.kazusa.utils.*
  8. import kotlinx.coroutines.*
  9. import kotlinx.coroutines.Dispatchers.IO
  10. import splitties.init.appCtx
  11. import java.io.IOException
  12. /**
  13. * web端书源调试
  14. */
  15. class BookSourceDebugWebSocket(handshakeRequest: NanoHTTPD.IHTTPSession) :
  16. NanoWSD.WebSocket(handshakeRequest),
  17. CoroutineScope by MainScope(),
  18. Debug.Callback {
  19. private val notPrintState = arrayOf(10, 20, 30, 40)
  20. override fun onOpen() {
  21. launch(IO) {
  22. kotlin.runCatching {
  23. while (isOpen) {
  24. ping("ping".toByteArray())
  25. delay(30000)
  26. }
  27. }
  28. }
  29. }
  30. override fun onClose(
  31. code: NanoWSD.WebSocketFrame.CloseCode,
  32. reason: String,
  33. initiatedByRemote: Boolean
  34. ) {
  35. cancel()
  36. Debug.cancelDebug(true)
  37. }
  38. override fun onMessage(message: NanoWSD.WebSocketFrame) {
  39. launch(IO) {
  40. kotlin.runCatching {
  41. if (!message.textPayload.isJson()) {
  42. send("数据必须为Json格式")
  43. close(NanoWSD.WebSocketFrame.CloseCode.NormalClosure, "调试结束", false)
  44. return@launch
  45. }
  46. val debugBean =
  47. GSON.fromJsonObject<Map<String, String>>(message.textPayload).getOrNull()
  48. if (debugBean != null) {
  49. val tag = debugBean["tag"]
  50. val key = debugBean["key"]
  51. if (tag.isNullOrBlank() || key.isNullOrBlank()) {
  52. send(appCtx.getString(R.string.cannot_empty))
  53. close(NanoWSD.WebSocketFrame.CloseCode.NormalClosure, "调试结束", false)
  54. return@launch
  55. }
  56. appDb.bookSourceDao.getBookSource(tag)?.let {
  57. Debug.callback = this@BookSourceDebugWebSocket
  58. Debug.startDebug(this, it, key)
  59. }
  60. } else {
  61. send("数据必须为Json格式")
  62. close(NanoWSD.WebSocketFrame.CloseCode.NormalClosure, "调试结束", false)
  63. return@launch
  64. }
  65. }
  66. }
  67. }
  68. override fun onPong(pong: NanoWSD.WebSocketFrame) {
  69. }
  70. override fun onException(exception: IOException) {
  71. Debug.cancelDebug(true)
  72. }
  73. override fun printLog(state: Int, msg: String) {
  74. if (state in notPrintState) {
  75. return
  76. }
  77. runOnIO {
  78. runCatching {
  79. send(msg)
  80. if (state == -1 || state == 1000) {
  81. Debug.cancelDebug(true)
  82. close(NanoWSD.WebSocketFrame.CloseCode.NormalClosure, "调试结束", false)
  83. }
  84. }.onFailure {
  85. it.printOnDebug()
  86. }
  87. }
  88. }
  89. }