Merge branch '534_federation_targets_reachability' into 'develop'
[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
17 timestamps()
18 end
19
20 defdelegate host(url_or_host), to: Instances
21
22 def changeset(struct, params \\ %{}) do
23 struct
24 |> cast(params, [:host, :unreachable_since])
25 |> validate_required([:host])
26 |> unique_constraint(:host)
27 end
28
29 def filter_reachable([]), do: []
30
31 def filter_reachable(urls_or_hosts) when is_list(urls_or_hosts) do
32 hosts =
33 urls_or_hosts
34 |> Enum.map(&(&1 && host(&1)))
35 |> Enum.filter(&(to_string(&1) != ""))
36
37 unreachable_hosts =
38 Repo.all(
39 from(i in Instance,
40 where:
41 i.host in ^hosts and
42 i.unreachable_since <= ^Instances.reachability_datetime_threshold(),
43 select: i.host
44 )
45 )
46
47 Enum.filter(urls_or_hosts, &(&1 && host(&1) not in unreachable_hosts))
48 end
49
50 def reachable?(url_or_host) when is_binary(url_or_host) do
51 !Repo.one(
52 from(i in Instance,
53 where:
54 i.host == ^host(url_or_host) and
55 i.unreachable_since <= ^Instances.reachability_datetime_threshold(),
56 select: true
57 )
58 )
59 end
60
61 def reachable?(_), do: true
62
63 def set_reachable(url_or_host) when is_binary(url_or_host) do
64 with host <- host(url_or_host),
65 %Instance{} = existing_record <- Repo.get_by(Instance, %{host: host}) do
66 {:ok, _instance} =
67 existing_record
68 |> changeset(%{unreachable_since: nil})
69 |> Repo.update()
70 end
71 end
72
73 def set_reachable(_), do: {:error, nil}
74
75 def set_unreachable(url_or_host, unreachable_since \\ nil)
76
77 def set_unreachable(url_or_host, unreachable_since) when is_binary(url_or_host) do
78 unreachable_since = unreachable_since || DateTime.utc_now()
79 host = host(url_or_host)
80 existing_record = Repo.get_by(Instance, %{host: host})
81
82 changes = %{unreachable_since: unreachable_since}
83
84 cond do
85 is_nil(existing_record) ->
86 %Instance{}
87 |> changeset(Map.put(changes, :host, host))
88 |> Repo.insert()
89
90 existing_record.unreachable_since &&
91 NaiveDateTime.compare(existing_record.unreachable_since, unreachable_since) != :gt ->
92 {:ok, existing_record}
93
94 true ->
95 existing_record
96 |> changeset(changes)
97 |> Repo.update()
98 end
99 end
100
101 def set_unreachable(_, _), do: {:error, nil}
102 end