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