chiya/lib/chiya_web/indie/micropub_handler.ex

94 lines
2.2 KiB
Elixir
Raw Normal View History

defmodule ChiyaWeb.Indie.MicropubHandler do
@behaviour PlugMicropub.HandlerBehaviour
2023-05-28 22:59:11 +02:00
require Logger
2023-05-31 21:32:34 +02:00
alias ChiyaWeb.Indie.Properties, as: Props
alias ChiyaWeb.Indie.Token
2023-05-28 22:59:11 +02:00
@impl true
def handle_create(type, properties, access_token) do
2023-05-31 21:32:34 +02:00
dbg(properties)
2023-05-31 22:15:39 +02:00
dbg(type)
2023-05-31 21:32:34 +02:00
with :ok <- Token.verify(access_token, "create", get_hostname()),
{:ok, post_type} <- Props.get_post_type(properties),
2023-05-31 22:15:39 +02:00
{:ok, note_attrs} <- get_attrs(type, post_type, properties),
2023-05-28 22:59:11 +02:00
{:ok, note} <- Chiya.Notes.create_note(note_attrs) do
2023-05-31 21:32:34 +02:00
{:ok, :created, Chiya.Notes.Note.note_url(note)} |> dbg()
2023-05-28 22:59:11 +02:00
else
error ->
Logger.error("Error occurred while creating note from micropub:")
dbg(error)
{:error, :unhandled_error}
end
end
@impl true
def handle_update(_, _, _, _, _) do
{:error, :insufficient_scope}
end
@impl true
def handle_delete(_url, _access_token) do
{:error, :insufficient_scope}
end
@impl true
def handle_undelete(_url, _access_token) do
{:error, :insufficient_scope}
end
@impl true
def handle_source_query(_url, _filter_properties, _access_token) do
{:error, :insufficient_scope}
end
@impl true
def handle_media(_files, _access_token) do
{:error, :insufficient_scope}
end
@impl true
def handle_config_query(_access_token) do
{:error, :insufficient_scope}
end
@impl true
def handle_syndicate_to_query(_access_token) do
{:error, :insufficient_scope}
end
2023-05-31 22:15:39 +02:00
defp get_attrs(type, post_type, properties) do
Logger.info("Creating a #{type}/#{post_type}..")
2023-05-31 21:32:34 +02:00
case post_type do
2023-05-31 22:15:39 +02:00
:note -> get_note_attrs(properties)
2023-05-31 21:32:34 +02:00
_ -> {:error, :insufficient_scope}
end
2023-05-28 22:59:11 +02:00
end
2023-05-31 22:15:39 +02:00
defp get_note_attrs(p) do
2023-05-31 21:32:34 +02:00
content = Props.get_content(p)
name = Props.get_title(p) || String.slice(content, 0..15)
tags = Props.get_tags(p) |> Enum.join(",")
2023-06-01 23:22:16 +02:00
published_at =
if Props.is_published?(p),
do: NaiveDateTime.local_now(),
else: nil
2023-05-31 21:32:34 +02:00
{:ok,
%{
content: content,
name: name,
2023-06-01 23:22:16 +02:00
tags_string: tags,
published_at: published_at
2023-05-31 21:32:34 +02:00
}}
|> dbg()
end
2023-05-28 22:59:11 +02:00
defp get_hostname(),
do: URI.parse(ChiyaWeb.Endpoint.url()).host
end