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) do
31 i.host == ^host(url) and i.unreachable_since <= ^Instances.reachability_time_threshold(),
37 def set_reachable(url) do
39 from(i in Instance, where: i.host == ^host(url)),
41 unreachable_since: nil,
42 reachability_checked_at: DateTime.utc_now()
47 def set_unreachable(url, unreachable_since \\ nil) do
48 unreachable_since = unreachable_since || DateTime.utc_now()
50 existing_record = Repo.get_by(Instance, %{host: host})
53 unreachable_since: unreachable_since,
54 reachability_checked_at: NaiveDateTime.utc_now()
59 if existing_record.unreachable_since &&
60 NaiveDateTime.compare(existing_record.unreachable_since, unreachable_since) != :gt,
61 do: Map.delete(changes, :unreachable_since),
64 {:ok, _instance} = Repo.update(update_changeset(existing_record, update_changes))
66 {:ok, _instance} = Repo.insert(update_changeset(%Instance{}, Map.put(changes, :host, host)))
70 defp host(url_or_host) do
71 if url_or_host =~ ~r/^http/i do
72 URI.parse(url_or_host).host