larra/library/include/larra/iq.hpp

82 lines
2.8 KiB
C++

#pragma once
#include <larra/serialization.hpp>
#include <larra/stream_error.hpp>
#include <larra/utils.hpp>
#include <string>
namespace larra::xmpp {
namespace iq {
template <auto& Name, typename PayloadType>
struct BaseImplWithPayload {
std::string id;
PayloadType payload;
static const inline std::string kName = Name;
static constexpr auto kDefaultName = "iq";
constexpr auto operator==(const BaseImplWithPayload&) const -> bool = default;
template <typename Self>
[[nodiscard]] constexpr auto Id(this Self&& self, std::string id) -> std::decay_t<Self> {
return utils::FieldSetHelper::With<"id", BaseImplWithPayload>(std::forward<Self>(self), std::move(id));
}
template <typename NewPayloadType, typename Self>
[[nodiscard]] constexpr auto Payload(this Self&& self, NewPayloadType value) {
return utils::FieldSetHelper::With<"payload", BaseImplWithPayload, false>(std::forward<Self>(self), std::move(value));
}
friend constexpr auto operator<<(xmlpp::Element* element, const BaseImplWithPayload& self) {
element->set_attribute("id", self.id);
element->set_attribute("type", kName);
using S = Serialization<PayloadType>;
S::Serialize(element->add_child_element(S::kDefaultName, S::kPrefix), self.payload);
}
[[nodiscard]] static constexpr auto Parse(xmlpp::Element* element) -> BaseImplWithPayload {
auto node = element->get_attribute("type");
if(!node) {
throw std::runtime_error("Not found attribute type for parse Iq");
}
if(node->get_value() != Name) {
throw std::runtime_error("Invalid attribute type for parse Iq");
}
auto idNode = element->get_attribute("id");
if(!idNode) {
throw std::runtime_error("Not found attribute id for parse Iq");
}
using S = Serialization<PayloadType>;
auto payload = element->get_first_child(S::kDefaultName);
if(!payload) {
throw std::runtime_error("Not found payload for parse Iq");
}
auto payload2 = dynamic_cast<xmlpp::Element*>(payload);
if(!payload2) {
throw std::runtime_error("Invalid payload for parse Iq");
}
return {.id = idNode->get_value(), .payload = S::Parse(payload2)};
}
};
static constexpr auto kGetName = "get";
template <typename Payload>
using Get = BaseImplWithPayload<kGetName, Payload>;
static constexpr auto kSetName = "set";
template <typename Payload>
using Set = BaseImplWithPayload<kSetName, Payload>;
static constexpr auto kResultName = "result";
template <typename Payload>
using Result = BaseImplWithPayload<kResultName, Payload>;
static constexpr auto kErrorName = "error";
template <typename Payload>
using Error = BaseImplWithPayload<kErrorName, Payload>;
} // namespace iq
template <typename Payload>
using Iq = std::variant<iq::Get<Payload>, iq::Set<Payload>, iq::Result<Payload>, iq::Error<Payload>>;
} // namespace larra::xmpp