Merge branch 'replies-count' into 'develop'
[akkoma] / lib / pleroma / object.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.Object do
6 use Ecto.Schema
7
8 alias Pleroma.Activity
9 alias Pleroma.Object
10 alias Pleroma.ObjectTombstone
11 alias Pleroma.Repo
12 alias Pleroma.User
13
14 import Ecto.Query
15 import Ecto.Changeset
16
17 require Logger
18
19 schema "objects" do
20 field(:data, :map)
21
22 timestamps()
23 end
24
25 def create(data) do
26 Object.change(%Object{}, %{data: data})
27 |> Repo.insert()
28 end
29
30 def change(struct, params \\ %{}) do
31 struct
32 |> cast(params, [:data])
33 |> validate_required([:data])
34 |> unique_constraint(:ap_id, name: :objects_unique_apid_index)
35 end
36
37 def get_by_ap_id(nil), do: nil
38
39 def get_by_ap_id(ap_id) do
40 Repo.one(from(object in Object, where: fragment("(?)->>'id' = ?", object.data, ^ap_id)))
41 end
42
43 # If we pass an Activity to Object.normalize(), we can try to use the preloaded object.
44 # Use this whenever possible, especially when walking graphs in an O(N) loop!
45 def normalize(%Activity{object: %Object{} = object}), do: object
46
47 # Catch and log Object.normalize() calls where the Activity's child object is not
48 # preloaded.
49 def normalize(%Activity{data: %{"object" => %{"id" => ap_id}}}) do
50 Logger.debug(
51 "Object.normalize() called without preloaded object (#{ap_id}). Consider preloading the object!"
52 )
53
54 Logger.debug("Backtrace: #{inspect(Process.info(:erlang.self(), :current_stacktrace))}")
55
56 normalize(ap_id)
57 end
58
59 def normalize(%Activity{data: %{"object" => ap_id}}) do
60 Logger.debug(
61 "Object.normalize() called without preloaded object (#{ap_id}). Consider preloading the object!"
62 )
63
64 Logger.debug("Backtrace: #{inspect(Process.info(:erlang.self(), :current_stacktrace))}")
65
66 normalize(ap_id)
67 end
68
69 # Old way, try fetching the object through cache.
70 def normalize(%{"id" => ap_id}), do: normalize(ap_id)
71 def normalize(ap_id) when is_binary(ap_id), do: get_cached_by_ap_id(ap_id)
72 def normalize(_), do: nil
73
74 # Owned objects can only be mutated by their owner
75 def authorize_mutation(%Object{data: %{"actor" => actor}}, %User{ap_id: ap_id}),
76 do: actor == ap_id
77
78 # Legacy objects can be mutated by anybody
79 def authorize_mutation(%Object{}, %User{}), do: true
80
81 def get_cached_by_ap_id(ap_id) do
82 key = "object:#{ap_id}"
83
84 Cachex.fetch!(:object_cache, key, fn _ ->
85 object = get_by_ap_id(ap_id)
86
87 if object do
88 {:commit, object}
89 else
90 {:ignore, object}
91 end
92 end)
93 end
94
95 def context_mapping(context) do
96 Object.change(%Object{}, %{data: %{"id" => context}})
97 end
98
99 def make_tombstone(%Object{data: %{"id" => id, "type" => type}}, deleted \\ DateTime.utc_now()) do
100 %ObjectTombstone{
101 id: id,
102 formerType: type,
103 deleted: deleted
104 }
105 |> Map.from_struct()
106 end
107
108 def swap_object_with_tombstone(object) do
109 tombstone = make_tombstone(object)
110
111 object
112 |> Object.change(%{data: tombstone})
113 |> Repo.update()
114 end
115
116 def delete(%Object{data: %{"id" => id}} = object) do
117 with {:ok, _obj} = swap_object_with_tombstone(object),
118 deleted_activity = Activity.delete_by_ap_id(id),
119 {:ok, true} <- Cachex.del(:object_cache, "object:#{id}") do
120 {:ok, object, deleted_activity}
121 end
122 end
123
124 def set_cache(%Object{data: %{"id" => ap_id}} = object) do
125 Cachex.put(:object_cache, "object:#{ap_id}", object)
126 {:ok, object}
127 end
128
129 def update_and_set_cache(changeset) do
130 with {:ok, object} <- Repo.update(changeset) do
131 set_cache(object)
132 else
133 e -> e
134 end
135 end
136
137 def increase_replies_count(ap_id) do
138 Object
139 |> where([o], fragment("?->>'id' = ?::text", o.data, ^to_string(ap_id)))
140 |> update([o],
141 set: [
142 data:
143 fragment(
144 """
145 jsonb_set(?, '{repliesCount}',
146 (coalesce((?->>'repliesCount')::int, 0) + 1)::varchar::jsonb, true)
147 """,
148 o.data,
149 o.data
150 )
151 ]
152 )
153 |> Repo.update_all([])
154 |> case do
155 {1, [object]} -> set_cache(object)
156 _ -> {:error, "Not found"}
157 end
158 end
159
160 def decrease_replies_count(ap_id) do
161 Object
162 |> where([o], fragment("?->>'id' = ?::text", o.data, ^to_string(ap_id)))
163 |> update([o],
164 set: [
165 data:
166 fragment(
167 """
168 jsonb_set(?, '{repliesCount}',
169 (greatest(0, (?->>'repliesCount')::int - 1))::varchar::jsonb, true)
170 """,
171 o.data,
172 o.data
173 )
174 ]
175 )
176 |> Repo.update_all([])
177 |> case do
178 {1, [object]} -> set_cache(object)
179 _ -> {:error, "Not found"}
180 end
181 end
182 end