Merge branch 's3-namespace' into 'develop'
[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 get_by_id(id) do
40 Repo.get(Activity, id)
41 end
42
43 def by_object_ap_id(ap_id) do
44 from(
45 activity in Activity,
46 where:
47 fragment(
48 "coalesce((?)->'object'->>'id', (?)->>'object') = ?",
49 activity.data,
50 activity.data,
51 ^to_string(ap_id)
52 )
53 )
54 end
55
56 def create_by_object_ap_id(ap_ids) when is_list(ap_ids) do
57 from(
58 activity in Activity,
59 where:
60 fragment(
61 "coalesce((?)->'object'->>'id', (?)->>'object') = ANY(?)",
62 activity.data,
63 activity.data,
64 ^ap_ids
65 ),
66 where: fragment("(?)->>'type' = 'Create'", activity.data)
67 )
68 end
69
70 def create_by_object_ap_id(ap_id) do
71 from(
72 activity in Activity,
73 where:
74 fragment(
75 "coalesce((?)->'object'->>'id', (?)->>'object') = ?",
76 activity.data,
77 activity.data,
78 ^to_string(ap_id)
79 ),
80 where: fragment("(?)->>'type' = 'Create'", activity.data)
81 )
82 end
83
84 def get_all_create_by_object_ap_id(ap_id) do
85 Repo.all(create_by_object_ap_id(ap_id))
86 end
87
88 def get_create_by_object_ap_id(ap_id) when is_binary(ap_id) do
89 create_by_object_ap_id(ap_id)
90 |> Repo.one()
91 end
92
93 def get_create_by_object_ap_id(_), do: nil
94
95 def normalize(obj) when is_map(obj), do: Activity.get_by_ap_id(obj["id"])
96 def normalize(ap_id) when is_binary(ap_id), do: Activity.get_by_ap_id(ap_id)
97 def normalize(_), do: nil
98
99 def get_in_reply_to_activity(%Activity{data: %{"object" => %{"inReplyTo" => ap_id}}}) do
100 get_create_by_object_ap_id(ap_id)
101 end
102
103 def get_in_reply_to_activity(_), do: nil
104
105 for {ap_type, type} <- @mastodon_notification_types do
106 def mastodon_notification_type(%Activity{data: %{"type" => unquote(ap_type)}}),
107 do: unquote(type)
108 end
109
110 def mastodon_notification_type(%Activity{}), do: nil
111 end