Merge develop branch upstream
[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.EctoType.ActivityPub.ObjectValidators
9 alias Pleroma.Object
10 alias Pleroma.Web.ActivityPub.ObjectValidators.CommonFixes
11 alias Pleroma.Web.ActivityPub.Utils
12
13 import Ecto.Changeset
14 import Pleroma.Web.ActivityPub.ObjectValidators.CommonValidations
15
16 @primary_key false
17
18 embedded_schema do
19 field(:id, ObjectValidators.ObjectID, primary_key: true)
20 field(:type, :string)
21 field(:object, ObjectValidators.ObjectID)
22 field(:actor, ObjectValidators.ObjectID)
23 field(:context, :string)
24 field(:to, ObjectValidators.Recipients, default: [])
25 field(:cc, ObjectValidators.Recipients, default: [])
26 end
27
28 def cast_and_validate(data) do
29 data
30 |> cast_data()
31 |> validate_data()
32 end
33
34 def cast_data(data) do
35 data =
36 data
37 |> fix()
38
39 %__MODULE__{}
40 |> changeset(data)
41 end
42
43 def changeset(struct, data) do
44 struct
45 |> cast(data, __schema__(:fields))
46 end
47
48 defp fix(data) do
49 data =
50 data
51 |> CommonFixes.fix_actor()
52 |> CommonFixes.fix_activity_addressing()
53
54 with %Object{} = object <- Object.normalize(data["object"]) do
55 data
56 |> CommonFixes.fix_activity_context(object)
57 |> CommonFixes.fix_object_action_recipients(object)
58 else
59 _ -> data
60 end
61 end
62
63 defp validate_data(data_cng) do
64 data_cng
65 |> validate_inclusion(:type, ["Like"])
66 |> validate_required([:id, :type, :object, :actor, :context, :to, :cc])
67 |> validate_actor_presence()
68 |> validate_object_presence()
69 |> validate_existing_like()
70 end
71
72 defp validate_existing_like(%{changes: %{actor: actor, object: object}} = cng) do
73 if Utils.get_existing_like(actor, %{data: %{"id" => object}}) do
74 cng
75 |> add_error(:actor, "already liked this object")
76 |> add_error(:object, "already liked by this actor")
77 else
78 cng
79 end
80 end
81
82 defp validate_existing_like(cng), do: cng
83 end