2020-02-18 08:57:00 +01:00
|
|
|
# Portions of this file are derived from Pleroma:
|
|
|
|
# Pleroma: A lightweight social networking server
|
|
|
|
# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/>
|
|
|
|
# SPDX-License-Identifier: AGPL-3.0-only
|
|
|
|
|
|
|
|
defmodule Mobilizon.Service.RichMedia.Parsers.TwitterCard do
|
|
|
|
@moduledoc """
|
|
|
|
Module to parse Twitter tags data in HTML pages
|
|
|
|
"""
|
|
|
|
alias Mobilizon.Service.RichMedia.Parsers.MetaTagsParser
|
|
|
|
require Logger
|
|
|
|
|
2021-01-22 18:14:52 +01:00
|
|
|
@twitter_card_properties [
|
|
|
|
:card,
|
|
|
|
:site,
|
|
|
|
:creator,
|
|
|
|
:title,
|
|
|
|
:description,
|
|
|
|
:image,
|
|
|
|
:"image:alt"
|
|
|
|
]
|
|
|
|
|
2020-02-18 08:57:00 +01:00
|
|
|
@spec parse(String.t(), map()) :: {:ok, map()} | {:error, String.t()}
|
|
|
|
def parse(html, data) do
|
|
|
|
Logger.debug("Using Twitter card parser")
|
|
|
|
|
2021-01-22 18:14:52 +01:00
|
|
|
with {:ok, data} <- parse_name_attrs(data, html),
|
2021-10-05 16:04:50 +02:00
|
|
|
{:ok, data} <- parse_property_attrs(data, html) do
|
|
|
|
data = transform_tags(data)
|
2021-01-22 18:14:52 +01:00
|
|
|
Logger.debug("Data found with Twitter card parser")
|
|
|
|
Logger.debug(inspect(data))
|
2020-02-18 08:57:00 +01:00
|
|
|
data
|
2021-01-22 18:14:52 +01:00
|
|
|
end
|
2020-02-18 08:57:00 +01:00
|
|
|
end
|
|
|
|
|
2021-10-05 16:04:50 +02:00
|
|
|
@spec parse_name_attrs(map(), String.t()) :: {:ok, map()} | {:error, String.t()}
|
2020-02-18 08:57:00 +01:00
|
|
|
defp parse_name_attrs(data, html) do
|
2021-10-05 16:04:50 +02:00
|
|
|
MetaTagsParser.parse(
|
|
|
|
html,
|
|
|
|
data,
|
|
|
|
"twitter",
|
|
|
|
"No twitter card metadata found",
|
|
|
|
:name,
|
|
|
|
:content,
|
|
|
|
[:"twitter:card"]
|
|
|
|
)
|
2020-02-18 08:57:00 +01:00
|
|
|
end
|
|
|
|
|
2021-10-05 16:04:50 +02:00
|
|
|
@spec parse_property_attrs(map(), String.t()) :: {:ok, map()} | {:error, String.t()}
|
|
|
|
defp parse_property_attrs(data, html) do
|
2021-01-22 18:14:52 +01:00
|
|
|
MetaTagsParser.parse(
|
|
|
|
html,
|
|
|
|
data,
|
|
|
|
"twitter",
|
|
|
|
"No twitter card metadata found",
|
|
|
|
:property,
|
|
|
|
:content,
|
|
|
|
@twitter_card_properties
|
|
|
|
)
|
|
|
|
end
|
|
|
|
|
2021-10-05 16:04:50 +02:00
|
|
|
@spec transform_tags(map()) :: map()
|
2021-01-22 18:14:52 +01:00
|
|
|
defp transform_tags(data) do
|
|
|
|
data
|
|
|
|
|> Enum.reject(fn {_, v} -> is_nil(v) end)
|
2022-01-18 12:52:45 +01:00
|
|
|
|> Enum.map(fn {k, v} -> {k, String.trim(v)} end)
|
2021-01-22 18:14:52 +01:00
|
|
|
|> Map.new()
|
|
|
|
|> Map.update(:image_remote_url, Map.get(data, :image), & &1)
|
2020-02-18 08:57:00 +01:00
|
|
|
end
|
|
|
|
end
|