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 "playlistsmodel.h"
0005 
0006 #include "plasmatube.h"
0007 
0008 using namespace Qt::Literals::StringLiterals;
0009 
0010 PlaylistsModel::PlaylistsModel(QObject *parent)
0011     : AbstractListModel(parent)
0012 {
0013     fill();
0014 }
0015 
0016 QVariant PlaylistsModel::data(const QModelIndex &index, int role) const
0017 {
0018     Q_ASSERT(checkIndex(index, QAbstractItemModel::CheckIndexOption::IndexIsValid));
0019 
0020     const auto &comment = m_playlists[index.row()];
0021 
0022     switch (role) {
0023     case IdRole:
0024         return comment.id();
0025     case TypeRole:
0026         return QStringLiteral("playlist");
0027     case TitleRole:
0028         return comment.title();
0029     case ThumbnailRole:
0030         return comment.thumbnail();
0031     case VideoCountRole:
0032         return comment.videoCount();
0033     default:
0034         return {};
0035     }
0036 }
0037 
0038 int PlaylistsModel::rowCount(const QModelIndex &parent) const
0039 {
0040     return parent.isValid() ? 0 : m_playlists.size();
0041 }
0042 
0043 void PlaylistsModel::fill()
0044 {
0045     if (isLoading()) {
0046         return;
0047     }
0048     setLoading(true);
0049 
0050     m_futureWatcher = new QFutureWatcher<QInvidious::PlaylistsResult>();
0051 
0052     auto future = PlasmaTube::instance().sourceManager()->selectedSource()->api()->requestPlaylists();
0053     m_futureWatcher->setFuture(future);
0054 
0055     connect(m_futureWatcher, &QFutureWatcherBase::finished, this, [this] {
0056         auto result = m_futureWatcher->result();
0057         if (auto playlists = std::get_if<QList<QInvidious::Playlist>>(&result)) {
0058             const auto rows = rowCount({});
0059             beginInsertRows({}, rows, rows + playlists->size() - 1);
0060             m_playlists << *playlists;
0061             endInsertRows();
0062         } else if (auto error = std::get_if<QInvidious::Error>(&result)) {
0063             // TODO: Log error
0064         }
0065 
0066         m_futureWatcher->deleteLater();
0067         m_futureWatcher = nullptr;
0068         setLoading(false);
0069     });
0070 }
0071 
0072 #include "moc_playlistsmodel.cpp"