Merge branch 'develop' of https://git.pleroma.social/pleroma/pleroma into develop
[akkoma] / lib / pleroma / instances / instance.ex
index a87590d8b2e457bc7e6ab0edb8d266bfb49cb4e3..4d7ed4ca1076abe35b697f2e29002f739b2124c8 100644 (file)
@@ -1,18 +1,22 @@
+# Pleroma: A lightweight social networking server
+# Copyright © 2017-2019 Pleroma Authors <https://pleroma.social/>
+# SPDX-License-Identifier: AGPL-3.0-only
+
 defmodule Pleroma.Instances.Instance do
   @moduledoc "Instance."
 
   alias Pleroma.Instances
   alias Pleroma.Instances.Instance
+  alias Pleroma.Repo
 
   use Ecto.Schema
 
-  import Ecto.{Query, Changeset}
-
-  alias Pleroma.Repo
+  import Ecto.Query
+  import Ecto.Changeset
 
   schema "instances" do
     field(:host, :string)
-    field(:unreachable_since, :naive_datetime)
+    field(:unreachable_since, :naive_datetime_usec)
 
     timestamps()
   end
@@ -26,7 +30,7 @@ defmodule Pleroma.Instances.Instance do
     |> unique_constraint(:host)
   end
 
-  def filter_reachable([]), do: []
+  def filter_reachable([]), do: %{}
 
   def filter_reachable(urls_or_hosts) when is_list(urls_or_hosts) do
     hosts =
@@ -34,17 +38,28 @@ defmodule Pleroma.Instances.Instance do
       |> Enum.map(&(&1 && host(&1)))
       |> Enum.filter(&(to_string(&1) != ""))
 
-    unreachable_hosts =
+    unreachable_since_by_host =
       Repo.all(
         from(i in Instance,
-          where:
-            i.host in ^hosts and
-              i.unreachable_since <= ^Instances.reachability_datetime_threshold(),
-          select: i.host
+          where: i.host in ^hosts,
+          select: {i.host, i.unreachable_since}
         )
       )
+      |> Map.new(& &1)
 
-    Enum.filter(urls_or_hosts, &(&1 && host(&1) not in unreachable_hosts))
+    reachability_datetime_threshold = Instances.reachability_datetime_threshold()
+
+    for entry <- Enum.filter(urls_or_hosts, &is_binary/1) do
+      host = host(entry)
+      unreachable_since = unreachable_since_by_host[host]
+
+      if !unreachable_since ||
+           NaiveDateTime.compare(unreachable_since, reachability_datetime_threshold) == :gt do
+        {entry, unreachable_since}
+      end
+    end
+    |> Enum.filter(& &1)
+    |> Map.new(& &1)
   end
 
   def reachable?(url_or_host) when is_binary(url_or_host) do