1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2019 Pleroma Authors <https://pleroma.social/>
3 # SPDX-License-Identifier: AGPL-3.0-only
5 defmodule Pleroma.Object do
10 alias Pleroma.Object.Fetcher
11 alias Pleroma.ObjectTombstone
20 @type t() :: %__MODULE__{}
28 def with_joined_activity(query, activity_type \\ "Create", join_type \\ :inner) do
29 object_position = Map.get(query.aliases, :object, 0)
31 join(query, join_type, [{object, object_position}], a in Activity,
34 "COALESCE(?->'object'->>'id', ?->>'object') = (? ->> 'id') AND (?->>'type' = ?) ",
46 Object.change(%Object{}, %{data: data})
50 def change(struct, params \\ %{}) do
52 |> cast(params, [:data])
53 |> validate_required([:data])
54 |> unique_constraint(:ap_id, name: :objects_unique_apid_index)
57 def get_by_id(nil), do: nil
58 def get_by_id(id), do: Repo.get(Object, id)
60 def get_by_id_and_maybe_refetch(id, opts \\ []) do
61 %{updated_at: updated_at} = object = get_by_id(id)
64 NaiveDateTime.diff(NaiveDateTime.utc_now(), updated_at) > opts[:interval] do
65 case Fetcher.refetch_object(object) do
66 {:ok, %Object{} = object} ->
70 Logger.error("Couldn't refresh #{object.data["id"]}:\n#{inspect(e)}")
78 def get_by_ap_id(nil), do: nil
80 def get_by_ap_id(ap_id) do
81 Repo.one(from(object in Object, where: fragment("(?)->>'id' = ?", object.data, ^ap_id)))
85 Get a single attachment by it's name and href
87 @spec get_attachment_by_name_and_href(String.t(), String.t()) :: Object.t() | nil
88 def get_attachment_by_name_and_href(name, href) do
91 where: fragment("(?)->>'name' = ?", o.data, ^name),
92 where: fragment("(?)->>'href' = ?", o.data, ^href)
98 defp warn_on_no_object_preloaded(ap_id) do
99 "Object.normalize() called without preloaded object (#{inspect(ap_id)}). Consider preloading the object"
102 Logger.debug("Backtrace: #{inspect(Process.info(:erlang.self(), :current_stacktrace))}")
105 def normalize(_, fetch_remote \\ true, options \\ [])
107 # If we pass an Activity to Object.normalize(), we can try to use the preloaded object.
108 # Use this whenever possible, especially when walking graphs in an O(N) loop!
109 def normalize(%Object{} = object, _, _), do: object
110 def normalize(%Activity{object: %Object{} = object}, _, _), do: object
112 # A hack for fake activities
113 def normalize(%Activity{data: %{"object" => %{"fake" => true} = data}}, _, _) do
114 %Object{id: "pleroma:fake_object_id", data: data}
117 # No preloaded object
118 def normalize(%Activity{data: %{"object" => %{"id" => ap_id}}}, fetch_remote, _) do
119 warn_on_no_object_preloaded(ap_id)
120 normalize(ap_id, fetch_remote)
123 # No preloaded object
124 def normalize(%Activity{data: %{"object" => ap_id}}, fetch_remote, _) do
125 warn_on_no_object_preloaded(ap_id)
126 normalize(ap_id, fetch_remote)
129 # Old way, try fetching the object through cache.
130 def normalize(%{"id" => ap_id}, fetch_remote, _), do: normalize(ap_id, fetch_remote)
131 def normalize(ap_id, false, _) when is_binary(ap_id), do: get_cached_by_ap_id(ap_id)
133 def normalize(ap_id, true, options) when is_binary(ap_id) do
134 Fetcher.fetch_object_from_id!(ap_id, options)
137 def normalize(_, _, _), do: nil
139 # Owned objects can only be mutated by their owner
140 def authorize_mutation(%Object{data: %{"actor" => actor}}, %User{ap_id: ap_id}),
143 # Legacy objects can be mutated by anybody
144 def authorize_mutation(%Object{}, %User{}), do: true
146 def get_cached_by_ap_id(ap_id) do
147 key = "object:#{ap_id}"
149 Cachex.fetch!(:object_cache, key, fn _ ->
150 object = get_by_ap_id(ap_id)
160 def context_mapping(context) do
161 Object.change(%Object{}, %{data: %{"id" => context}})
164 def make_tombstone(%Object{data: %{"id" => id, "type" => type}}, deleted \\ DateTime.utc_now()) do
173 def swap_object_with_tombstone(object) do
174 tombstone = make_tombstone(object)
177 |> Object.change(%{data: tombstone})
181 def delete(%Object{data: %{"id" => id}} = object) do
182 with {:ok, _obj} = swap_object_with_tombstone(object),
183 :ok <- delete_attachments(object),
184 deleted_activity = Activity.delete_all_by_object_ap_id(id),
185 {:ok, true} <- Cachex.del(:object_cache, "object:#{id}"),
186 {:ok, _} <- Cachex.del(:web_resp_cache, URI.parse(id).path) do
187 {:ok, object, deleted_activity}
191 defp delete_attachments(%{data: %{"attachment" => [_ | _] = attachments, "actor" => actor}}) do
193 Enum.flat_map(attachments, fn attachment ->
194 Enum.map(attachment["url"], & &1["href"])
197 names = Enum.map(attachments, & &1["name"])
199 uploader = Pleroma.Config.get([Pleroma.Upload, :uploader])
201 # find all objects for copies of the attachments, name and actor doesn't matter here
206 "to_jsonb(array(select jsonb_array_elements((?)#>'{url}') ->> 'href'))::jsonb \\?| (?)",
212 # we should delete 1 object for any given attachment, but don't delete files if
213 # there are more than 1 object for it
214 |> Enum.reduce(%{}, fn %{
217 "url" => [%{"href" => href}],
218 "actor" => obj_actor,
223 Map.update(acc, href, %{id: id, count: 1}, fn val ->
224 case obj_actor == actor and name in names do
226 # set id of the actor's object that will be deleted
227 %{val | id: id, count: val.count + 1}
230 # another actor's object, just increase count to not delete file
231 %{val | count: val.count + 1}
235 |> Enum.map(fn {href, %{id: id, count: count}} ->
236 # only delete files that have single instance
239 case Pleroma.Config.get([Pleroma.Upload, :base_url]) do
244 base_url = Pleroma.Config.get([__MODULE__, :base_url], Pleroma.Web.base_url())
246 file_path = String.trim_leading(href, "#{base_url}/#{prefix}")
248 uploader.delete_file(file_path)
254 from(o in Object, where: o.id in ^delete_ids)
260 defp delete_attachments(%{data: _data}), do: :ok
262 def prune(%Object{data: %{"id" => id}} = object) do
263 with {:ok, object} <- Repo.delete(object),
264 {:ok, true} <- Cachex.del(:object_cache, "object:#{id}"),
265 {:ok, _} <- Cachex.del(:web_resp_cache, URI.parse(id).path) do
270 def set_cache(%Object{data: %{"id" => ap_id}} = object) do
271 Cachex.put(:object_cache, "object:#{ap_id}", object)
275 def update_and_set_cache(changeset) do
276 with {:ok, object} <- Repo.update(changeset) do
281 def increase_replies_count(ap_id) do
283 |> where([o], fragment("?->>'id' = ?::text", o.data, ^to_string(ap_id)))
289 safe_jsonb_set(?, '{repliesCount}',
290 (coalesce((?->>'repliesCount')::int, 0) + 1)::varchar::jsonb, true)
297 |> Repo.update_all([])
299 {1, [object]} -> set_cache(object)
300 _ -> {:error, "Not found"}
304 def decrease_replies_count(ap_id) do
306 |> where([o], fragment("?->>'id' = ?::text", o.data, ^to_string(ap_id)))
312 safe_jsonb_set(?, '{repliesCount}',
313 (greatest(0, (?->>'repliesCount')::int - 1))::varchar::jsonb, true)
320 |> Repo.update_all([])
322 {1, [object]} -> set_cache(object)
323 _ -> {:error, "Not found"}
327 def increase_vote_count(ap_id, name) do
328 with %Object{} = object <- Object.normalize(ap_id),
329 "Question" <- object.data["type"] do
330 multiple = Map.has_key?(object.data, "anyOf")
333 (object.data["anyOf"] || object.data["oneOf"] || [])
335 %{"name" => ^name} = option ->
336 Kernel.update_in(option["replies"]["totalItems"], &(&1 + 1))
344 Map.put(object.data, "anyOf", options)
346 Map.put(object.data, "oneOf", options)
350 |> Object.change(%{data: data})
351 |> update_and_set_cache()
357 @doc "Updates data field of an object"
358 def update_data(%Object{data: data} = object, attrs \\ %{}) do
360 |> Object.change(%{data: Map.merge(data || %{}, attrs)})
364 def local?(%Object{data: %{"id" => id}}) do
365 String.starts_with?(id, Pleroma.Web.base_url() <> "/")