Merge remote-tracking branch 'remotes/upstream/develop' into 1335-user-api-id-fields...
[akkoma] / lib / pleroma / web / activity_pub / relay.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.Web.ActivityPub.Relay do
6 alias Pleroma.Activity
7 alias Pleroma.Object
8 alias Pleroma.User
9 alias Pleroma.Web.ActivityPub.ActivityPub
10 require Logger
11
12 def get_actor do
13 actor =
14 relay_ap_id()
15 |> User.get_or_create_service_actor_by_ap_id()
16
17 actor
18 end
19
20 def relay_ap_id do
21 "#{Pleroma.Web.Endpoint.url()}/relay"
22 end
23
24 @spec follow(String.t()) :: {:ok, Activity.t()} | {:error, any()}
25 def follow(target_instance) do
26 with %User{} = local_user <- get_actor(),
27 {:ok, %User{} = target_user} <- User.get_or_fetch_by_ap_id(target_instance),
28 {:ok, activity} <- ActivityPub.follow(local_user, target_user) do
29 Logger.info("relay: followed instance: #{target_instance}; id=#{activity.data["id"]}")
30 {:ok, activity}
31 else
32 error -> format_error(error)
33 end
34 end
35
36 @spec unfollow(String.t()) :: {:ok, Activity.t()} | {:error, any()}
37 def unfollow(target_instance) do
38 with %User{} = local_user <- get_actor(),
39 {:ok, %User{} = target_user} <- User.get_or_fetch_by_ap_id(target_instance),
40 {:ok, activity} <- ActivityPub.unfollow(local_user, target_user) do
41 User.unfollow(local_user, target_user)
42 Logger.info("relay: unfollowed instance: #{target_instance}: id=#{activity.data["id"]}")
43 {:ok, activity}
44 else
45 error -> format_error(error)
46 end
47 end
48
49 @spec publish(any()) :: {:ok, Activity.t(), Object.t()} | {:error, any()}
50 def publish(%Activity{data: %{"type" => "Create"}} = activity) do
51 with %User{} = user <- get_actor(),
52 %Object{} = object <- Object.normalize(activity) do
53 ActivityPub.announce(user, object, nil, true, false)
54 else
55 error -> format_error(error)
56 end
57 end
58
59 def publish(_), do: {:error, "Not implemented"}
60
61 @spec list() :: {:ok, [String.t()]} | {:error, any()}
62 def list do
63 with %User{} = user <- get_actor() do
64 list =
65 user
66 |> User.following()
67 |> Enum.map(fn entry -> URI.parse(entry).host end)
68 |> Enum.uniq()
69
70 {:ok, list}
71 else
72 error -> format_error(error)
73 end
74 end
75
76 defp format_error({:error, error}), do: format_error(error)
77
78 defp format_error(error) do
79 Logger.error("error: #{inspect(error)}")
80 {:error, error}
81 end
82 end