mastodon_client.rb 1.2 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
  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')
Yamagishi Kazutoshi's avatar
Yamagishi Kazutoshi committed
7
      client     = new(domain: domain)
8 9 10 11 12 13 14 15 16 17 18 19

      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?

Yamagishi Kazutoshi's avatar
Yamagishi Kazutoshi committed
20
    params = {
21 22 23
      grant_type: 'client_credentials',
      client_id: client_id,
      client_secret: client_secret,
Yamagishi Kazutoshi's avatar
Yamagishi Kazutoshi committed
24 25 26
    }

    res = http_client.post("https://#{domain}/oauth/token", params: params)
27 28 29 30 31 32 33 34 35 36 37 38

    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?

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

  private

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