[#534] Updating external instances reachability on incoming federation.
[akkoma] / lib / pleroma / instances / instance.ex
1 defmodule Pleroma.Instances.Instance do
2 @moduledoc "Instance."
3
4 alias Pleroma.Instances
5 alias Pleroma.Instances.Instance
6
7 use Ecto.Schema
8
9 import Ecto.{Query, Changeset}
10
11 alias Pleroma.Repo
12
13 schema "instances" do
14 field(:host, :string)
15 field(:unreachable_since, :naive_datetime)
16 field(:reachability_checked_at, :naive_datetime)
17
18 timestamps()
19 end
20
21 def update_changeset(struct, params \\ %{}) do
22 struct
23 |> cast(params, [:host, :unreachable_since, :reachability_checked_at])
24 |> unique_constraint(:host)
25 end
26
27 def reachable?(url) when is_binary(url) do
28 !Repo.one(
29 from(i in Instance,
30 where:
31 i.host == ^host(url) and i.unreachable_since <= ^Instances.reachability_time_threshold(),
32 select: true
33 )
34 )
35 end
36
37 def reachable?(_), do: true
38
39 def set_reachable(url) when is_binary(url) do
40 Repo.update_all(
41 from(i in Instance, where: i.host == ^host(url)),
42 set: [
43 unreachable_since: nil,
44 reachability_checked_at: DateTime.utc_now()
45 ]
46 )
47 end
48
49 def set_reachable(_), do: {0, :noop}
50
51 def set_unreachable(url, unreachable_since \\ nil)
52
53 def set_unreachable(url, unreachable_since) when is_binary(url) do
54 unreachable_since = unreachable_since || DateTime.utc_now()
55 host = host(url)
56 existing_record = Repo.get_by(Instance, %{host: host})
57
58 changes = %{
59 unreachable_since: unreachable_since,
60 reachability_checked_at: NaiveDateTime.utc_now()
61 }
62
63 if existing_record do
64 update_changes =
65 if existing_record.unreachable_since &&
66 NaiveDateTime.compare(existing_record.unreachable_since, unreachable_since) != :gt,
67 do: Map.delete(changes, :unreachable_since),
68 else: changes
69
70 {:ok, _instance} = Repo.update(update_changeset(existing_record, update_changes))
71 else
72 {:ok, _instance} = Repo.insert(update_changeset(%Instance{}, Map.put(changes, :host, host)))
73 end
74 end
75
76 def set_unreachable(_, _), do: {0, :noop}
77
78 defp host(url_or_host) do
79 if url_or_host =~ ~r/^http/i do
80 URI.parse(url_or_host).host
81 else
82 url_or_host
83 end
84 end
85 end