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
24 {:error, {:invalid_metadata, data}} = e ->
25 Logger.debug(fn -> "Incomplete or invalid metadata for #{url}: #{inspect(data)}" end)
29 Logger.error(fn -> "Rich media error for #{url}: #{inspect(error)}" end)
34 defp get_cached_or_parse(url) do
35 case Cachex.fetch!(:rich_media_cache, url, fn _ -> {:commit, parse_url(url)} end) do
39 {:error, :body_too_large} = e ->
42 {:error, {:content_type, _}} = e ->
45 # The TTL is not set for the errors above, since they are unlikely to change
48 ttl = Pleroma.Config.get([:rich_media, :failure_backoff], 60_000)
49 Cachex.expire(:rich_media_cache, url, ttl)
56 Set the rich media cache based on the expiration time of image.
58 Adopt behaviour `Pleroma.Web.RichMedia.Parser.TTL`
63 @behaviour Pleroma.Web.RichMedia.Parser.TTL
65 image_url = Map.get(data, :image)
66 # do some parsing in the url and get the ttl of the image
67 # and return ttl is unix time
68 parse_ttl_from_url(image_url)
72 Define the module in the config
74 config :pleroma, :rich_media,
75 ttl_setters: [MyModule]
77 @spec set_ttl_based_on_image(map(), String.t()) ::
78 {:ok, Integer.t() | :noop} | {:error, :no_key}
79 def set_ttl_based_on_image(data, url) do
80 case get_ttl_from_image(data, url) do
81 {:ok, ttl} when is_number(ttl) ->
84 case Cachex.expire_at(:rich_media_cache, url, ttl) do
85 {:ok, true} -> {:ok, ttl}
86 {:ok, false} -> {:error, :no_key}
94 defp get_ttl_from_image(data, url) do
95 [:rich_media, :ttl_setters]
96 |> Pleroma.Config.get()
97 |> Enum.reduce({:ok, nil}, fn
98 module, {:ok, _ttl} ->
106 def parse_url(url) do
107 with {:ok, %Tesla.Env{body: html}} <- Pleroma.Web.RichMedia.Helpers.rich_media_get(url),
108 {:ok, html} <- Floki.parse_document(html) do
111 |> Map.put("url", url)
112 |> clean_parsed_data()
113 |> check_parsed_data()
117 defp maybe_parse(html) do
118 Enum.reduce_while(parsers(), %{}, fn parser, acc ->
119 case parser.parse(html, acc) do
120 data when data != %{} -> {:halt, data}
126 defp check_parsed_data(%{"title" => title} = data)
127 when is_binary(title) and title != "" do
131 defp check_parsed_data(data) do
132 {:error, {:invalid_metadata, data}}
135 defp clean_parsed_data(data) do
137 |> Enum.reject(fn {key, val} ->
138 not match?({:ok, _}, Jason.encode(%{key => val}))