clacks/lib/clacks/activitypub/fetcher.ex

58 lines
1.5 KiB
Elixir
Raw Normal View History

2019-09-29 22:30:59 +00:00
defmodule Clacks.ActivityPub.Fetcher do
require Logger
@spec fetch_actor(id :: String.t()) :: map() | nil
def fetch_actor(id) do
%{host: id_host} = URI.parse(id)
with %{"type" => type, "id" => remote_id} = actor <- fetch(id),
"person" <- String.downcase(type),
2020-04-26 02:28:30 +00:00
%{host: ^id_host} <- URI.parse(remote_id) do
2019-09-29 22:30:59 +00:00
actor
else
_ ->
nil
end
end
@spec fetch_object(id :: String.t()) :: map() | nil
def fetch_object(id) do
%{host: id_host} = URI.parse(id)
2021-08-25 21:23:37 +00:00
with object when is_map(object) <- fetch(id),
remote_actor when is_binary(remote_actor) <- get_actor(object),
2020-04-26 02:28:30 +00:00
%{host: ^id_host} <- URI.parse(remote_actor) do
2019-09-29 22:30:59 +00:00
object
else
_ ->
nil
end
end
2019-09-30 21:02:03 +00:00
@spec fetch_activity(id :: String.t()) :: map() | nil
def fetch_activity(id) do
fetch_object(id)
end
2019-09-29 22:30:59 +00:00
@spec fetch(uri :: String.t()) :: map() | nil
defp fetch(uri) do
Logger.debug("Attempting to fetch AP object at #{uri}")
headers = [Accept: "application/activity+json, application/ld+json"]
2020-05-20 21:42:10 +00:00
with {:ok, %HTTPoison.Response{body: body}} <- Clacks.HTTP.get(uri, headers),
2019-09-29 22:30:59 +00:00
{:ok, data} <- Jason.decode(body) do
data
else
{:error, reason} ->
Logger.warn("Couldn't fetch AP object at #{uri}: #{reason}")
2019-09-29 22:30:59 +00:00
nil
end
end
2021-08-25 21:23:37 +00:00
@spec get_actor(data :: map()) :: String.t() | nil
defp get_actor(%{"actor" => actor}) when is_binary(actor), do: actor
defp get_actor(%{"attributedTo" => actor}) when is_binary(actor), do: actor
defp get_actor(_), do: nil
2019-09-29 22:30:59 +00:00
end