Utils: Add file access utils for json and text

This commit is contained in:
tt2468 2021-08-26 20:11:42 -07:00
parent 96ab90eea1
commit 8e539d6cdb
4 changed files with 52 additions and 0 deletions

View File

@ -1,4 +1,5 @@
#include "Json.h"
#include "Platform.h"
#include "../plugin-macros.generated.h"
bool Utils::Json::JsonArrayIsValidObsArray(json j)
@ -152,3 +153,24 @@ json Utils::Json::ObsDataToJson(obs_data_t *d, bool includeDefault)
return j;
}
bool Utils::Json::GetJsonFileContent(std::string fileName, json &content)
{
std::string textContent;
if (!Utils::Platform::GetTextFileContent(fileName, textContent))
return false;
try {
content = json::parse(textContent);
} catch (json::parse_error& e) {
blog(LOG_WARNING, "Failed to decode content of JSON file `%s`. Error: %s", fileName.c_str(), e.what());
return false;
}
return true;
}
bool Utils::Json::SetJsonFileContent(std::string fileName, json content, bool createNew)
{
std::string textContent = content.dump(2);
return Utils::Platform::SetTextFileContent(fileName, textContent, createNew);
}

View File

@ -1,5 +1,6 @@
#pragma once
#include <string>
#include <obs.hpp>
#include <nlohmann/json.hpp>
@ -10,5 +11,7 @@ namespace Utils {
bool JsonArrayIsValidObsArray(json j);
obs_data_t *JsonToObsData(json j);
json ObsDataToJson(obs_data_t *d, bool includeDefault = false);
bool GetJsonFileContent(std::string fileName, json &content);
bool SetJsonFileContent(std::string fileName, json content, bool createNew = true);
}
}

View File

@ -2,6 +2,7 @@
#include <QCommandLineParser>
#include <QNetworkInterface>
#include <QHostAddress>
#include <QFile>
#include <obs-frontend-api.h>
#include "Platform.h"
@ -98,3 +99,27 @@ void Utils::Platform::SendTrayNotification(QSystemTrayIcon::MessageIcon icon, QS
delete notification;
}, (void*)notification, false);
}
bool Utils::Platform::GetTextFileContent(std::string fileName, std::string &content)
{
QFile f(QString::fromStdString(fileName));
if (!f.open(QIODevice::ReadOnly | QIODevice::Text))
return false;
content = f.readAll().toStdString();
return true;
}
bool Utils::Platform::SetTextFileContent(std::string fileName, std::string content, bool createNew)
{
if (!createNew && !QFile::exists(QString::fromStdString(fileName)))
return false;
QFile f(QString::fromStdString(fileName));
if (!f.open(QIODevice::WriteOnly | QIODevice::Text))
return false;
QTextStream out(&f);
out << content.c_str();
return true;
}

View File

@ -10,5 +10,7 @@ namespace Utils {
QString GetCommandLineArgument(QString arg);
bool GetCommandLineFlagSet(QString arg);
void SendTrayNotification(QSystemTrayIcon::MessageIcon icon, QString title, QString body);
bool GetTextFileContent(std::string fileName, std::string &content);
bool SetTextFileContent(std::string filePath, std::string content, bool createNew = true);
}
}