|
| 1 | +#include "backup.h" |
| 2 | + |
| 3 | +Backup::Backup(QObject *parent) |
| 4 | + : QObject{parent} |
| 5 | +{ |
| 6 | +} |
| 7 | + |
| 8 | +void Backup::backup(QString filePath, bool includeSensitiveInfo) |
| 9 | +{ |
| 10 | + |
| 11 | + if (filePath.isEmpty()) { |
| 12 | + return; |
| 13 | + } |
| 14 | + |
| 15 | + // adding .json if needed |
| 16 | + if(!filePath.endsWith(".json")) { |
| 17 | + filePath.append(".json"); |
| 18 | + } |
| 19 | + |
| 20 | + QFile file(filePath); |
| 21 | + if (!(file.open(QIODevice::WriteOnly | QIODevice::Text))) { |
| 22 | + qDebug() << "[Backup] Cannot open file in write mode"; |
| 23 | + file.close(); |
| 24 | + return; |
| 25 | + } |
| 26 | + |
| 27 | + qDebug() << "[Backup] Starting backup..."; |
| 28 | + // adding all the keys in a json object and converting it into a string |
| 29 | + QJsonObject jsonObject; |
| 30 | + QSettings settings; |
| 31 | + QStringList keys = settings.allKeys(); |
| 32 | + |
| 33 | + // sensitive info must be excluded |
| 34 | + if(!includeSensitiveInfo) { |
| 35 | + keys.removeIf([](const QString& key){ |
| 36 | + return key.startsWith("osuirc") || key.startsWith("twitch"); |
| 37 | + }); |
| 38 | + } |
| 39 | + |
| 40 | + for(const QString& key: keys){ |
| 41 | + QString value = settings.value(key).toString(); |
| 42 | + jsonObject.insert(key, QJsonValue(value)); |
| 43 | + } |
| 44 | + QString jsonString = QJsonDocument(jsonObject).toJson(); |
| 45 | + |
| 46 | + // saving the backup |
| 47 | + QTextStream stream(&file); |
| 48 | + stream << jsonString; |
| 49 | + file.close(); |
| 50 | + qDebug() << "[Backup] Backup completed"; |
| 51 | +} |
| 52 | + |
| 53 | +void Backup::restore(QString filePath) |
| 54 | +{ |
| 55 | + if (filePath.isEmpty()) { |
| 56 | + return; |
| 57 | + } |
| 58 | + |
| 59 | + QFile file(filePath); |
| 60 | + if (!(file.open(QIODevice::ReadOnly | QIODevice::Text))) { |
| 61 | + qDebug() << "[Backup] Cannot open file in read mode"; |
| 62 | + file.close(); |
| 63 | + return; |
| 64 | + } |
| 65 | + |
| 66 | + qDebug() << "[Backup] Starting backup restore..."; |
| 67 | + QTextStream stream(&file); |
| 68 | + QString jsonString = stream.readAll(); |
| 69 | + file.close(); |
| 70 | + |
| 71 | + QSettings settings; |
| 72 | + QJsonDocument jsonDoc = QJsonDocument::fromJson(jsonString.toUtf8()); |
| 73 | + if (!jsonDoc.isNull()){ |
| 74 | + QJsonObject jsonObject = jsonDoc.object(); |
| 75 | + for (auto it = jsonObject.begin(); it != jsonObject.end(); ++it) { |
| 76 | + QString key = it.key(); |
| 77 | + QJsonValue value = it.value(); |
| 78 | + |
| 79 | + settings.setValue(key, value.toString()); |
| 80 | + } |
| 81 | + } |
| 82 | + qDebug() << "[Backup] Backup restored successfully"; |
| 83 | +} |
0 commit comments