1 defmodule Pleroma.Instances.Instance do
4 alias Pleroma.Instances
5 alias Pleroma.Instances.Instance
9 import Ecto.{Query, Changeset}
15 field(:unreachable_since, :naive_datetime)
20 defdelegate host(url_or_host), to: Instances
22 def changeset(struct, params \\ %{}) do
24 |> cast(params, [:host, :unreachable_since])
25 |> validate_required([:host])
26 |> unique_constraint(:host)
29 def filter_reachable([]), do: %{}
31 def filter_reachable(urls_or_hosts) when is_list(urls_or_hosts) do
34 |> Enum.map(&(&1 && host(&1)))
35 |> Enum.filter(&(to_string(&1) != ""))
37 unreachable_since_by_host =
40 where: i.host in ^hosts,
41 select: {i.host, i.unreachable_since}
46 reachability_datetime_threshold = Instances.reachability_datetime_threshold()
48 for entry <- Enum.filter(urls_or_hosts, &is_binary/1) do
50 unreachable_since = unreachable_since_by_host[host]
52 if !unreachable_since ||
53 NaiveDateTime.compare(unreachable_since, reachability_datetime_threshold) == :gt do
54 {entry, unreachable_since}
61 def reachable?(url_or_host) when is_binary(url_or_host) do
65 i.host == ^host(url_or_host) and
66 i.unreachable_since <= ^Instances.reachability_datetime_threshold(),
72 def reachable?(_), do: true
74 def set_reachable(url_or_host) when is_binary(url_or_host) do
75 with host <- host(url_or_host),
76 %Instance{} = existing_record <- Repo.get_by(Instance, %{host: host}) do
79 |> changeset(%{unreachable_since: nil})
84 def set_reachable(_), do: {:error, nil}
86 def set_unreachable(url_or_host, unreachable_since \\ nil)
88 def set_unreachable(url_or_host, unreachable_since) when is_binary(url_or_host) do
89 unreachable_since = unreachable_since || DateTime.utc_now()
90 host = host(url_or_host)
91 existing_record = Repo.get_by(Instance, %{host: host})
93 changes = %{unreachable_since: unreachable_since}
96 is_nil(existing_record) ->
98 |> changeset(Map.put(changes, :host, host))
101 existing_record.unreachable_since &&
102 NaiveDateTime.compare(existing_record.unreachable_since, unreachable_since) != :gt ->
103 {:ok, existing_record}
107 |> changeset(changes)
112 def set_unreachable(_, _), do: {:error, nil}