summaryrefslogtreecommitdiff
path: root/app/controllers/downloads_controller.rb
blob: d98ccc3cd28f62c5d7d9fb37b710fe975e02d5d7 (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
38
39
40
41
42
43
44
45
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?

    begin
      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

      @download.hits += 1
      @download.save

      send_file cached_filename

    rescue Aws::S3::Errors::NoSuchKey
      not_found
    end
  end

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