Merge branch 'develop' of git.pleroma.social:pleroma/pleroma into remake-remodel-dms
[akkoma] / lib / pleroma / web / activity_pub / object_validators / chat_message_validator.ex
1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/>
3 # SPDX-License-Identifier: AGPL-3.0-only
4
5 defmodule Pleroma.Web.ActivityPub.ObjectValidators.ChatMessageValidator do
6 use Ecto.Schema
7
8 alias Pleroma.User
9 alias Pleroma.Web.ActivityPub.ObjectValidators.Types
10
11 import Ecto.Changeset
12 import Pleroma.Web.ActivityPub.Transmogrifier, only: [fix_emoji: 1]
13
14 @primary_key false
15 @derive Jason.Encoder
16
17 embedded_schema do
18 field(:id, Types.ObjectID, primary_key: true)
19 field(:to, Types.Recipients, default: [])
20 field(:type, :string)
21 field(:content, Types.SafeText)
22 field(:actor, Types.ObjectID)
23 field(:published, Types.DateTime)
24 field(:emoji, :map, default: %{})
25 end
26
27 def cast_and_apply(data) do
28 data
29 |> cast_data
30 |> apply_action(:insert)
31 end
32
33 def cast_and_validate(data) do
34 data
35 |> cast_data()
36 |> validate_data()
37 end
38
39 def cast_data(data) do
40 %__MODULE__{}
41 |> changeset(data)
42 end
43
44 def fix(data) do
45 data
46 |> fix_emoji()
47 |> Map.put_new("actor", data["attributedTo"])
48 end
49
50 def changeset(struct, data) do
51 data = fix(data)
52
53 struct
54 |> cast(data, __schema__(:fields))
55 end
56
57 def validate_data(data_cng) do
58 data_cng
59 |> validate_inclusion(:type, ["ChatMessage"])
60 |> validate_required([:id, :actor, :to, :type, :content, :published])
61 |> validate_length(:to, is: 1)
62 |> validate_length(:content, max: Pleroma.Config.get([:instance, :remote_limit]))
63 |> validate_local_concern()
64 end
65
66 @doc """
67 Validates the following
68 - If both users are in our system
69 - If at least one of the users in this ChatMessage is a local user
70 - If the recipient is not blocking the actor
71 """
72 def validate_local_concern(cng) do
73 with actor_ap <- get_field(cng, :actor),
74 {_, %User{} = actor} <- {:find_actor, User.get_cached_by_ap_id(actor_ap)},
75 {_, %User{} = recipient} <-
76 {:find_recipient, User.get_cached_by_ap_id(get_field(cng, :to) |> hd())},
77 {_, false} <- {:blocking_actor?, User.blocks?(recipient, actor)},
78 {_, true} <- {:local?, Enum.any?([actor, recipient], & &1.local)} do
79 cng
80 else
81 {:blocking_actor?, true} ->
82 cng
83 |> add_error(:actor, "actor is blocked by recipient")
84
85 {:local?, false} ->
86 cng
87 |> add_error(:actor, "actor and recipient are both remote")
88
89 {:find_actor, _} ->
90 cng
91 |> add_error(:actor, "can't find user")
92
93 {:find_recipient, _} ->
94 cng
95 |> add_error(:to, "can't find user")
96 end
97 end
98 end