-
-
Notifications
You must be signed in to change notification settings - Fork 27
/
wantedlist.cpp
executable file
·467 lines (395 loc) · 14.2 KB
/
wantedlist.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
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
// Copyright (C) 2004-2024 Robert Griebl
// SPDX-License-Identifier: GPL-3.0-only
#include <QBuffer>
#include <QSaveFile>
#include <QDirIterator>
#include <QCoreApplication>
#include <QUrlQuery>
#include <QRegularExpression>
#include <QJsonDocument>
#include <QJsonParseError>
#include <QJsonObject>
#include <QJsonArray>
#include <QQmlEngine>
#include "bricklink/wantedlist.h"
#include "bricklink/core.h"
#include "bricklink/io.h"
#include "utility/exception.h"
#include "utility/transfer.h"
namespace BrickLink {
class WantedListPrivate
{
public:
~WantedListPrivate() { qDeleteAll(m_lots); }
private:
int m_id;
QString m_name;
QString m_description;
int m_itemCount = 0;
int m_itemLeftCount = 0;
int m_lotCount = 0;
double m_filled = 0.;
LotList m_lots;
friend class WantedList;
};
WantedList::WantedList()
: QObject()
, d(new WantedListPrivate)
{ }
WantedList::~WantedList()
{ /* needed to use std::unique_ptr on d */ }
const LotList &WantedList::lots() const
{
return d->m_lots;
}
int WantedList::id() const
{
return d->m_id;
}
QString WantedList::name() const
{
return d->m_name;
}
QString WantedList::description() const
{
return d->m_description;
}
double WantedList::filled() const
{
return d->m_filled;
}
int WantedList::itemLeftCount() const
{
return d->m_itemLeftCount;
}
int WantedList::itemCount() const
{
return d->m_itemCount;
}
int WantedList::lotCount() const
{
return d->m_lotCount;
}
void WantedList::setId(int id)
{
if (d->m_id != id) {
d->m_id = id;
emit idChanged(id);
}
}
void WantedList::setName(const QString &name)
{
if (d->m_name != name) {
d->m_name = name;
emit nameChanged(name);
}
}
void WantedList::setDescription(const QString &description)
{
if (d->m_description != description) {
d->m_description = description;
emit descriptionChanged(description);
}
}
void WantedList::setFilled(double f)
{
if (!qFuzzyCompare(d->m_filled, f)) {
d->m_filled = f;
emit filledChanged(f);
}
}
void WantedList::setItemLeftCount(int i)
{
if (d->m_itemLeftCount != i) {
d->m_itemLeftCount = i;
emit itemLeftCountChanged(i);
}
}
void WantedList::setItemCount(int i)
{
if (d->m_itemCount != i) {
d->m_itemCount = i;
emit itemCountChanged(i);
}
}
void WantedList::setLotCount(int i)
{
if (d->m_lotCount != i) {
d->m_lotCount = i;
emit lotCountChanged(i);
}
}
void WantedList::setLots(LotList &&lots)
{
if (d->m_lots != lots) {
qDeleteAll(d->m_lots);
d->m_lots = lots;
lots.clear();
emit lotsChanged(d->m_lots);
}
}
WantedLists::WantedLists(Core *core)
: QAbstractTableModel(core)
, m_core(core)
{
connect(core, &Core::authenticatedTransferStarted,
this, [this](TransferJob *job) {
if ((m_updateStatus == UpdateStatus::Updating) && (m_job == job))
emit updateStarted();
});
connect(core, &Core::authenticatedTransferProgress,
this, [this](TransferJob *job, int progress, int total) {
if ((m_updateStatus == UpdateStatus::Updating) && (m_job == job))
emit updateProgress(progress, total);
});
connect(core, &Core::authenticatedTransferFinished,
this, [this](TransferJob *job) {
bool jobCompleted = job->isCompleted() && (job->responseCode() == 200);
QByteArray type = job->userTag();
if (m_wantedListJobs.contains(job) && (type == "wantedList")) {
m_wantedListJobs.removeOne(job);
bool success = jobCompleted;
int id = job->userData(type).toInt();
QString message = tr("Failed to import wanted list %1").arg(id);
auto it = std::find_if(m_wantedLists.cbegin(), m_wantedLists.cend(), [id](const WantedList *wantedList) {
return wantedList->id() == id;
});
if (it == m_wantedLists.cend()) {
qWarning() << "Received wanted list data for an unknown wanted list:" << id;
return;
}
try {
if (!jobCompleted) {
throw Exception(message + u": " + job->errorString());
} else {
int invalidCount = parseWantedList(*it, job->data());
if (invalidCount) {
message = tr("%n lot(s) of your Wanted List could not be imported.",
nullptr, invalidCount);
}
message.clear();
}
} catch (const Exception &e) {
success = false;
message = message + u": " + e.errorString();
}
emit fetchLotsFinished(*it, success, message);
} else if ((job == m_job) && (type == "globalWantedList")) {
bool success = jobCompleted;
QString message = tr("Failed to import the wanted lists");
if (success) {
try {
const auto wantedLists = parseGlobalWantedList(job->data());
beginResetModel();
qDeleteAll(m_wantedLists);
m_wantedLists.clear();
m_wantedLists.reserve(wantedLists.size());
for (auto &wantedList : wantedLists) {
int row = int(m_wantedLists.count());
m_wantedLists.append(wantedList);
wantedList->setParent(this); // needed to prevent QML from taking ownership
connect(wantedList, &WantedList::nameChanged, this, [this, row]() { emitDataChanged(row, Name); });
connect(wantedList, &WantedList::descriptionChanged, this, [this, row]() { emitDataChanged(row, Description); });
connect(wantedList, &WantedList::filledChanged, this, [this, row]() { emitDataChanged(row, Filled); });
connect(wantedList, &WantedList::itemCountChanged, this, [this, row]() { emitDataChanged(row, ItemCount); });
connect(wantedList, &WantedList::lotCountChanged, this, [this, row]() { emitDataChanged(row, LotCount); });
connect(wantedList, &WantedList::itemLeftCountChanged, this, [this, row]() { emitDataChanged(row, ItemLeftCount); });
}
endResetModel();
emit countChanged(rowCount());
message.clear();
} catch (const Exception &e) {
success = false;
message = message + u": " + e.errorString();
}
}
setLastUpdated(QDateTime::currentDateTime());
setUpdateStatus(success ? UpdateStatus::Ok : UpdateStatus::UpdateFailed);
emit updateFinished(success, success ? QString { } : message);
m_job = nullptr;
}
});
connect(core->database(), &BrickLink::Database::databaseAboutToBeReset,
this, [this]() {
beginResetModel();
qDeleteAll(m_wantedLists);
m_wantedLists.clear();
endResetModel();
emit countChanged(rowCount());
});
}
int WantedLists::parseWantedList(WantedList *wantedList, const QByteArray &data)
{
IO::ParseResult pr = IO::fromBrickLinkXML(data, IO::Hint::Wanted);
wantedList->setLots(pr.takeLots());
return pr.invalidLotCount();
}
QVector<BrickLink::WantedList *> WantedLists::parseGlobalWantedList(const QByteArray &data)
{
QVector<BrickLink::WantedList *> wantedLists;
auto pos = data.indexOf("var wlJson");
if (pos < 0)
throw Exception("Invalid HTML - cannot parse");
auto startPos = data.indexOf('{', pos);
auto endPos = data.indexOf("};\r\n", pos);
if ((startPos <= pos) || (endPos < startPos))
throw Exception("Invalid HTML - found wlJSON, but could not parse line");
auto globalWantedList = data.mid(startPos, endPos - startPos + 1);
QJsonParseError err;
auto json = QJsonDocument::fromJson(globalWantedList, &err);
if (json.isNull())
throw Exception("Invalid JSON: %1 at %2").arg(err.errorString()).arg(err.offset);
const QJsonArray jsonWantedLists = json[u"wantedLists"].toArray();
wantedLists.reserve(jsonWantedLists.size());
for (auto &&jsonWantedList : jsonWantedLists) {
int id = jsonWantedList[u"id"].toInt(-1);
QString name = jsonWantedList[u"name"].toString();
QString desc = jsonWantedList[u"desc"].toString();
double filled = jsonWantedList[u"filledPct"].toDouble();
int lots = jsonWantedList[u"num"].toInt();
int items = jsonWantedList[u"totalNum"].toInt();
int itemsLeft = jsonWantedList[u"totalLeft"].toInt();
if (id >= 0 && !name.isEmpty() && lots && items) {
auto wantedList = new WantedList;
#if defined(__APPLE__) && defined(__clang__) && ((__clang_major__ - 0) == 15)
// We would be running into a brk assembly instruction at this point. Most likely
// a clang optimization gone wrong. Calling into QObject prevents the crash.
QObject *macClang15CrashWorkaround = wantedList;
macClang15CrashWorkaround->setObjectName({ });
#endif
wantedList->setId(id);
wantedList->setName(name);
wantedList->setDescription(desc);
wantedList->setLotCount(lots);
wantedList->setItemCount(items);
wantedList->setItemLeftCount(itemsLeft);
wantedList->setFilled(filled / 100.);
wantedLists << wantedList;
QQmlEngine::setObjectOwnership(wantedList, QQmlEngine::CppOwnership);
}
}
return wantedLists;
}
void WantedLists::emitDataChanged(int row, int col)
{
QModelIndex from = index(row, col < 0 ? 0 : col);
QModelIndex to = index(row, col < 0 ? columnCount() - 1 : col);
emit dataChanged(from, to);
}
void WantedLists::setLastUpdated(const QDateTime &lastUpdated)
{
if (lastUpdated != m_lastUpdated) {
m_lastUpdated = lastUpdated;
emit lastUpdatedChanged(lastUpdated);
}
}
void WantedLists::setUpdateStatus(UpdateStatus updateStatus)
{
if (updateStatus != m_updateStatus) {
m_updateStatus = updateStatus;
emit updateStatusChanged(updateStatus);
}
}
void WantedLists::startUpdate()
{
if (updateStatus() == UpdateStatus::Updating)
return;
Q_ASSERT(!m_job);
setUpdateStatus(UpdateStatus::Updating);
auto job = TransferJob::post(u"https://www.bricklink.com/v2/wanted/list.page"_qs);
job->setUserData("globalWantedList", true);
m_job = job;
m_core->retrieveAuthenticated(m_job);
}
void WantedLists::cancelUpdate()
{
if ((m_updateStatus == UpdateStatus::Updating) && m_job)
m_job->abort();
}
WantedList *WantedLists::wantedList(int index) const
{
return m_wantedLists.value(index);
}
void WantedLists::startFetchLots(WantedList *wantedList)
{
if (!wantedList)
return;
auto job = TransferJob::post(u"https://www.bricklink.com/files/clone/wanted/downloadXML.file"_qs,
{ { u"wantedMoreID"_qs, QString::number(wantedList->id()) } });
job->setUserData("wantedList", QVariant::fromValue(wantedList->id()));
m_wantedListJobs << job;
m_core->retrieveAuthenticated(job);
}
int WantedLists::rowCount(const QModelIndex &parent) const
{
return parent.isValid() ? 0 : int(m_wantedLists.count());
}
int WantedLists::columnCount(const QModelIndex &parent) const
{
return parent.isValid() ? 0 : ColumnCount;
}
QVariant WantedLists::data(const QModelIndex &index, int role) const
{
if (!index.isValid() || (index.row() < 0) || (index.row() >= m_wantedLists.size()))
return { };
WantedList *wantedList = m_wantedLists.at(index.row());
int col = index.column();
if (role == Qt::DisplayRole) {
switch (col) {
case Name: return wantedList->name();
case Description: return wantedList->description();
case ItemLeftCount: return QLocale::system().toString(wantedList->itemLeftCount());
case ItemCount: return QLocale::system().toString(wantedList->itemCount());
case LotCount: return QLocale::system().toString(wantedList->lotCount());
case Filled: return QLocale::system().toString(int(wantedList->filled() * 100)).append(u'%');
}
} else if (role == Qt::TextAlignmentRole) {
return int(Qt::AlignVCenter) | Qt::AlignLeft;
} else if (role == WantedListPointerRole) {
return QVariant::fromValue(wantedList);
} else if (role == WantedListSortRole) {
switch (col) {
case Name: return wantedList->name();
case Description: return wantedList->description();
case ItemLeftCount: return wantedList->itemLeftCount();
case ItemCount: return wantedList->itemCount();
case LotCount: return wantedList->lotCount();
case Filled: return QString::number(int(wantedList->filled() * 100)).append(u'%');
}
} else if (role == NameRole) {
return wantedList->name();
}
return { };
}
QVariant WantedLists::headerData(int section, Qt::Orientation orient, int role) const
{
if (orient == Qt::Horizontal) {
if (role == Qt::DisplayRole) {
switch (section) {
case Name: return tr("Name");
case Description: return tr("Description");
case ItemCount: return tr("Items");
case ItemLeftCount: return tr("Items left");
case LotCount: return tr("Lots");
case Filled: return tr("Filled");
}
} else if (role == Qt::TextAlignmentRole) {
return (section == Total) ? Qt::AlignRight : Qt::AlignLeft;
}
}
return { };
}
QHash<int, QByteArray> WantedLists::roleNames() const
{
static const QHash<int, QByteArray> roles = {
{ Qt::DisplayRole, "display" },
{ Qt::TextAlignmentRole, "textAlignment" },
{ Qt::DecorationRole, "decoration" },
{ Qt::BackgroundRole, "background" },
{ WantedListPointerRole, "wantedList" },
{ NameRole, "name" },
};
return roles;
}
} // namespace BrickLink
#include "moc_wantedlist.cpp"