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 Define a module that has `run` function
44 image_url = Map.get(data, :image)
45 # do some parsing in the url and get the ttl of the image
47 ttl = parse_ttl_from_url(image_url)
48 Cachex.expire_at(:rich_media_cache, url, ttl * 1000)
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 case Cachex.ttl(:rich_media_cache, url) do
60 modules = Pleroma.Config.get([:rich_media, :ttl_setters])
62 if Enum.count(modules) > 0 do
63 Enum.each(modules, & &1.run(data, url))
73 def set_ttl_based_on_image(data, _url), do: data
75 defp parse_url(url) do
77 {:ok, %Tesla.Env{body: html}} = Pleroma.HTTP.get(url, [], adapter: @hackney_options)
81 |> clean_parsed_data()
82 |> check_parsed_data()
85 {:error, "Parsing error: #{inspect(e)}"}
89 defp maybe_parse(html) do
90 Enum.reduce_while(parsers(), %{}, fn parser, acc ->
91 case parser.parse(html, acc) do
92 {:ok, data} -> {:halt, data}
93 {:error, _msg} -> {:cont, acc}
98 defp check_parsed_data(%{title: title} = data) when is_binary(title) and byte_size(title) > 0 do
102 defp check_parsed_data(data) do
103 {:error, "Found metadata was invalid or incomplete: #{inspect(data)}"}
106 defp clean_parsed_data(data) do
108 |> Enum.reject(fn {key, val} ->
109 with {:ok, _} <- Jason.encode(%{key => val}) do