File indexing completed on 2024-05-12 05:04:09
0001 // SPDX-FileCopyrightText: 2023 Joshua Goins <josh@redstrate.com> 0002 // SPDX-License-Identifier: GPL-3.0-or-later 0003 0004 #include "listsmodel.h" 0005 0006 #include "abstractaccount.h" 0007 #include "accountmanager.h" 0008 0009 using namespace Qt::Literals::StringLiterals; 0010 0011 ListsModel::ListsModel(QObject *parent) 0012 : QAbstractListModel(parent) 0013 { 0014 fillTimeline(); 0015 } 0016 0017 QVariant ListsModel::data(const QModelIndex &index, int role) const 0018 { 0019 Q_ASSERT(checkIndex(index, QAbstractItemModel::CheckIndexOption::IndexIsValid)); 0020 0021 const auto &list = m_lists[index.row()]; 0022 0023 switch (role) { 0024 case IdRole: 0025 return list.id; 0026 case TitleRole: 0027 return list.title; 0028 default: 0029 return {}; 0030 } 0031 } 0032 0033 bool ListsModel::loading() const 0034 { 0035 return m_loading; 0036 } 0037 0038 void ListsModel::setLoading(bool loading) 0039 { 0040 if (m_loading == loading) { 0041 return; 0042 } 0043 m_loading = loading; 0044 Q_EMIT loadingChanged(); 0045 } 0046 0047 int ListsModel::rowCount(const QModelIndex &parent) const 0048 { 0049 return parent.isValid() ? 0 : m_lists.size(); 0050 } 0051 0052 QHash<int, QByteArray> ListsModel::roleNames() const 0053 { 0054 return { 0055 {IdRole, "id"}, 0056 {TitleRole, "title"}, 0057 }; 0058 } 0059 0060 void ListsModel::fillTimeline() 0061 { 0062 const auto account = AccountManager::instance().selectedAccount(); 0063 0064 if (m_loading) { 0065 return; 0066 } 0067 setLoading(true); 0068 0069 account->get(account->apiUrl(QStringLiteral("/api/v1/lists")), true, this, [this](QNetworkReply *reply) { 0070 const auto doc = QJsonDocument::fromJson(reply->readAll()); 0071 auto lists = doc.array().toVariantList(); 0072 0073 if (!lists.isEmpty()) { 0074 QList<List> fetchedLists; 0075 0076 std::transform(lists.cbegin(), lists.cend(), std::back_inserter(fetchedLists), [=](const QVariant &value) -> auto { 0077 return fromSourceData(value.toJsonObject()); 0078 }); 0079 beginInsertRows({}, m_lists.size(), m_lists.size() + fetchedLists.size() - 1); 0080 m_lists += fetchedLists; 0081 endInsertRows(); 0082 } 0083 0084 setLoading(false); 0085 }); 0086 } 0087 0088 ListsModel::List ListsModel::fromSourceData(const QJsonObject &object) const 0089 { 0090 List list; 0091 list.id = object["id"_L1].toString(); 0092 list.title = object["title"_L1].toString(); 0093 0094 return list; 0095 } 0096 0097 #include "moc_listsmodel.cpp"