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 Cachex.fetch!(:rich_media_cache, url, fn _ ->
21 with {:ok, data} <- parse_url(url) do
22 {:commit, {:ok, data}}
24 error -> {:ignore, error}
27 |> set_ttl_based_on_image(url)
32 Set the rich media cache based on the expiration time of image.
34 Adopt behaviour `Pleroma.Web.RichMedia.Parser.TTL`
39 @behaviour Pleroma.Web.RichMedia.Parser.TTL
41 image_url = Map.get(data, :image)
42 # do some parsing in the url and get the ttl of the image
43 # and return ttl is unix time
44 parse_ttl_from_url(image_url)
48 Define the module in the config
50 config :pleroma, :rich_media,
51 ttl_setters: [MyModule]
53 @spec set_ttl_based_on_image({:ok, map()} | {:error, any()}, String.t()) ::
54 {:ok, map()} | {:error, any()}
55 def set_ttl_based_on_image({:ok, data}, url) do
56 with {:ok, nil} <- Cachex.ttl(:rich_media_cache, url),
57 {:ok, ttl} when is_number(ttl) <- get_ttl_from_image(data, url) do
58 Cachex.expire_at(:rich_media_cache, url, ttl * 1000)
66 def set_ttl_based_on_image({:error, _} = error, _) do
67 Logger.error("parsing error: #{inspect(error)}")
71 defp get_ttl_from_image(data, url) do
72 [:rich_media, :ttl_setters]
73 |> Pleroma.Config.get()
74 |> Enum.reduce({:ok, nil}, fn
75 module, {:ok, _ttl} ->
83 defp parse_url(url) do
84 with {:ok, %Tesla.Env{body: html}} <- Pleroma.Web.RichMedia.Helpers.rich_media_get(url),
85 {:ok, html} <- Floki.parse_document(html) do
88 |> Map.put("url", url)
89 |> clean_parsed_data()
90 |> check_parsed_data()
94 defp maybe_parse(html) do
95 Enum.reduce_while(parsers(), %{}, fn parser, acc ->
96 case parser.parse(html, acc) do
97 data when data != %{} -> {:halt, data}
103 defp check_parsed_data(%{"title" => title} = data)
104 when is_binary(title) and title != "" do
108 defp check_parsed_data(data) do
109 {:error, "Found metadata was invalid or incomplete: #{inspect(data)}"}
112 defp clean_parsed_data(data) do
114 |> Enum.reject(fn {key, val} ->
115 not match?({:ok, _}, Jason.encode(%{key => val}))