diff --git a/lib/philomena/images.ex b/lib/philomena/images.ex index 4888d67f..2b2eddca 100644 --- a/lib/philomena/images.ex +++ b/lib/philomena/images.ex @@ -335,21 +335,19 @@ defmodule Philomena.Images do new_sources = attrs["sources"] Multi.new() - |> Multi.run( - :image, - fn repo, _chg -> - image = repo.preload(image, [:sources]) + |> Multi.run(:image, fn repo, _chg -> + image = repo.preload(image, [:sources]) - image - |> Image.source_changeset(%{}, old_sources, new_sources) - |> repo.update() - |> case do - {:ok, image} -> - {:ok, {image, image.added_sources, image.removed_sources}} + image + |> Image.source_changeset(%{}, old_sources, new_sources) + |> repo.update() + |> case do + {:ok, image} -> + {:ok, {image, image.added_sources, image.removed_sources}} - error -> - error - end + error -> + error + end end) |> Multi.run(:added_source_changes, fn repo, %{image: {image, added_sources, _removed}} -> source_changes = @@ -383,7 +381,7 @@ defmodule Philomena.Images do %{ image_id: image.id, - source: source, + source_url: source, user_id: user_id, created_at: now, updated_at: now, diff --git a/lib/philomena/images/source_differ.ex b/lib/philomena/images/source_differ.ex index 19d8bd16..02843371 100644 --- a/lib/philomena/images/source_differ.ex +++ b/lib/philomena/images/source_differ.ex @@ -3,8 +3,8 @@ defmodule Philomena.Images.SourceDiffer do alias Philomena.Images.Source def diff_input(changeset, old_sources, new_sources) do - old_set = MapSet.new(old_sources) - new_set = MapSet.new(new_sources) + old_set = MapSet.new(flatten_input(old_sources)) + new_set = MapSet.new(flatten_input(new_sources)) source_set = MapSet.new(get_field(changeset, :sources), & &1.source) added_sources = MapSet.difference(new_set, old_set) @@ -47,4 +47,23 @@ defmodule Philomena.Images.SourceDiffer do defp source_structs(image_id, sources) do Enum.map(sources, &%Source{image_id: image_id, source: &1}) end + + defp flatten_input(input) when is_map(input) do + Enum.flat_map(Map.values(input), fn + %{"source" => source} -> + source = String.trim(source) + + if source != "" do + [source] + else + [] + end + + _ -> [] + end) + end + + defp flatten_input(_input) do + [] + end end diff --git a/priv/repo/structure.sql b/priv/repo/structure.sql index 47ea8bde..ab137a7c 100644 --- a/priv/repo/structure.sql +++ b/priv/repo/structure.sql @@ -841,9 +841,9 @@ ALTER SEQUENCE public.image_intensities_id_seq OWNED BY public.image_intensities -- Name: image_sources; Type: TABLE; Schema: public; Owner: - -- -CREATE TABLE public.image_sources( - image_id bigint NOT NULL, - source character varying(255) NOT NULL, +CREATE TABLE public.image_sources ( + image_id bigint NOT NULL, + source character varying(255) NOT NULL, CONSTRAINT image_sources_source_check CHECK (((source)::text ~* '^https?://'::text)) );