1 defmodule Pleroma.Instances.Instance do
4 alias Pleroma.Instances
6 alias Pleroma.Instances.Instance
10 import Ecto.{Query, Changeset}
14 field(:unreachable_since, :naive_datetime)
19 defdelegate host(url_or_host), to: Instances
21 def changeset(struct, params \\ %{}) do
23 |> cast(params, [:host, :unreachable_since])
24 |> validate_required([:host])
25 |> unique_constraint(:host)
28 def filter_reachable([]), do: %{}
30 def filter_reachable(urls_or_hosts) when is_list(urls_or_hosts) do
33 |> Enum.map(&(&1 && host(&1)))
34 |> Enum.filter(&(to_string(&1) != ""))
36 unreachable_since_by_host =
39 where: i.host in ^hosts,
40 select: {i.host, i.unreachable_since}
45 reachability_datetime_threshold = Instances.reachability_datetime_threshold()
47 for entry <- Enum.filter(urls_or_hosts, &is_binary/1) do
49 unreachable_since = unreachable_since_by_host[host]
51 if !unreachable_since ||
52 NaiveDateTime.compare(unreachable_since, reachability_datetime_threshold) == :gt do
53 {entry, unreachable_since}
60 def reachable?(url_or_host) when is_binary(url_or_host) do
64 i.host == ^host(url_or_host) and
65 i.unreachable_since <= ^Instances.reachability_datetime_threshold(),
71 def reachable?(_), do: true
73 def set_reachable(url_or_host) when is_binary(url_or_host) do
74 with host <- host(url_or_host),
75 %Instance{} = existing_record <- Repo.get_by(Instance, %{host: host}) do
78 |> changeset(%{unreachable_since: nil})
83 def set_reachable(_), do: {:error, nil}
85 def set_unreachable(url_or_host, unreachable_since \\ nil)
87 def set_unreachable(url_or_host, unreachable_since) when is_binary(url_or_host) do
88 unreachable_since = unreachable_since || DateTime.utc_now()
89 host = host(url_or_host)
90 existing_record = Repo.get_by(Instance, %{host: host})
92 changes = %{unreachable_since: unreachable_since}
95 is_nil(existing_record) ->
97 |> changeset(Map.put(changes, :host, host))
100 existing_record.unreachable_since &&
101 NaiveDateTime.compare(existing_record.unreachable_since, unreachable_since) != :gt ->
102 {:ok, existing_record}
106 |> changeset(changes)
111 def set_unreachable(_, _), do: {:error, nil}