Merge branch 'deactivated-user-posts' into 'develop'
[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 defp parsers do
7 Pleroma.Config.get([:rich_media, :parsers])
8 end
9
10 def parse(nil), do: {:error, "No URL provided"}
11
12 if Pleroma.Config.get(:env) == :test do
13 def parse(url), do: parse_url(url)
14 else
15 def parse(url) do
16 try do
17 Cachex.fetch!(:rich_media_cache, url, fn _ ->
18 {:commit, parse_url(url)}
19 end)
20 |> set_ttl_based_on_image(url)
21 rescue
22 e ->
23 {:error, "Cachex error: #{inspect(e)}"}
24 end
25 end
26 end
27
28 @doc """
29 Set the rich media cache based on the expiration time of image.
30
31 Adopt behaviour `Pleroma.Web.RichMedia.Parser.TTL`
32
33 ## Example
34
35 defmodule MyModule do
36 @behaviour Pleroma.Web.RichMedia.Parser.TTL
37 def ttl(data, url) do
38 image_url = Map.get(data, :image)
39 # do some parsing in the url and get the ttl of the image
40 # and return ttl is unix time
41 parse_ttl_from_url(image_url)
42 end
43 end
44
45 Define the module in the config
46
47 config :pleroma, :rich_media,
48 ttl_setters: [MyModule]
49 """
50 def set_ttl_based_on_image({:ok, data}, url) do
51 with {:ok, nil} <- Cachex.ttl(:rich_media_cache, url),
52 ttl when is_number(ttl) <- get_ttl_from_image(data, url) do
53 Cachex.expire_at(:rich_media_cache, url, ttl * 1000)
54 {:ok, data}
55 else
56 _ ->
57 {:ok, data}
58 end
59 end
60
61 defp get_ttl_from_image(data, url) do
62 Pleroma.Config.get([:rich_media, :ttl_setters])
63 |> Enum.reduce({:ok, nil}, fn
64 module, {:ok, _ttl} ->
65 module.ttl(data, url)
66
67 _, error ->
68 error
69 end)
70 end
71
72 defp parse_url(url) do
73 try do
74 {:ok, %Tesla.Env{body: html}} = Pleroma.Web.RichMedia.Helpers.rich_media_get(url)
75
76 html
77 |> parse_html()
78 |> maybe_parse()
79 |> Map.put("url", url)
80 |> clean_parsed_data()
81 |> check_parsed_data()
82 rescue
83 e ->
84 {:error, "Parsing error: #{inspect(e)} #{inspect(__STACKTRACE__)}"}
85 end
86 end
87
88 defp parse_html(html), do: Floki.parse_document!(html)
89
90 defp maybe_parse(html) do
91 Enum.reduce_while(parsers(), %{}, fn parser, acc ->
92 case parser.parse(html, acc) do
93 data when data != %{} -> {:halt, data}
94 _ -> {:cont, acc}
95 end
96 end)
97 end
98
99 defp check_parsed_data(%{"title" => title} = data)
100 when is_binary(title) and title != "" do
101 {:ok, data}
102 end
103
104 defp check_parsed_data(data) do
105 {:error, "Found metadata was invalid or incomplete: #{inspect(data)}"}
106 end
107
108 defp clean_parsed_data(data) do
109 data
110 |> Enum.reject(fn {key, val} ->
111 not match?({:ok, _}, Jason.encode(%{key => val}))
112 end)
113 |> Map.new()
114 end
115 end