Merge remote-tracking branch 'origin/develop' into remote-follow-api
[akkoma] / lib / pleroma / web / activity_pub / object_validators / like_validator.ex
1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>
3 # SPDX-License-Identifier: AGPL-3.0-only
4
5 defmodule Pleroma.Web.ActivityPub.ObjectValidators.LikeValidator do
6 use Ecto.Schema
7
8 alias Pleroma.Object
9 alias Pleroma.Web.ActivityPub.ObjectValidators.CommonFixes
10 alias Pleroma.Web.ActivityPub.Utils
11
12 import Ecto.Changeset
13 import Pleroma.Web.ActivityPub.ObjectValidators.CommonValidations
14
15 @primary_key false
16
17 embedded_schema do
18 quote do
19 unquote do
20 import Elixir.Pleroma.Web.ActivityPub.ObjectValidators.CommonFields
21 message_fields()
22 activity_fields()
23 end
24 end
25
26 field(:context, :string)
27 end
28
29 def cast_and_validate(data) do
30 data
31 |> cast_data()
32 |> validate_data()
33 end
34
35 def cast_data(data) do
36 data =
37 data
38 |> fix()
39
40 %__MODULE__{}
41 |> changeset(data)
42 end
43
44 def changeset(struct, data) do
45 struct
46 |> cast(data, __schema__(:fields))
47 end
48
49 defp fix(data) do
50 data =
51 data
52 |> CommonFixes.fix_actor()
53 |> CommonFixes.fix_activity_addressing()
54
55 with %Object{} = object <- Object.normalize(data["object"]) do
56 data
57 |> CommonFixes.fix_activity_context(object)
58 |> CommonFixes.fix_object_action_recipients(object)
59 else
60 _ -> data
61 end
62 end
63
64 defp validate_data(data_cng) do
65 data_cng
66 |> validate_inclusion(:type, ["Like"])
67 |> validate_required([:id, :type, :object, :actor, :context, :to, :cc])
68 |> validate_actor_presence()
69 |> validate_object_presence()
70 |> validate_existing_like()
71 end
72
73 defp validate_existing_like(%{changes: %{actor: actor, object: object}} = cng) do
74 if Utils.get_existing_like(actor, %{data: %{"id" => object}}) do
75 cng
76 |> add_error(:actor, "already liked this object")
77 |> add_error(:object, "already liked by this actor")
78 else
79 cng
80 end
81 end
82
83 defp validate_existing_like(cng), do: cng
84 end