fix emoji tests
[akkoma] / lib / pleroma / web / activity_pub / object_validators / emoji_react_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.EmojiReactValidator do
6 use Ecto.Schema
7
8 alias Pleroma.Emoji
9 alias Pleroma.Object
10 alias Pleroma.Web.ActivityPub.ObjectValidators.CommonFixes
11
12 import Ecto.Changeset
13 import Pleroma.Web.ActivityPub.ObjectValidators.CommonValidations
14
15 @primary_key false
16 @emoji_regex ~r/:[A-Za-z_-]+:/
17
18 embedded_schema do
19 quote do
20 unquote do
21 import Elixir.Pleroma.Web.ActivityPub.ObjectValidators.CommonFields
22 message_fields()
23 activity_fields()
24 tag_fields()
25 end
26 end
27
28 field(:context, :string)
29 field(:content, :string)
30 end
31
32 def cast_and_validate(data) do
33 data
34 |> cast_data()
35 |> validate_data()
36 end
37
38 def cast_data(data) do
39 data =
40 data
41 |> fix()
42
43 %__MODULE__{}
44 |> changeset(data)
45 end
46
47 def changeset(struct, data) do
48 struct
49 |> cast(data, __schema__(:fields) -- [:tag])
50 |> cast_embed(:tag)
51 end
52
53 defp fix(data) do
54 data =
55 data
56 |> CommonFixes.fix_actor()
57 |> CommonFixes.fix_activity_addressing()
58
59 data =
60 if Map.has_key?(data, "tag") do
61 data
62 else
63 Map.put(data, "tag", [])
64 end
65
66 case Object.normalize(data["object"]) do
67 %Object{} = object ->
68 data
69 |> CommonFixes.fix_activity_context(object)
70 |> CommonFixes.fix_object_action_recipients(object)
71
72 _ ->
73 data
74 end
75 end
76
77 defp matches_shortcode?(nil), do: false
78 defp matches_shortcode?(s), do: Regex.match?(@emoji_regex, s)
79
80 defp validate_emoji(cng) do
81 content = get_field(cng, :content)
82
83 if Emoji.is_unicode_emoji?(content) || matches_shortcode?(content) do
84 cng
85 else
86 cng
87 |> add_error(:content, "is not a valid emoji")
88 end
89 end
90
91 defp maybe_validate_tag_presence(cng) do
92 content = get_field(cng, :content)
93
94 if Emoji.is_unicode_emoji?(content) do
95 cng
96 else
97 tag = get_field(cng, :tag)
98 emoji_name = Emoji.stripped_name(content)
99 case tag do
100 [%{name: ^emoji_name, type: "Emoji", icon: %{url: _}}] ->
101 cng
102 _ ->
103 cng
104 |> add_error(:tag, "does not contain an Emoji tag")
105 end
106 end
107 end
108
109 defp validate_data(data_cng) do
110 data_cng
111 |> validate_inclusion(:type, ["EmojiReact"])
112 |> validate_required([:id, :type, :object, :actor, :context, :to, :cc, :content])
113 |> validate_actor_presence()
114 |> validate_object_presence()
115 |> validate_emoji()
116 |> maybe_validate_tag_presence()
117 end
118 end