about summary refs log tree commit diff
path: root/app/controllers/media_proxy_controller.rb
blob: d8da6ec22e89cc03f8ede183824a98280820ba05 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# frozen_string_literal: true

class MediaProxyController < ApplicationController
  include RoutingHelper

  skip_before_action :store_current_location
  skip_before_action :require_functional!

  before_action :authenticate_user!, if: :whitelist_mode?

  def show
    RedisLock.acquire(lock_options) do |lock|
      if lock.acquired?
        @media_attachment = MediaAttachment.remote.find(params[:id])
        redownload! if !@media_attachment.blocked? && @media_attachment.needs_redownload?
      else
        raise Mastodon::RaceConditionError
      end
    end

    redirect_to full_asset_url(@media_attachment.file.url(version))
  end

  private

  def redownload!
    @media_attachment.file_remote_url = @media_attachment.remote_url
    @media_attachment.created_at      = Time.now.utc
    @media_attachment.save!
  end

  def version
    if request.path.ends_with?('/small')
      :small
    else
      :original
    end
  end

  def lock_options
    { redis: Redis.current, key: "media_download:#{params[:id]}" }
  end
end