diff --git a/src/plugin/settings/actions.cpp b/src/plugin/settings/actions.cpp deleted file mode 100644 index c953e78..0000000 --- a/src/plugin/settings/actions.cpp +++ /dev/null @@ -1,70 +0,0 @@ -// Copyright © 2024 Seagate Technology LLC and/or its Affiliates -// Copyright 2018-present Network Optix, Inc. Licensed under MPL 2.0: www.mozilla.org/MPL/2.0/ - -#include "actions.h" - -#include -#include - -#include "settings_model.h" - -namespace settings -{ - -void dumpStringMap(const char *prefix, const char *appendix, const nx::sdk::IStringMap *stringMap); - -nx::sdk::Ptr generateActionResponse(const std::string &settingId, - nx::sdk::Ptr params) -{ - using namespace nx::sdk; - NX_PRINT << "cloudfuse actions.cpp:generateActionResponse(" << settingId << ")" << std::endl; - dumpStringMap("cloudfuse", NULL, params.get()); - - if (settingId == kCheckCredentialsButtonId) - { - // run Cloudfuse --dry-run to check credentials - // hard-coding a response for now - const char *cloudfuseOutput = "Cloudfuse call not implemented!"; - bool success = false; - // possible responses to user - std::string successMessage = "✅ Credentials verified"; - std::string failureMessage = "❌ Cloud connection or authentication error"; - std::string resultMessage; - - // build action response - const auto actionResponse = makePtr(); - if (success) - { - resultMessage = successMessage; - } - else - { - resultMessage = failureMessage; - } - actionResponse->setMessageToUser(resultMessage + - " \nCheck Output: " + nx::kit::utils::toString(cloudfuseOutput)); - - return actionResponse; - } - - return nullptr; -} - -void dumpStringMap(const char *prefix, const char *appendix, const nx::sdk::IStringMap *stringMap) -{ - if (!stringMap) - { - NX_PRINT << prefix << " null" << appendix; - return; - } - - NX_PRINT << prefix << "{"; - for (int i = 0; i < stringMap->count(); ++i) - { - NX_PRINT << prefix << " " << nx::kit::utils::toString(stringMap->key(i)) << ": " - << nx::kit::utils::toString(stringMap->value(i)) << ((i == stringMap->count() - 1) ? "" : ","); - } - NX_PRINT << prefix << "}" << appendix; -} - -} // namespace settings diff --git a/src/plugin/settings/actions.h b/src/plugin/settings/actions.h deleted file mode 100644 index b17952d..0000000 --- a/src/plugin/settings/actions.h +++ /dev/null @@ -1,18 +0,0 @@ -// Copyright © 2024 Seagate Technology LLC and/or its Affiliates -// Copyright 2018-present Network Optix, Inc. Licensed under MPL 2.0: www.mozilla.org/MPL/2.0/ - -#pragma once - -#include - -#include -#include -#include - -namespace settings -{ - -nx::sdk::Ptr generateActionResponse(const std::string &settingId, - nx::sdk::Ptr params); - -} // namespace settings diff --git a/src/plugin/settings/active_settings_builder.cpp b/src/plugin/settings/active_settings_builder.cpp deleted file mode 100644 index a661096..0000000 --- a/src/plugin/settings/active_settings_builder.cpp +++ /dev/null @@ -1,49 +0,0 @@ -// Copyright © 2024 Seagate Technology LLC and/or its Affiliates -// Copyright 2018-present Network Optix, Inc. Licensed under MPL 2.0: www.mozilla.org/MPL/2.0/ - -#include "active_settings_builder.h" - -namespace settings -{ - -using namespace nx::sdk; - -void ActiveSettingsBuilder::addRule(const std::string &activeSettingName, const std::string &activeSettingValue, - ActiveSettingHandler activeSettingHandler) -{ - ActiveSettingKey key{activeSettingName, activeSettingValue}; - m_rules[key] = activeSettingHandler; -} - -void ActiveSettingsBuilder::addDefaultRule(const std::string &activeSettingName, - ActiveSettingHandler activeSettingHandler) -{ - m_defaultRules[activeSettingName] = activeSettingHandler; -} - -void ActiveSettingsBuilder::updateSettings(const std::string &activeSettingName, nx::kit::Json *inOutSettingsModel, - std::map *inOutSettingsValues) const -{ - ActiveSettingKey key{activeSettingName, (*inOutSettingsValues)[activeSettingName]}; - - auto rulesIt = m_rules.find(key); - auto defaultRulesIt = m_defaultRules.find(activeSettingName); - - if (rulesIt != m_rules.cend()) - rulesIt->second(inOutSettingsModel, inOutSettingsValues); - else if (defaultRulesIt != m_defaultRules.cend()) - defaultRulesIt->second(inOutSettingsModel, inOutSettingsValues); -} - -bool ActiveSettingsBuilder::ActiveSettingKey::operator<(const ActiveSettingKey &other) const -{ - if (activeSettingName != other.activeSettingName) - return activeSettingName < other.activeSettingName; - - if (activeSettingValue != other.activeSettingValue) - return activeSettingValue < other.activeSettingValue; - - return false; -} - -} // namespace settings diff --git a/src/plugin/settings/active_settings_builder.h b/src/plugin/settings/active_settings_builder.h deleted file mode 100644 index f73d4fc..0000000 --- a/src/plugin/settings/active_settings_builder.h +++ /dev/null @@ -1,48 +0,0 @@ -// Copyright © 2024 Seagate Technology LLC and/or its Affiliates -// Copyright 2018-present Network Optix, Inc. Licensed under MPL 2.0: www.mozilla.org/MPL/2.0/ - -#pragma once - -#include -#include -#include - -#include -#include -#include -#include - -namespace settings -{ - -class ActiveSettingsBuilder -{ - public: - using ActiveSettingHandler = - std::function * /*inOutValues*/)>; - - struct ActiveSettingKey - { - std::string activeSettingName; - std::string activeSettingValue; - - bool operator<(const ActiveSettingKey &other) const; - }; - - public: - ActiveSettingsBuilder() = default; - - void addRule(const std::string &activeSettingName, const std::string &activeSettingValue, - ActiveSettingHandler activeSettingHandler); - - void addDefaultRule(const std::string &activeSettingName, ActiveSettingHandler activeSettingHandler); - - void updateSettings(const std::string &activeSettingName, nx::kit::Json *inOutSettingsModel, - std::map *inOutSettingsValues) const; - - private: - std::map m_rules; - std::map m_defaultRules; -}; - -} // namespace settings diff --git a/src/plugin/settings/active_settings_rules.cpp b/src/plugin/settings/active_settings_rules.cpp deleted file mode 100644 index 46dd93f..0000000 --- a/src/plugin/settings/active_settings_rules.cpp +++ /dev/null @@ -1,217 +0,0 @@ -// Copyright © 2024 Seagate Technology LLC and/or its Affiliates -// Copyright 2018-present Network Optix, Inc. Licensed under MPL 2.0: www.mozilla.org/MPL/2.0/ - -#include "active_settings_rules.h" -#include "settings_model.h" - -#include -#include - -#include -#include -#include - -namespace settings -{ - -using namespace nx::sdk; -using namespace nx::kit; - -const std::string kAdditionalComboBoxSetting = R"json( - { - "type": "ComboBox", - "name": ")json" + kAdditionalComboBoxId + - R"json(", - "caption": "Additional ComboBox", - "defaultValue": "Value 1", - "range": - [ - "Value 1", - "Value 2" - ] - } -)json"; - -const std::string kAdditionalCheckBoxSetting = R"json( - { - "type": "CheckBox", - "name": ")json" + kAdditionalCheckBoxId + - R"json(", - "caption": "Additional CheckBox", - "defaultValue": false - } -)json"; - -const std::string kAdditionalRadioButton = "Hide me"; - -// ------------------------------------------------------------------------------------------------ - -const std::map - kActiveSettingsRules = {{{kActiveComboBoxId, kShowAdditionalComboBoxValue}, showAdditionalComboBox}, - {{kActiveCheckBoxId, kShowAdditionalCheckBoxValue}, showAdditionalCheckBox}, - {{kActiveRadioButtonGroupId, kShowAdditionalRadioButtonValue}, showAdditionalRadioButton}, - {{kActiveRadioButtonGroupId, kHideAdditionalRadioButtonValue}, hideAdditionalRadioButton}}; - -const std::map< - /*activeSettingName*/ std::string, ActiveSettingsBuilder::ActiveSettingHandler> - kDefaultActiveSettingsRules = { - {kActiveComboBoxId, hideAdditionalComboBox}, - {kActiveCheckBoxId, hideAdditionalCheckBox}, - {kActiveMaxValueId, updateMinMaxSpinBoxes}, - {kActiveMinValueId, updateMinMaxSpinBoxes}, -}; - -// ------------------------------------------------------------------------------------------------ - -static Json::array::iterator findSetting(const std::string &settingName, nx::kit::Json::array *inOutSettings) -{ - auto findByName = [&](const nx::kit::Json &value) { return value[kName].string_value() == settingName; }; - - return std::find_if(inOutSettings->begin(), inOutSettings->end(), findByName); -} - -void showAdditionalSetting(Json *inOutModel, std::map *inOutValues, - const std::string activeSettingName, const std::string additionalSettingTemplate, - const std::string additionalSettingValue) -{ - Json::array items = inOutModel->array_items(); - - std::string error; - Json newItem = Json::parse(additionalSettingTemplate, error); - const std::string newItemName = newItem[kName].string_value(); - - const auto settingIt = findSetting(activeSettingName, &items); - if (settingIt != items.end()) - items.insert(settingIt + 1, newItem); - - *inOutModel = Json(items); - const auto valueIt = inOutValues->find(newItemName); - if (valueIt == inOutValues->cend()) - inOutValues->emplace(newItemName, additionalSettingValue); -} - -void hideAdditionalSetting(Json *inOutModel, std::map *inOutValues, - const std::string additionalSettingId) -{ - Json::array items = inOutModel->array_items(); - const auto it = findSetting(additionalSettingId, &items); - if (it != items.end()) - items.erase(it); - - *inOutModel = Json(items); - inOutValues->erase(additionalSettingId); -} - -void showAdditionalSettingOption(Json *inOutModel, std::map *inOutValues, - const std::string &activeSettingName, const std::string &additionalSettingOption) -{ - Json::array items = inOutModel->array_items(); - - auto settingIt = findSetting(activeSettingName, &items); - if (settingIt != items.end()) - { - Json::object settingWithRange = settingIt->object_items(); - Json::array range = settingWithRange[kRange].array_items(); - - if (std::find(range.begin(), range.end(), additionalSettingOption) == range.cend()) - { - range.push_back(additionalSettingOption); - settingWithRange[kRange] = range; - *settingIt = Json(settingWithRange); - } - } - - *inOutModel = Json(items); - const auto valueIt = inOutValues->find(activeSettingName); - if (valueIt == inOutValues->cend()) - inOutValues->emplace(activeSettingName, additionalSettingOption); -} - -void hideAdditionalSettingOption(Json *inOutModel, std::map *inOutValues, - const std::string &activeSettingName, const std::string &additionalSettingValue, - const std::string &newAdditionalSettingValue) -{ - Json::array items = inOutModel->array_items(); - auto settingIt = findSetting(activeSettingName, &items); - if (settingIt != items.end()) - { - Json::object settingWithRange = settingIt->object_items(); - Json::array range = settingWithRange[kRange].array_items(); - - const auto valueIt = std::find(range.cbegin(), range.cend(), additionalSettingValue); - if (valueIt != range.cend()) - range.erase(valueIt); - - settingWithRange[kRange] = range; - *settingIt = Json(settingWithRange); - } - - *inOutModel = Json(items); - (*inOutValues)[activeSettingName] = newAdditionalSettingValue; -} - -void showAdditionalComboBox(Json *inOutModel, std::map *inOutValues) -{ - showAdditionalSetting(inOutModel, inOutValues, kActiveComboBoxId, kAdditionalComboBoxSetting, - kAdditionalComboBoxValue); -} - -void hideAdditionalComboBox(Json *inOutModel, std::map *inOutValues) -{ - hideAdditionalSetting(inOutModel, inOutValues, kAdditionalComboBoxId); -} - -void showAdditionalCheckBox(Json *inOutModel, std::map *inOutValues) -{ - showAdditionalSetting(inOutModel, inOutValues, kActiveCheckBoxId, kAdditionalCheckBoxSetting, - kAdditionalCheckBoxValue); -} - -void hideAdditionalCheckBox(Json *inOutModel, std::map *inOutValues) -{ - hideAdditionalSetting(inOutModel, inOutValues, kAdditionalCheckBoxId); -} - -void showAdditionalRadioButton(Json *inOutModel, std::map *inOutValues) -{ - showAdditionalSettingOption(inOutModel, inOutValues, kActiveRadioButtonGroupId, kAdditionalRadioButton); -} - -void hideAdditionalRadioButton(Json *inOutModel, std::map *inOutValues) -{ - hideAdditionalSettingOption(inOutModel, inOutValues, kActiveRadioButtonGroupId, kHideAdditionalRadioButtonValue, - kDefaultActiveRadioButtonGroupValue); -} - -void updateMinMaxSpinBoxes(nx::kit::Json *inOutModel, std::map *inOutValues) -{ - Json::array items = inOutModel->array_items(); - auto minIt = findSetting(kActiveMinValueId, &items); - auto maxIt = findSetting(kActiveMaxValueId, &items); - - if (minIt == items.end() || maxIt == items.end()) - return; - - const std::string minValueStr = (*inOutValues)[kActiveMinValueId]; - const std::string maxValueStr = (*inOutValues)[kActiveMaxValueId]; - - if (minValueStr.empty() || maxValueStr.empty()) - return; - - const int minValue = std::stoi(minValueStr); - const int maxValue = std::stoi(maxValueStr); - - auto setMinMax = [](Json::array::iterator spinBoxIt, int min, int max) { - Json::object spinBox = spinBoxIt->object_items(); - spinBox[kMinValue] = min; - spinBox[kMaxValue] = max; - *spinBoxIt = Json(spinBox); - }; - - setMinMax(minIt, (*minIt)[kMinValue].int_value(), maxValue); - setMinMax(maxIt, minValue, (*maxIt)[kMaxValue].int_value()); - - *inOutModel = Json(items); -} - -} // namespace settings diff --git a/src/plugin/settings/active_settings_rules.h b/src/plugin/settings/active_settings_rules.h deleted file mode 100644 index b51a9ef..0000000 --- a/src/plugin/settings/active_settings_rules.h +++ /dev/null @@ -1,35 +0,0 @@ -// Copyright © 2024 Seagate Technology LLC and/or its Affiliates -// Copyright 2018-present Network Optix, Inc. Licensed under MPL 2.0: www.mozilla.org/MPL/2.0/ - -#pragma once - -#include "active_settings_builder.h" - -#include -#include - -namespace settings -{ - -extern const std::map - kActiveSettingsRules; - -extern const std::map< - /*activeSettingName*/ std::string, ActiveSettingsBuilder::ActiveSettingHandler> - kDefaultActiveSettingsRules; - -void showAdditionalComboBox(nx::kit::Json *inOutModel, std::map *inOutValues); - -void hideAdditionalComboBox(nx::kit::Json *inOutModel, std::map *inOutValues); - -void showAdditionalCheckBox(nx::kit::Json *inOutModel, std::map *inOutValues); - -void hideAdditionalCheckBox(nx::kit::Json *inOutModel, std::map *inOutValues); - -void showAdditionalRadioButton(nx::kit::Json *inOutModel, std::map *inOutValues); - -void hideAdditionalRadioButton(nx::kit::Json *inOutModel, std::map *inOutValues); - -void updateMinMaxSpinBoxes(nx::kit::Json *inOutModel, std::map *inOutValues); - -} // namespace settings diff --git a/src/plugin/settings/cloudfuse_helper.cpp b/src/plugin/settings/cloudfuse_helper.cpp deleted file mode 100644 index f68b677..0000000 --- a/src/plugin/settings/cloudfuse_helper.cpp +++ /dev/null @@ -1,20 +0,0 @@ -#include "cloudfuse_helper.h" - -// parseCloudfuseError takes in an error and trims the error down to it's most essential -// error, which from cloudfuse is the error returned between braces [] -std::string parseCloudfuseError(std::string error) -{ - std::size_t start = error.find_last_of('['); - if (start == std::string::npos) - { - return error; - } - - std::size_t end = error.find_last_of(']'); - if (end == std::string::npos) - { - return error; - } - - return error.substr(start, end); -} diff --git a/src/plugin/settings/cloudfuse_helper.h b/src/plugin/settings/cloudfuse_helper.h deleted file mode 100644 index 78cf565..0000000 --- a/src/plugin/settings/cloudfuse_helper.h +++ /dev/null @@ -1,5 +0,0 @@ -#include - -// parseCloudfuseError takes in an error and trims the error down to it's most essential -// error, which from cloudfuse is the error returned between braces [] -std::string parseCloudfuseError(std::string error); diff --git a/src/plugin/settings/device_agent.cpp b/src/plugin/settings/device_agent.cpp index 8f50e5d..2902fc3 100644 --- a/src/plugin/settings/device_agent.cpp +++ b/src/plugin/settings/device_agent.cpp @@ -10,10 +10,7 @@ #include #include #include -#include -#include "actions.h" -#include "active_settings_rules.h" #include "settings_model.h" #include "stub_analytics_plugin_settings_ini.h" @@ -27,19 +24,6 @@ using namespace nx::sdk::analytics; DeviceAgent::DeviceAgent(Engine *engine, const nx::sdk::IDeviceInfo *deviceInfo) : ConsumingDeviceAgent(deviceInfo, NX_DEBUG_ENABLE_OUTPUT, engine->plugin()->instanceId()), m_engine(engine) { - for (const auto &entry : kActiveSettingsRules) - { - const ActiveSettingsBuilder::ActiveSettingKey key = entry.first; - m_activeSettingsBuilder.addRule(key.activeSettingName, key.activeSettingValue, - /*activeSettingHandler*/ entry.second); - } - - for (const auto &entry : kDefaultActiveSettingsRules) - { - m_activeSettingsBuilder.addDefaultRule( - /*activeSettingName*/ entry.first, - /*activeSettingHandler*/ entry.second); - } } DeviceAgent::~DeviceAgent() @@ -57,147 +41,17 @@ std::string DeviceAgent::manifestString() const Result DeviceAgent::settingsReceived() { - const auto settingsResponse = new SettingsResponse(); - - const std::string settingsModelType = settingValue(kSettingsModelSettings); - - std::string settingsModel; - if (settingsModelType == kAlternativeSettingsModelOption) - { - settingsModel = kAlternativeSettingsModel; - } - else if (settingsModelType == kRegularSettingsModelOption) - { - const std::string languagePart = (settingValue(kCitySelector) == kGermanOption) - ? kGermanCitiesSettingsModelPart - : kEnglishCitiesSettingsModelPart; - - settingsModel = kRegularSettingsModelPart1 + languagePart + kRegularSettingsModelPart2; - } - - std::string parsingError; - Json parsedSettingsModel = Json::parse(settingsModel, parsingError); - std::map settingsValues = currentSettings(); - processActiveSettings(&parsedSettingsModel, &settingsValues); - - settingsResponse->setModel(parsedSettingsModel.dump()); - settingsResponse->setValues(makePtr(settingsValues)); - return settingsResponse; -} - -void DeviceAgent::dumpStringMap(const char *prefix, const char *appendix, const IStringMap *stringMap) const -{ - if (!stringMap) - { - NX_PRINT << prefix << " null" << appendix; - return; - } - - NX_PRINT << prefix << "{"; - for (int i = 0; i < stringMap->count(); ++i) - { - NX_PRINT << prefix << " " << nx::kit::utils::toString(stringMap->key(i)) << ": " - << nx::kit::utils::toString(stringMap->value(i)) << ((i == stringMap->count() - 1) ? "" : ","); - } - NX_PRINT << prefix << "}" << appendix; -} - -void DeviceAgent::dumpActiveSettingChangedAction(const IActiveSettingChangedAction *activeSettingChangedAction) const -{ - NX_PRINT << "IActiveSettingChangedAction:"; - NX_PRINT << "{"; - NX_PRINT << " \"activeSettingName\": " - << nx::kit::utils::toString(activeSettingChangedAction->activeSettingName()) << ","; - NX_PRINT << " \"settingsModel\": " << nx::kit::utils::toString(activeSettingChangedAction->settingsModel()) - << ","; - NX_PRINT << " \"settingsValues\":"; - dumpStringMap(/*prefix*/ " ", /*appendix*/ ",", activeSettingChangedAction->settingsValues().get()); - NX_PRINT << " \"params\":"; - dumpStringMap(/*prefix*/ " ", /*appendix*/ "", activeSettingChangedAction->params().get()); - NX_PRINT << "}"; + return Error(ErrorCode::noError, nullptr); } void DeviceAgent::doGetSettingsOnActiveSettingChange(Result *outResult, const IActiveSettingChangedAction *activeSettingChangedAction) { - if (NX_DEBUG_ENABLE_OUTPUT) - dumpActiveSettingChangedAction(activeSettingChangedAction); - - using namespace nx::kit; - - std::string parseError; - Json::object model = Json::parse(activeSettingChangedAction->settingsModel(), parseError).object_items(); - Json::array sections = model[kSections].array_items(); - - auto activeSettingsSectionIt = std::find_if(sections.begin(), sections.end(), [](Json §ion) { - return section[kCaption].string_value() == kActiveSettingsSectionCaption; - }); - - if (activeSettingsSectionIt == sections.cend()) - { - *outResult = error(ErrorCode::internalError, "Unable to find the active settings section"); - return; - } - - const std::string settingId(activeSettingChangedAction->activeSettingName()); - Json activeSettingsItems = (*activeSettingsSectionIt)[kItems]; - std::map values = toStdMap(shareToPtr(activeSettingChangedAction->settingsValues())); - - m_activeSettingsBuilder.updateSettings(settingId, &activeSettingsItems, &values); - - Json::array updatedActiveSettingsItems = activeSettingsItems.array_items(); - Json::object updatedActiveSection = activeSettingsSectionIt->object_items(); - updatedActiveSection[kItems] = updatedActiveSettingsItems; - *activeSettingsSectionIt = updatedActiveSection; - model[kSections] = sections; - - const auto settingsResponse = makePtr(); - settingsResponse->setValues(makePtr(values)); - settingsResponse->setModel(makePtr(Json(model).dump())); - - const nx::sdk::Ptr actionResponse = - generateActionResponse(settingId, activeSettingChangedAction->params()); - - auto response = makePtr(); - response->setSettingsResponse(settingsResponse); - response->setActionResponse(actionResponse); - - *outResult = response.releasePtr(); } void DeviceAgent::processActiveSettings(nx::kit::Json *inOutSettingsModel, std::map *inOutSettingsValues) { - Json::array sections = (*inOutSettingsModel)[kSections].array_items(); - auto activeSettingsSectionIt = std::find_if(sections.begin(), sections.end(), [](Json §ion) { - return section[kCaption].string_value() == kActiveSettingsSectionCaption; - }); - - if (activeSettingsSectionIt == sections.cend()) - return; - - Json activeSettingsItems = (*activeSettingsSectionIt)[kItems]; - std::vector activeSettingNames; - for (const Json &item : activeSettingsItems.array_items()) - { - if (item[kIsActive].bool_value()) - activeSettingNames.push_back(item[kName].string_value()); - } - - for (const std::string &activeSettingName : activeSettingNames) - { - m_activeSettingsBuilder.updateSettings(activeSettingName, &activeSettingsItems, inOutSettingsValues); - } - - Json::array updatedActiveSettingsItems = activeSettingsItems.array_items(); - Json::object updatedActiveSection = activeSettingsSectionIt->object_items(); - updatedActiveSection[kItems] = updatedActiveSettingsItems; - *activeSettingsSectionIt = updatedActiveSection; - - Json::object updatedModel = inOutSettingsModel->object_items(); - updatedModel[kSections] = sections; - - *inOutSettingsModel = Json(updatedModel); } void DeviceAgent::doSetNeededMetadataTypes(Result * /*outResult*/, const IMetadataTypes * /*neededMetadataTypes*/) @@ -206,11 +60,6 @@ void DeviceAgent::doSetNeededMetadataTypes(Result * /*outResult*/, const I void DeviceAgent::getPluginSideSettings(Result *outResult) const { - const auto response = new SettingsResponse(); - - response->setValue("pluginSideTestSpinBox", "100"); - - *outResult = response; } } // namespace settings diff --git a/src/plugin/settings/device_agent.h b/src/plugin/settings/device_agent.h index 27dadf8..aa304b7 100644 --- a/src/plugin/settings/device_agent.h +++ b/src/plugin/settings/device_agent.h @@ -7,7 +7,6 @@ #include -#include "active_settings_builder.h" #include "engine.h" #include "stub_analytics_plugin_settings_ini.h" @@ -34,17 +33,11 @@ class DeviceAgent : public nx::sdk::analytics::ConsumingDeviceAgent nx::sdk::Result *outResult, const nx::sdk::IActiveSettingChangedAction *activeSettingChangedAction) override; - private: - void dumpStringMap(const char *prefix, const char *appendix, const nx::sdk::IStringMap *stringMap) const; - - void dumpActiveSettingChangedAction(const nx::sdk::IActiveSettingChangedAction *activeSettingChangedAction) const; - private: void processActiveSettings(nx::kit::Json *inOutSettingModel, std::map *inOutSettingValue); private: Engine *const m_engine; - ActiveSettingsBuilder m_activeSettingsBuilder; }; } // namespace settings diff --git a/src/plugin/settings/engine.cpp b/src/plugin/settings/engine.cpp index c1ead54..24beccc 100644 --- a/src/plugin/settings/engine.cpp +++ b/src/plugin/settings/engine.cpp @@ -14,21 +14,16 @@ #include #include -#include "actions.h" -#include "active_settings_rules.h" #include "device_agent.h" #include "settings_model.h" #include "stub_analytics_plugin_settings_ini.h" -#include "cloudfuse_helper.h" - // TODO: get NX_PRINT_PREFIX working with non-member helper functions // #define NX_PRINT_PREFIX (this->logUtils.printPrefix) #include #include #include #include -#include #ifdef _WIN32 #include @@ -43,30 +38,17 @@ using namespace nx::sdk; using namespace nx::sdk::analytics; using namespace nx::kit; -static int maxWaitSecondsAfterMount = 10; +static std::string buildCapabilities(); +static std::string generatePassphrase(); +static void enableLogging(std::string iniDir); +static std::string parseCloudfuseError(std::string error); -void enableLogging(std::string iniDir); +static int maxWaitSecondsAfterMount = 10; Engine::Engine(Plugin *plugin) : nx::sdk::analytics::Engine(NX_DEBUG_ENABLE_OUTPUT, plugin->instanceId()), m_plugin(plugin), m_cfManager() { - // logging will begin the _next_ time the mediaserver starts - enableLogging(IniConfig::iniFilesDir()); NX_PRINT << "cloudfuse Engine::Engine"; - - for (const auto &entry : kActiveSettingsRules) - { - const ActiveSettingsBuilder::ActiveSettingKey key = entry.first; - m_activeSettingsBuilder.addRule(key.activeSettingName, key.activeSettingValue, - /*activeSettingHandler*/ entry.second); - } - - for (const auto &entry : kDefaultActiveSettingsRules) - { - m_activeSettingsBuilder.addDefaultRule( - /*activeSettingName*/ entry.first, - /*activeSettingHandler*/ entry.second); - } } Engine::~Engine() @@ -77,29 +59,8 @@ Engine::~Engine() { NX_PRINT << "cloudfuse Engine::~Engine failed to unmount cloudfuse with error: " + unmountRet.output; } -} - -void Engine::doObtainDeviceAgent(Result *outResult, const IDeviceInfo *deviceInfo) -{ - NX_PRINT << "cloudfuse Engine::doObtainDeviceAgent"; - *outResult = new DeviceAgent(this, deviceInfo); -} - -// functions are not "hoisted", so we need "prototypes" -std::string generatePassphrase(); - -static std::string buildCapabilities() -{ - std::string capabilities; - - if (ini().deviceDependent) - capabilities += "|deviceDependent"; - - // Delete first '|', if any. - if (!capabilities.empty() && capabilities.at(0) == '|') - capabilities.erase(0, 1); - - return capabilities; + // enable logging for the _next_ time the mediaserver starts + enableLogging(IniConfig::iniFilesDir()); } std::string Engine::manifestString() const @@ -118,115 +79,6 @@ std::string Engine::manifestString() const return result; } -void enableLogging(std::string iniDir) -{ - // enable logging by touching stdout and stderr redirect files - if (!fs::is_directory(iniDir)) - { - fs::create_directories(iniDir); - } - const std::string processName = utils::getProcessName(); - const std::string stdoutFilename = iniDir + processName + "_stdout.log"; - const std::string stderrFilename = iniDir + processName + "_stderr.log"; - if (!fs::exists(stdoutFilename) || !fs::exists(stderrFilename)) - { - NX_PRINT << "cloudfuse Engine::enableLogging - creating files"; - std::ofstream stdoutFile(stdoutFilename); - std::ofstream stderrFile(stderrFilename); - // the service will need to be restarted for logging to actually begin - } - NX_PRINT << "cloudfuse Engine::enableLogging - plugin stderr logging file: " + stderrFilename; -} - -bool Engine::updateModel(Json::object *model, bool mountSuccessful) const -{ - NX_PRINT << "cloudfuse Engine::updateModel"; - - // prepare the new status item - auto statusJson = mountSuccessful ? kStatusSuccess : kStatusFailure; - std::string error; - auto newStatus = Json::parse(statusJson, error); - if (error != "") - { - NX_PRINT << "Failed to parse status JSON with error: " << error; - return false; - } - - // find where to put it - auto items = (*model)[kItems]; - auto itemsArray = items.array_items(); - // find the status banner, if it's already present - auto statusBannerIt = std::find_if(itemsArray.begin(), itemsArray.end(), - [](Json &item) { return item[kName].string_value() == kStatusBannerId; }); - // if the banner is not there, add it - if (statusBannerIt == itemsArray.end()) - { - // add the status banner to the beginning of the list of items - itemsArray.insert(itemsArray.begin(), newStatus); - } - else - { - // update the status - *statusBannerIt = newStatus; - } - - // write the updated array back into the model Json - // TODO: why do we have to do this? - (*model)[kItems] = itemsArray; - - return true; -} - -bool Engine::settingsChanged() -{ - // If cloudfuse is not mounted and settings are the same, then return true so - // it tries to mount again. - if (!m_cfManager.isMounted()) - { - return true; - } - - std::map newValues = currentSettings(); - if (newValues == m_prevSettings) - { - return false; - } - // we only really care about certain values - // key ID - if (m_prevSettings[kKeyIdTextFieldId] != newValues[kKeyIdTextFieldId]) - { - return true; - } - // secret key - if (m_prevSettings[kSecretKeyPasswordFieldId] != newValues[kSecretKeyPasswordFieldId]) - { - return true; - } - if (!credentialsOnly) - { - // endpoint - if (m_prevSettings[kEndpointUrlTextFieldId] != newValues[kEndpointUrlTextFieldId]) - { - // if they're different, but both amount to the same thing, then there is no effective change - bool prevIsDefault = m_prevSettings[kEndpointUrlTextFieldId] == kDefaultEndpoint || - m_prevSettings[kEndpointUrlTextFieldId] == ""; - bool newIsDefault = - newValues[kEndpointUrlTextFieldId] == kDefaultEndpoint || newValues[kEndpointUrlTextFieldId] == ""; - if (!prevIsDefault || !newIsDefault) - { - return true; - } - } - // bucket name - if (m_prevSettings[kBucketNameTextFieldId] != newValues[kBucketNameTextFieldId]) - { - return true; - } - } - // nothing we care about changed - return false; -} - Result Engine::settingsReceived() { NX_PRINT << "cloudfuse Engine::settingsReceived"; @@ -319,27 +171,82 @@ bool Engine::mount() return true; } -std::string generatePassphrase() +void Engine::doObtainDeviceAgent(Result *outResult, const IDeviceInfo *deviceInfo) { - // Generate passphrase for config file - unsigned char key[32]; // AES-256 key - if (!RAND_bytes(key, sizeof(key))) + NX_PRINT << "cloudfuse Engine::doObtainDeviceAgent"; + *outResult = new DeviceAgent(this, deviceInfo); +} + +void Engine::getPluginSideSettings(Result *outResult) const +{ + NX_PRINT << "cloudfuse Engine::getPluginSideSettings"; + auto settingsResponse = new SettingsResponse(); + *outResult = settingsResponse; +} + +void Engine::doGetSettingsOnActiveSettingChange(Result *outResult, + const IActiveSettingChangedAction *activeSettingChangedAction) +{ + NX_PRINT << "cloudfuse Engine::doGetSettingsOnActiveSettingChange"; +} + +bool Engine::settingsChanged() +{ + // have the settings changed? + std::map newValues = currentSettings(); + if (newValues == m_prevSettings) { - return ""; + return false; } - // Need to encode passphrase to base64 to pass to cloudfuse - BIO *bmem, *b64; - BUF_MEM *bptr; - b64 = BIO_new(BIO_f_base64()); - bmem = BIO_new(BIO_s_mem()); - b64 = BIO_push(b64, bmem); - BIO_set_flags(b64, BIO_FLAGS_BASE64_NO_NL); - BIO_write(b64, key, 32); - BIO_flush(b64); - BIO_get_mem_ptr(b64, &bptr); + // check if settings are empty + if (newValues[kKeyIdTextFieldId] == "" && newValues[kSecretKeyPasswordFieldId] == "") + { + NX_PRINT << "Settings are empty. Ignoring..."; + return false; + } - return std::string(bptr->data, bptr->length); + // If cloudfuse is not mounted and settings are the same, then return true so + // it tries to mount again. + if (!m_cfManager.isMounted()) + { + return true; + } + + // we only really care about certain values + // key ID + if (m_prevSettings[kKeyIdTextFieldId] != newValues[kKeyIdTextFieldId]) + { + return true; + } + // secret key + if (m_prevSettings[kSecretKeyPasswordFieldId] != newValues[kSecretKeyPasswordFieldId]) + { + return true; + } + if (!credentialsOnly) + { + // endpoint + if (m_prevSettings[kEndpointUrlTextFieldId] != newValues[kEndpointUrlTextFieldId]) + { + // if they're different, but both amount to the same thing, then there is no effective change + bool prevIsDefault = m_prevSettings[kEndpointUrlTextFieldId] == kDefaultEndpoint || + m_prevSettings[kEndpointUrlTextFieldId] == ""; + bool newIsDefault = + newValues[kEndpointUrlTextFieldId] == kDefaultEndpoint || newValues[kEndpointUrlTextFieldId] == ""; + if (!prevIsDefault || !newIsDefault) + { + return true; + } + } + // bucket name + if (m_prevSettings[kBucketNameTextFieldId] != newValues[kBucketNameTextFieldId]) + { + return true; + } + } + // nothing we care about changed + return false; } nx::sdk::Error Engine::validateMount() @@ -509,47 +416,121 @@ nx::sdk::Error Engine::spawnMount() return Error(ErrorCode::noError, nullptr); } -void Engine::getPluginSideSettings(Result *outResult) const +bool Engine::updateModel(Json::object *model, bool mountSuccessful) const { - NX_PRINT << "cloudfuse Engine::getPluginSideSettings"; - auto settingsResponse = new SettingsResponse(); - settingsResponse->setValue(kEnginePluginSideSetting, kEnginePluginSideSettingValue); + NX_PRINT << "cloudfuse Engine::updateModel"; - *outResult = settingsResponse; + // prepare the new status item + auto statusJson = mountSuccessful ? kStatusSuccess : kStatusFailure; + std::string error; + auto newStatus = Json::parse(statusJson, error); + if (error != "") + { + NX_PRINT << "Failed to parse status JSON with error: " << error; + return false; + } + + // find where to put it + auto items = (*model)[kItems]; + auto itemsArray = items.array_items(); + // find the status banner, if it's already present + auto statusBannerIt = std::find_if(itemsArray.begin(), itemsArray.end(), + [](Json &item) { return item[kName].string_value() == kStatusBannerId; }); + // if the banner is not there, add it + if (statusBannerIt == itemsArray.end()) + { + // add the status banner to the beginning of the list of items + itemsArray.insert(itemsArray.begin(), newStatus); + } + else + { + // update the status + *statusBannerIt = newStatus; + } + + // write the updated array back into the model Json + // TODO: why do we have to do this? + (*model)[kItems] = itemsArray; + + return true; } -void Engine::doGetSettingsOnActiveSettingChange(Result *outResult, - const IActiveSettingChangedAction *activeSettingChangedAction) +// static helper functions + +void enableLogging(std::string iniDir) { - NX_PRINT << "cloudfuse Engine::doGetSettingsOnActiveSettingChange"; - std::string parseError; - Json model = Json::parse(activeSettingChangedAction->settingsModel(), parseError); - if (parseError != "") + // enable logging by touching stdout and stderr redirect files + if (!fs::is_directory(iniDir)) { - std::string errorMessage = "Failed to parse activeSettingChangedAction model JSON. Here's why: " + parseError; - NX_PRINT << errorMessage; - *outResult = error(ErrorCode::internalError, errorMessage); - return; + fs::create_directories(iniDir); + } + const std::string processName = utils::getProcessName(); + const std::string stdoutFilename = iniDir + processName + "_stdout.log"; + const std::string stderrFilename = iniDir + processName + "_stderr.log"; + if (!fs::exists(stdoutFilename) || !fs::exists(stderrFilename)) + { + NX_PRINT << "cloudfuse Engine::enableLogging - creating files"; + std::ofstream stdoutFile(stdoutFilename); + std::ofstream stderrFile(stderrFilename); + // the service will need to be restarted for logging to actually begin } + NX_PRINT << "cloudfuse Engine::enableLogging - plugin stderr logging file: " + stderrFilename; +} + +std::string buildCapabilities() +{ + std::string capabilities; + + if (ini().deviceDependent) + capabilities += "|deviceDependent"; + + // Delete first '|', if any. + if (!capabilities.empty() && capabilities.at(0) == '|') + capabilities.erase(0, 1); - Json::object modelObject = model.object_items(); + return capabilities; +} - const std::string settingId(activeSettingChangedAction->activeSettingName()); +std::string generatePassphrase() +{ + // Generate passphrase for config file + unsigned char key[32]; // AES-256 key + if (!RAND_bytes(key, sizeof(key))) + { + return ""; + } + // Need to encode passphrase to base64 to pass to cloudfuse + BIO *bmem, *b64; + BUF_MEM *bptr; - std::map values = toStdMap(shareToPtr(activeSettingChangedAction->settingsValues())); + b64 = BIO_new(BIO_f_base64()); + bmem = BIO_new(BIO_s_mem()); + b64 = BIO_push(b64, bmem); + BIO_set_flags(b64, BIO_FLAGS_BASE64_NO_NL); + BIO_write(b64, key, 32); + BIO_flush(b64); + BIO_get_mem_ptr(b64, &bptr); - const auto settingsResponse = makePtr(); - settingsResponse->setValues(makePtr(values)); - settingsResponse->setModel(makePtr(Json(modelObject).dump())); + return std::string(bptr->data, bptr->length); +} - const nx::sdk::Ptr actionResponse = - generateActionResponse(settingId, activeSettingChangedAction->params()); +// parseCloudfuseError takes in an error and trims the error down to it's most essential +// error, which from cloudfuse is the error returned between braces [] +std::string parseCloudfuseError(std::string error) +{ + std::size_t start = error.find_last_of('['); + if (start == std::string::npos) + { + return error; + } - auto response = makePtr(); - response->setSettingsResponse(settingsResponse); - response->setActionResponse(actionResponse); + std::size_t end = error.find_last_of(']'); + if (end == std::string::npos) + { + return error; + } - *outResult = response.releasePtr(); + return error.substr(start, end); } } // namespace settings diff --git a/src/plugin/settings/engine.h b/src/plugin/settings/engine.h index 6d1b1a0..bcd036c 100644 --- a/src/plugin/settings/engine.h +++ b/src/plugin/settings/engine.h @@ -3,8 +3,7 @@ #pragma once -#include "active_settings_builder.h" - +#include #include #include @@ -28,10 +27,7 @@ class Engine : public nx::sdk::analytics::Engine virtual std::string manifestString() const override; virtual nx::sdk::Result settingsReceived() override; - bool settingsChanged(); bool mount(); - nx::sdk::Error validateMount(); - nx::sdk::Error spawnMount(); protected: virtual void doObtainDeviceAgent(nx::sdk::Result *outResult, @@ -44,11 +40,13 @@ class Engine : public nx::sdk::analytics::Engine const nx::sdk::IActiveSettingChangedAction *activeSettingChangedAction) override; private: - bool updateModel(nx::kit::Json::object *model, bool mountSuccessful) const; + bool settingsChanged(); + nx::sdk::Error validateMount(); + nx::sdk::Error spawnMount(); + bool updateModel(nx::kit::detail::json11::Json::object *model, bool mountSuccessful) const; private: nx::sdk::analytics::Plugin *const m_plugin; - ActiveSettingsBuilder m_activeSettingsBuilder; CloudfuseMngr m_cfManager; std::map m_prevSettings; std::string m_passphrase; diff --git a/src/plugin/settings/settings_model.h b/src/plugin/settings/settings_model.h index 32083de..7366b4e 100644 --- a/src/plugin/settings/settings_model.h +++ b/src/plugin/settings/settings_model.h @@ -8,48 +8,8 @@ namespace settings { -static const std::string kCaption = "caption"; -static const std::string kSections = "sections"; static const std::string kName = "name"; -static const std::string kRange = "range"; static const std::string kItems = "items"; -static const std::string kIsActive = "isActive"; -static const std::string kMinValue = "minValue"; -static const std::string kMaxValue = "maxValue"; - -// ------------------------------------------------------------------------------------------------ -// TODO: rip out these old stub settings model variables -static const std::string kRegularSettingsModelOption = "regular"; -static const std::string kAlternativeSettingsModelOption = "alternative"; -static const std::string kSettingsModelSettings = "settingsModelComboBox"; -static const std::string kCitySelector = "languageSelectorSettings"; -static const std::string kEnglishOption = "English"; -static const std::string kGermanOption = "German"; -static const std::string kActiveSettingsSectionCaption = "Active settings section"; -static const std::string kAdvancedSettingsGroupBoxCaption = "Advanced Settings"; -static const std::string kActiveComboBoxId = "activeComboBox"; -static const std::string kAdditionalComboBoxId = "additionalComboBox"; -static const std::string kShowAdditionalComboBoxValue = "Show additional ComboBox"; -static const std::string kAdditionalComboBoxValue = "Value 1"; -static const std::string kActiveCheckBoxId = "activeCheckBox"; -static const std::string kAdditionalCheckBoxId = "additionalCheckBox"; -static const std::string kShowAdditionalCheckBoxValue = "true"; -static const std::string kAdditionalCheckBoxValue = "false"; -static const std::string kActiveRadioButtonGroupId = "activeRadioButtonGroup"; -static const std::string kShowAdditionalRadioButtonValue = "Show something"; -static const std::string kHideAdditionalRadioButtonValue = "Hide me"; -static const std::string kDefaultActiveRadioButtonGroupValue = "Some value"; -static const std::string kActiveMinValueId = "activeMinValue"; -static const std::string kActiveMaxValueId = "activeMaxValue"; -static const std::string kShowUrlButtonId = "showUrlButton"; -static const std::string kEnginePluginSideSetting = "testPluginSideSpinBox"; -static const std::string kEnginePluginSideSettingValue = "42"; -static const std::string kAlternativeSettingsModel = /*suppress newline*/ 1 + (const char *)R"json(")json"; -static const std::string kRegularSettingsModelPart1 = /*suppress newline*/ 1 + R"json()json"; -static const std::string kEnglishCitiesSettingsModelPart = /*suppress newline*/ 1 + R"json()json"; -static const std::string kGermanCitiesSettingsModelPart = /*suppress newline*/ 1 + R"json()json"; -static const std::string kRegularSettingsModelPart2 = /*suppress newline*/ 1 + R"json(")json"; -// ------------------------------------------------------------------------------------------------ // Enable this flag hide all but the credentials section // NOTE: enabling this will prevent the user from changing the default endpoint (kDefaultEndpoint) @@ -96,8 +56,7 @@ static const std::string kBucketNameTextFieldId = "bucketName"; static const std::string kAdvancedGroupBox = R"json( { "type": "GroupBox", - "caption": ")json" + kAdvancedSettingsGroupBoxCaption + - R"json(", + "caption": "Advanced Settings", "items": [ { diff --git a/src/plugin/utils.cpp b/src/plugin/utils.cpp deleted file mode 100644 index 10b8cd1..0000000 --- a/src/plugin/utils.cpp +++ /dev/null @@ -1,89 +0,0 @@ -// Copyright © 2024 Seagate Technology LLC and/or its Affiliates -// Copyright 2018-present Network Optix, Inc. Licensed under MPL 2.0: www.mozilla.org/MPL/2.0/ - -#include "utils.h" - -#include -#include -#include - -using namespace nx::sdk; - -bool toBool(std::string str) -{ - std::transform(str.begin(), str.begin(), str.end(), ::tolower); - return str == "true" || str == "1"; -} - -bool startsWith(const std::string &str, const std::string &prefix) -{ - return str.rfind(prefix, 0) == 0; -} - -std::vector loadFile(const std::string &path) -{ - std::ifstream file(path, std::ios::binary); - if (!file.is_open()) - return {}; - - return std::vector(std::istreambuf_iterator(file), {}); -} - -std::string imageFormatFromPath(const std::string &path) -{ - auto endsWith = [](const std::string &str, const std::string &suffix) { - if (suffix.size() > str.size()) - return false; - - return std::equal(suffix.rbegin(), suffix.rend(), str.rbegin()); - }; - - if (endsWith(path, ".jpg") || endsWith(path, ".jpeg")) - return "image/jpeg"; - - if (endsWith(path, ".png")) - return "image/png"; - - if (endsWith(path, ".tiff")) - return "image/tiff"; - - return ""; -} - -bool isHttpOrHttpsUrl(const std::string &path) -{ - auto startsWith = [](const std::string &str, const std::string &prefix) { - if (prefix.size() > str.size()) - return false; - - return std::equal(prefix.begin(), prefix.end(), str.begin()); - }; - - return startsWith(path, "http://") || startsWith(path, "https://"); -} - -std::string join(const std::vector &strings, const std::string &delimiter, const std::string &itemPrefix, - const std::string &itemPostfix) -{ - std::string result; - for (size_t i = 0; i < strings.size(); ++i) - { - result += itemPrefix + strings[i] + itemPostfix; - if (i != strings.size() - 1) - result += delimiter; - } - - return result; -} - -std::map toStdMap(const Ptr &sdkMap) -{ - std::map result; - if (!sdkMap) - return result; - - for (int i = 0; i < sdkMap->count(); ++i) - result[sdkMap->key(i)] = sdkMap->value(i); - - return result; -} diff --git a/src/plugin/utils.h b/src/plugin/utils.h deleted file mode 100644 index f98a6bb..0000000 --- a/src/plugin/utils.h +++ /dev/null @@ -1,119 +0,0 @@ -// Copyright © 2024 Seagate Technology LLC and/or its Affiliates -// Copyright 2018-present Network Optix, Inc. Licensed under MPL 2.0: www.mozilla.org/MPL/2.0/ - -#pragma once - -#include -#include -#include - -#include -#include - -bool toBool(std::string str); - -bool startsWith(const std::string &str, const std::string &prefix); - -template T clamp(const T &value, const T &lowerBound, const T &upperBound) -{ - if (value < lowerBound) - return lowerBound; - - if (value > upperBound) - return upperBound; - - return value; -} - -std::vector loadFile(const std::string &path); - -std::string imageFormatFromPath(const std::string &path); - -bool isHttpOrHttpsUrl(const std::string &path); - -std::string join(const std::vector &strings, const std::string &delimiter, - const std::string &itemPrefix = std::string(), const std::string &itemPostfix = std::string()); - -std::map toStdMap(const nx::sdk::Ptr &sdkMap); - -template class SimpleOptional -{ - - public: - SimpleOptional() = default; - - SimpleOptional(const T &value) : m_value(value), m_isInitialized(true) - { - } - - template - SimpleOptional(const SimpleOptional &other) : m_value(other.value()), m_isInitialized(other.isInitialized()) - { - } - - const T *operator->() const - { - if (!m_isInitialized) - return nullptr; - - return &m_value; - } - - T *operator->() - { - if (!m_isInitialized) - return nullptr; - - return &m_value; - } - - const T &operator*() const - { - return m_value; - } - - T &operator*() - { - return m_value; - } - - template SimpleOptional &operator=(const SimpleOptional &other) - { - m_value = other.value(); - m_isInitialized = other.isInitialized(); - - return *this; - } - - template SimpleOptional &operator=(U &&value) - { - m_value = std::forward(value); - m_isInitialized = true; - - return *this; - } - - explicit operator bool() const - { - return m_isInitialized; - } - - const T &value() const - { - return m_value; - } - - bool isInitialized() const - { - return m_isInitialized; - } - - void reset() - { - m_isInitialized = false; - } - - private: - T m_value{}; - bool m_isInitialized = false; -};