mastodon_client.rb 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. # frozen_string_literal: true
  2. class MastodonClient < ApplicationRecord
  3. class << self
  4. def obtain!(domain, callback_url)
  5. new_client = Mastodon::REST::Client.new(base_url: "https://#{domain}").create_app('Mastodon Bridge', callback_url, 'read follow')
  6. client = self.new(domain: domain)
  7. client.client_id = new_client.client_id
  8. client.client_secret = new_client.client_secret
  9. client.save!
  10. client
  11. end
  12. end
  13. def client_token
  14. return attributes['client_token'] if attributes['client_token'].present?
  15. res = http_client.post("https://#{domain}/oauth/token", params: {
  16. grant_type: 'client_credentials',
  17. client_id: client_id,
  18. client_secret: client_secret,
  19. })
  20. info = Oj.load(res.to_s, mode: :null)
  21. return if info.nil?
  22. update!(client_token: info['access_token'])
  23. info['access_token']
  24. end
  25. def still_valid?
  26. return false if client_token.blank?
  27. res = http_client.get("https://#{domain}/api/v1/apps/verify_credentials", headers: { 'Authorization': "Bearer #{client_token}" })
  28. res.code == 200
  29. end
  30. private
  31. def http_client
  32. HTTP.timeout(:per_operation, connect: 2, read: 5, write: 5)
  33. end
  34. end