Simple bridge server for various bots of mine
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.

98 lines
2.0 KiB

2 years ago
  1. # Prototype of the heimdall server
  2. $LOAD_PATH << "."
  3. $VERSION = "0.1"
  4. $PORT = 9128
  5. require "proto"
  6. require "socket"
  7. PROTO_CODES = {
  8. :SUCCESS => 0,
  9. :BADJSON => 1,
  10. :NOMETHOD => 2,
  11. :INVPARAM => 3,
  12. :NOTIMPL => 4
  13. }
  14. PROTO_MESSAGES = {
  15. :SUCCESS => "Done",
  16. :BADJSON => "Invalid JSON object",
  17. :NOMETHOD => "Invalid method",
  18. :INVPARAM => "Invalid parameters",
  19. :NOTIMPL => "Not implemented"
  20. }
  21. class Server
  22. @channelPool
  23. @channelListeners
  24. @methods
  25. def initialize()
  26. @channelPool = {}
  27. @channelListeners = {}
  28. @methods = [
  29. "join",
  30. "useradd",
  31. "userdel",
  32. "userinfo",
  33. "lusers",
  34. "lchannels",
  35. "chantop",
  36. "chansend",
  37. "chanedit"
  38. ]
  39. end
  40. def send(client,message)
  41. client.puts JSON.dump(message)
  42. end
  43. def err(client,code)
  44. client.puts JSON.dump({
  45. :error=>PROTO_MESSAGES[code],
  46. :code=>PROTO_CODES[code]
  47. })
  48. client.close
  49. end
  50. def serve(client)
  51. # basic validation steps
  52. begin
  53. # 1. JSON validation
  54. data = client.gets
  55. data = JSON.load(data)
  56. rescue JSON::ParserError
  57. err(client,:BADJSON)
  58. end
  59. # 2. Method validation
  60. method = data[:method]
  61. err(client,:NOMETHOD) if not @methods.include?(method)
  62. # last but not least: calling the given method
  63. if not self.methods.include?(method) then
  64. err(client,:NOTIMPL)
  65. return
  66. end
  67. send(client,self.method(method).call(client,data))
  68. end
  69. def join(client,data)
  70. chaind = data["chanid"]
  71. chanid = rand(89999999)+10000000 if not chanid
  72. if not @channelPool[chanid] then
  73. @channelPool[chanid] = Heimdall::Channel.new
  74. @channelListeners
  75. end
  76. return {
  77. :code=>PROTO_CODE[:SUCCESS],
  78. :method=>"join",
  79. :chanid=>chanid,
  80. }
  81. end
  82. end
  83. puts "Starting heimdall v#{$VERSION} server on port #{$PORT}..."
  84. server = TCPServer.new 9128
  85. loop do
  86. Thread.start(server.accept) do |client|
  87. puts "Received client connection on #{client.addr}"
  88. end
  89. end