Merge branch 'update-service-files-of-openrc-and-systemd-to-new-recommended-paths...
[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 @primary_key {:id, Pleroma.FlakeId, autogenerate: true}
12
13 # https://github.com/tootsuite/mastodon/blob/master/app/models/notification.rb#L19
14 @mastodon_notification_types %{
15 "Create" => "mention",
16 "Follow" => "follow",
17 "Announce" => "reblog",
18 "Like" => "favourite"
19 }
20
21 schema "activities" do
22 field(:data, :map)
23 field(:local, :boolean, default: true)
24 field(:actor, :string)
25 field(:recipients, {:array, :string})
26 has_many(:notifications, Notification, on_delete: :delete_all)
27
28 timestamps()
29 end
30
31 def get_by_ap_id(ap_id) do
32 Repo.one(
33 from(
34 activity in Activity,
35 where: fragment("(?)->>'id' = ?", activity.data, ^to_string(ap_id))
36 )
37 )
38 end
39
40 def get_by_id(id) do
41 Repo.get(Activity, id)
42 end
43
44 def by_object_ap_id(ap_id) do
45 from(
46 activity in Activity,
47 where:
48 fragment(
49 "coalesce((?)->'object'->>'id', (?)->>'object') = ?",
50 activity.data,
51 activity.data,
52 ^to_string(ap_id)
53 )
54 )
55 end
56
57 def create_by_object_ap_id(ap_ids) when is_list(ap_ids) do
58 from(
59 activity in Activity,
60 where:
61 fragment(
62 "coalesce((?)->'object'->>'id', (?)->>'object') = ANY(?)",
63 activity.data,
64 activity.data,
65 ^ap_ids
66 ),
67 where: fragment("(?)->>'type' = 'Create'", activity.data)
68 )
69 end
70
71 def create_by_object_ap_id(ap_id) do
72 from(
73 activity in Activity,
74 where:
75 fragment(
76 "coalesce((?)->'object'->>'id', (?)->>'object') = ?",
77 activity.data,
78 activity.data,
79 ^to_string(ap_id)
80 ),
81 where: fragment("(?)->>'type' = 'Create'", activity.data)
82 )
83 end
84
85 def get_all_create_by_object_ap_id(ap_id) do
86 Repo.all(create_by_object_ap_id(ap_id))
87 end
88
89 def get_create_by_object_ap_id(ap_id) when is_binary(ap_id) do
90 create_by_object_ap_id(ap_id)
91 |> Repo.one()
92 end
93
94 def get_create_by_object_ap_id(_), do: nil
95
96 def normalize(obj) when is_map(obj), do: Activity.get_by_ap_id(obj["id"])
97 def normalize(ap_id) when is_binary(ap_id), do: Activity.get_by_ap_id(ap_id)
98 def normalize(_), do: nil
99
100 def get_in_reply_to_activity(%Activity{data: %{"object" => %{"inReplyTo" => ap_id}}}) do
101 get_create_by_object_ap_id(ap_id)
102 end
103
104 def get_in_reply_to_activity(_), do: nil
105
106 for {ap_type, type} <- @mastodon_notification_types do
107 def mastodon_notification_type(%Activity{data: %{"type" => unquote(ap_type)}}),
108 do: unquote(type)
109 end
110
111 def mastodon_notification_type(%Activity{}), do: nil
112 end