Merge branch 'release/2.1.2' into 'stable'
[akkoma] / lib / pleroma / web / rich_media / parser.ex
1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/>
3 # SPDX-License-Identifier: AGPL-3.0-only
4
5 defmodule Pleroma.Web.RichMedia.Parser do
6 require Logger
7
8 defp parsers do
9 Pleroma.Config.get([:rich_media, :parsers])
10 end
11
12 def parse(nil), do: {:error, "No URL provided"}
13
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)
17 else
18 @spec parse(String.t()) :: {:ok, map()} | {:error, any()}
19 def parse(url) do
20 with {:ok, data} <- get_cached_or_parse(url),
21 {:ok, _} <- set_ttl_based_on_image(data, url) do
22 {:ok, data}
23 else
24 error ->
25 Logger.error(fn -> "Rich media error: #{inspect(error)}" end)
26 end
27 end
28
29 defp get_cached_or_parse(url) do
30 case Cachex.fetch!(:rich_media_cache, url, fn _ -> {:commit, parse_url(url)} end) do
31 {:ok, _data} = res ->
32 res
33
34 {:error, :body_too_large} = e ->
35 e
36
37 {:error, {:content_type, _}} = e ->
38 e
39
40 # The TTL is not set for the errors above, since they are unlikely to change
41 # with time
42 {:error, _} = e ->
43 ttl = Pleroma.Config.get([:rich_media, :failure_backoff], 60_000)
44 Cachex.expire(:rich_media_cache, url, ttl)
45 e
46 end
47 end
48 end
49
50 @doc """
51 Set the rich media cache based on the expiration time of image.
52
53 Adopt behaviour `Pleroma.Web.RichMedia.Parser.TTL`
54
55 ## Example
56
57 defmodule MyModule do
58 @behaviour Pleroma.Web.RichMedia.Parser.TTL
59 def ttl(data, url) do
60 image_url = Map.get(data, :image)
61 # do some parsing in the url and get the ttl of the image
62 # and return ttl is unix time
63 parse_ttl_from_url(image_url)
64 end
65 end
66
67 Define the module in the config
68
69 config :pleroma, :rich_media,
70 ttl_setters: [MyModule]
71 """
72 @spec set_ttl_based_on_image(map(), String.t()) ::
73 {:ok, Integer.t() | :noop} | {:error, :no_key}
74 def set_ttl_based_on_image(data, url) do
75 case get_ttl_from_image(data, url) do
76 {:ok, ttl} when is_number(ttl) ->
77 ttl = ttl * 1000
78
79 case Cachex.expire_at(:rich_media_cache, url, ttl) do
80 {:ok, true} -> {:ok, ttl}
81 {:ok, false} -> {:error, :no_key}
82 end
83
84 _ ->
85 {:ok, :noop}
86 end
87 end
88
89 defp get_ttl_from_image(data, url) do
90 [:rich_media, :ttl_setters]
91 |> Pleroma.Config.get()
92 |> Enum.reduce({:ok, nil}, fn
93 module, {:ok, _ttl} ->
94 module.ttl(data, url)
95
96 _, error ->
97 error
98 end)
99 end
100
101 defp parse_url(url) do
102 with {:ok, %Tesla.Env{body: html}} <- Pleroma.Web.RichMedia.Helpers.rich_media_get(url),
103 {:ok, html} <- Floki.parse_document(html) do
104 html
105 |> maybe_parse()
106 |> Map.put("url", url)
107 |> clean_parsed_data()
108 |> check_parsed_data()
109 end
110 end
111
112 defp maybe_parse(html) do
113 Enum.reduce_while(parsers(), %{}, fn parser, acc ->
114 case parser.parse(html, acc) do
115 data when data != %{} -> {:halt, data}
116 _ -> {:cont, acc}
117 end
118 end)
119 end
120
121 defp check_parsed_data(%{"title" => title} = data)
122 when is_binary(title) and title != "" do
123 {:ok, data}
124 end
125
126 defp check_parsed_data(data) do
127 {:error, "Found metadata was invalid or incomplete: #{inspect(data)}"}
128 end
129
130 defp clean_parsed_data(data) do
131 data
132 |> Enum.reject(fn {key, val} ->
133 not match?({:ok, _}, Jason.encode(%{key => val}))
134 end)
135 |> Map.new()
136 end
137 end