58 lines
1.5 KiB
Elixir
58 lines
1.5 KiB
Elixir
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),
|
|
%{host: ^id_host} <- URI.parse(remote_id) do
|
|
actor
|
|
else
|
|
_ ->
|
|
nil
|
|
end
|
|
end
|
|
|
|
@spec fetch_object(id :: String.t()) :: map() | nil
|
|
def fetch_object(id) do
|
|
%{host: id_host} = URI.parse(id)
|
|
|
|
with object when is_map(object) <- fetch(id),
|
|
remote_actor when is_binary(remote_actor) <- get_actor(object),
|
|
%{host: ^id_host} <- URI.parse(remote_actor) do
|
|
object
|
|
else
|
|
_ ->
|
|
nil
|
|
end
|
|
end
|
|
|
|
@spec fetch_activity(id :: String.t()) :: map() | nil
|
|
def fetch_activity(id) do
|
|
fetch_object(id)
|
|
end
|
|
|
|
@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"]
|
|
|
|
with {:ok, %HTTPoison.Response{body: body}} <- Clacks.HTTP.get(uri, headers),
|
|
{:ok, data} <- Jason.decode(body) do
|
|
data
|
|
else
|
|
{:error, reason} ->
|
|
Logger.warn("Couldn't fetch AP object at #{uri}: #{reason}")
|
|
nil
|
|
end
|
|
end
|
|
|
|
@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
|
|
end
|