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 4d434e0f3a

View file

@ -17,6 +17,7 @@
#include <QJsonArray>
#include <QJsonDocument>
#include <QJsonObject>
#include <QJsonParseError>
#include <QStandardPaths>
#include <QtConcurrent>
@ -958,19 +959,47 @@ void App::loadLibrary()
return;
}
QJsonDocument doc = QJsonDocument::fromJson(file.readAll());
if (!doc.isArray()) {
const QByteArray data = file.readAll();
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;
}
QJsonArray gamesArray = doc.array();
for (const QJsonValue &value : gamesArray) {
if (value.isObject()) {
Game *game = Game::fromJson(value.toObject(), this);
if (game) {
m_gameModel->addGame(game);
}
QJsonArray gamesArray;
if (doc.isArray()) {
gamesArray = doc.array();
} else if (doc.isObject()) {
const QJsonObject rootObj = doc.object();
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);
}
}