File indexing completed on 2025-02-23 04:35:16
0001 // SPDX-FileCopyrightText: 2023 Joshua Goins <josh@redstrate.com> 0002 // SPDX-License-Identifier: GPL-3.0-or-later 0003 0004 #include "pipedinstancesmodel.h" 0005 0006 #include "plasmatube.h" 0007 0008 #include <QUrlQuery> 0009 0010 using namespace Qt::Literals::StringLiterals; 0011 0012 PipedInstancesModel::PipedInstancesModel(QObject *parent) 0013 : QAbstractListModel(parent) 0014 { 0015 fill(); 0016 } 0017 0018 QVariant PipedInstancesModel::data(const QModelIndex &index, int role) const 0019 { 0020 Q_ASSERT(checkIndex(index, QAbstractItemModel::CheckIndexOption::IndexIsValid)); 0021 0022 const auto &instance = m_instances[index.row()]; 0023 0024 switch (role) { 0025 case NameRole: 0026 return instance.name; 0027 case URLRole: 0028 return instance.url; 0029 default: 0030 return {}; 0031 } 0032 } 0033 0034 bool PipedInstancesModel::loading() const 0035 { 0036 return m_loading; 0037 } 0038 0039 void PipedInstancesModel::setLoading(bool loading) 0040 { 0041 if (m_loading == loading) { 0042 return; 0043 } 0044 m_loading = loading; 0045 Q_EMIT loadingChanged(); 0046 } 0047 0048 int PipedInstancesModel::rowCount(const QModelIndex &parent) const 0049 { 0050 return parent.isValid() ? 0 : static_cast<int>(m_instances.size()); 0051 } 0052 0053 QHash<int, QByteArray> PipedInstancesModel::roleNames() const 0054 { 0055 return {{NameRole, "name"}, {URLRole, "url"}}; 0056 } 0057 0058 void PipedInstancesModel::fill() 0059 { 0060 if (m_loading) { 0061 return; 0062 } 0063 setLoading(true); 0064 0065 QUrl url(QStringLiteral("https://raw.githubusercontent.com/wiki/TeamPiped/Piped/Instances.md")); 0066 0067 auto reply = m_netManager.get(QNetworkRequest(url)); 0068 connect(reply, &QNetworkReply::finished, this, [this, reply] { 0069 QTextStream stream(reply->readAll()); 0070 0071 bool beginList = false; 0072 0073 QString line; 0074 while (stream.readLineInto(&line)) { 0075 if (line == QStringLiteral("--- | --- | --- | --- | ---")) { 0076 beginList = true; 0077 } else if (beginList) { 0078 const QStringList parts = line.split("|"_L1); 0079 const QString name = parts[0].trimmed(); 0080 const QString url = parts[1].trimmed(); 0081 0082 beginInsertRows({}, m_instances.size(), m_instances.size()); 0083 m_instances.push_back({name, url}); 0084 endInsertRows(); 0085 } 0086 } 0087 0088 setLoading(false); 0089 }); 0090 } 0091 0092 #include "moc_pipedinstancesmodel.cpp"