-
Notifications
You must be signed in to change notification settings - Fork 17
/
update.cc
77 lines (68 loc) · 1.92 KB
/
update.cc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
#include "update.h"
#include <algorithm>
#include <QJsonDocument>
#include <QJsonObject>
#include <QNetworkReply>
#include <QNetworkRequest>
#include <QSettings>
#include <QString>
Update::Update(QObject *parent)
: QObject(parent)
{
manager = new QNetworkAccessManager(this);
connect(manager, &QNetworkAccessManager::finished, this, &Update::handleReply);
timer = new QTimer(this);
connect(timer, &QTimer::timeout, [&] { check(); });
timer->setInterval(INTERVAL_INIT);
timer->start();
}
void Update::check()
{
QSettings settings;
if (settings.value("updatecheck", true).toBool()) {
manager->get(QNetworkRequest(QUrl("https://api.github.com/repos/lanthora/cake/releases/latest")));
} else {
timer->stop();
}
}
void Update::handleReply(QNetworkReply *reply)
{
if (reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt() != 200) {
updateTimer();
reply->deleteLater();
return;
}
QByteArray response = reply->readAll();
QString latestVersion = [&] {
QJsonDocument doc = QJsonDocument::fromJson(response);
if (doc.isObject()) {
QJsonObject obj = doc.object();
return obj["tag_name"].toString();
}
return QString();
}();
if (latestVersion.isEmpty()) {
updateTimer();
reply->deleteLater();
return;
}
if (QString(latestVersion) != this->notifiedVersion) {
this->notifiedVersion = QString(latestVersion);
notify(QString(CAKE_VERSION), QString(latestVersion));
}
updateTimer(INTERVAL_ONEDAY);
reply->deleteLater();
}
void Update::updateTimer(int interval)
{
if (interval) {
timer->setInterval(interval);
return;
}
if (timer->interval() == INTERVAL_ONEDAY) {
timer->setInterval(INTERVAL_INIT);
return;
}
timer->setInterval(std::min(timer->interval() * 2, INTERVAL_LIMIT));
return;
}