Object.Fetcher: Handle error on Containment.contain_origin/2
[akkoma] / lib / pleroma / object / fetcher.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.Fetcher do
6 alias Pleroma.HTTP
7 alias Pleroma.Object
8 alias Pleroma.Object.Containment
9 alias Pleroma.Web.ActivityPub.Transmogrifier
10 alias Pleroma.Web.OStatus
11
12 require Logger
13
14 defp reinject_object(data) do
15 Logger.debug("Reinjecting object #{data["id"]}")
16
17 with data <- Transmogrifier.fix_object(data),
18 {:ok, object} <- Object.create(data) do
19 {:ok, object}
20 else
21 e ->
22 Logger.error("Error while processing object: #{inspect(e)}")
23 {:error, e}
24 end
25 end
26
27 # TODO:
28 # This will create a Create activity, which we need internally at the moment.
29 def fetch_object_from_id(id, options \\ []) do
30 if object = Object.get_cached_by_ap_id(id) do
31 {:ok, object}
32 else
33 Logger.info("Fetching #{id} via AP")
34
35 with {:ok, data} <- fetch_and_contain_remote_object_from_id(id),
36 nil <- Object.normalize(data, false),
37 params <- %{
38 "type" => "Create",
39 "to" => data["to"],
40 "cc" => data["cc"],
41 # TODO: Should we seriously keep this attributedTo thing?
42 "actor" => data["actor"] || data["attributedTo"],
43 "object" => data
44 },
45 :ok <- Containment.contain_origin(id, params),
46 {:ok, activity} <- Transmogrifier.handle_incoming(params, options),
47 {:object, _data, %Object{} = object} <-
48 {:object, data, Object.normalize(activity, false)} do
49 {:ok, object}
50 else
51 {:error, {:reject, nil}} ->
52 {:reject, nil}
53
54 {:object, data, nil} ->
55 reinject_object(data)
56
57 object = %Object{} ->
58 {:ok, object}
59
60 :error ->
61 {:error, "Object containment failed."}
62
63 _e ->
64 Logger.info("Couldn't get object via AP, trying out OStatus fetching...")
65
66 case OStatus.fetch_activity_from_url(id) do
67 {:ok, [activity | _]} -> {:ok, Object.normalize(activity, false)}
68 e -> e
69 end
70 end
71 end
72 end
73
74 def fetch_object_from_id!(id, options \\ []) do
75 with {:ok, object} <- fetch_object_from_id(id, options) do
76 object
77 else
78 _e ->
79 nil
80 end
81 end
82
83 def fetch_and_contain_remote_object_from_id(id) do
84 Logger.info("Fetching object #{id} via AP")
85
86 with true <- String.starts_with?(id, "http"),
87 {:ok, %{body: body, status: code}} when code in 200..299 <-
88 HTTP.get(
89 id,
90 [{:Accept, "application/activity+json"}]
91 ),
92 {:ok, data} <- Jason.decode(body),
93 :ok <- Containment.contain_origin_from_id(id, data) do
94 {:ok, data}
95 else
96 {:ok, %{status: code}} when code in [404, 410] ->
97 {:error, "Object has been deleted"}
98
99 e ->
100 {:error, e}
101 end
102 end
103 end