Class: Chatrix::Api::Media

Inherits:
ApiComponent show all
Defined in:
lib/chatrix/api/media.rb

Overview

Contains methods for accessing the media endpoints of a server.

Constant Summary collapse

MEDIA_PATH =

API path for media operations.

Because for some reason this one is different.

'/_matrix/media/r0'.freeze

Instance Method Summary collapse

Methods inherited from ApiComponent

#make_request

Constructor Details

#initialize(matrix) ⇒ Media

Initializes a new Media instance.

Parameters:

  • matrix (Matrix)

    The matrix API instance.



15
16
17
18
# File 'lib/chatrix/api/media.rb', line 15

def initialize(matrix)
  super
  @media_uri = @matrix.homeserver + MEDIA_PATH
end

Instance Method Details

#download(server, id) ⇒ HTTParty::Response

Download media from the server.

Parameters:

  • server (String)

    The server component of an mxc:// URL.

  • id (String)

    The media ID of the mxc:// URL (the path).

Returns:

  • (HTTParty::Response)

    The HTTParty response object for the request. Use the response object to inspect the returned data.



25
26
27
28
29
30
31
32
# File 'lib/chatrix/api/media.rb', line 25

def download(server, id)
  make_request(
    :get,
    "/download/#{server}/#{id}",
    headers: { 'Accept' => '*/*' },
    base: @media_uri
  )
end

#get_thumbnail(server, id, width, height, method = 'scale') ⇒ HTTParty::Response

Download the thumbnail for a media resource.

Parameters:

  • server (String)

    The server component of an mxc:// URL.

  • id (String)

    The media ID of the mxc:// URL (the path).

  • width (Fixnum)

    Desired width of the thumbnail.

  • height (Fixnum)

    Desired height of the thumbnail.

  • method ('scale', 'crop') (defaults to: 'scale')

    Desired resizing method.

Returns:

  • (HTTParty::Response)

    The HTTParty response object for the request. Use the response object to inspect the returned data.



42
43
44
45
46
47
48
49
50
# File 'lib/chatrix/api/media.rb', line 42

def get_thumbnail(server, id, width, height, method = 'scale')
  make_request(
    :get,
    "/thumbnail/#{server}/#{id}",
    headers: { 'Accept' => 'image/jpeg, image/png' },
    params: { width: width, height: height, method: method },
    base: @media_uri
  )
end

#upload(type, path) ⇒ String

Uploads a new media file to the server.

Parameters:

  • type (String)

    The Content-Type of the media being uploaded.

  • path (String)

    Path to a file to upload.

Returns:

  • (String)

    The MXC URL for the uploaded object (mxc://...).



56
57
58
59
60
61
62
63
64
65
66
67
# File 'lib/chatrix/api/media.rb', line 56

def upload(type, path)
  File.open(path, 'r') do |file|
    make_request(
      :post, '/upload',
      headers: {
        'Content-Type' => type, 'Content-Length' => file.size.to_s,
        'Transfer-Encoding' => 'chunked'
      },
      content: file, base: @media_uri
    )['content_uri']
  end
end