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