Fix issues with cached images being accessed while the download is still running

This commit is contained in:
Bart De Vries 2021-10-06 16:07:05 +02:00
parent 044dbf5f23
commit de954f644a
2 changed files with 26 additions and 7 deletions

View File

@ -109,7 +109,7 @@ void Fetcher::fetch(const QStringList &urls)
qCDebug(kastsFetcher) << "end of Fetcher::fetch";
}
QString Fetcher::image(const QString &url) const
QString Fetcher::image(const QString &url)
{
if (url.isEmpty()) {
return QLatin1String("no-image");
@ -123,18 +123,35 @@ QString Fetcher::image(const QString &url) const
}
}
// avoid restarting an image download if it's already running
if (m_ongoingImageDownloads.contains(url)) {
return QLatin1String("fetching");
}
// if image has not yet been cached, then check for network connectivity if
// possible; and download the image
if (canCheckNetworkStatus()) {
if (networkConnected() && (!isMeteredConnection() || SettingsManager::self()->allowMeteredImageDownloads())) {
download(url, path);
} else {
if (!networkConnected() || (isMeteredConnection() && !SettingsManager::self()->allowMeteredImageDownloads())) {
return QLatin1String("no-image");
}
} else {
download(url, path);
}
m_ongoingImageDownloads.insert(url);
QNetworkRequest request((QUrl(url)));
request.setTransferTimeout();
QNetworkReply *reply = get(request);
connect(reply, &QNetworkReply::finished, this, [=]() {
if (reply->isOpen() && !reply->error()) {
QByteArray data = reply->readAll();
QFile file(path);
file.open(QIODevice::WriteOnly);
file.write(data);
file.close();
Q_EMIT downloadFinished(url);
}
m_ongoingImageDownloads.remove(url);
reply->deleteLater();
});
return QLatin1String("fetching");
}

View File

@ -39,7 +39,7 @@ public:
Q_INVOKABLE void fetch(const QString &url);
Q_INVOKABLE void fetch(const QStringList &urls);
Q_INVOKABLE void fetchAll();
Q_INVOKABLE QString image(const QString &url) const;
Q_INVOKABLE QString image(const QString &url);
Q_INVOKABLE QNetworkReply *download(const QString &url, const QString &fileName) const;
QNetworkReply *get(QNetworkRequest &request) const;
@ -74,6 +74,8 @@ private:
QNetworkReply *head(QNetworkRequest &request) const;
void setHeader(QNetworkRequest &request) const;
QSet<QString> m_ongoingImageDownloads;
QNetworkAccessManager *manager;
int m_updateProgress;
int m_updateTotal;