File indexing completed on 2024-05-19 16:01:05

0001 // SPDX-FileCopyrightText: 2022 Carl Schwan <carl@carlschwan.eu>
0002 // SPDX-License-Identifier: LGPL-2.0-or-later
0003 
0004 #include "poll.h"
0005 
0006 #include <QJsonArray>
0007 #include <algorithm>
0008 
0009 Poll::Poll() = default;
0010 
0011 Poll::Poll(const QJsonObject &json)
0012 {
0013     m_id = json[QStringLiteral("id")].toString();
0014     m_expiresAt = QDateTime::fromString(json[QStringLiteral("expires_at")].toString(), Qt::ISODate);
0015     m_expired = json[QStringLiteral("expired")].toBool();
0016     m_multiple = json[QStringLiteral("multiple")].toBool();
0017     m_votesCount = json[QStringLiteral("votes_count")].toInt(-1);
0018     m_votersCount = json[QStringLiteral("voters_count")].toInt(-1);
0019     m_voted = json[QStringLiteral("voted")].toBool();
0020     const auto ownVotes = json[QStringLiteral("own_votes")].toArray();
0021     std::transform(
0022         ownVotes.cbegin(),
0023         ownVotes.cend(),
0024         std::back_inserter(m_ownVotes),
0025         [](const QJsonValue &value) -> auto{ return value.toInt(); });
0026 
0027     const auto emojis = json[QStringLiteral("emojis")].toArray();
0028 
0029     const auto options = json[QStringLiteral("options")].toArray();
0030     std::transform(options.cbegin(), options.cend(), std::back_inserter(m_options), [emojis](const QJsonValue &value) -> QVariantMap {
0031         const auto option = value.toObject();
0032         QString title = option[QStringLiteral("title")].toString();
0033         for (const auto &emoji : emojis) {
0034             const auto emojiObj = emoji.toObject();
0035             title = title.replace(QLatin1Char(':') + emojiObj["shortcode"].toString() + QLatin1Char(':'),
0036                                   "<img height=\"16\" align=\"middle\" width=\"16\" src=\"" + emojiObj["static_url"].toString() + "\">");
0037         }
0038         return {
0039             {"title", title},
0040             {"votesCount", option[QStringLiteral("votes_count")].toInt(-1)},
0041         };
0042     });
0043 }
0044 
0045 QString Poll::id() const
0046 {
0047     return m_id;
0048 }
0049 
0050 QDateTime Poll::expiresAt() const
0051 {
0052     return m_expiresAt;
0053 }
0054 
0055 bool Poll::expired() const
0056 {
0057     return m_expired;
0058 }
0059 
0060 bool Poll::multiple() const
0061 {
0062     return m_multiple;
0063 }
0064 
0065 int Poll::votesCount() const
0066 {
0067     return m_votesCount;
0068 }
0069 
0070 int Poll::votersCount() const
0071 {
0072     return m_votersCount;
0073 }
0074 
0075 bool Poll::voted() const
0076 {
0077     return m_voted;
0078 }
0079 
0080 QList<int> Poll::ownVotes() const
0081 {
0082     return m_ownVotes;
0083 }
0084 
0085 QList<QVariantMap> Poll::options() const
0086 {
0087     return m_options;
0088 }