2024-05-06 07:47:53 +00:00
|
|
|
# frozen_string_literal: true
|
|
|
|
|
|
|
|
module StorageManager
|
|
|
|
class S3
|
|
|
|
attr_reader :base_url
|
|
|
|
|
|
|
|
def initialize(endpoint:, access_key_id:, secret_access_key:, bucket:, base_url:)
|
|
|
|
@s3 = Aws::S3::Resource.new(
|
|
|
|
region: "weur",
|
|
|
|
endpoint: endpoint,
|
|
|
|
credentials: Aws::Credentials.new(access_key_id, secret_access_key),
|
|
|
|
).bucket(bucket)
|
|
|
|
@base_url = base_url
|
|
|
|
end
|
|
|
|
|
|
|
|
def delete(path)
|
|
|
|
return unless exists?(path)
|
|
|
|
@s3.object(trim(path)).delete
|
|
|
|
end
|
|
|
|
|
|
|
|
def exists?(path)
|
|
|
|
@s3.object(trim(path)).exists?
|
|
|
|
end
|
|
|
|
|
2024-10-13 06:04:55 +00:00
|
|
|
def get(path, &block)
|
|
|
|
file = @s3.object(trim(path)).get.body
|
|
|
|
block&.call(file)
|
|
|
|
file
|
2024-05-06 07:47:53 +00:00
|
|
|
end
|
|
|
|
|
|
|
|
def put(path, io)
|
|
|
|
@s3.object(trim(path)).put(body: io, content_type: Marcel::MimeType.for(io))
|
|
|
|
end
|
|
|
|
|
|
|
|
def upload(path, body)
|
|
|
|
put(path, body)
|
|
|
|
"#{base_url}#{path}"
|
|
|
|
end
|
|
|
|
|
|
|
|
def url_for(entry)
|
|
|
|
"#{base_url}#{entry.path}"
|
|
|
|
end
|
|
|
|
|
|
|
|
def trim(path)
|
|
|
|
# R2 for some reason doesn't trim preceding slashes
|
|
|
|
path.sub(%r{^/}, "")
|
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|