QuestionValidator: Create
[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.Activity
9 alias Pleroma.Object
10 alias Pleroma.User
11
12 def validate_any_presence(cng, fields) do
13 non_empty =
14 fields
15 |> Enum.map(fn field -> get_field(cng, field) end)
16 |> Enum.any?(fn
17 [] -> false
18 _ -> true
19 end)
20
21 if non_empty do
22 cng
23 else
24 fields
25 |> Enum.reduce(cng, fn field, cng ->
26 cng
27 |> add_error(field, "none of #{inspect(fields)} present")
28 end)
29 end
30 end
31
32 def validate_actor_presence(cng, options \\ []) do
33 field_name = Keyword.get(options, :field_name, :actor)
34
35 cng
36 |> validate_change(field_name, fn field_name, actor ->
37 if User.get_cached_by_ap_id(actor) do
38 []
39 else
40 [{field_name, "can't find user"}]
41 end
42 end)
43 end
44
45 def validate_object_presence(cng, options \\ []) do
46 field_name = Keyword.get(options, :field_name, :object)
47 allowed_types = Keyword.get(options, :allowed_types, false)
48
49 cng
50 |> validate_change(field_name, fn field_name, object_id ->
51 object = Object.get_cached_by_ap_id(object_id) || Activity.get_by_ap_id(object_id)
52
53 cond do
54 !object ->
55 [{field_name, "can't find object"}]
56
57 object && allowed_types && object.data["type"] not in allowed_types ->
58 [{field_name, "object not in allowed types"}]
59
60 true ->
61 []
62 end
63 end)
64 end
65
66 def validate_object_or_user_presence(cng, options \\ []) do
67 field_name = Keyword.get(options, :field_name, :object)
68 options = Keyword.put(options, :field_name, field_name)
69
70 actor_cng =
71 cng
72 |> validate_actor_presence(options)
73
74 object_cng =
75 cng
76 |> validate_object_presence(options)
77
78 if actor_cng.valid?, do: actor_cng, else: object_cng
79 end
80 end