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)
16 field(:reachability_checked_at, :naive_datetime)
21 defdelegate host(url), to: Instances
23 def changeset(struct, params \\ %{}) do
25 |> cast(params, [:host, :unreachable_since, :reachability_checked_at])
26 |> validate_required([:host])
27 |> unique_constraint(:host)
30 def filter_reachable([]), do: []
32 def filter_reachable(urls) when is_list(urls) do
35 |> Enum.map(&(&1 && host(&1)))
36 |> Enum.filter(&(to_string(&1) != ""))
43 i.unreachable_since <= ^Instances.reachability_datetime_threshold(),
48 Enum.filter(urls, &(&1 && host(&1) not in unreachable_hosts))
51 def reachable?(url) when is_binary(url) do
55 i.host == ^host(url) and
56 i.unreachable_since <= ^Instances.reachability_datetime_threshold(),
62 def reachable?(_), do: true
64 def set_reachable(url) when is_binary(url) do
65 with host <- host(url),
66 %Instance{} = existing_record <- Repo.get_by(Instance, %{host: host}) do
69 |> changeset(%{unreachable_since: nil, reachability_checked_at: DateTime.utc_now()})
74 def set_reachable(_), do: {0, :noop}
76 def set_unreachable(url, unreachable_since \\ nil)
78 def set_unreachable(url, unreachable_since) when is_binary(url) do
79 unreachable_since = unreachable_since || DateTime.utc_now()
81 existing_record = Repo.get_by(Instance, %{host: host})
84 unreachable_since: unreachable_since,
85 reachability_checked_at: NaiveDateTime.utc_now()
90 if existing_record.unreachable_since &&
91 NaiveDateTime.compare(existing_record.unreachable_since, unreachable_since) != :gt,
92 do: Map.delete(changes, :unreachable_since),
97 |> changeset(update_changes)
102 |> changeset(Map.put(changes, :host, host))
107 def set_unreachable(_, _), do: {0, :noop}