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