Merge branch 'media-preview-proxy-nostream' into 'develop'
[akkoma] / lib / pleroma / instances / instance.ex
1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/>
3 # SPDX-License-Identifier: AGPL-3.0-only
4
5 defmodule Pleroma.Instances.Instance do
6 @moduledoc "Instance."
7
8 alias Pleroma.Instances
9 alias Pleroma.Instances.Instance
10 alias Pleroma.Repo
11
12 use Ecto.Schema
13
14 import Ecto.Query
15 import Ecto.Changeset
16
17 require Logger
18
19 schema "instances" do
20 field(:host, :string)
21 field(:unreachable_since, :naive_datetime_usec)
22 field(:favicon, :string)
23 field(:favicon_updated_at, :naive_datetime)
24
25 timestamps()
26 end
27
28 defdelegate host(url_or_host), to: Instances
29
30 def changeset(struct, params \\ %{}) do
31 struct
32 |> cast(params, [:host, :unreachable_since, :favicon, :favicon_updated_at])
33 |> validate_required([:host])
34 |> unique_constraint(:host)
35 end
36
37 def filter_reachable([]), do: %{}
38
39 def filter_reachable(urls_or_hosts) when is_list(urls_or_hosts) do
40 hosts =
41 urls_or_hosts
42 |> Enum.map(&(&1 && host(&1)))
43 |> Enum.filter(&(to_string(&1) != ""))
44
45 unreachable_since_by_host =
46 Repo.all(
47 from(i in Instance,
48 where: i.host in ^hosts,
49 select: {i.host, i.unreachable_since}
50 )
51 )
52 |> Map.new(& &1)
53
54 reachability_datetime_threshold = Instances.reachability_datetime_threshold()
55
56 for entry <- Enum.filter(urls_or_hosts, &is_binary/1) do
57 host = host(entry)
58 unreachable_since = unreachable_since_by_host[host]
59
60 if !unreachable_since ||
61 NaiveDateTime.compare(unreachable_since, reachability_datetime_threshold) == :gt do
62 {entry, unreachable_since}
63 end
64 end
65 |> Enum.filter(& &1)
66 |> Map.new(& &1)
67 end
68
69 def reachable?(url_or_host) when is_binary(url_or_host) do
70 !Repo.one(
71 from(i in Instance,
72 where:
73 i.host == ^host(url_or_host) and
74 i.unreachable_since <= ^Instances.reachability_datetime_threshold(),
75 select: true
76 )
77 )
78 end
79
80 def reachable?(_), do: true
81
82 def set_reachable(url_or_host) when is_binary(url_or_host) do
83 with host <- host(url_or_host),
84 %Instance{} = existing_record <- Repo.get_by(Instance, %{host: host}) do
85 {:ok, _instance} =
86 existing_record
87 |> changeset(%{unreachable_since: nil})
88 |> Repo.update()
89 end
90 end
91
92 def set_reachable(_), do: {:error, nil}
93
94 def set_unreachable(url_or_host, unreachable_since \\ nil)
95
96 def set_unreachable(url_or_host, unreachable_since) when is_binary(url_or_host) do
97 unreachable_since = parse_datetime(unreachable_since) || NaiveDateTime.utc_now()
98 host = host(url_or_host)
99 existing_record = Repo.get_by(Instance, %{host: host})
100
101 changes = %{unreachable_since: unreachable_since}
102
103 cond do
104 is_nil(existing_record) ->
105 %Instance{}
106 |> changeset(Map.put(changes, :host, host))
107 |> Repo.insert()
108
109 existing_record.unreachable_since &&
110 NaiveDateTime.compare(existing_record.unreachable_since, unreachable_since) != :gt ->
111 {:ok, existing_record}
112
113 true ->
114 existing_record
115 |> changeset(changes)
116 |> Repo.update()
117 end
118 end
119
120 def set_unreachable(_, _), do: {:error, nil}
121
122 defp parse_datetime(datetime) when is_binary(datetime) do
123 NaiveDateTime.from_iso8601(datetime)
124 end
125
126 defp parse_datetime(datetime), do: datetime
127
128 def get_or_update_favicon(%URI{host: host} = instance_uri) do
129 existing_record = Repo.get_by(Instance, %{host: host})
130 now = NaiveDateTime.utc_now()
131
132 if existing_record && existing_record.favicon_updated_at &&
133 NaiveDateTime.diff(now, existing_record.favicon_updated_at) < 86_400 do
134 existing_record.favicon
135 else
136 favicon = scrape_favicon(instance_uri)
137
138 if existing_record do
139 existing_record
140 |> changeset(%{favicon: favicon, favicon_updated_at: now})
141 |> Repo.update()
142 else
143 %Instance{}
144 |> changeset(%{host: host, favicon: favicon, favicon_updated_at: now})
145 |> Repo.insert()
146 end
147
148 favicon
149 end
150 rescue
151 e ->
152 Logger.warn("Instance.get_or_update_favicon(\"#{host}\") error: #{inspect(e)}")
153 nil
154 end
155
156 defp scrape_favicon(%URI{} = instance_uri) do
157 try do
158 with {:ok, %Tesla.Env{body: html}} <-
159 Pleroma.HTTP.get(to_string(instance_uri), [{"accept", "text/html"}], pool: :media),
160 {_, [favicon_rel | _]} when is_binary(favicon_rel) <-
161 {:parse,
162 html |> Floki.parse_document!() |> Floki.attribute("link[rel=icon]", "href")},
163 {_, favicon} when is_binary(favicon) <-
164 {:merge, URI.merge(instance_uri, favicon_rel) |> to_string()} do
165 favicon
166 else
167 _ -> nil
168 end
169 rescue
170 e ->
171 Logger.warn(
172 "Instance.scrape_favicon(\"#{to_string(instance_uri)}\") error: #{inspect(e)}"
173 )
174
175 nil
176 end
177 end
178 end