fp/apps/bright/lib/bright/uploads.ex
CJ_Clippy aa75c224fc
Some checks failed
ci / build (push) Failing after 23m29s
ci / Tests & Checks (push) Failing after 3m32s
move services/bright to apps/bright
2025-02-10 08:16:50 -08:00

76 lines
2.6 KiB
Elixir

defmodule Bright.Uploads do
@moduledoc """
Provides functions to download a file from a URL and upload a file to S3.
"""
require Logger
alias ExAws.S3
@doc """
Downloads a file from the given URL and saves it to the specified local path.
## Parameters
- `url` (string): The URL of the file to download.
- `destination_path` (string): The local path where the file will be saved.
## Examples
iex> Bright.Uploads.download_file("https://example.com/file.txt", "./file.txt")
:ok
"""
def download_file(url, destination_path) do
case HTTPoison.get(url) do
{:ok, %HTTPoison.Response{status_code: 200, body: body}} ->
# Logger.debug "WE GOT A GOOD RESPONSE SO LETS WRITE"
case File.write(destination_path, body) do
:ok -> {:ok, "File downloaded successfully"}
{:error, reason} -> {:error, reason}
end
{:ok, %HTTPoison.Response{status_code: status_code}} ->
{:error, "Failed to download file. Status code: #{status_code}"}
{:error, %HTTPoison.Error{reason: reason}} ->
{:error, reason}
end
end
@doc """
Uploads a file to an S3 bucket.
## Parameters
- `file_path` (string): The local path of the file to upload.
- `bucket` (string): The name of the S3 bucket.
- `key` (string): The key under which the file will be stored in S3.
## Examples
iex> Bright.Uploads.upload_file_to_s3("./file.txt", "my-bucket", "uploads/file.txt")
:ok
"""
def upload_file_to_s3(file_path, bucket, key) do
# Logger.debug "upload_file_to_s3 with \nfile_path=#{file_path} \naws_ex region=#{Application.get_env(:bright, :aws_region)} \nbucket=#{bucket} \nkey=#{key} \naws_access_key_id=#{Application.get_env(:bright, :aws_access_key_id)} aws_secret_access_key=#{Application.get_env(:bright, :aws_secret_access_key)}"
# Logger.debug "#{inspect(Application.get_all_env(:ex_aws))}"
# Throw if any S3 env vars are missing
# Application.get_env(:bright, :aws_bucket) || raise("aws_bucket is missing.")
# Application.get_env(:bright, :aws_host) || raise("aws_host is missing.")
# Application.get_env(:bright, :aws_access_key_id) || raise("aws_access_key_id is missing.")
# Application.get_env(:bright, :aws_secret_access_key) || raise("aws_secret_access_key is missing.")
# Application.get_env(:bright, :aws_region) || raise("aws_region is missing.")
case File.read(file_path) do
{:ok, file_content} ->
S3.put_object(bucket, key, file_content)
|> ExAws.request()
{:error, reason} ->
{:error, reason}
end
end
end