1 # Pleroma: A lightweight social networking server
2 # Copyright _ 2017-2020 Pleroma Authors <https://pleroma.social/>
3 # SPDX-License-Identifier: AGPL-3.0-only
5 defmodule Pleroma.Web.RichMedia.Helpers do
10 alias Pleroma.Web.RichMedia.Parser
17 @spec validate_page_url(URI.t() | binary()) :: :ok | :error
18 defp validate_page_url(page_url) when is_binary(page_url) do
19 validate_tld = Pleroma.Config.get([Pleroma.Formatter, :validate_tld])
22 |> Linkify.Parser.url?(validate_tld: validate_tld)
23 |> parse_uri(page_url)
26 defp validate_page_url(%URI{host: host, scheme: "https", authority: authority})
27 when is_binary(authority) do
29 host in Config.get([:rich_media, :ignore_hosts], []) ->
32 get_tld(host) in Config.get([:rich_media, :ignore_tld], []) ->
40 defp validate_page_url(_), do: :error
42 defp parse_uri(true, url) do
48 defp parse_uri(_, _), do: :error
57 def fetch_data_for_object(object) do
58 with true <- Config.get([:rich_media, :enabled]),
59 false <- object.data["sensitive"] || false,
61 HTML.extract_first_external_url(object, object.data["content"]),
62 :ok <- validate_page_url(page_url),
63 {:ok, rich_media} <- Parser.parse(page_url) do
64 %{page_url: page_url, rich_media: rich_media}
70 def fetch_data_for_activity(%Activity{data: %{"type" => "Create"}} = activity) do
71 with true <- Config.get([:rich_media, :enabled]),
72 %Object{} = object <- Object.normalize(activity) do
73 fetch_data_for_object(object)
79 def fetch_data_for_activity(_), do: %{}
81 def perform(:fetch, %Activity{} = activity) do
82 fetch_data_for_activity(activity)
86 def rich_media_get(url) do
87 headers = [{"user-agent", Pleroma.Application.user_agent() <> "; Bot"}]
90 if Application.get_env(:tesla, :adapter) == Tesla.Adapter.Hackney do
91 Keyword.merge(@rich_media_options,
99 Pleroma.HTTP.get(url, headers, options)