refactor: API split (#721)

* refactor: API split

* refactor: cleanup hyperiond
This commit is contained in:
brindosch
2020-03-26 17:59:41 +01:00
committed by GitHub
parent c6c6453267
commit 2739aec1e3
23 changed files with 2044 additions and 1128 deletions

529
libsrc/api/API.cpp Normal file
View File

@@ -0,0 +1,529 @@
// project includes
#include <api/API.h>
// stl includes
#include <iostream>
#include <iterator>
// Qt includes
#include <QResource>
#include <QDateTime>
#include <QCryptographicHash>
#include <QImage>
#include <QBuffer>
#include <QByteArray>
#include <QTimer>
// hyperion includes
#include <leddevice/LedDeviceWrapper.h>
#include <hyperion/GrabberWrapper.h>
#include <utils/jsonschema/QJsonFactory.h>
#include <utils/jsonschema/QJsonSchemaChecker.h>
#include <HyperionConfig.h>
#include <utils/SysInfo.h>
#include <utils/ColorSys.h>
#include <utils/Process.h>
//#include <utils/ApiSync.h>
// bonjour wrapper
#include <bonjour/bonjourbrowserwrapper.h>
// ledmapping int <> string transform methods
#include <hyperion/ImageProcessor.h>
// api includes
#include <api/JsonCB.h>
using namespace hyperion;
API::API(Logger *log, const bool &localConnection, QObject *parent)
: QObject(parent)
{
qRegisterMetaType<int64_t>("int64_t");
qRegisterMetaType<VideoMode>("VideoMode");
qRegisterMetaType<std::map<int, registerData>>("std::map<int,registerData>");
// Init
_log = log;
_authManager = AuthManager::getInstance();
_instanceManager = HyperionIManager::getInstance();
_localConnection = localConnection;
_authorized = false;
_adminAuthorized = false;
_hyperion = _instanceManager->getHyperionInstance(0);
_currInstanceIndex = 0;
// TODO FIXME
// report back current registers when a Hyperion instance request it
//connect(ApiSync::getInstance(), &ApiSync::requestActiveRegister, this, &API::requestActiveRegister, Qt::QueuedConnection);
// connect to possible token responses that has been requested
connect(_authManager, &AuthManager::tokenResponse, this, &API::checkTokenResponse);
}
void API::init(void)
{
bool apiAuthRequired = _authManager->isAuthRequired();
// For security we block external connections if default PW is set
if (!_localConnection && API::hasHyperionDefaultPw())
{
emit forceClose();
}
// if this is localConnection and network allows unauth locals, set authorized flag
if (apiAuthRequired && _localConnection)
_authorized = !_authManager->isLocalAuthRequired();
// admin access is allowed, when the connection is local and the option for local admin isn't set. Con: All local connections get full access
if (_localConnection)
{
_adminAuthorized = !_authManager->isLocalAdminAuthRequired();
// just in positive direction
if (_adminAuthorized)
_authorized = true;
}
}
void API::setColor(const int &priority, const std::vector<uint8_t> &ledColors, const int &timeout_ms, const QString &origin, const hyperion::Components &callerComp)
{
std::vector<ColorRgb> fledColors;
if (ledColors.size() % 3 == 0)
{
for (unsigned i = 0; i < ledColors.size(); i += 3)
{
fledColors.emplace_back(ColorRgb{ledColors[i], ledColors[i + 1], ledColors[i + 2]});
}
QMetaObject::invokeMethod(_hyperion, "setColor", Qt::QueuedConnection, Q_ARG(int, priority), Q_ARG(std::vector<ColorRgb>, fledColors), Q_ARG(int, timeout_ms), Q_ARG(QString, origin));
//QMetaObject::invokeMethod(ApiSync::getInstance(), "setColor", Qt::QueuedConnection, Q_ARG(QObject *, _hyperion), Q_ARG(int, priority), Q_ARG(std::vector<ColorRgb>, fledColors), Q_ARG(int, timeout_ms), Q_ARG(QString, origin), Q_ARG(hyperion::Components, callerComp));
}
}
bool API::setImage(ImageCmdData &data, hyperion::Components comp, QString &replyMsg, const hyperion::Components &callerComp)
{
// truncate name length
data.imgName.truncate(16);
if (data.format == "auto")
{
QImage img = QImage::fromData(data.data);
if (img.isNull())
{
replyMsg = "Failed to parse picture, the file might be corrupted";
return false;
}
// check for requested scale
if (data.scale > 24)
{
if (img.height() > data.scale)
{
img = img.scaledToHeight(data.scale);
}
if (img.width() > data.scale)
{
img = img.scaledToWidth(data.scale);
}
}
// check if we need to force a scale
if (img.width() > 2000 || img.height() > 2000)
{
data.scale = 2000;
if (img.height() > data.scale)
{
img = img.scaledToHeight(data.scale);
}
if (img.width() > data.scale)
{
img = img.scaledToWidth(data.scale);
}
}
data.width = img.width();
data.height = img.height();
// extract image
img = img.convertToFormat(QImage::Format_ARGB32_Premultiplied);
data.data.clear();
data.data.reserve(img.width() * img.height() * 3);
for (int i = 0; i < img.height(); ++i)
{
const QRgb *scanline = reinterpret_cast<const QRgb *>(img.scanLine(i));
for (int j = 0; j < img.width(); ++j)
{
data.data.append((char)qRed(scanline[j]));
data.data.append((char)qGreen(scanline[j]));
data.data.append((char)qBlue(scanline[j]));
}
}
}
else
{
// check consistency of the size of the received data
if (data.data.size() != data.width * data.height * 3)
{
replyMsg = "Size of image data does not match with the width and height";
return false;
}
}
// copy image
Image<ColorRgb> image(data.width, data.height);
memcpy(image.memptr(), data.data.data(), data.data.size());
QMetaObject::invokeMethod(_hyperion, "registerInput", Qt::QueuedConnection, Q_ARG(int, data.priority), Q_ARG(hyperion::Components, comp), Q_ARG(QString, data.origin), Q_ARG(QString, data.imgName));
QMetaObject::invokeMethod(_hyperion, "setInputImage", Qt::QueuedConnection, Q_ARG(int, data.priority), Q_ARG(Image<ColorRgb>, image), Q_ARG(int64_t, data.duration));
//QMetaObject::invokeMethod(ApiSync::getInstance(), "registerInput", Qt::QueuedConnection, Q_ARG(QObject *, _hyperion), Q_ARG(int, data.priority), Q_ARG(hyperion::Components, comp), Q_ARG(QString, data.origin), Q_ARG(QString, data.imgName), Q_ARG(hyperion::Components, callerComp));
//QMetaObject::invokeMethod(ApiSync::getInstance(), "setInputImage", Qt::QueuedConnection, Q_ARG(QObject *, _hyperion), Q_ARG(int, data.priority), Q_ARG(Image<ColorRgb>, image), Q_ARG(int64_t, data.duration), Q_ARG(hyperion::Components, comp), Q_ARG(hyperion::Components, callerComp));
return true;
}
bool API::clearPriority(const int &priority, QString &replyMsg, const hyperion::Components &callerComp)
{
if (priority < 0 || (priority > 0 && priority < 254))
{
QMetaObject::invokeMethod(_hyperion, "clear", Qt::QueuedConnection, Q_ARG(int, priority));
//QMetaObject::invokeMethod(ApiSync::getInstance(), "clearPriority", Qt::QueuedConnection, Q_ARG(QObject *, _hyperion), Q_ARG(int, priority), Q_ARG(hyperion::Components, callerComp));
}
else
{
replyMsg = QString("Priority %1 is not allowed to be cleared").arg(priority);
return false;
}
return true;
}
bool API::setComponentState(const QString &comp, bool &compState, QString &replyMsg, const hyperion::Components &callerComp)
{
Components component = stringToComponent(comp);
if (component != COMP_INVALID)
{
QMetaObject::invokeMethod(_hyperion, "compStateChangeRequest", Qt::QueuedConnection, Q_ARG(hyperion::Components, component), Q_ARG(bool, compState));
//QMetaObject::invokeMethod(ApiSync::getInstance(), "compStateChangeRequest", Qt::QueuedConnection, Q_ARG(QObject *, _hyperion), Q_ARG(hyperion::Components, component), Q_ARG(bool, compState), Q_ARG(hyperion::Components, callerComp));
return true;
}
replyMsg = QString("Unknown component name: %1").arg(comp);
return false;
}
void API::setLedMappingType(const int &type, const hyperion::Components &callerComp)
{
QMetaObject::invokeMethod(_hyperion, "setLedMappingType", Qt::QueuedConnection, Q_ARG(int, type));
//QMetaObject::invokeMethod(ApiSync::getInstance(), "setLedMappingType", Qt::QueuedConnection, Q_ARG(QObject *, _hyperion), Q_ARG(int, type), Q_ARG(hyperion::Components, callerComp));
}
void API::setVideoMode(const VideoMode &mode, const hyperion::Components &callerComp)
{
QMetaObject::invokeMethod(_hyperion, "setVideoMode", Qt::QueuedConnection, Q_ARG(VideoMode, mode));
//QMetaObject::invokeMethod(ApiSync::getInstance(), "setVideoMode", Qt::QueuedConnection, Q_ARG(QObject *, _hyperion), Q_ARG(VideoMode, mode), Q_ARG(hyperion::Components, callerComp));
}
void API::setEffect(const EffectCmdData &dat, const hyperion::Components &callerComp)
{
if (!dat.args.isEmpty())
{
QMetaObject::invokeMethod(_hyperion, "setEffect", Qt::QueuedConnection, Q_ARG(QString, dat.effectName), Q_ARG(QJsonObject, dat.args), Q_ARG(int, dat.priority), Q_ARG(int, dat.duration), Q_ARG(QString, dat.pythonScript), Q_ARG(QString, dat.origin), Q_ARG(QString, dat.data));
}
else
{
QMetaObject::invokeMethod(_hyperion, "setEffect", Qt::QueuedConnection, Q_ARG(QString, dat.effectName), Q_ARG(int, dat.priority), Q_ARG(int, dat.duration), Q_ARG(QString, dat.origin));
//QMetaObject::invokeMethod(ApiSync::getInstance(), "setEffect", Qt::QueuedConnection, Q_ARG(QObject *, _hyperion), Q_ARG(QString, dat.effectName), Q_ARG(int, dat.priority), Q_ARG(int, dat.duration), Q_ARG(QString, dat.origin), Q_ARG(hyperion::Components, callerComp));
}
}
void API::setSourceAutoSelect(const bool state, const hyperion::Components &callerComp)
{
QMetaObject::invokeMethod(_hyperion, "setSourceAutoSelect", Qt::QueuedConnection, Q_ARG(bool, state));
//QMetaObject::invokeMethod(ApiSync::getInstance(), "setSourceAutoSelect", Qt::QueuedConnection, Q_ARG(QObject *, _hyperion), Q_ARG(bool, state), Q_ARG(hyperion::Components, callerComp));
}
void API::setVisiblePriority(const int &priority, const hyperion::Components &callerComp)
{
QMetaObject::invokeMethod(_hyperion, "setVisiblePriority", Qt::QueuedConnection, Q_ARG(int, priority));
//QMetaObject::invokeMethod(ApiSync::getInstance(), "setVisiblePriority", Qt::QueuedConnection, Q_ARG(QObject *, _hyperion), Q_ARG(int, priority), Q_ARG(hyperion::Components, callerComp));
}
void API::registerInput(const int &priority, const hyperion::Components &component, const QString &origin, const QString &owner, const hyperion::Components &callerComp)
{
if (_activeRegisters.count(priority))
_activeRegisters.erase(priority);
_activeRegisters.insert({priority, registerData{component, origin, owner, callerComp}});
QMetaObject::invokeMethod(_hyperion, "registerInput", Qt::QueuedConnection, Q_ARG(int, priority), Q_ARG(hyperion::Components, component), Q_ARG(QString, origin), Q_ARG(QString, owner));
//QMetaObject::invokeMethod(ApiSync::getInstance(), "registerInput", Qt::QueuedConnection, Q_ARG(QObject *, _hyperion), Q_ARG(int, priority), Q_ARG(hyperion::Components, component), Q_ARG(QString, origin), Q_ARG(QString, owner), Q_ARG(hyperion::Components, callerComp));
}
void API::unregisterInput(const int &priority)
{
if (_activeRegisters.count(priority))
_activeRegisters.erase(priority);
}
bool API::setHyperionInstance(const quint8 &inst)
{
if (_currInstanceIndex == inst)
return true;
bool isRunning;
QMetaObject::invokeMethod(_instanceManager, "IsInstanceRunning", Qt::BlockingQueuedConnection, Q_RETURN_ARG(bool, isRunning), Q_ARG(quint8, inst));
if (!isRunning)
return false;
disconnect(_hyperion, 0, this, 0);
QMetaObject::invokeMethod(_instanceManager, "getHyperionInstance", Qt::BlockingQueuedConnection, Q_RETURN_ARG(Hyperion *, _hyperion), Q_ARG(quint8, inst));
_currInstanceIndex = inst;
return true;
}
std::map<hyperion::Components, bool> API::getAllComponents()
{
std::map<hyperion::Components, bool> comps;
//QMetaObject::invokeMethod(_hyperion, "getAllComponents", Qt::BlockingQueuedConnection, Q_RETURN_ARG(std::map<hyperion::Components, bool>, comps));
return comps;
}
bool API::isHyperionEnabled()
{
int res;
QMetaObject::invokeMethod(_hyperion, "isComponentEnabled", Qt::BlockingQueuedConnection, Q_RETURN_ARG(int, res), Q_ARG(hyperion::Components, hyperion::COMP_ALL));
return res > 0;
}
QVector<QVariantMap> API::getAllInstanceData(void)
{
QVector<QVariantMap> vec;
QMetaObject::invokeMethod(_instanceManager, "getInstanceData", Qt::BlockingQueuedConnection, Q_RETURN_ARG(QVector<QVariantMap>, vec));
return vec;
}
void API::startInstance(const quint8 &index)
{
QMetaObject::invokeMethod(_instanceManager, "startInstance", Qt::QueuedConnection, Q_ARG(quint8, index));
}
void API::stopInstance(const quint8 &index)
{
QMetaObject::invokeMethod(_instanceManager, "stopInstance", Qt::QueuedConnection, Q_ARG(quint8, index));
}
void API::requestActiveRegister(QObject *callerInstance)
{
// TODO FIXME
//if (_activeRegisters.size())
// QMetaObject::invokeMethod(ApiSync::getInstance(), "answerActiveRegister", Qt::QueuedConnection, Q_ARG(QObject *, callerInstance), Q_ARG(MapRegister, _activeRegisters));
}
bool API::deleteInstance(const quint8 &index, QString &replyMsg)
{
if (_adminAuthorized)
{
QMetaObject::invokeMethod(_instanceManager, "deleteInstance", Qt::QueuedConnection, Q_ARG(quint8, index));
return true;
}
replyMsg = NO_AUTH;
return false;
}
QString API::createInstance(const QString &name)
{
if (_adminAuthorized)
{
bool success;
QMetaObject::invokeMethod(_instanceManager, "createInstance", Qt::BlockingQueuedConnection, Q_RETURN_ARG(bool, success), Q_ARG(QString, name));
if (!success)
return QString("Instance name '%1' is already in use").arg(name);
return "";
}
return NO_AUTH;
}
QString API::setInstanceName(const quint8 &index, const QString &name)
{
if (_adminAuthorized)
{
QMetaObject::invokeMethod(_instanceManager, "saveName", Qt::QueuedConnection, Q_ARG(quint8, index), Q_ARG(QString, name));
return "";
}
return NO_AUTH;
}
QString API::deleteEffect(const QString &name)
{
if (_adminAuthorized)
{
QString res;
QMetaObject::invokeMethod(_hyperion, "deleteEffect", Qt::BlockingQueuedConnection, Q_RETURN_ARG(QString, res), Q_ARG(QString, name));
return res;
}
return NO_AUTH;
}
QString API::saveEffect(const QJsonObject &data)
{
if (_adminAuthorized)
{
QString res;
QMetaObject::invokeMethod(_hyperion, "saveEffect", Qt::BlockingQueuedConnection, Q_RETURN_ARG(QString, res), Q_ARG(QJsonObject, data));
return res;
}
return NO_AUTH;
}
void API::saveSettings(const QJsonObject &data)
{
if (!_adminAuthorized)
return;
QMetaObject::invokeMethod(_hyperion, "saveSettings", Qt::QueuedConnection, Q_ARG(QJsonObject, data), Q_ARG(bool, true));
}
bool API::updateHyperionPassword(const QString &password, const QString &newPassword)
{
if (!_adminAuthorized)
return false;
bool res;
QMetaObject::invokeMethod(_authManager, "updateUserPassword", Qt::BlockingQueuedConnection, Q_RETURN_ARG(bool, res), Q_ARG(QString, "Hyperion"), Q_ARG(QString, password), Q_ARG(QString, newPassword));
return res;
}
QString API::createToken(const QString &comment, AuthManager::AuthDefinition &def)
{
if (!_adminAuthorized)
return NO_AUTH;
if (comment.isEmpty())
return "comment is empty";
QMetaObject::invokeMethod(_authManager, "createToken", Qt::BlockingQueuedConnection, Q_RETURN_ARG(AuthManager::AuthDefinition, def), Q_ARG(QString, comment));
return "";
}
QString API::renameToken(const QString &id, const QString &comment)
{
if (!_adminAuthorized)
return NO_AUTH;
if (comment.isEmpty() || id.isEmpty())
return "Empty comment or id";
QMetaObject::invokeMethod(_authManager, "renameToken", Qt::QueuedConnection, Q_ARG(QString, id), Q_ARG(QString, comment));
return "";
}
QString API::deleteToken(const QString &id)
{
if (!_adminAuthorized)
return NO_AUTH;
if (id.isEmpty())
return "Empty id";
QMetaObject::invokeMethod(_authManager, "deleteToken", Qt::QueuedConnection, Q_ARG(QString, id));
return "";
}
void API::setNewTokenRequest(const QString &comment, const QString &id)
{
QMetaObject::invokeMethod(_authManager, "setNewTokenRequest", Qt::QueuedConnection, Q_ARG(QObject *, this), Q_ARG(QString, comment), Q_ARG(QString, id));
}
void API::cancelNewTokenRequest(const QString &comment, const QString &id)
{
QMetaObject::invokeMethod(_authManager, "cancelNewTokenRequest", Qt::QueuedConnection, Q_ARG(QObject *, this), Q_ARG(QString, comment), Q_ARG(QString, id));
}
bool API::handlePendingTokenRequest(const QString &id, const bool accept)
{
if (!_adminAuthorized)
return false;
QMetaObject::invokeMethod(_authManager, "handlePendingTokenRequest", Qt::QueuedConnection, Q_ARG(QString, id), Q_ARG(bool, accept));
return true;
}
bool API::getTokenList(QVector<AuthManager::AuthDefinition> &def)
{
if (!_adminAuthorized)
return false;
QMetaObject::invokeMethod(_authManager, "getTokenList", Qt::BlockingQueuedConnection, Q_RETURN_ARG(QVector<AuthManager::AuthDefinition>, def));
return true;
}
bool API::getPendingTokenRequests(QVector<AuthManager::AuthDefinition> &map)
{
if (!_adminAuthorized)
return false;
QMetaObject::invokeMethod(_authManager, "getPendingRequests", Qt::BlockingQueuedConnection, Q_RETURN_ARG(QVector<AuthManager::AuthDefinition>, map));
return true;
}
bool API::isUserTokenAuthorized(const QString &userToken)
{
bool res;
QMetaObject::invokeMethod(_authManager, "isUserTokenAuthorized", Qt::BlockingQueuedConnection, Q_RETURN_ARG(bool, res), Q_ARG(QString, "Hyperion"), Q_ARG(QString, userToken));
if (res)
{
_authorized = true;
_adminAuthorized = true;
// Listen for ADMIN ACCESS protected signals
connect(_authManager, &AuthManager::newPendingTokenRequest, this, &API::onPendingTokenRequest, Qt::UniqueConnection);
}
return res;
}
bool API::getUserToken(QString &userToken)
{
if (!_adminAuthorized)
return false;
QMetaObject::invokeMethod(_authManager, "getUserToken", Qt::BlockingQueuedConnection, Q_RETURN_ARG(QString, userToken));
return true;
}
bool API::isTokenAuthorized(const QString &token)
{
bool res;
QMetaObject::invokeMethod(_authManager, "isTokenAuthorized", Qt::BlockingQueuedConnection, Q_RETURN_ARG(bool, res), Q_ARG(QString, token));
if (res)
_authorized = true;
return res;
}
bool API::isUserAuthorized(const QString &password)
{
bool res;
QMetaObject::invokeMethod(_authManager, "isUserAuthorized", Qt::BlockingQueuedConnection, Q_RETURN_ARG(bool, res), Q_ARG(QString, "Hyperion"), Q_ARG(QString, password));
if (res)
{
_authorized = true;
_adminAuthorized = true;
// Listen for ADMIN ACCESS protected signals
connect(_authManager, &AuthManager::newPendingTokenRequest, this, &API::onPendingTokenRequest, Qt::UniqueConnection);
}
return res;
}
bool API::hasHyperionDefaultPw()
{
bool res;
QMetaObject::invokeMethod(_authManager, "isUserAuthorized", Qt::BlockingQueuedConnection, Q_RETURN_ARG(bool, res), Q_ARG(QString, "Hyperion"), Q_ARG(QString, "hyperion"));
return res;
}
void API::logout()
{
_authorized = false;
_adminAuthorized = false;
// Stop listenig for ADMIN ACCESS protected signals
disconnect(_authManager, &AuthManager::newPendingTokenRequest, this, &API::onPendingTokenRequest);
stopDataConnectionss();
}
void API::checkTokenResponse(const bool &success, QObject *caller, const QString &token, const QString &comment, const QString &id)
{
if (this == caller)
emit onTokenResponse(success, token, comment, id);
}
void API::stopDataConnectionss()
{
}

View File

@@ -10,7 +10,7 @@
"subcommand" : {
"type" : "string",
"required" : true,
"enum" : ["requestToken","createToken","deleteToken","getTokenList","logout","login","required","adminRequired","newPasswordRequired","newPassword","answerRequest","getPendingRequests"]
"enum" : ["requestToken","createToken","renameToken","deleteToken","getTokenList","logout","login","tokenRequired","adminRequired","newPasswordRequired","newPassword","answerRequest","getPendingTokenRequests"]
},
"tan" : {
"type" : "integer"

File diff suppressed because it is too large Load Diff

View File

@@ -35,7 +35,7 @@ JsonCB::JsonCB(QObject* parent)
, _prioMuxer(nullptr)
{
_availableCommands << "components-update" << "sessions-update" << "priorities-update" << "imageToLedMapping-update"
<< "adjustment-update" << "videomode-update" << "effects-update" << "settings-update" << "leds-update" << "instance-update";
<< "adjustment-update" << "videomode-update" << "effects-update" << "settings-update" << "leds-update" << "instance-update" << "token-update";
}
bool JsonCB::subscribeFor(const QString& type, const bool & unsubscribe)
@@ -131,6 +131,14 @@ bool JsonCB::subscribeFor(const QString& type, const bool & unsubscribe)
connect(HyperionIManager::getInstance(), &HyperionIManager::change, this, &JsonCB::handleInstanceChange, Qt::UniqueConnection);
}
if (type == "token-update")
{
if (unsubscribe)
disconnect(AuthManager::getInstance(), &AuthManager::tokenChange, this, &JsonCB::handleTokenChange);
else
connect(AuthManager::getInstance(), &AuthManager::tokenChange, this, &JsonCB::handleTokenChange, Qt::UniqueConnection);
}
return true;
}
@@ -401,3 +409,17 @@ void JsonCB::handleInstanceChange()
}
doCallback("instance-update", QVariant(arr));
}
void JsonCB::handleTokenChange(const QVector<AuthManager::AuthDefinition> &def)
{
QJsonArray arr;
for (const auto &entry : def)
{
QJsonObject sub;
sub["comment"] = entry.comment;
sub["id"] = entry.id;
sub["last_use"] = entry.lastUse;
arr.push_back(sub);
}
doCallback("token-update", QVariant(arr));
}

View File

@@ -47,14 +47,14 @@ EffectEngine::~EffectEngine()
{
}
bool EffectEngine::saveEffect(const QJsonObject& obj, QString& resultMsg)
QString EffectEngine::saveEffect(const QJsonObject& obj)
{
return _effectFileHandler->saveEffect(obj, resultMsg);
return _effectFileHandler->saveEffect(obj);
}
bool EffectEngine::deleteEffect(const QString& effectName, QString& resultMsg)
QString EffectEngine::deleteEffect(const QString& effectName)
{
return _effectFileHandler->deleteEffect(effectName, resultMsg);
return _effectFileHandler->deleteEffect(effectName);
}
const std::list<ActiveEffectDefinition> &EffectEngine::getActiveEffects()

View File

@@ -58,8 +58,9 @@ void EffectFileHandler::handleSettingsUpdate(const settings::type& type, const Q
}
}
bool EffectFileHandler::deleteEffect(const QString& effectName, QString& resultMsg)
QString EffectFileHandler::deleteEffect(const QString& effectName)
{
QString resultMsg;
std::list<EffectDefinition> effectsDefinition = getEffects();
std::list<EffectDefinition>::iterator it = std::find_if(effectsDefinition.begin(), effectsDefinition.end(), find_effect(effectName));
@@ -82,7 +83,7 @@ bool EffectFileHandler::deleteEffect(const QString& effectName, QString& resultM
if (result)
{
updateEffects();
return true;
return "";
} else
resultMsg = "Can't delete effect configuration file: " + effectConfigurationFile.absoluteFilePath() + ". Please check permissions";
} else
@@ -92,11 +93,12 @@ bool EffectFileHandler::deleteEffect(const QString& effectName, QString& resultM
} else
resultMsg = "Effect " + effectName + " not found";
return false;
return resultMsg;
}
bool EffectFileHandler::saveEffect(const QJsonObject& message, QString& resultMsg)
QString EffectFileHandler::saveEffect(const QJsonObject& message)
{
QString resultMsg;
if (!message["args"].toObject().isEmpty())
{
QString scriptName;
@@ -111,8 +113,7 @@ bool EffectFileHandler::saveEffect(const QJsonObject& message, QString& resultMs
{
if(!JsonUtils::validate("EffectFileHandler", message["args"].toObject(), it->schemaFile, _log))
{
resultMsg = "Error during arg validation against schema, please consult the Hyperion Log";
return false;
return "Error during arg validation against schema, please consult the Hyperion Log";
}
QJsonObject effectJson;
@@ -123,8 +124,7 @@ bool EffectFileHandler::saveEffect(const QJsonObject& message, QString& resultMs
{
if (message["name"].toString().trimmed().isEmpty() || message["name"].toString().trimmed().startsWith("."))
{
resultMsg = "Can't save new effect. Effect name is empty or begins with a dot.";
return false;
return "Can't save new effect. Effect name is empty or begins with a dot.";
}
effectJson["name"] = message["name"].toString();
@@ -140,8 +140,7 @@ bool EffectFileHandler::saveEffect(const QJsonObject& message, QString& resultMs
newFileName.setFile(iter->file);
if (newFileName.absoluteFilePath().mid(0, 1) == ":")
{
resultMsg = "The effect name '" + message["name"].toString() + "' is assigned to an internal effect. Please rename your effekt.";
return false;
return "The effect name '" + message["name"].toString() + "' is assigned to an internal effect. Please rename your effekt.";
}
} else
{
@@ -156,21 +155,18 @@ bool EffectFileHandler::saveEffect(const QJsonObject& message, QString& resultMs
QFileInfo imageFileName(effectArray[0].toString().replace("$ROOT",_rootPath) + "/" + message["args"].toObject().value("image").toString());
if(!FileUtils::writeFile(imageFileName.absoluteFilePath(), QByteArray::fromBase64(message["imageData"].toString("").toUtf8()), _log))
{
resultMsg = "Error while saving image file '" + message["args"].toObject().value("image").toString() + ", please check the Hyperion Log";
return false;
return "Error while saving image file '" + message["args"].toObject().value("image").toString() + ", please check the Hyperion Log";
}
}
if(!JsonUtils::write(newFileName.absoluteFilePath(), effectJson, _log))
{
resultMsg = "Error while saving effect, please check the Hyperion Log";
return false;
return "Error while saving effect, please check the Hyperion Log";
}
Info(_log, "Reload effect list");
updateEffects();
resultMsg = "";
return true;
return "";
} else
resultMsg = "Can't save new effect. Effect path empty";
} else
@@ -178,7 +174,7 @@ bool EffectFileHandler::saveEffect(const QJsonObject& message, QString& resultMs
} else
resultMsg = "Missing or empty Object 'args'";
return false;
return resultMsg;
}
void EffectFileHandler::updateEffects()

View File

@@ -8,11 +8,11 @@
#include <QJsonObject>
#include <QTimer>
AuthManager* AuthManager::manager = nullptr;
AuthManager *AuthManager::manager = nullptr;
AuthManager::AuthManager(QObject* parent)
AuthManager::AuthManager(QObject *parent)
: QObject(parent)
, _authTable(new AuthTable("",this))
, _authTable(new AuthTable("", this))
, _metaTable(new MetaTable(this))
, _pendingRequests()
, _authRequired(true)
@@ -21,10 +21,12 @@ AuthManager::AuthManager(QObject* parent)
{
AuthManager::manager = this;
// get uuid
_uuid = _metaTable->getUUID();
// Register meta
qRegisterMetaType<QVector<AuthManager::AuthDefinition>>("QVector<AuthManager::AuthDefinition>");
// setup timer
_timer->setInterval(1000);
connect(_timer, &QTimer::timeout, this, &AuthManager::checkTimeout);
@@ -34,16 +36,16 @@ AuthManager::AuthManager(QObject* parent)
connect(_authBlockTimer, &QTimer::timeout, this, &AuthManager::checkAuthBlockTimeout);
// init with default user and password
if(!_authTable->userExist("Hyperion"))
if (!_authTable->userExist("Hyperion"))
{
_authTable->createUser("Hyperion","hyperion");
_authTable->createUser("Hyperion", "hyperion");
}
// update Hyperion user token on startup
_authTable->setUserToken("Hyperion");
}
const AuthManager::AuthDefinition AuthManager::createToken(const QString& comment)
AuthManager::AuthDefinition AuthManager::createToken(const QString &comment)
{
const QString token = QUuid::createUuid().toString().mid(1, 36);
const QString id = QUuid::createUuid().toString().mid(1, 36).left(5);
@@ -55,14 +57,15 @@ const AuthManager::AuthDefinition AuthManager::createToken(const QString& commen
def.token = token;
def.id = id;
emit tokenChange(getTokenList());
return def;
}
const QVector<AuthManager::AuthDefinition> AuthManager::getTokenList()
QVector<AuthManager::AuthDefinition> AuthManager::getTokenList()
{
QVector<QVariantMap> vector = _authTable->getTokenList();
QVector<AuthManager::AuthDefinition> finalVec;
for(const auto& entry : vector)
for (const auto &entry : vector)
{
AuthDefinition def;
def.comment = entry["comment"].toString();
@@ -70,67 +73,73 @@ const QVector<AuthManager::AuthDefinition> AuthManager::getTokenList()
def.lastUse = entry["last_use"].toString();
// don't add empty ids
if(!entry["id"].toString().isEmpty())
if (!entry["id"].toString().isEmpty())
finalVec.append(def);
}
return finalVec;
}
const QString AuthManager::getUserToken(const QString & usr)
const QString AuthManager::getUserToken(const QString &usr)
{
QString tok = _authTable->getUserToken(usr);
return QString(_authTable->getUserToken(usr));
}
void AuthManager::setAuthBlock(const bool& user)
void AuthManager::setAuthBlock(const bool &user)
{
// current timestamp +10 minutes
if(user)
_userAuthAttempts.append(QDateTime::currentMSecsSinceEpoch()+600000);
if (user)
_userAuthAttempts.append(QDateTime::currentMSecsSinceEpoch() + 600000);
else
_tokenAuthAttempts.append(QDateTime::currentMSecsSinceEpoch()+600000);
_tokenAuthAttempts.append(QDateTime::currentMSecsSinceEpoch() + 600000);
QMetaObject::invokeMethod(_authBlockTimer, "start", Qt::QueuedConnection);
_authBlockTimer->start();
}
bool AuthManager::isUserAuthorized(const QString& user, const QString& pw)
bool AuthManager::isUserAuthorized(const QString &user, const QString &pw)
{
if(isUserAuthBlocked())
if (isUserAuthBlocked())
return false;
if(!_authTable->isUserAuthorized(user, pw)){
if (!_authTable->isUserAuthorized(user, pw))
{
setAuthBlock(true);
return false;
}
return true;
}
bool AuthManager::isTokenAuthorized(const QString& token)
bool AuthManager::isTokenAuthorized(const QString &token)
{
if(isTokenAuthBlocked())
if (isTokenAuthBlocked())
return false;
if(!_authTable->tokenExist(token)){
if (!_authTable->tokenExist(token))
{
setAuthBlock();
return false;
}
// timestamp update
tokenChange(getTokenList());
return true;
}
bool AuthManager::isUserTokenAuthorized(const QString& usr, const QString& token)
bool AuthManager::isUserTokenAuthorized(const QString &usr, const QString &token)
{
if(isUserAuthBlocked())
if (isUserAuthBlocked())
return false;
if(!_authTable->isUserTokenAuthorized(usr, token)){
if (!_authTable->isUserTokenAuthorized(usr, token))
{
setAuthBlock(true);
return false;
}
return true;
}
bool AuthManager::updateUserPassword(const QString& user, const QString& pw, const QString& newPw)
bool AuthManager::updateUserPassword(const QString &user, const QString &pw, const QString &newPw)
{
if(isUserAuthorized(user, pw))
if (isUserAuthorized(user, pw))
return _authTable->updateUserPassword(user, newPw);
return false;
@@ -141,64 +150,90 @@ bool AuthManager::resetHyperionUser()
return _authTable->resetHyperionUser();
}
void AuthManager::setNewTokenRequest(QObject* caller, const QString& comment, const QString& id)
void AuthManager::setNewTokenRequest(QObject *caller, const QString &comment, const QString &id)
{
if(!_pendingRequests.contains(id))
if (!_pendingRequests.contains(id))
{
AuthDefinition newDef {id, comment, caller, uint64_t(QDateTime::currentMSecsSinceEpoch()+60000)};
AuthDefinition newDef{id, comment, caller, uint64_t(QDateTime::currentMSecsSinceEpoch() + 180000)};
_pendingRequests[id] = newDef;
_timer->start();
emit newPendingTokenRequest(id, comment);
}
}
bool AuthManager::acceptTokenRequest(const QString& id)
void AuthManager::cancelNewTokenRequest(QObject *caller, const QString &comment, const QString &id)
{
if(_pendingRequests.contains(id))
if (_pendingRequests.contains(id))
{
const QString token = QUuid::createUuid().toString().remove("{").remove("}");
AuthDefinition def = _pendingRequests.take(id);
_authTable->createToken(token, def.comment, id);
emit tokenResponse(true, def.caller, token, def.comment, id);
return true;
AuthDefinition def = _pendingRequests.value(id);
if (def.caller == caller)
_pendingRequests.remove(id);
emit newPendingTokenRequest(id, "");
}
return false;
}
bool AuthManager::denyTokenRequest(const QString& id)
void AuthManager::handlePendingTokenRequest(const QString &id, const bool &accept)
{
if(_pendingRequests.contains(id))
if (_pendingRequests.contains(id))
{
AuthDefinition def = _pendingRequests.take(id);
emit tokenResponse(false, def.caller, QString(), def.comment, id);
if (accept)
{
const QString token = QUuid::createUuid().toString().remove("{").remove("}");
_authTable->createToken(token, def.comment, id);
emit tokenResponse(true, def.caller, token, def.comment, id);
emit tokenChange(getTokenList());
}
else
{
emit tokenResponse(false, def.caller, QString(), def.comment, id);
}
}
}
QVector<AuthManager::AuthDefinition> AuthManager::getPendingRequests()
{
QVector<AuthManager::AuthDefinition> finalVec;
for (const auto &entry : _pendingRequests)
{
AuthDefinition def;
def.comment = entry.comment;
def.id = entry.id;
def.timeoutTime = entry.timeoutTime - QDateTime::currentMSecsSinceEpoch();
finalVec.append(def);
}
return finalVec;
}
bool AuthManager::renameToken(const QString &id, const QString &comment)
{
if (_authTable->renameToken(id, comment))
{
emit tokenChange(getTokenList());
return true;
}
return false;
}
const QMap<QString, AuthManager::AuthDefinition> AuthManager::getPendingRequests()
bool AuthManager::deleteToken(const QString &id)
{
return _pendingRequests;
}
bool AuthManager::deleteToken(const QString& id)
{
if(_authTable->deleteToken(id))
if (_authTable->deleteToken(id))
{
//emit tokenDeleted(token);
emit tokenChange(getTokenList());
return true;
}
return false;
}
void AuthManager::handleSettingsUpdate(const settings::type& type, const QJsonDocument& config)
void AuthManager::handleSettingsUpdate(const settings::type &type, const QJsonDocument &config)
{
if(type == settings::NETWORK)
if (type == settings::NETWORK)
{
const QJsonObject& obj = config.object();
const QJsonObject &obj = config.object();
_authRequired = obj["apiAuth"].toBool(true);
_localAuthRequired = obj["localApiAuth"].toBool(false);
_localAdminAuthRequired = obj["localAdminAuth"].toBool(false);
_localAdminAuthRequired = obj["localAdminAuth"].toBool(true);
}
}
@@ -209,38 +244,43 @@ void AuthManager::checkTimeout()
QMapIterator<QString, AuthDefinition> i(_pendingRequests);
while (i.hasNext())
{
i.next();
i.next();
const AuthDefinition& def = i.value();
if(def.timeoutTime <= now)
const AuthDefinition &def = i.value();
if (def.timeoutTime <= now)
{
emit tokenResponse(false, def.caller, QString(), def.comment, def.id);
_pendingRequests.remove(i.key());
}
}
// abort if empty
if(_pendingRequests.isEmpty())
if (_pendingRequests.isEmpty())
_timer->stop();
}
void AuthManager::checkAuthBlockTimeout(){
void AuthManager::checkAuthBlockTimeout()
{
// handle user auth block
for (auto it = _userAuthAttempts.begin(); it != _userAuthAttempts.end(); it++) {
for (auto it = _userAuthAttempts.begin(); it != _userAuthAttempts.end(); it++)
{
// after 10 minutes, we remove the entry
if (*it < (uint64_t)QDateTime::currentMSecsSinceEpoch()) {
if (*it < (uint64_t)QDateTime::currentMSecsSinceEpoch())
{
_userAuthAttempts.erase(it--);
}
}
// handle token auth block
for (auto it = _tokenAuthAttempts.begin(); it != _tokenAuthAttempts.end(); it++) {
for (auto it = _tokenAuthAttempts.begin(); it != _tokenAuthAttempts.end(); it++)
{
// after 10 minutes, we remove the entry
if (*it < (uint64_t)QDateTime::currentMSecsSinceEpoch()) {
if (*it < (uint64_t)QDateTime::currentMSecsSinceEpoch())
{
_tokenAuthAttempts.erase(it--);
}
}
// if the lists are empty we stop
if(_userAuthAttempts.empty() && _tokenAuthAttempts.empty())
if (_userAuthAttempts.empty() && _tokenAuthAttempts.empty())
_authBlockTimer->stop();
}

View File

@@ -290,13 +290,12 @@ unsigned Hyperion::getLedCount() const
return _ledString.leds().size();
}
void Hyperion::setSourceAutoSelectEnabled(bool enabled)
void Hyperion::setSourceAutoSelect(const bool state)
{
if(_muxer.setSourceAutoSelectEnabled(enabled))
update();
_muxer.setSourceAutoSelectEnabled(state);
}
bool Hyperion::setCurrentSourcePriority(int priority )
bool Hyperion::setVisiblePriority(const int& priority)
{
return _muxer.setPriority(priority);
}
@@ -465,14 +464,14 @@ const Hyperion::InputInfo Hyperion::getPriorityInfo(const int priority) const
return _muxer.getInputInfo(priority);
}
bool Hyperion::saveEffect(const QJsonObject& obj, QString& resultMsg)
QString Hyperion::saveEffect(const QJsonObject& obj)
{
return _effectEngine->saveEffect(obj, resultMsg);
return _effectEngine->saveEffect(obj);
}
bool Hyperion::deleteEffect(const QString& effectName, QString& resultMsg)
QString Hyperion::deleteEffect(const QString& effectName)
{
return _effectEngine->deleteEffect(effectName, resultMsg);
return _effectEngine->deleteEffect(effectName);
}
const std::list<EffectDefinition> & Hyperion::getEffects() const