88 lines
1.8 KiB
Elixir

defmodule Bright.B2 do
@moduledoc """
The B2 context.
"""
import Ecto.Query, warn: false
require Logger
alias ExAws.S3
alias Bright.Repo
alias Bright.Cache
alias Bright.B2
@doc """
Put a file from local disk to Backblaze. This function uses the filename as the S3 key. Use put/2 if you want to specify the key
"""
def put(local_file) do
object_key = Path.basename(local_file)
put(local_file, object_key)
end
@doc """
Put a file from local disk to Backblaze.
"""
def put(local_file, object_key) do
bucket = Application.get_env(:bright, :aws_bucket)
if bucket === nil do
raise("bucket specification is missing")
end
s3_cdn_endpoint = Application.get_env(:bright, :s3_cdn_endpoint)
if s3_cdn_endpoint === nil do
raise("s3_cdn_endpoint specification is missing")
end
cdn_url = "#{s3_cdn_endpoint}/#{object_key}"
local_file
|> S3.Upload.stream_file
|> S3.upload(bucket, object_key)
|> ExAws.request
|> case do
{:ok, %{status_code: 200}} -> {:ok, %{key: object_key, cdn_url: cdn_url}}
{:error, reason} -> {:error, reason}
end
end
@doc """
Download a file from Backblaze to local disk
"""
def get(object_key, local_file) do
# B2.get("test/SampleVideo_1280x720_1mb.mp4", local_file)
bucket = Application.get_env(:bright, :aws_bucket)
S3.download_file(bucket, object_key, local_file)
|> ExAws.request
|> case do
{:ok, :done} -> {:ok, local_file}
{:error, reason} -> {:error, reason}
end
end
@doc """
Given a S3 object_key, generate an appropriate CDN url.
"""
def generate_cdn_url(object_key) do
cdn_url = Application.get_env(:bright, :public_s3_endpoint) || raise(":public_s3_endpoint missing from App env")
"#{cdn_url}/#{object_key}"
end
end