LikeValidator: Fix up missing recipients.

This commit is contained in:
lain 2020-05-04 17:08:31 +02:00
parent 335aabc39c
commit e03c301ebe
2 changed files with 44 additions and 3 deletions

View File

@ -5,6 +5,7 @@
defmodule Pleroma.Web.ActivityPub.ObjectValidators.LikeValidator do defmodule Pleroma.Web.ActivityPub.ObjectValidators.LikeValidator do
use Ecto.Schema use Ecto.Schema
alias Pleroma.Object
alias Pleroma.Web.ActivityPub.ObjectValidators.Types alias Pleroma.Web.ActivityPub.ObjectValidators.Types
alias Pleroma.Web.ActivityPub.Utils alias Pleroma.Web.ActivityPub.Utils
@ -19,8 +20,8 @@ defmodule Pleroma.Web.ActivityPub.ObjectValidators.LikeValidator do
field(:object, Types.ObjectID) field(:object, Types.ObjectID)
field(:actor, Types.ObjectID) field(:actor, Types.ObjectID)
field(:context, :string) field(:context, :string)
field(:to, {:array, :string}) field(:to, {:array, :string}, default: [])
field(:cc, {:array, :string}) field(:cc, {:array, :string}, default: [])
end end
def cast_and_validate(data) do def cast_and_validate(data) do
@ -31,7 +32,34 @@ def cast_and_validate(data) do
def cast_data(data) do def cast_data(data) do
%__MODULE__{} %__MODULE__{}
|> cast(data, [:id, :type, :object, :actor, :context, :to, :cc]) |> changeset(data)
end
def changeset(struct, data) do
struct
|> cast(data, __schema__(:fields))
|> fix_after_cast()
end
def fix_after_cast(cng) do
cng
|> fix_recipients()
end
def fix_recipients(cng) do
to = get_field(cng, :to) || []
cc = get_field(cng, :cc) || []
object = get_field(cng, :object)
with {[], []} <- {to, cc},
%Object{data: %{"actor" => actor}} <- Object.get_cached_by_ap_id(object),
{:ok, actor} <- Types.ObjectID.cast(actor) do
cng
|> put_change(:to, [actor])
else
_ ->
cng
end
end end
def validate_data(data_cng) do def validate_data(data_cng) do

View File

@ -36,6 +36,19 @@ test "is valid for a valid object", %{valid_like: valid_like} do
assert LikeValidator.cast_and_validate(valid_like).valid? assert LikeValidator.cast_and_validate(valid_like).valid?
end end
test "sets the 'to' field to the object actor if no recipients are given", %{
valid_like: valid_like,
user: user
} do
without_recipients =
valid_like
|> Map.delete("to")
{:ok, object, _meta} = ObjectValidator.validate(without_recipients, [])
assert object["to"] == [user.ap_id]
end
test "it errors when the actor is missing or not known", %{valid_like: valid_like} do test "it errors when the actor is missing or not known", %{valid_like: valid_like} do
without_actor = Map.delete(valid_like, "actor") without_actor = Map.delete(valid_like, "actor")