mastodon_client.rb 1.18 KB
Newer Older
Eugen Rochko's avatar
Eugen Rochko committed
1 2
# frozen_string_literal: true

Eugen Rochko's avatar
Eugen Rochko committed
3
class MastodonClient < ApplicationRecord
4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
  class << self
    def obtain!(domain, callback_url)
      new_client = Mastodon::REST::Client.new(base_url: "https://#{domain}").create_app('Mastodon Bridge', callback_url, 'read follow')
      client     = self.new(domain: domain)

      client.client_id     = new_client.client_id
      client.client_secret = new_client.client_secret

      client.save!
      client
    end
  end

  def client_token
    return attributes['client_token'] if attributes['client_token'].present?

20
    res = http_client.post("https://#{domain}/oauth/token", params: {
21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
      grant_type: 'client_credentials',
      client_id: client_id,
      client_secret: client_secret,
    })

    info = Oj.load(res.to_s, mode: :null)

    return if info.nil?

    update!(client_token: info['access_token'])
    info['access_token']
  end

  def still_valid?
    return false if client_token.blank?

37
    res = http_client.get("https://#{domain}/api/v1/apps/verify_credentials", headers: { 'Authorization': "Bearer #{client_token}" })
38 39
    res.code == 200
  end
40 41 42 43 44 45

  private

  def http_client
    HTTP.timeout(:per_operation, connect: 2, read: 5, write: 5)
  end
Eugen Rochko's avatar
Eugen Rochko committed
46
end