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