2025-12-30 21:35:52 +00:00
|
|
|
defmodule SimpleshopTheme.Media.Image do
|
|
|
|
|
use Ecto.Schema
|
|
|
|
|
import Ecto.Changeset
|
|
|
|
|
|
|
|
|
|
@primary_key {:id, :binary_id, autogenerate: true}
|
|
|
|
|
@foreign_key_type :binary_id
|
|
|
|
|
|
|
|
|
|
schema "images" do
|
|
|
|
|
field :image_type, :string
|
|
|
|
|
field :filename, :string
|
|
|
|
|
field :content_type, :string
|
|
|
|
|
field :file_size, :integer
|
|
|
|
|
field :data, :binary
|
|
|
|
|
field :is_svg, :boolean, default: false
|
|
|
|
|
field :svg_content, :string
|
2026-01-21 22:08:19 +00:00
|
|
|
field :source_width, :integer
|
|
|
|
|
field :source_height, :integer
|
|
|
|
|
field :variants_status, :string, default: "pending"
|
2025-12-30 21:35:52 +00:00
|
|
|
|
|
|
|
|
timestamps(type: :utc_datetime)
|
|
|
|
|
end
|
|
|
|
|
|
|
|
|
|
@max_file_size 5_000_000
|
|
|
|
|
|
|
|
|
|
@doc false
|
|
|
|
|
def changeset(image, attrs) do
|
|
|
|
|
image
|
2026-01-21 22:08:19 +00:00
|
|
|
|> cast(attrs, [
|
|
|
|
|
:image_type,
|
|
|
|
|
:filename,
|
|
|
|
|
:content_type,
|
|
|
|
|
:file_size,
|
|
|
|
|
:data,
|
|
|
|
|
:is_svg,
|
|
|
|
|
:svg_content,
|
|
|
|
|
:source_width,
|
|
|
|
|
:source_height,
|
|
|
|
|
:variants_status
|
|
|
|
|
])
|
2025-12-30 21:35:52 +00:00
|
|
|
|> validate_required([:image_type, :filename, :content_type, :file_size, :data])
|
|
|
|
|
|> validate_inclusion(:image_type, ~w(logo header product))
|
|
|
|
|
|> validate_number(:file_size, less_than: @max_file_size)
|
|
|
|
|
|> detect_svg()
|
|
|
|
|
end
|
|
|
|
|
|
|
|
|
|
defp detect_svg(changeset) do
|
|
|
|
|
content_type = get_change(changeset, :content_type)
|
|
|
|
|
|
2026-01-31 14:24:58 +00:00
|
|
|
if content_type == "image/svg+xml" or
|
|
|
|
|
String.ends_with?(get_change(changeset, :filename) || "", ".svg") do
|
2025-12-30 21:35:52 +00:00
|
|
|
changeset
|
|
|
|
|
|> put_change(:is_svg, true)
|
|
|
|
|
|> maybe_store_svg_content()
|
|
|
|
|
else
|
|
|
|
|
changeset
|
|
|
|
|
end
|
|
|
|
|
end
|
|
|
|
|
|
|
|
|
|
defp maybe_store_svg_content(changeset) do
|
|
|
|
|
case get_change(changeset, :data) do
|
|
|
|
|
nil ->
|
|
|
|
|
changeset
|
|
|
|
|
|
|
|
|
|
svg_binary when is_binary(svg_binary) ->
|
|
|
|
|
put_change(changeset, :svg_content, svg_binary)
|
|
|
|
|
end
|
|
|
|
|
end
|
|
|
|
|
end
|