diff options
Diffstat (limited to 'lib/command/addmeme.ex')
| -rw-r--r-- | lib/command/addmeme.ex | 105 |
1 files changed, 105 insertions, 0 deletions
diff --git a/lib/command/addmeme.ex b/lib/command/addmeme.ex new file mode 100644 index 0000000..a4df2f3 --- /dev/null +++ b/lib/command/addmeme.ex @@ -0,0 +1,105 @@ +require Logger + +alias Nosedrum.TextCommand.Predicates +alias Nostrum.Struct.Message + +alias Thulani.Command.Util +alias Thulani.Schema.Meme +alias Thulani.Schema.Image + +defmodule Thulani.Command.AddMeme do + @behaviour Nosedrum.TextCommand + + @impl true + def aliases, do: ["addmeme"] + + @impl true + # TODO + def usage, do: ["addmeme <title:str>"] + + @impl true + def predicates, do: [&Predicates.guild_only/1] + + @impl true + def description, do: "add a meme to the db" + + @impl true + def command( + msg, + [title, content] + ) do + result = + Thulani.Repo.transaction(fn -> + %{ + content: content, + title: title, + metadata: Util.metadata(msg) + } + |> Map.merge(media(msg)) + |> dbg + |> Meme.insert_changeset() + |> Thulani.Repo.insert() + end) + + case result do + {:ok, _meme} -> + Logger.debug("inserted meme ok") + msg |> Util.react!("👌") + + {:error, changeset} -> + Logger.error("updating") + + Ecto.Changeset.traverse_errors( + changeset, + fn {msg, opts} -> + dbg({msg, opts}) + end + ) + end + + {:ok} + end + + defp media( + %Message{ + attachments: [ + %Message.Attachment{ + url: url, + filename: filename + } + ] + } = msg + ) do + data = Req.get!(url).body + hash = :crypto.hash(:sha, data) + + existing_image = image_with_hash(hash) |> Thulani.Repo.one() + + if is_nil(existing_image) do + Logger.debug("no existing image") + + %{ + image: %{ + filename: filename, + data: data, + data_hash: hash, + metadata: Util.metadata(msg) + } + } + else + Logger.debug("found existing image", existing_image: existing_image) + + %{ + image_id: existing_image.id + } + end + end + + defp media(_invalid), do: %{} + + defp image_with_hash(hash) when is_binary(hash) do + import Ecto.Query + + from(i in Image, where: i.data_hash == ^hash, limit: 1) + end +end |
