Cache transformations
This commit is contained in:
@@ -5,8 +5,12 @@ defmodule MusicLibrary.Application do
|
||||
|
||||
use Application
|
||||
|
||||
alias MusicLibrary.Assets
|
||||
|
||||
@impl true
|
||||
def start(_type, _args) do
|
||||
_ = Assets.Cache.new()
|
||||
|
||||
children = [
|
||||
MusicLibraryWeb.Telemetry,
|
||||
MusicLibrary.Vault,
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
defmodule MusicLibrary.Assets.Cache do
|
||||
def new do
|
||||
:ets.new(__MODULE__, [:named_table, :public, read_concurrency: true])
|
||||
end
|
||||
|
||||
def set(payload, format, content) do
|
||||
:ets.insert(__MODULE__, {{payload, format}, content})
|
||||
end
|
||||
|
||||
def get(payload, format) do
|
||||
case :ets.lookup(__MODULE__, {payload, format}) do
|
||||
[{{^payload, ^format}, content}] -> {:found, content}
|
||||
[] -> :not_found
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -6,18 +6,25 @@ defmodule MusicLibrary.Records.Cover do
|
||||
|
||||
@external_resource fallback_path
|
||||
|
||||
@size 2000
|
||||
@default_size 2000
|
||||
@default_format "image/jpeg"
|
||||
|
||||
def fallback_data, do: unquote(fallback_data)
|
||||
|
||||
def resize(cover_data, size \\ @size) do
|
||||
def resize(cover_data, size \\ @default_size, format \\ @default_format) do
|
||||
{:ok, thumb} = Operation.thumbnail_buffer(cover_data, size)
|
||||
Image.write_to_buffer(thumb, ".jpg")
|
||||
Image.write_to_buffer(thumb, extension(format))
|
||||
end
|
||||
|
||||
def correct_size?(cover_data) do
|
||||
{:ok, image} = Image.new_from_buffer(cover_data)
|
||||
|
||||
Image.width(image) == @size
|
||||
def convert(cover_data, data_format, target_format) do
|
||||
if data_format == target_format do
|
||||
{:ok, cover_data}
|
||||
else
|
||||
{:ok, image} = Image.new_from_buffer(cover_data)
|
||||
Image.write_to_buffer(image, extension(target_format))
|
||||
end
|
||||
end
|
||||
|
||||
defp extension("image/jpeg"), do: ".jpg"
|
||||
defp extension("image/webp"), do: ".webp"
|
||||
end
|
||||
|
||||
Reference in New Issue
Block a user