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
35 ttl = Pleroma.Config.get([:rich_media, :failure_backoff], 60_000)
36 Cachex.expire(:rich_media_cache, url, ttl)
43 Set the rich media cache based on the expiration time of image.
45 Adopt behaviour `Pleroma.Web.RichMedia.Parser.TTL`
50 @behaviour Pleroma.Web.RichMedia.Parser.TTL
52 image_url = Map.get(data, :image)
53 # do some parsing in the url and get the ttl of the image
54 # and return ttl is unix time
55 parse_ttl_from_url(image_url)
59 Define the module in the config
61 config :pleroma, :rich_media,
62 ttl_setters: [MyModule]
64 @spec set_ttl_based_on_image(map(), String.t()) ::
65 {:ok, Integer.t() | :noop} | {:error, :no_key}
66 def set_ttl_based_on_image(data, url) do
67 case get_ttl_from_image(data, url) do
68 {:ok, ttl} when is_number(ttl) ->
71 case Cachex.expire_at(:rich_media_cache, url, ttl) do
72 {:ok, true} -> {:ok, ttl}
73 {:ok, false} -> {:error, :no_key}
81 defp get_ttl_from_image(data, url) do
82 [:rich_media, :ttl_setters]
83 |> Pleroma.Config.get()
84 |> Enum.reduce({:ok, nil}, fn
85 module, {:ok, _ttl} ->
93 defp parse_url(url) do
94 with {:ok, %Tesla.Env{body: html}} <- Pleroma.Web.RichMedia.Helpers.rich_media_get(url),
95 {:ok, html} <- Floki.parse_document(html) do
98 |> Map.put("url", url)
99 |> clean_parsed_data()
100 |> check_parsed_data()
104 defp maybe_parse(html) do
105 Enum.reduce_while(parsers(), %{}, fn parser, acc ->
106 case parser.parse(html, acc) do
107 data when data != %{} -> {:halt, data}
113 defp check_parsed_data(%{"title" => title} = data)
114 when is_binary(title) and title != "" do
118 defp check_parsed_data(data) do
119 {:error, "Found metadata was invalid or incomplete: #{inspect(data)}"}
122 defp clean_parsed_data(data) do
124 |> Enum.reject(fn {key, val} ->
125 not match?({:ok, _}, Jason.encode(%{key => val}))