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.

74 lines
2.3 KiB

  1. class ApiController < ApplicationController
  2. protect_from_forgery with: :null_session
  3. skip_before_action :verify_authenticity_token
  4. before_action :set_rate_limit_headers
  5. before_action :set_cors_headers
  6. rescue_from ActiveRecord::RecordInvalid do |e|
  7. render json: { error: e.to_s }, status: 422
  8. end
  9. rescue_from ActiveRecord::RecordNotFound do
  10. render json: { error: 'Record not found' }, status: 404
  11. end
  12. rescue_from Goldfinger::Error do
  13. render json: { error: 'Remote account could not be resolved' }, status: 422
  14. end
  15. rescue_from HTTP::Error do
  16. render json: { error: 'Remote data could not be fetched' }, status: 503
  17. end
  18. rescue_from OpenSSL::SSL::SSLError do
  19. render json: { error: 'Remote SSL certificate could not be verified' }, status: 503
  20. end
  21. def doorkeeper_unauthorized_render_options(*)
  22. { json: { error: 'Not authorized' } }
  23. end
  24. def doorkeeper_forbidden_render_options(*)
  25. { json: { error: 'This action is outside the authorized scopes' } }
  26. end
  27. protected
  28. def set_rate_limit_headers
  29. return if request.env['rack.attack.throttle_data'].nil?
  30. now = Time.now.utc
  31. match_data = request.env['rack.attack.throttle_data']['api']
  32. response.headers['X-RateLimit-Limit'] = match_data[:limit].to_s
  33. response.headers['X-RateLimit-Remaining'] = (match_data[:limit] - match_data[:count]).to_s
  34. response.headers['X-RateLimit-Reset'] = (now + (match_data[:period] - now.to_i % match_data[:period])).to_s
  35. end
  36. def set_cors_headers
  37. response.headers['Access-Control-Allow-Origin'] = '*'
  38. response.headers['Access-Control-Allow-Methods'] = 'POST, PUT, DELETE, GET, OPTIONS'
  39. response.headers['Access-Control-Request-Method'] = '*'
  40. response.headers['Access-Control-Allow-Headers'] = 'Origin, X-Requested-With, Content-Type, Accept, Authorization'
  41. end
  42. def current_resource_owner
  43. User.find(doorkeeper_token.resource_owner_id) if doorkeeper_token
  44. end
  45. def current_user
  46. super || current_resource_owner
  47. end
  48. def render_empty
  49. render json: {}, status: 200
  50. end
  51. def set_maps(statuses)
  52. status_ids = statuses.flat_map { |s| [s.id, s.reblog_of_id] }.compact.uniq
  53. @reblogs_map = Status.reblogs_map(status_ids, current_user.account)
  54. @favourites_map = Status.favourites_map(status_ids, current_user.account)
  55. end
  56. end