+ |> validate_required([:id, :actor, :to, :type, :published])
+ |> validate_content_or_attachment()
+ |> validate_length(:to, is: 1)
+ |> validate_length(:content, max: Pleroma.Config.get([:instance, :remote_limit]))
+ |> validate_local_concern()
+ end
+
+ def validate_content_or_attachment(cng) do
+ attachment = get_field(cng, :attachment)
+
+ if attachment do
+ cng
+ else
+ cng
+ |> validate_required([:content])
+ end
+ end
+
+ @doc """
+ Validates the following
+ - If both users are in our system
+ - If at least one of the users in this ChatMessage is a local user
+ - If the recipient is not blocking the actor
+ """
+ def validate_local_concern(cng) do
+ with actor_ap <- get_field(cng, :actor),
+ {_, %User{} = actor} <- {:find_actor, User.get_cached_by_ap_id(actor_ap)},
+ {_, %User{} = recipient} <-
+ {:find_recipient, User.get_cached_by_ap_id(get_field(cng, :to) |> hd())},
+ {_, false} <- {:blocking_actor?, User.blocks?(recipient, actor)},
+ {_, true} <- {:local?, Enum.any?([actor, recipient], & &1.local)} do
+ cng
+ else
+ {:blocking_actor?, true} ->
+ cng
+ |> add_error(:actor, "actor is blocked by recipient")
+
+ {:local?, false} ->
+ cng
+ |> add_error(:actor, "actor and recipient are both remote")
+
+ {:find_actor, _} ->
+ cng
+ |> add_error(:actor, "can't find user")
+
+ {:find_recipient, _} ->
+ cng
+ |> add_error(:to, "can't find user")
+ end