ce3b46d501b467c0762bdf2297389396dfc468df
[akkoma] / lib / pleroma / instances / instance.ex
1 defmodule Pleroma.Instances.Instance do
2 @moduledoc "Instance."
3
4 alias Pleroma.Instances
5 alias Pleroma.Repo
6 alias Pleroma.Instances.Instance
7
8 use Ecto.Schema
9
10 import Ecto.{Query, Changeset}
11
12 schema "instances" do
13 field(:host, :string)
14 field(:unreachable_since, :naive_datetime)
15
16 timestamps()
17 end
18
19 defdelegate host(url_or_host), to: Instances
20
21 def changeset(struct, params \\ %{}) do
22 struct
23 |> cast(params, [:host, :unreachable_since])
24 |> validate_required([:host])
25 |> unique_constraint(:host)
26 end
27
28 def filter_reachable([]), do: %{}
29
30 def filter_reachable(urls_or_hosts) when is_list(urls_or_hosts) do
31 hosts =
32 urls_or_hosts
33 |> Enum.map(&(&1 && host(&1)))
34 |> Enum.filter(&(to_string(&1) != ""))
35
36 unreachable_since_by_host =
37 Repo.all(
38 from(i in Instance,
39 where: i.host in ^hosts,
40 select: {i.host, i.unreachable_since}
41 )
42 )
43 |> Map.new(& &1)
44
45 reachability_datetime_threshold = Instances.reachability_datetime_threshold()
46
47 for entry <- Enum.filter(urls_or_hosts, &is_binary/1) do
48 host = host(entry)
49 unreachable_since = unreachable_since_by_host[host]
50
51 if !unreachable_since ||
52 NaiveDateTime.compare(unreachable_since, reachability_datetime_threshold) == :gt do
53 {entry, unreachable_since}
54 end
55 end
56 |> Enum.filter(& &1)
57 |> Map.new(& &1)
58 end
59
60 def reachable?(url_or_host) when is_binary(url_or_host) do
61 !Repo.one(
62 from(i in Instance,
63 where:
64 i.host == ^host(url_or_host) and
65 i.unreachable_since <= ^Instances.reachability_datetime_threshold(),
66 select: true
67 )
68 )
69 end
70
71 def reachable?(_), do: true
72
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
76 {:ok, _instance} =
77 existing_record
78 |> changeset(%{unreachable_since: nil})
79 |> Repo.update()
80 end
81 end
82
83 def set_reachable(_), do: {:error, nil}
84
85 def set_unreachable(url_or_host, unreachable_since \\ nil)
86
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})
91
92 changes = %{unreachable_since: unreachable_since}
93
94 cond do
95 is_nil(existing_record) ->
96 %Instance{}
97 |> changeset(Map.put(changes, :host, host))
98 |> Repo.insert()
99
100 existing_record.unreachable_since &&
101 NaiveDateTime.compare(existing_record.unreachable_since, unreachable_since) != :gt ->
102 {:ok, existing_record}
103
104 true ->
105 existing_record
106 |> changeset(changes)
107 |> Repo.update()
108 end
109 end
110
111 def set_unreachable(_, _), do: {:error, nil}
112 end