115 lines
2.6 KiB
Elixir
115 lines
2.6 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
|
|
# Escape % characters in label text to prevent ImageMagick property interpolation
|
|
escaped_label =
|
|
options.label
|
|
|> String.slice(0, Constants.max_label_length())
|
|
|> String.replace("%", "%%")
|
|
|
|
args ++
|
|
[
|
|
"-pointsize",
|
|
options.size,
|
|
"label:#{escaped_label}"
|
|
]
|
|
end
|
|
|
|
defp size_settings(args, %{align: alignment, height: height, width: width} = options) do
|
|
# Escape % characters in label text to prevent ImageMagick property interpolation
|
|
escaped_label =
|
|
options.label
|
|
|> String.slice(0, Constants.max_label_length())
|
|
|> String.replace("%", "%%")
|
|
|
|
args ++
|
|
[
|
|
"-gravity",
|
|
Tools.process_gravity(alignment),
|
|
"-size",
|
|
"#{width}x#{height}",
|
|
"caption:#{escaped_label}"
|
|
]
|
|
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
|
|
# Escape % characters to prevent ImageMagick from interpreting them as property variables
|
|
comment =
|
|
options
|
|
|> Map.drop([:filepath, :link])
|
|
|> Jason.encode!()
|
|
|> inspect()
|
|
|> String.replace("%", "%%")
|
|
|
|
args ++
|
|
[
|
|
"-set",
|
|
"comment",
|
|
comment,
|
|
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
|