revert 4a94c9a31ef11f63ea71ad9c1f085c18cf8ef083
[akkoma] / lib / pleroma / web / rel_me.ex
1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>
3 # SPDX-License-Identifier: AGPL-3.0-only
4
5 defmodule Pleroma.Web.RelMe do
6 @options [
7 max_body: 2_000_000,
8 recv_timeout: 2_000
9 ]
10
11 if Pleroma.Config.get(:env) == :test do
12 def parse(url) when is_binary(url), do: parse_url(url)
13 else
14 @cachex Pleroma.Config.get([:cachex, :provider], Cachex)
15 def parse(url) when is_binary(url) do
16 @cachex.fetch!(:rel_me_cache, url, fn _ ->
17 {:commit, parse_url(url)}
18 end)
19 rescue
20 e -> {:error, "Cachex error: #{inspect(e)}"}
21 end
22 end
23
24 def parse(_), do: {:error, "No URL provided"}
25
26 defp parse_url(url) do
27 with {:ok, %Tesla.Env{body: html, status: status}} when status in 200..299 <-
28 Pleroma.HTTP.get(url, [], @options),
29 {:ok, html_tree} <- Floki.parse_document(html),
30 data <-
31 Floki.attribute(html_tree, "link[rel~=me]", "href") ++
32 Floki.attribute(html_tree, "a[rel~=me]", "href") do
33 {:ok, data}
34 end
35 rescue
36 e -> {:error, "Parsing error: #{inspect(e)}"}
37 end
38
39 def maybe_put_rel_me("http" <> _ = target_page, profile_urls) when is_list(profile_urls) do
40 {:ok, rel_me_hrefs} = parse(target_page)
41
42 true = Enum.any?(rel_me_hrefs, fn x -> x in profile_urls end)
43
44 "me"
45 rescue
46 _ -> nil
47 end
48
49 def maybe_put_rel_me(_, _) do
50 nil
51 end
52 end