media_proxy_controller.rb 1.3 KB

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