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)}
29 {:error, "Cachex error: #{inspect(e)}"}
34 defp parse_url(url) do
36 {:ok, %Tesla.Env{body: html}} = Pleroma.HTTP.get(url, [], adapter: @hackney_options)
40 |> clean_parsed_data()
41 |> check_parsed_data()
44 {:error, "Parsing error: #{inspect(e)}"}
48 defp maybe_parse(html) do
49 Enum.reduce_while(parsers(), %{}, fn parser, acc ->
50 case parser.parse(html, acc) do
51 {:ok, data} -> {:halt, data}
52 {:error, _msg} -> {:cont, acc}
57 defp check_parsed_data(%{title: title} = data) when is_binary(title) and byte_size(title) > 0 do
61 defp check_parsed_data(data) do
62 {:error, "Found metadata was invalid or incomplete: #{inspect(data)}"}
65 defp clean_parsed_data(data) do
67 |> Enum.reject(fn {key, val} ->
68 with {:ok, _} <- Jason.encode(%{key => val}) do