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