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