Add option to return activity from object fetch, don't unnecessarily synthesize Create if one already exists

This commit is contained in:
Shadowfacts 2020-04-25 22:27:59 -04:00
parent 8178fc3ba6
commit f51d4a6be4
Signed by: shadowfacts
GPG Key ID: 94A5AB95422746E5
1 changed files with 38 additions and 13 deletions

View File

@ -24,6 +24,17 @@ defmodule Clacks.Object do
changeset(%__MODULE__{}, %{data: data}) changeset(%__MODULE__{}, %{data: data})
end end
@spec get_actor(object :: t()) :: Clacks.Actor.t() | nil
def get_actor(object) do
case object.data["actor"] || object.data["attributedTo"] do
nil ->
nil
id when is_binary(id) ->
Clacks.Actor.get_by_ap_id(id)
end
end
@spec get_by_ap_id( @spec get_by_ap_id(
ap_id :: String.t(), ap_id :: String.t(),
force_refetch :: boolean(), force_refetch :: boolean(),
@ -42,8 +53,9 @@ defmodule Clacks.Object do
Repo.one(from o in __MODULE__, where: fragment("?->>'id'", o.data) == ^ap_id) Repo.one(from o in __MODULE__, where: fragment("?->>'id'", o.data) == ^ap_id)
end end
@spec fetch(ap_id :: String.t(), synthesize_create :: boolean()) :: t() | nil @spec fetch(ap_id :: String.t(), synthesize_create :: boolean(), return :: :object | :activity) ::
def fetch(ap_id, synthesize_create \\ true) do t() | nil
def fetch(ap_id, synthesize_create \\ true, return \\ :object) do
case Clacks.ActivityPub.Fetcher.fetch_object(ap_id) do case Clacks.ActivityPub.Fetcher.fetch_object(ap_id) do
nil -> nil ->
nil nil
@ -61,6 +73,9 @@ defmodule Clacks.Object do
actor = data["actor"] || data["attributedTo"] actor = data["actor"] || data["attributedTo"]
_ = Clacks.Actor.get_by_ap_id(actor) _ = Clacks.Actor.get_by_ap_id(actor)
activity =
case Clacks.Activity.get_by_object_ap_id(ap_id) do
nil ->
if synthesize_create do if synthesize_create do
create = Clacks.ActivityPub.synthesized_create(data) create = Clacks.ActivityPub.synthesized_create(data)
@ -71,10 +86,20 @@ defmodule Clacks.Object do
actor: actor actor: actor
}) })
{:ok, _create} = Repo.insert_or_update(changeset) {:ok, create} = Repo.insert_or_update(changeset)
create
else
nil
end end
object %Clacks.Activity{} = activity ->
activity
end
case return do
:object -> object
:activity -> activity
end
{:error, changeset} -> {:error, changeset} ->
Logger.error("Couldn't store remote object #{ap_id}: #{inspect(changeset)}") Logger.error("Couldn't store remote object #{ap_id}: #{inspect(changeset)}")