Core: harden library.json loading for migration

This commit is contained in:
Marco Allegretti 2026-01-25 14:32:42 +01:00
parent 3ec2badcd7
commit ed9367fd71

View file

@ -17,6 +17,7 @@
#include <QJsonArray> #include <QJsonArray>
#include <QJsonDocument> #include <QJsonDocument>
#include <QJsonObject> #include <QJsonObject>
#include <QJsonParseError>
#include <QStandardPaths> #include <QStandardPaths>
#include <QtConcurrent> #include <QtConcurrent>
@ -958,19 +959,47 @@ void App::loadLibrary()
return; return;
} }
QJsonDocument doc = QJsonDocument::fromJson(file.readAll()); const QByteArray data = file.readAll();
if (!doc.isArray()) { QJsonParseError parseError;
QJsonDocument doc = QJsonDocument::fromJson(data, &parseError);
if (parseError.error != QJsonParseError::NoError) {
qWarning() << "Failed to parse library.json:" << parseError.errorString() << "at offset" << parseError.offset;
return; return;
} }
QJsonArray gamesArray = doc.array(); QJsonArray gamesArray;
for (const QJsonValue &value : gamesArray) { if (doc.isArray()) {
if (value.isObject()) { gamesArray = doc.array();
Game *game = Game::fromJson(value.toObject(), this); } else if (doc.isObject()) {
if (game) { const QJsonObject rootObj = doc.object();
m_gameModel->addGame(game); const QJsonValue gamesValue = rootObj.value(QStringLiteral("games"));
} if (gamesValue.isArray()) {
gamesArray = gamesValue.toArray();
} else {
qWarning() << "Invalid library.json format: expected a JSON array (or an object with a 'games' array)";
return;
} }
} else {
qWarning() << "Invalid library.json format: expected a JSON array (or an object with a 'games' array)";
return;
}
m_gameModel->clear();
for (int i = 0; i < gamesArray.size(); ++i) {
const QJsonValue value = gamesArray.at(i);
if (!value.isObject()) {
qWarning() << "Skipping invalid library entry (not an object) at index" << i;
continue;
}
Game *game = Game::fromJson(value.toObject(), this);
if (!game) {
qWarning() << "Skipping invalid game entry at index" << i;
continue;
}
m_gameModel->addGame(game);
} }
} }