Skip to content

Instantly share code, notes, and snippets.

@mazz
Created March 24, 2024 01:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mazz/7894cf994c47a08066a0c9a23c6c26a4 to your computer and use it in GitHub Desktop.
Save mazz/7894cf994c47a08066a0c9a23c6c26a4 to your computer and use it in GitHub Desktop.
def presign_upload(entry, socket) do
uploads = socket.assigns.uploads
bucket = FaithfulWord.config([:s3, :bucket])
dbg(socket.assigns.upload_path_prefix)
## HACK to generate dir path on s3 by uploading an empty .gitkeep file
## this must be done before the upload occurs
# gitkeep_file = File.read!("gitkeep")
# ExAws.S3.put_object(
# "goshen-media-main",
# "#{socket.assigns.upload_path_prefix}/.gitkeep",
# gitkeep_file
# )
# |> ExAws.request!()
generate_recursive_s3_path(socket.assigns.upload_path_prefix)
key = "#{socket.assigns.upload_path_prefix}/#{URI.encode(entry.client_name)}"
dbg(key)
# key = "testdir/#{URI.encode(entry.client_name)}"
# dbg(key)
{:ok, presigned_url} = presigned_put(key: key)
# meta = %{uploader: "S3", key: key, url: presigned_url}
config = %{
region: "us-east-005",
# access_key_id: FaithfulWord.config([:s3, :access_key]),
# secret_access_key: FaithfulWord.config([:s3, :secret])
access_key_id: "keyid",
secret_access_key: "secret"
}
{:ok, fields} =
sign_form_upload(config, bucket,
key: key,
content_type: entry.client_type,
max_file_size: uploads[entry.upload_config].max_file_size,
expires_in: :timer.hours(1)
)
meta = %{
uploader: "ExternalUploader",
key: key,
url: presigned_url,
fields: fields
}
{:ok, meta, socket}
end
def presigned_put(opts) do
key = Keyword.fetch!(opts, :key)
# max_file_size = opts[:max_file_size] || 10_000_000
max_file_size = opts[:max_file_size] || 10_000_000_000
expires_in = opts[:expires_in] || 7200
dbg(key)
basename_slug = Slug.slugify(Path.basename(Path.rootname(key)))
dbg(basename_slug)
slugified_basename = Path.dirname(key) <> "/" <> basename_slug <> Path.extname(key)
dbg(slugified_basename)
dbg(key)
uri = "https://s3.us-east-005.backblazeb2.com/goshen-media-main/#{slugified_basename}"
dbg(uri)
url =
:aws_signature.sign_v4_query_params(
"keyid",
"secret",
"us-east-005",
"S3",
:calendar.universal_time(),
"PUT",
uri,
ttl: expires_in,
uri_encode_path: false,
body_digest: "UNSIGNED-PAYLOAD"
)
dbg(url)
{:ok, url}
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment