File indexing completed on 2024-02-18 05:01:13

0001 /*
0002    SPDX-FileCopyrightText: 2019-2024 Laurent Montel <montel@kde.org>
0003 
0004    SPDX-License-Identifier: LGPL-2.0-or-later
0005 */
0006 
0007 #include "avatarmanager.h"
0008 #include "rocketchataccount.h"
0009 #include "ruqola_debug.h"
0010 #include <QTimer>
0011 #include <chrono>
0012 using namespace std::chrono_literals;
0013 
0014 AvatarManager::AvatarManager(RocketChatAccount *account, QObject *parent)
0015     : QObject(parent)
0016     , mAccount(account)
0017     , mTimer(new QTimer(this))
0018 {
0019     mTimer->setSingleShot(true);
0020     // increase interval otherwise we can have some error
0021     mTimer->setInterval(2s);
0022     connect(mTimer, &QTimer::timeout, this, &AvatarManager::slotLoadNextAvatar);
0023 }
0024 
0025 AvatarManager::~AvatarManager() = default;
0026 
0027 void AvatarManager::slotLoadNextAvatar()
0028 {
0029     const Utils::AvatarInfo info = mAvatarDownloadIdentifer.constFirst();
0030     const QUrl url = Utils::avatarUrl(mAccount->serverUrl(), info);
0031     // qDebug() << " url " << url;
0032     if (url.isEmpty()) {
0033         return;
0034     }
0035     slotInsertAvatarUrl(info, url);
0036 }
0037 
0038 void AvatarManager::slotRescheduleDownload()
0039 {
0040     // if problem we need to reschedule after several seconds
0041     QTimer::singleShot(20s, this, &AvatarManager::slotLoadNextAvatar);
0042 }
0043 
0044 void AvatarManager::insertInDownloadQueue(const Utils::AvatarInfo &info)
0045 {
0046     if (!info.isValid()) {
0047         qCWarning(RUQOLA_LOG) << "AvatarManager::insertInDownloadQueue info is not valid!" << info;
0048         return;
0049     }
0050     bool startDownload = false;
0051     if (mAvatarDownloadIdentifer.isEmpty()) {
0052         startDownload = true;
0053     }
0054     if (!mAvatarDownloadIdentifer.contains(info)) {
0055         mAvatarDownloadIdentifer.append(info);
0056     }
0057     if (startDownload) {
0058         mTimer->start();
0059     }
0060 }
0061 
0062 RocketChatAccount *AvatarManager::account() const
0063 {
0064     return mAccount;
0065 }
0066 
0067 void AvatarManager::slotInsertAvatarUrl(const Utils::AvatarInfo &info, const QUrl &url)
0068 {
0069     const QString identifier = info.generateAvatarIdentifier();
0070     qDebug() << "AvatarManager::slotInsertAvatarUrl: identifier " << identifier;
0071     // Use etag in identifier ?
0072     if (!url.isEmpty()) {
0073         Q_EMIT insertAvatarUrl(identifier, url);
0074     } // Else error for downloading => don't redownload it + continue.
0075 
0076     mAvatarDownloadIdentifer.removeAll(info);
0077     // qDebug() << " mAvatarDownloadUserIds" << mAvatarDownloadUserIds;
0078     if (!mAvatarDownloadIdentifer.isEmpty()) {
0079         mTimer->start();
0080     }
0081 }
0082 
0083 #include "moc_avatarmanager.cpp"