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.Parser do
9 Pleroma.Config.get([:rich_media, :parsers])
12 def parse(nil), do: {:error, "No URL provided"}
14 if Pleroma.Config.get(:env) == :test do
15 @spec parse(String.t()) :: {:ok, map()} | {:error, any()}
16 def parse(url), do: parse_url(url)
18 @spec parse(String.t()) :: {:ok, map()} | {:error, any()}
20 with {:ok, data} <- get_cached_or_parse(url),
21 {:ok, _} <- set_ttl_based_on_image(data, url) do
25 Logger.error(fn -> "Rich media error: #{inspect(error)}" end)
29 defp get_cached_or_parse(url) do
30 case Cachex.fetch!(:rich_media_cache, url, fn _ -> {:commit, parse_url(url)} end) do
34 {:error, :body_too_large} = e ->
37 {:error, {:content_type, _}} = e ->
40 # The TTL is not set for the errors above, since they are unlikely to change
43 ttl = Pleroma.Config.get([:rich_media, :failure_backoff], 60_000)
44 Cachex.expire(:rich_media_cache, url, ttl)
51 Set the rich media cache based on the expiration time of image.
53 Adopt behaviour `Pleroma.Web.RichMedia.Parser.TTL`
58 @behaviour Pleroma.Web.RichMedia.Parser.TTL
60 image_url = Map.get(data, :image)
61 # do some parsing in the url and get the ttl of the image
62 # and return ttl is unix time
63 parse_ttl_from_url(image_url)
67 Define the module in the config
69 config :pleroma, :rich_media,
70 ttl_setters: [MyModule]
72 @spec set_ttl_based_on_image(map(), String.t()) ::
73 {:ok, Integer.t() | :noop} | {:error, :no_key}
74 def set_ttl_based_on_image(data, url) do
75 case get_ttl_from_image(data, url) do
76 {:ok, ttl} when is_number(ttl) ->
79 case Cachex.expire_at(:rich_media_cache, url, ttl) do
80 {:ok, true} -> {:ok, ttl}
81 {:ok, false} -> {:error, :no_key}
89 defp get_ttl_from_image(data, url) do
90 [:rich_media, :ttl_setters]
91 |> Pleroma.Config.get()
92 |> Enum.reduce({:ok, nil}, fn
93 module, {:ok, _ttl} ->
101 defp parse_url(url) do
102 with {:ok, %Tesla.Env{body: html}} <- Pleroma.Web.RichMedia.Helpers.rich_media_get(url),
103 {:ok, html} <- Floki.parse_document(html) do
106 |> Map.put("url", url)
107 |> clean_parsed_data()
108 |> check_parsed_data()
112 defp maybe_parse(html) do
113 Enum.reduce_while(parsers(), %{}, fn parser, acc ->
114 case parser.parse(html, acc) do
115 data when data != %{} -> {:halt, data}
121 defp check_parsed_data(%{"title" => title} = data)
122 when is_binary(title) and title != "" do
126 defp check_parsed_data(data) do
127 {:error, "Found metadata was invalid or incomplete: #{inspect(data)}"}
130 defp clean_parsed_data(data) do
132 |> Enum.reject(fn {key, val} ->
133 not match?({:ok, _}, Jason.encode(%{key => val}))