Merge branch 'develop' of https://git.pleroma.social/pleroma/pleroma into develop
[akkoma] / lib / pleroma / web / rel_me.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.Web.RelMe do
6 @options [
7 pool: :media,
8 max_body: 2_000_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 def parse(url) when is_binary(url) do
15 Cachex.fetch!(:rel_me_cache, url, fn _ ->
16 {:commit, parse_url(url)}
17 end)
18 rescue
19 e -> {:error, "Cachex error: #{inspect(e)}"}
20 end
21 end
22
23 def parse(_), do: {:error, "No URL provided"}
24
25 defp parse_url(url) do
26 opts =
27 if Application.get_env(:tesla, :adapter) == Tesla.Adapter.Hackney do
28 Keyword.merge(@options,
29 recv_timeout: 2_000,
30 with_body: true
31 )
32 else
33 @options
34 end
35
36 with {:ok, %Tesla.Env{body: html, status: status}} when status in 200..299 <-
37 Pleroma.HTTP.get(url, [], adapter: opts),
38 {:ok, html_tree} <- Floki.parse_document(html),
39 data <-
40 Floki.attribute(html_tree, "link[rel~=me]", "href") ++
41 Floki.attribute(html_tree, "a[rel~=me]", "href") do
42 {:ok, data}
43 end
44 rescue
45 e -> {:error, "Parsing error: #{inspect(e)}"}
46 end
47
48 def maybe_put_rel_me("http" <> _ = target_page, profile_urls) when is_list(profile_urls) do
49 {:ok, rel_me_hrefs} = parse(target_page)
50
51 true = Enum.any?(rel_me_hrefs, fn x -> x in profile_urls end)
52
53 "me"
54 rescue
55 _ -> nil
56 end
57
58 def maybe_put_rel_me(_, _) do
59 nil
60 end
61 end