Merge branch 'develop' of git.pleroma.social:pleroma/pleroma into remake-remodel-dms
[akkoma] / lib / pleroma / web / activity_pub / object_validators / create_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 # NOTES
6 # - Can probably be a generic create validator
7 # - doesn't embed, will only get the object id
8 defmodule Pleroma.Web.ActivityPub.ObjectValidators.CreateChatMessageValidator do
9 use Ecto.Schema
10
11 alias Pleroma.Object
12 alias Pleroma.Web.ActivityPub.ObjectValidators.Types
13
14 import Ecto.Changeset
15
16 @primary_key false
17
18 embedded_schema do
19 field(:id, Types.ObjectID, primary_key: true)
20 field(:actor, Types.ObjectID)
21 field(:type, :string)
22 field(:to, Types.Recipients, default: [])
23 field(:object, Types.ObjectID)
24 end
25
26 def cast_and_apply(data) do
27 data
28 |> cast_data
29 |> apply_action(:insert)
30 end
31
32 def cast_data(data) do
33 cast(%__MODULE__{}, data, __schema__(:fields))
34 end
35
36 def cast_and_validate(data, meta \\ []) do
37 cast_data(data)
38 |> validate_data(meta)
39 end
40
41 def validate_data(cng, meta \\ []) do
42 cng
43 |> validate_required([:id, :actor, :to, :type, :object])
44 |> validate_inclusion(:type, ["Create"])
45 |> validate_recipients_match(meta)
46 |> validate_object_nonexistence()
47 end
48
49 def validate_object_nonexistence(cng) do
50 cng
51 |> validate_change(:object, fn :object, object_id ->
52 if Object.get_cached_by_ap_id(object_id) do
53 [{:object, "The object to create already exists"}]
54 else
55 []
56 end
57 end)
58 end
59
60 def validate_recipients_match(cng, meta) do
61 object_recipients = meta[:object_data]["to"] || []
62
63 cng
64 |> validate_change(:to, fn :to, recipients ->
65 activity_set = MapSet.new(recipients)
66 object_set = MapSet.new(object_recipients)
67
68 if MapSet.equal?(activity_set, object_set) do
69 []
70 else
71 [{:to, "Recipients don't match with object recipients"}]
72 end
73 end)
74 end
75 end