mirror-chatterino2/src/common/DownloadManager.cpp

84 lines
2.1 KiB
C++
Raw Normal View History

2018-08-19 19:02:49 +02:00
#include "DownloadManager.hpp"
#include "common/QLogging.hpp"
2018-08-29 23:39:02 +02:00
#include "singletons/Paths.hpp"
2018-08-19 19:02:49 +02:00
#include <QDesktopServices>
namespace chatterino {
DownloadManager::DownloadManager(QObject *parent)
: QObject(parent)
, manager_(new QNetworkAccessManager)
2018-08-19 19:02:49 +02:00
{
}
DownloadManager::~DownloadManager()
{
this->manager_->deleteLater();
2018-08-19 19:02:49 +02:00
}
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));
this->reply_ = this->manager_->get(request);
2018-08-19 19:02:49 +02:00
this->file_ = new QFile;
this->file_->setFileName(saveFilePath);
this->file_->open(QIODevice::WriteOnly);
2018-08-19 19:02:49 +02:00
connect(this->reply_, SIGNAL(downloadProgress(qint64, qint64)), this,
2018-08-19 19:02:49 +02:00
SLOT(onDownloadProgress(qint64, qint64)));
connect(this->manager_, SIGNAL(finished(QNetworkReply *)), this,
2018-08-19 19:02:49 +02:00
SLOT(onFinished(QNetworkReply *)));
connect(this->reply_, SIGNAL(readyRead()), this, SLOT(onReadyRead()));
connect(this->reply_, SIGNAL(finished()), this, SLOT(onReplyFinished()));
2018-08-19 19:02:49 +02:00
}
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
};
}
if (this->file_->isOpen())
2018-10-21 13:43:02 +02:00
{
this->file_->close();
this->file_->deleteLater();
2018-08-19 19:02:49 +02:00
}
emit downloadComplete();
}
void DownloadManager::onReadyRead()
{
this->file_->write(this->reply_->readAll());
2018-08-19 19:02:49 +02:00
}
void DownloadManager::onReplyFinished()
{
if (this->file_->isOpen())
2018-10-21 13:43:02 +02:00
{
this->file_->close();
this->file_->deleteLater();
2018-08-19 19:02:49 +02:00
}
}
2018-08-19 19:02:49 +02:00
} // namespace chatterino