media_proxy_controller.rb 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. # frozen_string_literal: true
  2. class MediaProxyController < ApplicationController
  3. include RoutingHelper
  4. include Authorization
  5. skip_before_action :store_current_location
  6. skip_before_action :require_functional!
  7. before_action :authenticate_user!, if: :whitelist_mode?
  8. rescue_from ActiveRecord::RecordInvalid, with: :not_found
  9. rescue_from Mastodon::UnexpectedResponseError, with: :not_found
  10. rescue_from Mastodon::NotPermittedError, with: :not_found
  11. rescue_from HTTP::TimeoutError, HTTP::ConnectionError, OpenSSL::SSL::SSLError, with: :internal_server_error
  12. def show
  13. RedisLock.acquire(lock_options) do |lock|
  14. if lock.acquired?
  15. @media_attachment = MediaAttachment.remote.attached.find(params[:id])
  16. authorize @media_attachment.status, :show?
  17. redownload! if @media_attachment.needs_redownload? && !reject_media?
  18. else
  19. raise Mastodon::RaceConditionError
  20. end
  21. end
  22. redirect_to full_asset_url(@media_attachment.file.url(version))
  23. end
  24. private
  25. def redownload!
  26. @media_attachment.download_file!
  27. @media_attachment.created_at = Time.now.utc
  28. @media_attachment.save!
  29. end
  30. def version
  31. if request.path.end_with?('/small')
  32. :small
  33. else
  34. :original
  35. end
  36. end
  37. def lock_options
  38. { redis: Redis.current, key: "media_download:#{params[:id]}", autorelease: 15.minutes.seconds }
  39. end
  40. def reject_media?
  41. DomainBlock.reject_media?(@media_attachment.account.domain)
  42. end
  43. end