You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

90 lines
2.5 KiB

  1. class ApiController < ApplicationController
  2. DEFAULT_STATUSES_LIMIT = 20
  3. DEFAULT_ACCOUNTS_LIMIT = 40
  4. protect_from_forgery with: :null_session
  5. skip_before_action :verify_authenticity_token
  6. before_action :set_rate_limit_headers
  7. rescue_from ActiveRecord::RecordInvalid do |e|
  8. render json: { error: e.to_s }, status: 422
  9. end
  10. rescue_from ActiveRecord::RecordNotFound do
  11. render json: { error: 'Record not found' }, status: 404
  12. end
  13. rescue_from Goldfinger::Error do
  14. render json: { error: 'Remote account could not be resolved' }, status: 422
  15. end
  16. rescue_from HTTP::Error do
  17. render json: { error: 'Remote data could not be fetched' }, status: 503
  18. end
  19. rescue_from OpenSSL::SSL::SSLError do
  20. render json: { error: 'Remote SSL certificate could not be verified' }, status: 503
  21. end
  22. def doorkeeper_unauthorized_render_options(*)
  23. { json: { error: 'Not authorized' } }
  24. end
  25. def doorkeeper_forbidden_render_options(*)
  26. { json: { error: 'This action is outside the authorized scopes' } }
  27. end
  28. protected
  29. def set_rate_limit_headers
  30. return if request.env['rack.attack.throttle_data'].nil?
  31. now = Time.now.utc
  32. match_data = request.env['rack.attack.throttle_data']['api']
  33. response.headers['X-RateLimit-Limit'] = match_data[:limit].to_s
  34. response.headers['X-RateLimit-Remaining'] = (match_data[:limit] - match_data[:count]).to_s
  35. response.headers['X-RateLimit-Reset'] = (now + (match_data[:period] - now.to_i % match_data[:period])).to_s
  36. end
  37. def set_pagination_headers(next_path = nil, prev_path = nil)
  38. links = []
  39. links << [next_path, [['rel', 'next']]] if next_path
  40. links << [prev_path, [['rel', 'prev']]] if prev_path
  41. response.headers['Link'] = LinkHeader.new(links)
  42. end
  43. def current_resource_owner
  44. User.find(doorkeeper_token.resource_owner_id) if doorkeeper_token
  45. end
  46. def current_user
  47. super || current_resource_owner
  48. rescue ActiveRecord::RecordNotFound
  49. nil
  50. end
  51. def require_user!
  52. current_resource_owner
  53. rescue ActiveRecord::RecordNotFound
  54. render json: { error: 'This method requires an authenticated user' }, status: 422
  55. end
  56. def render_empty
  57. render json: {}, status: 200
  58. end
  59. def set_maps(statuses)
  60. if current_account.nil?
  61. @reblogs_map = {}
  62. @favourites_map = {}
  63. return
  64. end
  65. status_ids = statuses.flat_map { |s| [s.id, s.reblog_of_id] }.compact.uniq
  66. @reblogs_map = Status.reblogs_map(status_ids, current_account)
  67. @favourites_map = Status.favourites_map(status_ids, current_account)
  68. end
  69. end