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