200addd6ebdba96a600c4a46816dd7b7559bb421
[akkoma] / lib / pleroma / activity.ex
1 defmodule Pleroma.Activity do
2 use Ecto.Schema
3 alias Pleroma.{Repo, Activity, Notification}
4 import Ecto.Query
5
6 # https://github.com/tootsuite/mastodon/blob/master/app/models/notification.rb#L19
7 @mastodon_notification_types %{
8 "Create" => "mention",
9 "Follow" => "follow",
10 "Announce" => "reblog",
11 "Like" => "favourite"
12 }
13
14 schema "activities" do
15 field(:data, :map)
16 field(:local, :boolean, default: true)
17 field(:actor, :string)
18 field(:recipients, {:array, :string})
19 has_many(:notifications, Notification, on_delete: :delete_all)
20
21 timestamps()
22 end
23
24 def get_by_ap_id(ap_id) do
25 Repo.one(
26 from(
27 activity in Activity,
28 where: fragment("(?)->>'id' = ?", activity.data, ^to_string(ap_id))
29 )
30 )
31 end
32
33 # TODO:
34 # Go through these and fix them everywhere.
35 # Wrong name, only returns create activities
36 def all_by_object_ap_id_q(ap_id) do
37 from(
38 activity in Activity,
39 where:
40 fragment(
41 "coalesce((?)->'object'->>'id', (?)->>'object') = ?",
42 activity.data,
43 activity.data,
44 ^to_string(ap_id)
45 ),
46 where: fragment("(?)->>'type' = 'Create'", activity.data)
47 )
48 end
49
50 # Wrong name, returns all.
51 def all_non_create_by_object_ap_id_q(ap_id) do
52 from(
53 activity in Activity,
54 where:
55 fragment(
56 "coalesce((?)->'object'->>'id', (?)->>'object') = ?",
57 activity.data,
58 activity.data,
59 ^to_string(ap_id)
60 )
61 )
62 end
63
64 # Wrong name plz fix thx
65 def all_by_object_ap_id(ap_id) do
66 Repo.all(all_by_object_ap_id_q(ap_id))
67 end
68
69 def create_activity_by_object_id_query(ap_ids) do
70 from(
71 activity in Activity,
72 where:
73 fragment(
74 "coalesce((?)->'object'->>'id', (?)->>'object') = ANY(?)",
75 activity.data,
76 activity.data,
77 ^ap_ids
78 ),
79 where: fragment("(?)->>'type' = 'Create'", activity.data)
80 )
81 end
82
83 def get_create_activity_by_object_ap_id(ap_id) when is_binary(ap_id) do
84 create_activity_by_object_id_query([ap_id])
85 |> Repo.one()
86 end
87
88 def get_create_activity_by_object_ap_id(_), do: nil
89
90 def normalize(obj) when is_map(obj), do: Activity.get_by_ap_id(obj["id"])
91 def normalize(ap_id) when is_binary(ap_id), do: Activity.get_by_ap_id(ap_id)
92 def normalize(_), do: nil
93
94 def get_in_reply_to_activity(%Activity{data: %{"object" => %{"inReplyTo" => ap_id}}}) do
95 get_create_activity_by_object_ap_id(ap_id)
96 end
97
98 def get_in_reply_to_activity(_), do: nil
99
100 for {ap_type, type} <- @mastodon_notification_types do
101 def mastodon_notification_type(%Activity{data: %{"type" => unquote(ap_type)}}),
102 do: unquote(type)
103 end
104
105 def mastodon_notification_type(%Activity{}), do: nil
106 end