1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2019 Pleroma Authors <https://pleroma.social/>
3 # SPDX-License-Identifier: AGPL-3.0-only
5 defmodule Pleroma.Instances.Instance do
8 alias Pleroma.Instances
9 alias Pleroma.Instances.Instance
19 field(:unreachable_since, :naive_datetime_usec)
24 defdelegate host(url_or_host), to: Instances
26 def changeset(struct, params \\ %{}) do
28 |> cast(params, [:host, :unreachable_since])
29 |> validate_required([:host])
30 |> unique_constraint(:host)
33 def filter_reachable([]), do: %{}
35 def filter_reachable(urls_or_hosts) when is_list(urls_or_hosts) do
38 |> Enum.map(&(&1 && host(&1)))
39 |> Enum.filter(&(to_string(&1) != ""))
41 unreachable_since_by_host =
44 where: i.host in ^hosts,
45 select: {i.host, i.unreachable_since}
50 reachability_datetime_threshold = Instances.reachability_datetime_threshold()
52 for entry <- Enum.filter(urls_or_hosts, &is_binary/1) do
54 unreachable_since = unreachable_since_by_host[host]
56 if !unreachable_since ||
57 NaiveDateTime.compare(unreachable_since, reachability_datetime_threshold) == :gt do
58 {entry, unreachable_since}
65 def reachable?(url_or_host) when is_binary(url_or_host) do
69 i.host == ^host(url_or_host) and
70 i.unreachable_since <= ^Instances.reachability_datetime_threshold(),
76 def reachable?(_), do: true
78 def set_reachable(url_or_host) when is_binary(url_or_host) do
79 with host <- host(url_or_host),
80 %Instance{} = existing_record <- Repo.get_by(Instance, %{host: host}) do
83 |> changeset(%{unreachable_since: nil})
88 def set_reachable(_), do: {:error, nil}
90 def set_unreachable(url_or_host, unreachable_since \\ nil)
92 def set_unreachable(url_or_host, unreachable_since) when is_binary(url_or_host) do
93 unreachable_since = parse_datetime(unreachable_since) || NaiveDateTime.utc_now()
94 host = host(url_or_host)
95 existing_record = Repo.get_by(Instance, %{host: host})
97 changes = %{unreachable_since: unreachable_since}
100 is_nil(existing_record) ->
102 |> changeset(Map.put(changes, :host, host))
105 existing_record.unreachable_since &&
106 NaiveDateTime.compare(existing_record.unreachable_since, unreachable_since) != :gt ->
107 {:ok, existing_record}
111 |> changeset(changes)
116 def set_unreachable(_, _), do: {:error, nil}
118 defp parse_datetime(datetime) when is_binary(datetime) do
119 NaiveDateTime.from_iso8601(datetime)
122 defp parse_datetime(datetime), do: datetime