2018-12-24 13:34:45 +01:00
|
|
|
# Portions of this file are derived from Pleroma:
|
|
|
|
# Copyright © 2017-2018 Pleroma Authors <https://pleroma.social>
|
|
|
|
# SPDX-License-Identifier: AGPL-3.0-only
|
2018-12-27 11:24:04 +01:00
|
|
|
# Upstream: https://git.pleroma.social/pleroma/pleroma/blob/develop/lib/xml_builder.ex
|
2018-12-24 13:34:45 +01:00
|
|
|
|
2020-01-22 22:40:40 +01:00
|
|
|
defmodule Mobilizon.Federation.WebFinger.XmlBuilder do
|
2018-06-14 18:15:27 +02:00
|
|
|
@moduledoc """
|
2021-09-24 16:46:42 +02:00
|
|
|
Extremely basic XML encoder. Builds XRD for WebFinger host_meta.
|
2018-06-14 18:15:27 +02:00
|
|
|
"""
|
|
|
|
|
2021-09-24 16:46:42 +02:00
|
|
|
@typep content :: list({tag :: atom(), attributes :: map()}) | String.t()
|
|
|
|
@typep document :: {tag :: atom(), attributes :: map(), content :: content}
|
|
|
|
|
|
|
|
@doc """
|
|
|
|
Return the XML representation for a document.
|
|
|
|
"""
|
|
|
|
@spec to_doc(document :: document) :: String.t()
|
|
|
|
def to_doc(document), do: ~s(<?xml version="1.0" encoding="UTF-8"?>) <> to_xml(document)
|
|
|
|
|
|
|
|
@spec to_xml(document) :: String.t()
|
|
|
|
@spec to_xml({tag :: atom(), attributes :: map()}) :: String.t()
|
|
|
|
@spec to_xml({tag :: atom(), content :: content}) :: String.t()
|
|
|
|
@spec to_xml(content :: content) :: String.t()
|
|
|
|
defp to_xml({tag, attributes, content}) do
|
2018-05-17 11:32:23 +02:00
|
|
|
open_tag = make_open_tag(tag, attributes)
|
|
|
|
content_xml = to_xml(content)
|
|
|
|
|
|
|
|
"<#{open_tag}>#{content_xml}</#{tag}>"
|
|
|
|
end
|
|
|
|
|
2021-09-24 16:46:42 +02:00
|
|
|
defp to_xml({tag, %{} = attributes}) do
|
2018-05-17 11:32:23 +02:00
|
|
|
open_tag = make_open_tag(tag, attributes)
|
|
|
|
|
|
|
|
"<#{open_tag} />"
|
|
|
|
end
|
|
|
|
|
2021-09-24 16:46:42 +02:00
|
|
|
defp to_xml({tag, content}), do: to_xml({tag, %{}, content})
|
2018-05-17 11:32:23 +02:00
|
|
|
|
2021-09-24 16:46:42 +02:00
|
|
|
defp to_xml(content) when is_binary(content), do: to_string(content)
|
2018-05-17 11:32:23 +02:00
|
|
|
|
2021-09-24 16:46:42 +02:00
|
|
|
defp to_xml(content) when is_list(content) do
|
2021-11-26 14:30:46 +01:00
|
|
|
Enum.map_join(content, &to_xml/1)
|
2018-05-17 11:32:23 +02:00
|
|
|
end
|
|
|
|
|
2021-09-24 16:46:42 +02:00
|
|
|
defp to_xml(%NaiveDateTime{} = time), do: NaiveDateTime.to_iso8601(time)
|
2018-05-17 11:32:23 +02:00
|
|
|
|
2021-09-24 16:46:42 +02:00
|
|
|
@spec make_open_tag(tag :: atom, attributes :: map()) :: String.t()
|
2018-05-17 11:32:23 +02:00
|
|
|
defp make_open_tag(tag, attributes) do
|
|
|
|
attributes_string =
|
2021-11-26 14:30:46 +01:00
|
|
|
Enum.map_join(attributes, " ", fn {attribute, value} -> "#{attribute}=\"#{value}\"" end)
|
2018-05-17 11:32:23 +02:00
|
|
|
|
2021-09-24 16:46:42 +02:00
|
|
|
[to_string(tag), attributes_string] |> Enum.join(" ") |> String.trim()
|
2018-05-17 11:32:23 +02:00
|
|
|
end
|
|
|
|
end
|