This commit is contained in:
2023-12-26 16:38:19 +08:00
commit cfc7804e38
222 changed files with 1347 additions and 0 deletions
+126
View File
@@ -0,0 +1,126 @@
#include "downloader.h"
#include <QCoreApplication>
#include <QDebug>
#include <QJsonDocument>
#include <QRegularExpression>
Downloader::Downloader(QObject *parent)
: QObject{parent}
{
m_pNetWorkAccessManager = new QNetworkAccessManager(this);
dir.setPath(QCoreApplication::applicationDirPath());
}
void Downloader::setUrl(const QString &_url)
{
m_pUrl = QUrl(_url);
}
void Downloader::startDownload(const QString &_url)
{
if(m_bIsDownloading)
return;
m_bIsDownloading = true;
if(!_url.isEmpty())
m_pUrl.setUrl(_url);
if(!dir.exists())
{
dir.mkpath(".");
}
/* Rename old downloads */
QString _path = dir.path() + "/" + m_fileName;
if(QFile::exists(_path))
{
QFile _file(_path);
_file.rename(_path + "_" + QDateTime::currentDateTime().toString("yyyy-MM-dd"));
}
QFile::remove(dir.filePath(m_fileName));
QFile::remove(dir.filePath(m_fileName + ".part"));
QNetworkRequest request;
request.setUrl(m_pUrl);
m_pReply = m_pNetWorkAccessManager->get(request);
connect(m_pReply, &QNetworkReply::downloadProgress, this, [&](qint64 received, qint64 total)
{
emit doProgress(received, total);
if (total > 0)
{
if(file.fileName() != (dir.filePath(m_fileName + ".part")))
file.setFileName(dir.filePath(m_fileName + ".part"));
if(!file.isOpen())
{
file.open(QIODevice::WriteOnly | QIODevice::Append);
}
file.write(m_pReply->readAll());
}
});
connect(m_pReply, &QNetworkReply::metaDataChanged, this, [&]()
{
QString filename = "";
QVariant variant = m_pReply->header( QNetworkRequest::ContentDispositionHeader );
if ( variant.isValid() )
{
QString contentDisposition = QByteArray::fromPercentEncoding( variant.toByteArray() ).constData();
QRegularExpression regExp( "(.*)filename=\"(?<filename>.*)\"" );
QRegularExpressionMatch match = regExp.match( contentDisposition );
if ( match.hasMatch() )
{
filename = match.captured( "filename" );
}
m_fileName = filename;
auto localApplicationFilePath = QCoreApplication::applicationDirPath();
file.setFileName(localApplicationFilePath + "/" + m_fileName);
};
});
// connect(m_pReply, SIGNAL(readyRead()), this, SLOT(onReadyRead()));
connect(m_pReply, &QNetworkReply::finished, this, [&]()
{
if(file.isOpen())
file.close();
if(!file.exists())
{
emit doShowInfo("not exits");
}
if(file.isOpen())
{
emit doShowInfo("not close");
}
if(!file.rename(dir.path() + "/" + m_fileName))
{
emit doShowInfo("rename file failed");
}
file.setFileName(dir.filePath(m_fileName));
m_bIsDownloading = false;
emit doFinished();
});
connect(m_pReply, SIGNAL(errorOccurred(QNetworkReply::NetworkError)), this, SIGNAL(onError(QNetworkReply::NetworkError)));
}
void Downloader::checkVersion()
{
QNetworkRequest request(CHECK_URL);
m_pNetWorkAccessManager->get(request);
}
const QFile &Downloader::getFile() const
{
return file;
}
const QDir &Downloader::getDir() const
{
return dir;
}
const QString &Downloader::fileName() const
{
return m_fileName;
}
void Downloader::setFileName(const QString &newFileName)
{
m_fileName = newFileName;
}
+59
View File
@@ -0,0 +1,59 @@
#ifndef DOWNLOADER_H
#define DOWNLOADER_H
#include <QObject>
#include <QNetworkAccessManager>
#include <QNetworkReply>
#include <memory>
#include <QUrl>
#include <QFile>
#include <QDir>
extern QString CHECK_URL;
class Downloader : public QObject
{
Q_OBJECT
public:
explicit Downloader(QObject *parent = nullptr);
void setUrl(const QString &);
void startDownload(const QString &_url = NULL);
void checkVersion();
const QFile &getFile() const;
const QDir &getDir() const;
const QString &fileName() const;
void setFileName(const QString &newFileName);
public slots:
signals:
void doProgress(qint64, qint64);
void onError(QNetworkReply::NetworkError);
void doFinished();
void doShowInfo(const QString&);
private:
QNetworkAccessManager *m_pNetWorkAccessManager{nullptr};
QNetworkReply *m_pReply{nullptr};
bool m_bIsDownloading = false; //正在下载标识
QUrl m_pUrl{};
QString m_fileName = "";
QFile file;
QDir dir;
};
#endif // DOWNLOADER_H
+43
View File
@@ -0,0 +1,43 @@
#include <QApplication>
#include "updaterdialog.h"
void loadQss()
{
QFile f(":qdarkstyle/dark/darkstyle.qss");
// QFile f(":qdarkstyle/light/lightstyle.qss");
if (!f.exists())
{
printf("Unable to set stylesheet, file not found\n");
}
else
{
f.open(QFile::ReadOnly | QFile::Text);
QTextStream ts(&f);
qApp->setStyleSheet(ts.readAll());
}
}
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
loadQss();
if(argc > 1)
{
APPNAME = argv[1];
APPVERSION = argv[2];
APPDATE = argv[3];
MODIFYCNT = argv[4];
}
else
{
APPNAME = "LaunchControl";
APPVERSION = "0";
}
CHECK_URL = CHECK_URL + APPNAME + "/updates.json";
UpdaterDialog w;
w.show();
return a.exec();
}
+378
View File
@@ -0,0 +1,378 @@
#include "updaterdialog.h"
#include "ui_updaterdialog.h"
#include <QDesktopServices>
#include <QJsonDocument>
#include <QJsonObject>
#include <QMessageBox>
#include <QMetaEnum>
#include <cmath>
#include <private/qzipreader_p.h>
QString CHECK_URL = "http://www.tianzd.cn:1995/TianZD/deploy/raw/branch/master/";
QString PLATFORM = "windows";
QString APPVERSION = "";
QString APPNAME = "";
QString APPDATE = "0";
QString MODIFYCNT = "0";
UpdaterDialog::UpdaterDialog(QWidget *parent) :
QDialog(parent),
ui(new Ui::UpdaterDialog)
{
ui->setupUi(this);
this->setWindowTitle("Updater");
ui->btn_update->setEnabled(0);
m_startTime = 0;
m_version = APPVERSION;
ui->versionInput->setText(m_version);
ui->show->setEnabled(0);
ui->label_2->setText("");
ui->label_3->setText("");
ui->label_4->setText(APPNAME);
// ui->versionInput->setEnabled(false);
}
UpdaterDialog::~UpdaterDialog()
{
delete ui;
}
void UpdaterDialog::showStatus(const QString &s)
{
// ui->show->clear();
ui->show->appendPlainText(s);
}
void UpdaterDialog::on_btn_check_clicked()
{
ui->show->clear();
ui->btn_update->setEnabled(0);
//version
m_version = ui->versionInput->text();
if(!m_pManager)
{
m_pManager = new QNetworkAccessManager(this);
connect(m_pManager, SIGNAL(finished(QNetworkReply *)), this, SLOT(onCheckReply(QNetworkReply *)));
}
QNetworkRequest request(CHECK_URL);
m_pManager->get(request);
}
bool UpdaterDialog::checkVersion(const QString &_localVersion, const QString &_remoteVersion)
{
//版本号分割,1.1.2分为1 1 2
QStringList _list_curr = _localVersion.split(".");
QStringList _list_lastest = _remoteVersion.split(".");
//检查是否需要更新
bool _isNotLatest = false;
//版本号为空
if(_list_curr.count() == 0)
{
m_bDownloadFullExe = true;
return true;
}
if(_list_curr.count() != _list_lastest.count())
_isNotLatest = true;
for(int i = 0; i < _list_curr.count(); ++i)
{
if(_list_curr[i].toUInt() < _list_lastest[i].toUInt())
{
_isNotLatest = true;
}
}
//版本号一致,检查日期
if(!_isNotLatest)
{
if(m_lastChangeTime.toUInt() > APPDATE.toUInt())
{
_isNotLatest = true;
}
//检查修改次数
if(m_modifyCnt != "" && m_modifyCnt != " " && MODIFYCNT != "" && MODIFYCNT != " ")
{
if(m_modifyCnt.toUInt() > MODIFYCNT.toUInt())
{
_isNotLatest = true;
}
}
}
return _isNotLatest;
}
void UpdaterDialog::onCheckReply(QNetworkReply *reply)
{
/* There was a network error */
if (reply->error() != QNetworkReply::NoError)
{
showStatus("check error");
return;
}
/* Try to create a JSON document from downloaded data */
QJsonDocument document = QJsonDocument::fromJson(reply->readAll());
/* JSON is invalid */
if (document.isNull())
{
showStatus("reply doc is null");
return;
}
/* Get the platform information */
QJsonObject updates = document.object().value("updates").toObject();
QJsonObject platform = updates.value(PLATFORM).toObject();
/* Get update information */
m_changelog = platform.value("changelog").toString();
m_patchVersion = platform.value("patch-version").toString();
m_fullVersion = platform.value("full-version").toString();
m_lastChangeTime = platform.value("modify-time").toString();
m_modifyCnt = platform.value("modifyCnt").toString();
m_bDownloadFullExe = platform.value("download-full").toBool();
if(m_version == "" || m_version == "0") //当前版本号为空
{
m_bDownloadFullExe = true;
}
m_fileName = APPNAME + "-patch-v" + m_patchVersion + ".zip";
m_patchUrl = platform.value("patch-url").toString() + APPNAME + "/" + APPNAME + "-patch-v" + m_patchVersion + ".zip";
m_fullUrl = platform.value("full-url").toString() + APPNAME + "/" + APPNAME + "-full-v" + m_fullVersion + ".exe";
QString _remoteVersion = m_bDownloadFullExe ? m_fullVersion : m_patchVersion;
bool _isNotLatest = checkVersion(m_version, _remoteVersion);
if(_isNotLatest)
{
showStatus("======================================"
+ tr("\ncurrent version: v") + m_version
+ tr("\nmodify time: ") + APPDATE
+ tr("\nmodify cnt: ") + MODIFYCNT
+ "\n ------------------------------"
+ tr("\nlatest version: v") + _remoteVersion
+ tr("\nmodify time: ") + m_lastChangeTime
+ tr("\nmodify cnt: ") + m_modifyCnt
+ tr("\nchange log: ") + m_changelog
+ "\n======================================"
);
if(m_bDownloadFullExe)
{
showStatus("need download full exe");
m_fileName = APPNAME + "-full-v" + m_patchVersion + ".exe";
}
showStatus(tr("click update button to update"));
}
else
{
showStatus("======================================"
+ tr("\ncurrent software is up-to-date")
+ tr("\nversion : v") + _remoteVersion
+ tr("\nmodify time: ") + m_lastChangeTime
+ tr("\nmodify cnt: ") + m_modifyCnt
+ "\n======================================"
+ tr("\nno need to update")
+ tr("\nclick cancel button to quit"));
}
ui->btn_update->setEnabled(1);
}
void UpdaterDialog::calculateSizes(qint64 received, qint64 total)
{
QString totalSize;
QString receivedSize;
if (total < 1024)
totalSize = tr("%1 bytes").arg(total);
else if (total < 1048576)
totalSize = tr("%1 KB").arg(round(total / 1024));
else
totalSize = tr("%1 MB").arg((total / 1048576.0));
if (received < 1024)
receivedSize = tr("%1 bytes").arg(received);
else if (received < 1048576)
receivedSize = tr("%1 KB").arg(received / 1024);
else
receivedSize = tr("%1 MB").arg(received / 1048576.0);
ui->label_2->setText(tr("Downloading updates") + " (" + receivedSize + " " + tr("of") + " " + totalSize
+ ")");
}
/**
* Uses two time samples (from the current time and a previous sample) to
* calculate how many bytes have been downloaded.
*
* Then, this function proceeds to calculate the appropiate units of time
* (hours, minutes or seconds) and constructs a user-friendly string, which
* is displayed in the dialog.
*/
void UpdaterDialog::calculateTimeRemaining(qint64 received, qint64 total)
{
static quint64 lastRec = 0;
static uint lastTime = 0;
uint _time = QDateTime::currentDateTime().toMSecsSinceEpoch();
double _speed = (received - lastRec) / 1024.0 / (_time - lastTime) * 1000.0;
lastTime = _time;
lastRec = received;
uint difference = QDateTime::currentDateTime().toSecsSinceEpoch() - m_startTime;
if (difference > 0)
{
QString timeString;
qreal timeRemaining = (total - received) / (received / difference);
if (timeRemaining > 7200)
{
timeRemaining /= 3600;
int hours = int(timeRemaining + 0.5);
if (hours > 1)
timeString = tr("about %1 hours").arg(hours);
else
timeString = tr("about one hour");
}
else if (timeRemaining > 60)
{
timeRemaining /= 60;
int minutes = int(timeRemaining + 0.5);
if (minutes > 1)
timeString = tr("%1 minutes").arg(minutes);
else
timeString = tr("1 minute");
}
else if (timeRemaining <= 60)
{
int seconds = int(timeRemaining + 0.5);
if (seconds > 1)
timeString = tr("%1 seconds").arg(seconds);
else
timeString = tr("1 second");
}
ui->label_3->setText(tr("speed: %1 kb/s ").arg(_speed) + tr("Time remaining") + ": " + timeString);
}
}
void UpdaterDialog::on_btn_update_clicked()
{
if(!m_pDownloader)
{
m_pDownloader = new Downloader(this);
connect(m_pDownloader, &Downloader::doShowInfo, this, [&](const QString & s)
{
showStatus(s);
});
connect(m_pDownloader, &Downloader::onError, this, [&](QNetworkReply::NetworkError e)
{
QMetaEnum metaEnum = QMetaEnum::fromType<QNetworkReply::NetworkError>();
QString str = QString(metaEnum.valueToKey(e));
ui->show->appendPlainText(str);
});
connect(m_pDownloader, &Downloader::doFinished, this, [&]()
{
uint _end_time = QDateTime::currentSecsSinceEpoch();
uint _total_time = _end_time - m_startTime;
ui->label_3->setText("total time: " + QString::number(_total_time, 'g', 3) +
"s average speed: " + QString::number((m_totalSize / 1024.0 / _total_time), 'g', 3) + "kb/s");
ui->show->appendPlainText("download finished");
onDownloadFinished();
});
connect(m_pDownloader, &Downloader::doProgress, this, [&](quint64 received, quint64 total)
{
m_totalSize = total;
if (total > 0)
{
ui->progressBar->setMinimum(0);
ui->progressBar->setMaximum(100);
ui->progressBar->setValue((received * 100) / total);
calculateSizes(received, total);
calculateTimeRemaining(received, total);
}
else
{
ui->progressBar->setMinimum(0);
ui->progressBar->setMaximum(0);
ui->progressBar->setValue(-1);
ui->show->appendPlainText(tr("Downloading Updates") + "...");
}
});
}
m_pDownloader->setFileName(m_fileName);
m_startTime = QDateTime::currentDateTime().toSecsSinceEpoch();
QString _url = m_bDownloadFullExe ? m_fullUrl : m_patchUrl;
m_pDownloader->startDownload(_url);
}
void UpdaterDialog::on_btn_cancel_clicked()
{
if(!m_UpdateProc)
{
m_UpdateProc = new QProcess;
}
#if defined Q_OS_WIN
m_UpdateProc->setProgram(APPNAME + ".exe");
#elif defined Q_OS_LINUX
m_UpdateProc->setProgram("./" + APPNAME);
#endif
m_UpdateProc->start();
m_UpdateProc->waitForStarted();
QApplication::quit();
}
void UpdaterDialog::onDownloadFinished()
{
// ui->show->appendPlainText(m_pDownloader->fileName());
// ui->show->appendPlainText("m_bDownloadFullExe");
auto localInformation = QMessageBox::question(this, "update", "download finished\nstart update?");
if(localInformation == QMessageBox::Yes)
{
QString _appName;
if(!m_bDownloadFullExe)
{
//解压文件
QFileInfo f(m_pDownloader->getFile());
QString _path = f.fileName();
QZipReader * zipReader = new QZipReader(_path);
zipReader->extractAll(f.path());
_appName = APPNAME + ".exe";
}
else
{
_appName = m_pDownloader->fileName();
}
QFileInfo f2(QCoreApplication::applicationDirPath() + "/" + _appName);
if(f2.exists())
{
QDesktopServices::openUrl(f2.absoluteFilePath());
}
QApplication::quit();
}
}
+75
View File
@@ -0,0 +1,75 @@
#ifndef UPDATERDIALOG_H
#define UPDATERDIALOG_H
#include <QDialog>
#include <QProcess>
#include "downloader.h"
extern QString APPVERSION;
extern QString APPNAME;
extern QString CHECK_URL;
extern QString APPDATE;
extern QString MODIFYCNT;
namespace Ui
{
class UpdaterDialog;
}
class UpdaterDialog : public QDialog
{
Q_OBJECT
public:
explicit UpdaterDialog(QWidget *parent = nullptr);
~UpdaterDialog();
void showStatus(const QString &);
void calculateSizes(qint64 received, qint64 total);
void calculateTimeRemaining(qint64 received, qint64 total);
bool checkVersion(const QString & _localVersion, const QString & _remoteVersion);
private slots:
void on_btn_check_clicked();
void onCheckReply(QNetworkReply *);
void on_btn_update_clicked();
void on_btn_cancel_clicked();
void onDownloadFinished();
private:
Ui::UpdaterDialog *ui;
Downloader * m_pDownloader = nullptr;
QString m_version;
QNetworkAccessManager *m_pManager{nullptr};
QString m_platform;
QString m_changelog;
QString m_moduleName;
QString m_patchUrl;
QString m_patchVersion;
QString m_moduleVersion;
QString m_fullUrl;
QString m_fullVersion;
QString m_lastChangeTime;
QString m_modifyCnt;
QString m_fileName = "";
bool m_bDownloadFullExe = false;
uint m_startTime;
quint64 m_totalSize;
QProcess *m_UpdateProc{nullptr};
};
#endif // UPDATERDIALOG_H
+264
View File
@@ -0,0 +1,264 @@
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>UpdaterDialog</class>
<widget class="QDialog" name="UpdaterDialog">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>578</width>
<height>606</height>
</rect>
</property>
<property name="windowTitle">
<string>Dialog</string>
</property>
<layout class="QGridLayout" name="gridLayout">
<property name="leftMargin">
<number>20</number>
</property>
<property name="topMargin">
<number>10</number>
</property>
<property name="rightMargin">
<number>20</number>
</property>
<property name="bottomMargin">
<number>10</number>
</property>
<item row="0" column="0" rowspan="2" colspan="2">
<layout class="QVBoxLayout" name="verticalLayout">
<property name="leftMargin">
<number>0</number>
</property>
<property name="rightMargin">
<number>0</number>
</property>
<item>
<layout class="QHBoxLayout" name="horizontalLayout_3">
<item>
<widget class="QLabel" name="labelIcon">
<property name="sizePolicy">
<sizepolicy hsizetype="Expanding" vsizetype="Preferred">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="minimumSize">
<size>
<width>48</width>
<height>48</height>
</size>
</property>
<property name="maximumSize">
<size>
<width>48</width>
<height>48</height>
</size>
</property>
<property name="font">
<font>
<pointsize>14</pointsize>
</font>
</property>
<property name="styleSheet">
<string notr="true">border-image: url(:/140xfd.png);</string>
</property>
<property name="text">
<string/>
</property>
<property name="alignment">
<set>Qt::AlignCenter</set>
</property>
</widget>
</item>
<item>
<widget class="QLabel" name="label_4">
<property name="font">
<font>
<family>Times New Roman</family>
<pointsize>12</pointsize>
<bold>true</bold>
</font>
</property>
<property name="text">
<string>updater</string>
</property>
</widget>
</item>
<item>
<spacer name="horizontalSpacer_3">
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
<property name="sizeType">
<enum>QSizePolicy::Preferred</enum>
</property>
<property name="sizeHint" stdset="0">
<size>
<width>40</width>
<height>20</height>
</size>
</property>
</spacer>
</item>
</layout>
</item>
<item>
<layout class="QHBoxLayout" name="horizontalLayout_2">
<item>
<widget class="QLabel" name="label">
<property name="font">
<font>
<family>Times New Roman</family>
<pointsize>12</pointsize>
<bold>true</bold>
</font>
</property>
<property name="text">
<string>Version:</string>
</property>
</widget>
</item>
<item>
<widget class="QLineEdit" name="versionInput">
<property name="font">
<font>
<family>Times New Roman</family>
<pointsize>12</pointsize>
<bold>true</bold>
</font>
</property>
</widget>
</item>
<item>
<widget class="QPushButton" name="btn_check">
<property name="sizePolicy">
<sizepolicy hsizetype="Expanding" vsizetype="Fixed">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="font">
<font>
<family>Times New Roman</family>
<pointsize>12</pointsize>
<bold>true</bold>
</font>
</property>
<property name="text">
<string>check</string>
</property>
</widget>
</item>
</layout>
</item>
<item>
<widget class="QPlainTextEdit" name="show"/>
</item>
<item>
<widget class="QLabel" name="label_2">
<property name="font">
<font>
<family>Times New Roman</family>
<pointsize>12</pointsize>
<bold>true</bold>
</font>
</property>
<property name="text">
<string>TextLabel</string>
</property>
</widget>
</item>
<item>
<widget class="QProgressBar" name="progressBar">
<property name="font">
<font>
<family>Times New Roman</family>
<pointsize>12</pointsize>
<bold>true</bold>
</font>
</property>
<property name="value">
<number>0</number>
</property>
</widget>
</item>
<item>
<widget class="QLabel" name="label_3">
<property name="font">
<font>
<family>Times New Roman</family>
<pointsize>12</pointsize>
<bold>true</bold>
</font>
</property>
<property name="text">
<string>TextLabel</string>
</property>
</widget>
</item>
<item>
<layout class="QHBoxLayout" name="horizontalLayout">
<item>
<spacer name="horizontalSpacer">
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
<property name="sizeHint" stdset="0">
<size>
<width>40</width>
<height>20</height>
</size>
</property>
</spacer>
</item>
<item>
<widget class="QPushButton" name="btn_cancel">
<property name="sizePolicy">
<sizepolicy hsizetype="Expanding" vsizetype="Fixed">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="font">
<font>
<family>Times New Roman</family>
<pointsize>12</pointsize>
<bold>true</bold>
</font>
</property>
<property name="text">
<string>cancel</string>
</property>
</widget>
</item>
<item>
<widget class="QPushButton" name="btn_update">
<property name="sizePolicy">
<sizepolicy hsizetype="Expanding" vsizetype="Fixed">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="font">
<font>
<family>Times New Roman</family>
<pointsize>12</pointsize>
<bold>true</bold>
</font>
</property>
<property name="text">
<string>update</string>
</property>
</widget>
</item>
</layout>
</item>
</layout>
</item>
</layout>
</widget>
<resources/>
<connections/>
</ui>