summaryrefslogtreecommitdiff
path: root/app/controllers/downloads_controller.rb
blob: 14e3b0456b8a026081d7428cf0bf7e2a4806fd9a (plain)
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
require 'aws-sdk-core/s3'
require 'fileutils'

class DownloadsController < ApplicationController
  before_action :set_download, only: [:show, :edit, :update, :destroy]

  # GET /downloads
  # GET /downloads.json
  def index
    @downloads = Download.all
  end

  # GET /downloads/:filename
  def show
    not_found if @download.nil?

    s3client = Aws::S3::Client.new()
    s3obj = Aws::S3::Object.new(ENV['S3_DOWNLOADS_BUCKET'], @download.filename, client: s3client)
    resp = s3obj.get

    FileUtils.mkdir_p(Rails.root.join('tmp', 'downloads'))

    cached_filename = Rails.root.join('tmp', 'downloads', @download.filename)

    File.open(cached_filename, 'wb') do |file|
      file.write resp.body.read
    end

    send_file cached_filename
  end

  private
    # Use callbacks to share common setup or constraints between actions.
    def set_download
      @download = Download.find_by(filename: params[:id])
    end
end