Refactor rich media parsers to restrict the allowed properties

Signed-off-by: Thomas Citharel <tcit@tcit.fr>
This commit is contained in:
Thomas Citharel
2021-01-22 18:14:52 +01:00
parent a6c2fb97a7
commit f0141c97e8
4 changed files with 103 additions and 20 deletions

View File

@@ -10,25 +10,49 @@ defmodule Mobilizon.Service.RichMedia.Parsers.TwitterCard do
alias Mobilizon.Service.RichMedia.Parsers.MetaTagsParser
require Logger
@twitter_card_properties [
:card,
:site,
:creator,
:title,
:description,
:image,
:"image:alt"
]
@spec parse(String.t(), map()) :: {:ok, map()} | {:error, String.t()}
def parse(html, data) do
Logger.debug("Using Twitter card parser")
res =
with {:ok, data} <- parse_name_attrs(data, html),
{:ok, data} <- parse_property_attrs(data, html),
data <- transform_tags(data) do
Logger.debug("Data found with Twitter card parser")
Logger.debug(inspect(data))
data
|> parse_name_attrs(html)
|> parse_property_attrs(html)
Logger.debug("Data found with Twitter card parser")
Logger.debug(inspect(res))
res
end
end
defp parse_name_attrs(data, html) do
MetaTagsParser.parse(html, data, "twitter", %{}, "name")
MetaTagsParser.parse(html, data, "twitter", %{}, :name, :content, [:"twitter:card"])
end
defp parse_property_attrs({_, data}, html) do
MetaTagsParser.parse(html, data, "twitter", "No twitter card metadata found", "property")
MetaTagsParser.parse(
html,
data,
"twitter",
"No twitter card metadata found",
:property,
:content,
@twitter_card_properties
)
end
defp transform_tags(data) do
data
|> Enum.reject(fn {_, v} -> is_nil(v) end)
|> Map.new()
|> Map.update(:image_remote_url, Map.get(data, :image), & &1)
end
end