7e745d07e2959cf630523b641853bcb8dd936aa2
[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 pool: :media,
8 max_body: 2_000_000,
9 recv_timeout: 2_000
10 ]
11
12 if Pleroma.Config.get(:env) == :test do
13 def parse(url) when is_binary(url), do: parse_url(url)
14 else
15 @cachex Pleroma.Config.get([:cachex, :provider], Cachex)
16 def parse(url) when is_binary(url) do
17 @cachex.fetch!(:rel_me_cache, url, fn _ ->
18 {:commit, parse_url(url)}
19 end)
20 rescue
21 e -> {:error, "Cachex error: #{inspect(e)}"}
22 end
23 end
24
25 def parse(_), do: {:error, "No URL provided"}
26
27 defp parse_url(url) do
28 with {:ok, %Tesla.Env{body: html, status: status}} when status in 200..299 <-
29 Pleroma.HTTP.get(url, [], @options),
30 {:ok, html_tree} <- Floki.parse_document(html),
31 data <-
32 Floki.attribute(html_tree, "link[rel~=me]", "href") ++
33 Floki.attribute(html_tree, "a[rel~=me]", "href") do
34 {:ok, data}
35 end
36 rescue
37 e -> {:error, "Parsing error: #{inspect(e)}"}
38 end
39
40 def maybe_put_rel_me("http" <> _ = target_page, profile_urls) when is_list(profile_urls) do
41 {:ok, rel_me_hrefs} = parse(target_page)
42
43 true = Enum.any?(rel_me_hrefs, fn x -> x in profile_urls end)
44
45 "me"
46 rescue
47 _ -> nil
48 end
49
50 def maybe_put_rel_me(_, _) do
51 nil
52 end
53 end