summaryrefslogtreecommitdiff
path: root/lib/pleroma/web/activity_pub/object_validators/create_chat_message_validator.ex
blob: 8384c16a7ee5002a2e9ed3599e7d9627382f2747 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
# Pleroma: A lightweight social networking server
# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>
# SPDX-License-Identifier: AGPL-3.0-only

# NOTES
# - Can probably be a generic create validator
# - doesn't embed, will only get the object id
defmodule Pleroma.Web.ActivityPub.ObjectValidators.CreateChatMessageValidator do
  use Ecto.Schema
  alias Pleroma.EctoType.ActivityPub.ObjectValidators

  alias Pleroma.Object

  import Ecto.Changeset
  import Pleroma.Web.ActivityPub.ObjectValidators.CommonValidations

  @primary_key false

  embedded_schema do
    field(:id, ObjectValidators.ObjectID, primary_key: true)
    field(:actor, ObjectValidators.ObjectID)
    field(:type, :string)
    field(:to, ObjectValidators.Recipients, default: [])
    field(:object, ObjectValidators.ObjectID)
  end

  def cast_and_apply(data) do
    data
    |> cast_data
    |> apply_action(:insert)
  end

  def cast_data(data) do
    cast(%__MODULE__{}, data, __schema__(:fields))
  end

  def cast_and_validate(data, meta \\ []) do
    cast_data(data)
    |> validate_data(meta)
  end

  def validate_data(cng, meta \\ []) do
    cng
    |> validate_required([:id, :actor, :to, :type, :object])
    |> validate_inclusion(:type, ["Create"])
    |> validate_actor_presence()
    |> validate_recipients_match(meta)
    |> validate_actors_match(meta)
    |> validate_object_nonexistence()
  end

  def validate_object_nonexistence(cng) do
    cng
    |> validate_change(:object, fn :object, object_id ->
      if Object.get_cached_by_ap_id(object_id) do
        [{:object, "The object to create already exists"}]
      else
        []
      end
    end)
  end

  def validate_actors_match(cng, meta) do
    object_actor = meta[:object_data]["actor"]

    cng
    |> validate_change(:actor, fn :actor, actor ->
      if actor == object_actor do
        []
      else
        [{:actor, "Actor doesn't match with object actor"}]
      end
    end)
  end

  def validate_recipients_match(cng, meta) do
    object_recipients = meta[:object_data]["to"] || []

    cng
    |> validate_change(:to, fn :to, recipients ->
      activity_set = MapSet.new(recipients)
      object_set = MapSet.new(object_recipients)

      if MapSet.equal?(activity_set, object_set) do
        []
      else
        [{:to, "Recipients don't match with object recipients"}]
      end
    end)
  end
end