19d9c51af2ee7646520d3d65580d24d507ca4de2
[akkoma] / lib / pleroma / object / fetcher.ex
1 defmodule Pleroma.Object.Fetcher do
2 alias Pleroma.Object
3 alias Pleroma.Object.Containment
4 alias Pleroma.Web.ActivityPub.Transmogrifier
5 alias Pleroma.Web.OStatus
6
7 require Logger
8
9 @httpoison Application.get_env(:pleroma, :httpoison)
10
11 # TODO:
12 # This will create a Create activity, which we need internally at the moment.
13 def fetch_object_from_id(id) do
14 if object = Object.get_cached_by_ap_id(id) do
15 {:ok, object}
16 else
17 Logger.info("Fetching #{id} via AP")
18
19 with {:ok, data} <- fetch_and_contain_remote_object_from_id(id),
20 nil <- Object.normalize(data, false),
21 params <- %{
22 "type" => "Create",
23 "to" => data["to"],
24 "cc" => data["cc"],
25 "actor" => data["actor"] || data["attributedTo"],
26 "object" => data
27 },
28 :ok <- Containment.contain_origin(id, params),
29 {:ok, activity} <- Transmogrifier.handle_incoming(params) do
30 {:ok, Object.normalize(activity.data["object"], false)}
31 else
32 {:error, {:reject, nil}} ->
33 {:reject, nil}
34
35 object = %Object{} ->
36 {:ok, object}
37
38 _e ->
39 Logger.info("Couldn't get object via AP, trying out OStatus fetching...")
40
41 case OStatus.fetch_activity_from_url(id) do
42 {:ok, [activity | _]} -> {:ok, Object.normalize(activity.data["object"], false)}
43 e -> e
44 end
45 end
46 end
47 end
48
49 def fetch_object_from_id!(id) do
50 with {:ok, object} <- fetch_object_from_id(id) do
51 object
52 else
53 _e ->
54 nil
55 end
56 end
57
58 def fetch_and_contain_remote_object_from_id(id) do
59 Logger.info("Fetching #{id} via AP")
60
61 with true <- String.starts_with?(id, "http"),
62 {:ok, %{body: body, status_code: code}} when code in 200..299 <-
63 @httpoison.get(
64 id,
65 [Accept: "application/activity+json"],
66 follow_redirect: true,
67 timeout: 10000,
68 recv_timeout: 20000
69 ),
70 {:ok, data} <- Jason.decode(body),
71 :ok <- Containment.contain_origin_from_id(id, data) do
72 {:ok, data}
73 else
74 e ->
75 {:error, e}
76 end
77 end
78 end