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