| 1 |
/* |
| 2 |
* SPDX-FileCopyrightText: 2018-2018 CSSlayer <[email protected]> |
| 3 |
* |
| 4 |
* SPDX-License-Identifier: LGPL-2.1-or-later |
| 5 |
* |
| 6 |
*/ |
| 7 |
|
| 8 |
#include "filedownloader.h" |
| 9 |
#include "pipelinejob.h" |
| 10 |
#include <QMessageBox> |
| 11 |
#include <QNetworkReply> |
| 12 |
#include <QNetworkRequest> |
| 13 |
#include <QString> |
| 14 |
#include <QTemporaryFile> |
| 15 |
#include <fcitx-utils/i18n.h> |
| 16 |
|
| 17 |
namespace fcitx { |
| 18 |
|
| 19 |
FileDownloader::FileDownloader(const QUrl &url, const QString &dest, |
| 20 |
QObject *parent) |
| 21 |
: PipelineJob(parent), url_(url), file_(dest), progress_(0) {} |
| 22 |
|
| 23 |
void FileDownloader::start() { |
| 24 |
if (!file_.open(QIODevice::WriteOnly)) { |
| 25 |
Q_EMIT message(QMessageBox::Warning, |
| 26 |
_("Create temporary file failed.")); |
| 27 |
Q_EMIT finished(false); |
| 28 |
return; |
| 29 |
} |
| 30 |
Q_EMIT message(QMessageBox::Information, _("Temporary file created.")); |
| 31 |
|
| 32 |
QNetworkRequest request(url_); |
| 33 |
request.setRawHeader( |
| 34 |
"Referer", |
| 35 |
QString("%1://%2").arg(url_.scheme()).arg(url_.host()).toLatin1()); |
| 36 |
reply_ = nam_.get(request); |
| 37 |
|
| 38 |
if (!reply_) { |
| 39 |
Q_EMIT message(QMessageBox::Warning, _("Failed to create request.")); |
| 40 |
Q_EMIT finished(false); |
| 41 |
return; |
| 42 |
} |
| 43 |
Q_EMIT message(QMessageBox::Information, _("Download started.")); |
| 44 |
|
| 45 |
connect(reply_, &QNetworkReply::readyRead, this, |
| 46 |
&FileDownloader::readyToRead); |
| 47 |
connect(reply_, &QNetworkReply::finished, this, |
| 48 |
&FileDownloader::downloadFinished); |
| 49 |
connect(reply_, &QNetworkReply::downloadProgress, this, |
| 50 |
&FileDownloader::updateProgress); |
| 51 |
} |
| 52 |
|
| 53 |
void FileDownloader::abort() { |
| 54 |
reply_->abort(); |
| 55 |
delete reply_; |
| 56 |
reply_ = nullptr; |
| 57 |
} |
| 58 |
|
| 59 |
void FileDownloader::cleanUp() { file_.remove(); } |
| 60 |
|
| 61 |
void FileDownloader::readyToRead() { file_.write(reply_->readAll()); } |
| 62 |
|
| 63 |
void FileDownloader::updateProgress(qint64 downloaded, qint64 total) { |
| 64 |
if (total <= 0) { |
| 65 |
return; |
| 66 |
} |
| 67 |
|
| 68 |
int percent = (int)(((qreal)downloaded / total) * 100); |
| 69 |
if (percent > 100) { |
| 70 |
percent = 100; |
| 71 |
} |
| 72 |
if (percent >= progress_ + 10) { |
| 73 |
Q_EMIT message(QMessageBox::Information, |
| 74 |
QString::fromUtf8(_("%1% Downloaded.")).arg(percent)); |
| 75 |
progress_ = percent; |
| 76 |
} |
| 77 |
} |
| 78 |
|
| 79 |
void FileDownloader::downloadFinished() { |
| 80 |
file_.close(); |
| 81 |
Q_EMIT message(QMessageBox::Information, _("Download Finished")); |
| 82 |
Q_EMIT finished(true); |
| 83 |
} |
| 84 |
|
| 85 |
} // namespace fcitx |