1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2019 Pleroma Authors <https://pleroma.social/>
3 # SPDX-License-Identifier: AGPL-3.0-only
5 defmodule Pleroma.Web.RichMedia.Parser do
14 Pleroma.Config.get([:rich_media, :parsers])
17 def parse(nil), do: {:error, "No URL provided"}
19 if Pleroma.Config.get(:env) == :test do
20 def parse(url), do: parse_url(url)
24 Cachex.fetch!(:rich_media_cache, url, fn _ ->
25 {:commit, parse_url(url)}
27 |> set_ttl_based_on_image(url)
30 {:error, "Cachex error: #{inspect(e)}"}
36 Set the rich media cache based on the expiration time of image.
38 Adopt behaviour `Pleroma.Web.RichMedia.Parser.TTL`
43 @behaviour Pleroma.Web.RichMedia.Parser.TTL
45 image_url = Map.get(data, :image)
46 # do some parsing in the url and get the ttl of the image
47 # and return ttl is unix time
48 parse_ttl_from_url(image_url)
52 Define the module in the config
54 config :pleroma, :rich_media,
55 ttl_setters: [MyModule]
57 def set_ttl_based_on_image({:ok, data}, url) do
58 with {:ok, nil} <- Cachex.ttl(:rich_media_cache, url),
59 ttl when is_number(ttl) <- get_ttl_from_image(data, url) do
60 Cachex.expire_at(:rich_media_cache, url, ttl * 1000)
68 defp get_ttl_from_image(data, url) do
69 Pleroma.Config.get([:rich_media, :ttl_setters])
70 |> Enum.reduce({:ok, nil}, fn
71 module, {:ok, _ttl} ->
79 defp parse_url(url) do
81 {:ok, %Tesla.Env{body: html}} = Pleroma.HTTP.get(url, [], adapter: @hackney_options)
86 |> clean_parsed_data()
87 |> check_parsed_data()
90 {:error, "Parsing error: #{inspect(e)}"}
94 defp maybe_parse(html) do
95 Enum.reduce_while(parsers(), %{}, fn parser, acc ->
96 case parser.parse(html, acc) do
97 {:ok, data} -> {:halt, data}
98 {:error, _msg} -> {:cont, acc}
103 defp check_parsed_data(%{title: title} = data) when is_binary(title) and byte_size(title) > 0 do
107 defp check_parsed_data(data) do
108 {:error, "Found metadata was invalid or incomplete: #{inspect(data)}"}
111 defp clean_parsed_data(data) do
113 |> Enum.reject(fn {key, val} ->
114 with {:ok, _} <- Jason.encode(%{key => val}) do