-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathqc.cpp
239 lines (207 loc) · 6.49 KB
/
qc.cpp
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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
#include <QUrl>
#include <QSettings>
#include <QNetworkAccessManager>
#include <QNetworkReply>
#include <QNetworkRequest>
#include "qc.h"
#include "qcsecret.h"
#include "json/json.h"
#include "platform.h"
#include "trace.h"
#include "../o2/o1requestor.h"
using namespace QtJson;
static Qc *instance_;
static const int recordsPerUpload = 150;
Qc::Qc(QObject *parent): O1(parent) {
manager = 0;
requestor = 0;
setRequestTokenUrl(QUrl(QC_REQUEST_TOKEN_URL));
setAuthorizeUrl(QUrl(QC_AUTHORIZE_URL));
setAccessTokenUrl(QUrl(QC_ACCESS_TOKEN_URL));
setClientId(QC_OAUTH_CLIENT_ID);
setClientSecret(QC_OAUTH_CLIENT_SECRET);
}
Qc::~Qc() {
delete requestor;
delete manager;
}
Qc *Qc::instance() {
if (!instance_) {
instance_ = new Qc();
}
return instance_;
}
void Qc::close() {
delete instance_;
instance_ = 0;
}
void Qc::upload() {
Trace _("Qc::upload");
Database db(Platform::instance()->dbPath());
// Do nothing if database is empty
{
qlonglong total = -1;
QSqlQuery query("select count(*) from log where inqc = 0", db.db());
query.next();
total = query.value(0).toLongLong();
if (total == 0) {
qDebug() << "No records to upload";
emit uploadFinished(UploadComplete);
return;
}
}
// Mark all records as uploaded if QC is not enabled, then succeed
if (!enabled()) {
qDebug() << "QC not enabled";
QSqlQuery query("update log set ingqc = 1", db.db());
query.exec();
emit uploadFinished(UploadComplete);
return;
}
// Fail if not logged in
if (!linked()) {
qDebug() << "Not logged in";
emit uploadFinished(UploadFailed);
return;
}
QSqlQuery query(db.db());
query.setForwardOnly(true);
if (!query.exec("select id, date, steps from log where inqc = 0")) {
qCritical() << "Qc::upload: Could not query log:" << query.lastError().text();
emit uploadFinished(UploadFailed);
return;
}
int numRecords = 0;
QVariantMap input;
input["dev"] = Platform::instance()->deviceId();
input["schema"] = "steps";
QVariantList measurements;
uploadedRecords.clear();
while (query.next()) {
if (++numRecords > recordsPerUpload) {
break;
}
qlonglong id = query.value(0).toLongLong();
uploadedRecords.append(id);
QString date = query.value(1).toString();
int steps = query.value(2).toInt();
QMap<QString, QString> tags = getTags(db, id);
QVariantMap measurement;
measurement["at"] = QDateTime::fromString(date, Qt::ISODate).toMSecsSinceEpoch() / 1000.;
measurement["count"] = steps;
foreach (QString key, tags.keys()) {
if (key == "detectedActivity") {
QString activity = tags["detectedActivity"];
if (activity == "0") {
measurement["activity"] = "idle";
} else if (activity == "2") {
measurement["activity"] = "walking";
} else {
measurement["activity"] = "running";
}
} else if (key.startsWith("x-")) {
measurement[key] = tags[key];
} else {
measurement["x-" + key] = tags[key];
}
}
measurements.append(measurement);
}
input["m"] = measurements;
qDebug() << Json::serialize(input);
uploadBatch(input);
}
void Qc::uploadBatch(const QVariantMap &batch) {
Trace _("Qc::uploadBatch");
if (!manager) {
manager = new QNetworkAccessManager();
}
if (!requestor) {
requestor = new O1Requestor(manager, this);
}
// Set up HTTP request
QByteArray body = Json::serialize(batch);
QNetworkRequest request;
request.setUrl(QUrl(QC_INPUT_URL));
request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");
// ...And post it
QNetworkReply *reply = requestor->post(request, QList<O1RequestParameter>(), body);
connect(reply, SIGNAL(error(QNetworkReply::NetworkError)), this, SLOT(onError(QNetworkReply::NetworkError)));
connect(reply, SIGNAL(finished()), this, SLOT(onFinished()));
}
void Qc::onError(QNetworkReply::NetworkError error) {
Trace _("Qc::onError");
QNetworkReply *reply = qobject_cast<QNetworkReply *>(sender());
if (!reply) {
return;
}
qDebug() << error << reply->errorString();
finishBatch(true);
}
void Qc::onFinished() {
Trace _("Qc::onFinished");
QNetworkReply *reply = qobject_cast<QNetworkReply *>(sender());
if (!reply) {
return;
}
if (reply->error() == QNetworkReply::NoError) {
finishBatch(false);
}
reply->deleteLater();
}
bool Qc::enabled() {
return QSettings().value("qc.enabled", false).toBool();
}
void Qc::setEnabled(bool v) {
QSettings().setValue("qc.enabled", v);
emit enabledChanged();
}
QMap<QString, QString> Qc::getTags(Database &db, qlonglong id) {
QMap<QString, QString> ret;
QSqlQuery query(db.db());
query.prepare("select name, value from tags where logId = ?");
query.bindValue(0, id);
if (!query.exec()) {
qCritical() << "Qc::getTags: Could not query log:" << query.lastError().text();
return ret;
}
while (query.next()) {
QString name = query.value(0).toString();
QString value = query.value(1).toString();
ret.insert(name, value);
}
return ret;
}
void Qc::finishBatch(bool failed) {
Trace _("Qc::finishBatch");
if (failed) {
qDebug() << "Result: Failed";
emit uploadFinished(UploadFailed);
return;
}
// Mark uploaded records in the log
Database db(Platform::instance()->dbPath());
db.transaction();
foreach (qlonglong id, uploadedRecords) {
QSqlQuery query(db.db());
query.prepare("update log set inqc = 1 where id = ?");
query.bindValue(0, id);
query.exec();
}
db.commit();
// Determine upload result: Are there any records left in the log?
int result = UploadIncomplete;
qlonglong total = -1;
QSqlQuery query("select count(*) from log where inqc = 0", db.db());
query.next();
total = query.value(0).toLongLong();
qDebug() << total << "records left";
if (total == 0) {
qDebug() << "Result: Complete";
result = UploadComplete;
} else {
qDebug() << "Result: Incomplete";
result = UploadIncomplete;
}
emit uploadFinished(result);
}