Merge branch 'feature/delete-validator' into 'develop'
[akkoma] / lib / pleroma / web / activity_pub / object_validators / common_validations.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.CommonValidations do
6 import Ecto.Changeset
7
8 alias Pleroma.Object
9 alias Pleroma.User
10
11 def validate_recipients_presence(cng, fields \\ [:to, :cc]) do
12 non_empty =
13 fields
14 |> Enum.map(fn field -> get_field(cng, field) end)
15 |> Enum.any?(fn
16 [] -> false
17 _ -> true
18 end)
19
20 if non_empty do
21 cng
22 else
23 fields
24 |> Enum.reduce(cng, fn field, cng ->
25 cng
26 |> add_error(field, "no recipients in any field")
27 end)
28 end
29 end
30
31 def validate_actor_presence(cng, options \\ []) do
32 field_name = Keyword.get(options, :field_name, :actor)
33
34 cng
35 |> validate_change(field_name, fn field_name, actor ->
36 if User.get_cached_by_ap_id(actor) do
37 []
38 else
39 [{field_name, "can't find user"}]
40 end
41 end)
42 end
43
44 def validate_object_presence(cng, options \\ []) do
45 field_name = Keyword.get(options, :field_name, :object)
46 allowed_types = Keyword.get(options, :allowed_types, false)
47
48 cng
49 |> validate_change(field_name, fn field_name, object_id ->
50 object = Object.get_cached_by_ap_id(object_id)
51
52 cond do
53 !object ->
54 [{field_name, "can't find object"}]
55
56 object && allowed_types && object.data["type"] not in allowed_types ->
57 [{field_name, "object not in allowed types"}]
58
59 true ->
60 []
61 end
62 end)
63 end
64
65 def validate_object_or_user_presence(cng, options \\ []) do
66 field_name = Keyword.get(options, :field_name, :object)
67 options = Keyword.put(options, :field_name, field_name)
68
69 actor_cng =
70 cng
71 |> validate_actor_presence(options)
72
73 object_cng =
74 cng
75 |> validate_object_presence(options)
76
77 if actor_cng.valid?, do: actor_cng, else: object_cng
78 end
79 end