From cb0e06d603790b6cfa0909847a2f1fdf284e12b8 Mon Sep 17 00:00:00 2001 From: Claudio Ortolina Date: Thu, 28 Nov 2024 17:15:12 +0000 Subject: [PATCH] Add batch operation to resize covers with incorrect sizes --- lib/music_library/records/batch.ex | 46 +++++++++++++++++++++--------- lib/music_library/records/cover.ex | 9 +++++- 2 files changed, 40 insertions(+), 15 deletions(-) diff --git a/lib/music_library/records/batch.ex b/lib/music_library/records/batch.ex index 9add50e2..0041c56e 100644 --- a/lib/music_library/records/batch.ex +++ b/lib/music_library/records/batch.ex @@ -1,7 +1,7 @@ defmodule MusicLibrary.Records.Batch do require Logger - alias MusicLibrary.Records.Record + alias MusicLibrary.Records.{Cover, Record} alias MusicLibrary.Repo import Ecto.Query @@ -20,6 +20,18 @@ defmodule MusicLibrary.Records.Batch do end end + def refresh_old_artwork do + run_on_all_records(&refresh_old_artwork/1) + end + + def refresh_old_artwork(record) do + if Cover.correct_size?(record.cover_data) do + :ok + else + MusicLibrary.Records.refresh_cover(record) + end + end + def update_release_ids do run_on_all_records(&update_release_ids/1) end @@ -44,21 +56,27 @@ defmodule MusicLibrary.Records.Batch do q = from(r in Record) stream = Repo.stream(q) - Repo.transaction(fn -> - Enum.reduce(stream, [], fn record, acc -> - case fun.(record) do - {:error, reason} -> - Logger.error("Failed to run function on record #{record.id} with #{inspect(reason)}") - [record.id | acc] + Repo.transaction( + fn -> + Enum.reduce(stream, [], fn record, acc -> + case fun.(record) do + {:error, reason} -> + Logger.error( + "Failed to run function on record #{record.id} with #{inspect(reason)}" + ) - :ok -> - acc + [record.id | acc] - {:ok, _record} -> - acc - end - end) - end) + :ok -> + acc + + {:ok, _record} -> + acc + end + end) + end, + timeout: :infinity + ) end defp musicbrainz do diff --git a/lib/music_library/records/cover.ex b/lib/music_library/records/cover.ex index dad9d1c2..6ca8c402 100644 --- a/lib/music_library/records/cover.ex +++ b/lib/music_library/records/cover.ex @@ -1,6 +1,13 @@ defmodule MusicLibrary.Records.Cover do + @size 600 def resize(cover_data) do - {:ok, thumb} = Vix.Vips.Operation.thumbnail_buffer(cover_data, 600) + {:ok, thumb} = Vix.Vips.Operation.thumbnail_buffer(cover_data, @size) Vix.Vips.Image.write_to_buffer(thumb, ".jpg") end + + def correct_size?(cover_data) do + {:ok, image} = Vix.Vips.Image.new_from_buffer(cover_data) + + Vix.Vips.Image.width(image) == @size + end end