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 def update_changeset(struct, params \\ %{}) do
23 |> cast(params, [:host, :unreachable_since, :reachability_checked_at])
24 |> unique_constraint(:host)
27 def reachable?(url) when is_binary(url) do
31 i.host == ^host(url) and i.unreachable_since <= ^Instances.reachability_time_threshold(),
37 def reachable?(_), do: true
39 def set_reachable(url) when is_binary(url) do
41 from(i in Instance, where: i.host == ^host(url)),
43 unreachable_since: nil,
44 reachability_checked_at: DateTime.utc_now()
49 def set_reachable(_), do: {0, :noop}
51 def set_unreachable(url, unreachable_since \\ nil)
53 def set_unreachable(url, unreachable_since) when is_binary(url) do
54 unreachable_since = unreachable_since || DateTime.utc_now()
56 existing_record = Repo.get_by(Instance, %{host: host})
59 unreachable_since: unreachable_since,
60 reachability_checked_at: NaiveDateTime.utc_now()
65 if existing_record.unreachable_since &&
66 NaiveDateTime.compare(existing_record.unreachable_since, unreachable_since) != :gt,
67 do: Map.delete(changes, :unreachable_since),
70 {:ok, _instance} = Repo.update(update_changeset(existing_record, update_changes))
72 {:ok, _instance} = Repo.insert(update_changeset(%Instance{}, Map.put(changes, :host, host)))
76 def set_unreachable(_, _), do: {0, :noop}
78 defp host(url_or_host) do
79 if url_or_host =~ ~r/^http/i do
80 URI.parse(url_or_host).host