Class: Async::Matrix::ApplicationService::Server

Inherits:
Object
  • Object
show all
Defined in:
lib/async/matrix/application_service/server.rb

Overview

Rack 3 application implementing the Matrix Application Service API.

Routes:

PUT  /_matrix/app/v1/transactions/{txnId}  — receive events from homeserver
GET  /_matrix/app/v1/users/{userId}         — user existence query
GET  /_matrix/app/v1/rooms/{roomAlias}       — room alias query
POST /_matrix/app/v1/ping                    — healthcheck

Constant Summary collapse

CONTENT_JSON =
{"content-type" => "application/json"}.freeze
EMPTY_BODY =
["{}"].freeze
RESP_NOT_FOUND =
[404, CONTENT_JSON, ['{"errcode":"M_UNRECOGNIZED"}']].freeze
RESP_FORBIDDEN =
[403, CONTENT_JSON, ['{"errcode":"M_FORBIDDEN"}']].freeze
RESP_BAD_JSON =
[400, CONTENT_JSON, ['{"errcode":"M_BAD_JSON"}']].freeze
RESP_BAD_METHOD =
[405, CONTENT_JSON, ['{"errcode":"M_UNRECOGNIZED"}']].freeze

Instance Method Summary collapse

Constructor Details

#initialize(hs_token:, dispatcher: Dispatcher.new) ⇒ Server

Returns a new instance of Server.



31
32
33
34
35
# File 'lib/async/matrix/application_service/server.rb', line 31

def initialize(hs_token:, dispatcher: Dispatcher.new)
  @hs_token   = hs_token
  @dispatcher = dispatcher
  @txn_store  = TransactionStore.new
end

Instance Method Details

#call(env) ⇒ Object



51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
# File 'lib/async/matrix/application_service/server.rb', line 51

def call(env)
  request = Rack::Request.new(env)
  method  = request.request_method
  path    = request.path_info

  case path
  when %r{\A/_matrix/app/v1/transactions/(.+)\z}
    return RESP_BAD_METHOD unless method == "PUT"
    return RESP_FORBIDDEN  unless authorized?(request)
    handle_transaction(request, Regexp.last_match(1))

  when %r{\A/_matrix/app/v1/users/(.+)\z}
    return RESP_BAD_METHOD unless method == "GET"
    return RESP_FORBIDDEN  unless authorized?(request)
    [200, CONTENT_JSON, EMPTY_BODY]

  when %r{\A/_matrix/app/v1/rooms/(.+)\z}
    return RESP_BAD_METHOD unless method == "GET"
    return RESP_FORBIDDEN  unless authorized?(request)
    RESP_NOT_FOUND

  when "/_matrix/app/v1/ping"
    return RESP_BAD_METHOD unless method == "POST"
    [200, CONTENT_JSON, EMPTY_BODY]

  else
    RESP_NOT_FOUND
  end
end

#register(handler) ⇒ Object

Register a Bot or a plain handler on the internal dispatcher.

Accepts either:

- A Bot (responds to #handlers) — registers all its handlers
- A plain handler (responds to #event_types and #call)


43
44
45
46
47
48
49
# File 'lib/async/matrix/application_service/server.rb', line 43

def register(handler)
  if handler.respond_to?(:handlers)
    handler.handlers.each { |h| @dispatcher.register(h) }
  else
    @dispatcher.register(handler)
  end
end