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
12 Pleroma.Config.get([:rich_media, :parsers])
15 def parse(nil), do: {:error, "No URL provided"}
17 if Pleroma.Config.get(:env) == :test do
18 def parse(url), do: parse_url(url)
22 Cachex.fetch!(:rich_media_cache, url, fn _ ->
23 {:commit, parse_url(url)}
25 |> set_ttl_based_on_image(url)
28 {:error, "Cachex error: #{inspect(e)}"}
34 Set the rich media cache based on the expiration time of image.
36 Adopt behaviour `Pleroma.Web.RichMedia.Parser.TTL`
41 @behaviour Pleroma.Web.RichMedia.Parser.TTL
43 image_url = Map.get(data, :image)
44 # do some parsing in the url and get the ttl of the image
45 # and return ttl is unix time
46 parse_ttl_from_url(image_url)
50 Define the module in the config
52 config :pleroma, :rich_media,
53 ttl_setters: [MyModule]
55 def set_ttl_based_on_image({:ok, data}, url) do
56 with {:ok, nil} <- Cachex.ttl(:rich_media_cache, url),
57 ttl when is_number(ttl) <- get_ttl_from_image(data, url) do
58 Cachex.expire_at(:rich_media_cache, url, ttl * 1000)
66 defp get_ttl_from_image(data, url) do
67 Pleroma.Config.get([:rich_media, :ttl_setters])
68 |> Enum.reduce({:ok, nil}, fn
69 module, {:ok, _ttl} ->
77 defp parse_url(url) do
79 if Application.get_env(:tesla, :adapter) == Tesla.Adapter.Hackney do
80 Keyword.merge(@options,
89 {:ok, %Tesla.Env{body: html}} = Pleroma.HTTP.get(url, [], adapter: opts)
95 |> clean_parsed_data()
96 |> check_parsed_data()
99 {:error, "Parsing error: #{inspect(e)} #{inspect(__STACKTRACE__)}"}
103 defp parse_html(html), do: Floki.parse_document!(html)
105 defp maybe_parse(html) do
106 Enum.reduce_while(parsers(), %{}, fn parser, acc ->
107 case parser.parse(html, acc) do
108 {:ok, data} -> {:halt, data}
109 {:error, _msg} -> {:cont, acc}
114 defp check_parsed_data(%{title: title} = data)
115 when is_binary(title) and byte_size(title) > 0 do
119 defp check_parsed_data(data) do
120 {:error, "Found metadata was invalid or incomplete: #{inspect(data)}"}
123 defp clean_parsed_data(data) do
125 |> Enum.reject(fn {key, val} ->
126 with {:ok, _} <- Jason.encode(%{key => val}) do