Class: Chatrix::Matrix

Inherits:
Object
  • Object
show all
Includes:
HTTParty
Defined in:
lib/chatrix/matrix.rb

Overview

Note:

Any of the methods may raise the errors listed in #parse_response. Consider this when calling the methods.

Note:

Endpoints that require a room ID in the official API can be passed a room alias in this implementation, the room ID will be automatically looked up from the homeserver.

Provides an interface to the Matrix API on a homeserver.

Detailed information about the data structures is not included here and can be found on the Matrix API page.

Constant Summary collapse

METHODS =

Maps HTTP methods to their respective HTTParty method.

{
  get: -> (path, options, &block) { get path, options, &block },
  put: -> (path, options, &block) { put path, options, &block },
  post: -> (path, options, &block) { post path, options, &block },
  delete: -> (path, options, &block) { delete path, options, &block }
}.freeze
ERROR_HANDLERS =

Registered request error handlers.

{
  400 => [RequestError, 'Request failed'],
  401 => [AuthenticationError, 'Server requests additional authentication'],
  403 => [ForbiddenError, 'You do not have access to that resource'],
  404 => [NotFoundError, 'The resource was not found'],
  429 => [RateLimitError, 'The request was rate limited']
}.tap do |h|
  h.default = [ApiError, 'An unknown API error occurred.']
end.freeze
DEFAULT_HOMESERVER =

Default homeserver used if none is specified.

'https://matrix.org'.freeze
API_PATH =

API path used.

'/_matrix/client/r0'.freeze

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(token = nil, homeserver = DEFAULT_HOMESERVER) ⇒ Matrix

Initializes a new instance of Matrix.

Parameters:

  • token (String) (defaults to: nil)

    The access token to use.

  • homeserver (String) (defaults to: DEFAULT_HOMESERVER)

    The homeserver to make requests to.



89
90
91
92
93
94
95
96
97
98
99
# File 'lib/chatrix/matrix.rb', line 89

def initialize(token = nil, homeserver = DEFAULT_HOMESERVER)
  @homeserver = homeserver
  @base_uri = @homeserver + API_PATH
  @access_token = token

  @session = Api::Session.new self
  @users = Api::Users.new self
  @rooms = Api::Rooms.new self
  @media = Api::Media.new self
  @push = Api::Push.new self
end

Instance Attribute Details

#access_tokenString

Returns the access token used when performing requests to the homeserver.

Returns:

  • (String)

    the access token used when performing requests to the homeserver.



60
61
62
# File 'lib/chatrix/matrix.rb', line 60

def access_token
  @access_token
end

#homeserverString (readonly)

Returns the homeserver for this API object.

Returns:

  • (String)

    the homeserver for this API object.



63
64
65
# File 'lib/chatrix/matrix.rb', line 63

def homeserver
  @homeserver
end

#mediaApi::Media (readonly)

Returns the instance of Api::Media to perform media-related API calls with.

Returns:

  • (Api::Media)

    the instance of Api::Media to perform media-related API calls with.



79
80
81
# File 'lib/chatrix/matrix.rb', line 79

def media
  @media
end

#pushApi::Push (readonly)

Returns the instance of Api::Push to perform push-related API calls with.

Returns:

  • (Api::Push)

    the instance of Api::Push to perform push-related API calls with.



83
84
85
# File 'lib/chatrix/matrix.rb', line 83

def push
  @push
end

#roomsApi::Rooms (readonly)

Returns the instance of Api::Rooms to perform room-related API calls with.

Returns:

  • (Api::Rooms)

    the instance of Api::Rooms to perform room-related API calls with.



75
76
77
# File 'lib/chatrix/matrix.rb', line 75

def rooms
  @rooms
end

#sessionApi::Session (readonly)

Returns the instance of Api::Session to perform session-related API calls with.

Returns:

  • (Api::Session)

    the instance of Api::Session to perform session-related API calls with.



67
68
69
# File 'lib/chatrix/matrix.rb', line 67

def session
  @session
end

#usersApi::Users (readonly)

Returns the instance of Api::Users to perform user-related API calls with.

Returns:

  • (Api::Users)

    the instance of Api::Users to perform user-related API calls with.



71
72
73
# File 'lib/chatrix/matrix.rb', line 71

def users
  @users
end

Instance Method Details

#create_filter(user, filter) ⇒ String

Uploads a filter to the server.

Parameters:

  • user (String)

    The user to upload the filter as.

  • filter (Hash)

    The filter definition.

Returns:

  • (String)

    The ID of the created filter.



158
159
160
# File 'lib/chatrix/matrix.rb', line 158

def create_filter(user, filter)
  make_request(:post, "/user/#{user}/filter", content: filter)['filter_id']
end

#get_filter(user, filter) ⇒ Hash

Gets the definition for a filter.

Parameters:

  • user (String)

    The user that has the filter.

  • filter (String)

    The ID of the filter to get.

Returns:

  • (Hash)

    The filter definition.



150
151
152
# File 'lib/chatrix/matrix.rb', line 150

def get_filter(user, filter)
  make_request(:get, "/user/#{user}/filter/#{filter}").parsed_response
end

#make_body(content) ⇒ Hash{Symbol => Object} (private)

Create a hash with body content based on the type of content.

Parameters:

  • content (Hash, #read, Object)

    Some kind of content to put into the request body. Can be a Hash, stream object, or other kind of object.

Returns:

  • (Hash{Symbol => Object})

    A hash with the relevant body key and value.



234
235
236
237
238
# File 'lib/chatrix/matrix.rb', line 234

def make_body(content)
  key = content.respond_to?(:read) ? :body_stream : :body
  value = content.is_a?(Hash) ? content.to_json : content
  { key => value }
end

#make_options(params, content, headers = {}) ⇒ Hash (private)

Create an options Hash to pass to a server request.

This method embeds the access_token into the query parameters.

Parameters:

  • params (Hash{String=>String}, nil)

    Query parameters to add to the options hash.

  • content (Hash, #read, nil)

    Request content. Can be a hash, stream, or nil.

Returns:

  • (Hash)

    Options hash ready to be passed into a server request.



220
221
222
223
224
225
226
# File 'lib/chatrix/matrix.rb', line 220

def make_options(params, content, headers = {})
  { headers: headers }.tap do |o|
    o[:query] = @access_token ? { access_token: @access_token } : {}
    o[:query].merge!(params) if params.is_a? Hash
    o.merge! make_body content
  end
end

#make_request(method, path, opts = {}) {|fragment| ... } ⇒ HTTParty::Response

Helper method for performing requests to the homeserver.

Parameters:

  • method (Symbol)

    HTTP request method to use. Use only symbols available as keys in METHODS.

  • path (String)

    The API path to query, relative to the base API path, eg. /login.

  • opts (Hash) (defaults to: {})

    Additional request options.

Options Hash (opts):

  • :params (Hash)

    Additional parameters to include in the query string (part of the URL, not put in the request body).

  • :content (Hash, #read)

    Content to put in the request body. If set, must be a Hash or a stream object.

  • :headers (Hash{String => String})

    Additional headers to include in the request.

  • :base (String, nil)

    If this is set, it will be used as the base URI for the request instead of the default (@base_uri).

Yields:

  • (fragment)

    HTTParty will call the block during the request.

Returns:

  • (HTTParty::Response)

    The HTTParty response object.



201
202
203
204
205
206
# File 'lib/chatrix/matrix.rb', line 201

def make_request(method, path, opts = {}, &block)
  path = (opts[:base] || @base_uri) + URI.encode(path)
  options = make_options opts[:params], opts[:content], opts[:headers]

  parse_response METHODS[method].call(path, options, &block)
end

#parse_filter(filter) ⇒ String (private)

Parses a filter object for use in a query string.

Parameters:

  • filter (String, Hash)

    The filter object to parse.

Returns:

  • (String)

    Query-friendly filter object. Or the filter parameter as-is if it failed to parse.



272
273
274
# File 'lib/chatrix/matrix.rb', line 272

def parse_filter(filter)
  filter.is_a?(Hash) ? URI.encode(filter.to_json) : filter
end

#parse_response(response) ⇒ HTTParty::Response (private)

Parses a HTTParty Response object and returns it if it was successful.

Parameters:

  • response (HTTParty::Response)

    The response object to parse.

Returns:

  • (HTTParty::Response)

    The same response object that was passed in, if the request was successful.

Raises:

  • (RequestError)

    If a 400 response code was returned from the request.

  • (AuthenticationError)

    If a 401 response code was returned from the request.

  • (ForbiddenError)

    If a 403 response code was returned from the request.

  • (NotFoundError)

    If a 404 response code was returned from the request.

  • (RateLimitError)

    If a 429 response code was returned from the request.

  • (ApiError)

    If an unknown response code was returned from the request.



258
259
260
261
262
263
264
265
266
# File 'lib/chatrix/matrix.rb', line 258

def parse_response(response)
  case response.code
  when 200 # OK
    response
  else
    handler = ERROR_HANDLERS[response.code]
    raise handler.first.new(response.parsed_response), handler.last
  end
end

#search(from: nil, options: {}) ⇒ Hash

Performs a full text search on the server.

Parameters:

  • from (String) (defaults to: nil)

    Where to return events from, if given. This can be obtained from previous calls to #search.

  • options (Hash) (defaults to: {})

    Search options, see the official documentation for details on how to structure this.

Returns:

  • (Hash)

    the search results.



168
169
170
171
172
# File 'lib/chatrix/matrix.rb', line 168

def search(from: nil, options: {})
  make_request(
    :post, '/search', params: { next_batch: from }, content: options
  ).parsed_response
end

#sync(filter: nil, since: nil, full_state: false, set_presence: true, timeout: 30_000) ⇒ Hash

Synchronize with the latest state on the server.

For initial sync, call this method with the since parameter set to nil.

Parameters:

  • filter (String, Hash) (defaults to: nil)

    The ID of a filter to use, or provided directly as a hash.

  • since (String, nil) (defaults to: nil)

    A point in time to continue sync from. Will retrieve a snapshot of the state if not set, which will also provide a next_batch value to use for since in the next call.

  • full_state (Boolean) (defaults to: false)

    If true, all state events will be returned for all rooms the user is a member of.

  • set_presence (Boolean) (defaults to: true)

    If true, the user performing this request will have their presence updated to show them as being online.

  • timeout (Fixnum) (defaults to: 30_000)

    Maximum time (in milliseconds) to wait before the request is aborted.

Returns:

  • (Hash)

    The initial snapshot of the state (if no since value was provided), or a delta to use for updating state.



134
135
136
137
138
139
140
141
142
143
144
# File 'lib/chatrix/matrix.rb', line 134

def sync(filter: nil, since: nil, full_state: false,
         set_presence: true, timeout: 30_000)
  options = { full_state: full_state }

  options[:since] = since if since
  options[:set_presence] = 'offline' unless set_presence
  options[:timeout] = timeout if timeout
  options[:filter] = parse_filter filter

  make_request(:get, '/sync', params: options).parsed_response
end

#turn_serverHash

Gets information about the TURN server. Contains credentials and server URIs for connecting.

Returns:

  • (Hash)

    TURN server details.



177
178
179
# File 'lib/chatrix/matrix.rb', line 177

def turn_server
  make_request(:get, '/voip/turnServer').parsed_response
end

#versionsArray<String>

Gets supported API versions from the server.

Returns:

  • (Array<String>)

    an array with the supported versions.



103
104
105
106
107
# File 'lib/chatrix/matrix.rb', line 103

def versions
  make_request(
    :get, '/versions', base: "#{@homeserver}/_matrix/client"
  )['versions']
end

#whois(user) ⇒ Hash

Performs a whois lookup on the specified user.

Parameters:

  • user (String)

    The user to look up.

Returns:

  • (Hash)

    Information about the user.



112
113
114
# File 'lib/chatrix/matrix.rb', line 112

def whois(user)
  make_request(:get, "/admin/whois/#{user}").parsed_response
end