mirror-chatterino2/src/common/DownloadManager.cpp

83 lines
1.9 KiB
C++
Raw Normal View History

2018-08-19 19:02:49 +02:00
#include "DownloadManager.hpp"
2018-08-29 23:39:02 +02:00
#include "singletons/Paths.hpp"
2018-08-19 19:02:49 +02:00
#include <QDesktopServices>
#include "common/QLogging.hpp"
2018-08-19 19:02:49 +02:00
namespace chatterino {
DownloadManager::DownloadManager(QObject *parent)
: QObject(parent)
{
manager = new QNetworkAccessManager;
}
DownloadManager::~DownloadManager()
{
manager->deleteLater();
}
void DownloadManager::setFile(QString fileURL, const QString &channelName)
{
QString saveFilePath;
2018-08-29 23:39:02 +02:00
saveFilePath =
getPaths()->twitchProfileAvatars + "/twitch/" + channelName + ".png";
2018-08-19 19:02:49 +02:00
QNetworkRequest request;
request.setUrl(QUrl(fileURL));
reply = manager->get(request);
file = new QFile;
file->setFileName(saveFilePath);
file->open(QIODevice::WriteOnly);
connect(reply, SIGNAL(downloadProgress(qint64, qint64)), this,
SLOT(onDownloadProgress(qint64, qint64)));
connect(manager, SIGNAL(finished(QNetworkReply *)), this,
SLOT(onFinished(QNetworkReply *)));
connect(reply, SIGNAL(readyRead()), this, SLOT(onReadyRead()));
connect(reply, SIGNAL(finished()), this, SLOT(onReplyFinished()));
}
void DownloadManager::onDownloadProgress(qint64 bytesRead, qint64 bytesTotal)
{
qCDebug(chatterinoCommon)
<< "Download progress: " << bytesRead << "/" << bytesTotal;
2018-08-19 19:02:49 +02:00
}
void DownloadManager::onFinished(QNetworkReply *reply)
{
2018-10-21 13:43:02 +02:00
switch (reply->error())
{
2019-09-26 00:51:05 +02:00
case QNetworkReply::NoError: {
qCDebug(chatterinoCommon) << "file is downloaded successfully.";
2018-10-21 13:43:02 +02:00
}
break;
2019-09-26 00:51:05 +02:00
default: {
qCDebug(chatterinoCommon) << reply->errorString().toLatin1();
2018-08-19 19:02:49 +02:00
};
}
2018-10-21 13:43:02 +02:00
if (file->isOpen())
{
2018-08-19 19:02:49 +02:00
file->close();
file->deleteLater();
}
emit downloadComplete();
}
void DownloadManager::onReadyRead()
{
file->write(reply->readAll());
}
void DownloadManager::onReplyFinished()
{
2018-10-21 13:43:02 +02:00
if (file->isOpen())
{
2018-08-19 19:02:49 +02:00
file->close();
file->deleteLater();
}
}
} // namespace chatterino