Files
labelmaker/lib/labelmaker_web/controllers/label_controller.ex
2025-09-01 15:18:11 -04:00

95 lines
2.1 KiB
Elixir

defmodule LabelmakerWeb.LabelController do
use LabelmakerWeb, :controller
alias LabelmakerWeb.Constants
alias LabelmakerWeb.Tools
@label_dir Path.join(:code.priv_dir(:labelmaker), "static/labels")
def show(conn, params) do
options = Tools.process_parameters(params)
filename =
options
|> inspect()
|> (fn str -> :crypto.hash(:sha256, str) end).()
|> Base.encode16(case: :lower)
filename = filename <> ".png"
filepath = Path.join(@label_dir, filename)
options = Map.put(options, :filepath, filepath)
unless File.exists?(filepath) do
basic_settings(options)
|> outline_settings(options)
|> size_settings(options)
|> final_settings(options)
|> generate_image()
end
conn
|> put_resp_content_type("image/png")
|> send_file(200, filepath)
end
defp basic_settings(options) do
[
"-background",
"none",
"-fill",
options.color,
"-font",
options.font
]
end
defp size_settings(args, %{height: "", width: ""} = options) do
args ++
[
"-pointsize",
options.size,
"label:#{String.slice(options.label, 0, Constants.max_label_length())}"
]
end
defp size_settings(args, %{align: alignment, height: height, width: width} = options) do
args ++
[
"-gravity",
Tools.process_gravity(alignment),
"-size",
"#{width}x#{height}",
"caption:#{String.slice(options.label, 0, Constants.max_label_length())}"
]
end
defp outline_settings(args, %{outline: "none"}), do: args
defp outline_settings(args, %{outline: color}) do
args ++
[
"-stroke",
color,
"-strokewidth",
"1"
]
end
defp final_settings(args, options) do
args ++
[
"-set",
"comment",
inspect(Jason.encode!(Map.drop(options, [:filepath, :link]))),
options.filepath
]
end
defp generate_image(args) do
File.mkdir_p!(@label_dir)
# IO.inspect((["magick"] ++ args) |> Enum.join(" "))
{_, 0} = System.cmd("magick", args)
end
end