93 lines
2.0 KiB
Elixir
93 lines
2.0 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)
|
|
|> size_settings(options)
|
|
|> outline_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: 0, width: 0} = options) do
|
|
args ++
|
|
[
|
|
"-pointsize",
|
|
options.size,
|
|
"label:#{String.slice(options.label, 0, Constants.max_label_length())}"
|
|
]
|
|
end
|
|
|
|
defp size_settings(args, %{gravity: gravity, height: height, width: width} = options) do
|
|
args ++
|
|
[
|
|
"-gravity",
|
|
gravity,
|
|
"-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)
|
|
|
|
{_, 0} = System.cmd("magick", args)
|
|
end
|
|
end
|