2017-07-03 17:54:57 -04:00
|
|
|
require "google/cloud/storage"
|
2017-07-05 11:24:32 -04:00
|
|
|
require "active_support/core_ext/object/to_query"
|
2017-07-03 17:54:57 -04:00
|
|
|
|
2017-07-06 05:33:29 -04:00
|
|
|
class ActiveStorage::Site::GCSSite < ActiveStorage::Site
|
2017-07-03 17:54:57 -04:00
|
|
|
attr_reader :client, :bucket
|
|
|
|
|
|
|
|
def initialize(project:, keyfile:, bucket:)
|
|
|
|
@client = Google::Cloud::Storage.new(project: project, keyfile: keyfile)
|
|
|
|
@bucket = @client.bucket(bucket)
|
|
|
|
end
|
|
|
|
|
2017-07-04 10:05:06 -04:00
|
|
|
def upload(key, io)
|
|
|
|
bucket.create_file(io, key)
|
2017-07-03 17:54:57 -04:00
|
|
|
end
|
|
|
|
|
|
|
|
def download(key)
|
|
|
|
io = file_for(key).download
|
|
|
|
io.rewind
|
|
|
|
io.read
|
|
|
|
end
|
|
|
|
|
|
|
|
def delete(key)
|
|
|
|
file_for(key).try(:delete)
|
|
|
|
end
|
|
|
|
|
|
|
|
def exist?(key)
|
|
|
|
file_for(key).present?
|
|
|
|
end
|
|
|
|
|
|
|
|
|
2017-07-04 14:01:03 -04:00
|
|
|
def url(key, expires_in:, disposition:, filename:)
|
|
|
|
file_for(key).signed_url(expires: expires_in) + "&" +
|
|
|
|
{ "response-content-disposition" => "#{disposition}; filename=\"#{filename}\"" }.to_query
|
|
|
|
end
|
|
|
|
|
2017-07-03 17:54:57 -04:00
|
|
|
def byte_size(key)
|
|
|
|
file_for(key).size
|
|
|
|
end
|
|
|
|
|
|
|
|
def checksum(key)
|
2017-07-04 08:54:38 -04:00
|
|
|
convert_to_hex base64: file_for(key).md5
|
2017-07-03 17:54:57 -04:00
|
|
|
end
|
|
|
|
|
|
|
|
|
|
|
|
private
|
|
|
|
def file_for(key)
|
|
|
|
bucket.file(key)
|
|
|
|
end
|
2017-07-04 08:54:38 -04:00
|
|
|
|
|
|
|
def convert_to_hex(base64:)
|
|
|
|
base64.unpack("m0").first.unpack("H*").first
|
|
|
|
end
|
2017-07-03 17:54:57 -04:00
|
|
|
end
|