Store image hashes in the db - part 1

This commit is contained in:
Claudio Ortolina
2024-09-30 20:09:32 +01:00
parent 9cd24bad17
commit 180224d381
5 changed files with 60 additions and 3 deletions
+17
View File
@@ -129,6 +129,23 @@ defmodule MusicLibrary.Records.Importer do
end)
end
def generate_all_cover_hashes do
Rec
|> Repo.all()
|> Enum.each(fn r ->
if r.image_data != nil do
generate_cover_image_hash(r)
IO.puts("Generated cover image hash for #{r.title}")
end
end)
end
def generate_cover_image_hash(record) do
record
|> Rec.generate_image_data_hash()
|> Repo.update!()
end
defp blob_get(url) do
req =
Finch.build(:get, url, [
+24 -1
View File
@@ -12,6 +12,7 @@ defmodule MusicLibrary.Records.Record do
field :title, :string
field :image_url, :string
field :image_data, :binary
field :image_data_hash, :string
field :year, :integer
field :musicbrainz_id, Ecto.UUID
field :genres, {:array, :string}
@@ -40,6 +41,7 @@ defmodule MusicLibrary.Records.Record do
:image_data
])
|> cast_embed(:artists, with: &artist_changeset/2)
|> generate_image_data_hash()
|> validate_required([:type, :title, :musicbrainz_id, :year, :genres])
end
@@ -57,7 +59,28 @@ defmodule MusicLibrary.Records.Record do
end
def add_image_data(record, image_data) do
change(record, image_data: image_data)
record
|> change(image_data: image_data)
|> generate_image_data_hash()
end
def generate_image_data_hash(record = %__MODULE__{image_data: image_data}) do
hash = :crypto.hash(:sha256, image_data) |> Base.encode16()
record
|> change()
|> put_change(:image_data_hash, hash)
end
def generate_image_data_hash(changeset) do
case get_change(changeset, :image_data) do
nil ->
changeset
image_data ->
hash = :crypto.hash(:sha256, image_data) |> Base.encode16()
put_change(changeset, :image_data_hash, hash)
end
end
def formats, do: @formats
@@ -25,7 +25,11 @@
>
<:col :let={{_id, record}} label="Image">
<span class="relative inline-block drop-shadow-xl">
<img class="max-w-16 rounded-lg" src={~p"/images/#{record.id}"} alt={record.title} />
<img
class="max-w-16 rounded-lg"
alt={record.title}
src={~p"/images/#{record.id}?vsn=#{record.image_data_hash || ""}"}
/>
<span class="absolute right-1 bottom-0 block text-white drop-shadow-md">
<%= Records.Record.format_short_label(record.format) %>
</span>
@@ -13,7 +13,11 @@
<div class="md:columns-2">
<span class="relative block md:inline-block drop-shadow">
<img class="w-full" src={~p"/images/#{@record.id}"} alt={@record.title} />
<img
class="w-full"
src={~p"/images/#{@record.id}?vsn=#{@record.image_data_hash}"}
alt={@record.title}
/>
<span class="absolute right-2 bottom-1 block text-white drop-shadow-md">
<%= Records.Record.format_short_label(@record.format) %>
</span>
@@ -0,0 +1,9 @@
defmodule MusicLibrary.Repo.Migrations.AddImageDataHashToRecords do
use Ecto.Migration
def change do
alter table(:records) do
add :image_data_hash, :string
end
end
end