Commit 07377e0a authored by jan.koester's avatar jan.koester
Browse files

test

parent 21c9c58c
Loading
Loading
Loading
Loading
+580 −131

File changed.

Preview size limit exceeded, changes collapsed.

+41 −15
Changes for plugins/gameinfo/gameinfo.cpp: 41 added lines, 15 removed lines.
Original line number Diff line number Diff line
@@ -112,22 +112,48 @@ namespace blogi {
                    rlock.lock();
                    i->refresh(hldsdata);
                    rlock.unlock();
                    condat << "<div class=\"gameserver\" ><table>";
                    condat << "<tr><td>Gameport: </td><td> " << hldsdata.Port << "</td></tr>";
                    condat << "<tr><td>Gamename: </td><td> " << hldsdata.GameName << "</td></tr>";
                    condat << "<tr><td>Servername: </td><td>" << hldsdata.ServerName << "</td></tr>";
                    condat << "<tr><td>Modname: </td><td>" << hldsdata.ModName << "</td></tr>";
                    condat << "<tr><td>Mapname: </td><td>" << hldsdata.MapName << "</td></tr>";
                    condat << "<tr><td>pwprotected: </td><td>";
                    if(hldsdata.pwProtected)
                        condat << "yes";
                    else
                        condat << "no";
                    condat << "</td></tr>";
                    condat << "<tr><td>Players: </td><td>" << hldsdata.Players  << "("
                    << hldsdata.BotsAmount << ")" << "/"
                    condat << "<div class=\"gamestatus-card\">";
                    condat << "<h2 class=\"server-name\">" << hldsdata.ServerName << "</h2>";
                    const char* statusClass = (hldsdata.MaxPlayers > 0) ? "online" : "offline";
                    condat << "<div class=\"status-indicator " << statusClass << "\">"
                           << ((hldsdata.MaxPlayers > 0) ? "ONLINE" : "OFFLINE") << "</div>";
                    // Start the details grid container
                    condat << "<div class=\"details-grid\">";
                    // Row 1: Gameport
                    condat << "<div class=\"detail-item\">"
                           << "<span class=\"label\">Gameport:</span>"
                           << "<span class=\"value\">" << hldsdata.Port << "</span>"
                           << "</div>";
                    // Row 2: Gamename
                    condat << "<div class=\"detail-item\">"
                           << "<span class=\"label\">Gamename:</span>"
                           << "<span class=\"value\">" << hldsdata.GameName << "</span>"
                           << "</div>";
                    // Row 3: Modname
                    condat << "<div class=\"detail-item\">"
                           << "<span class=\"label\">Modname:</span>"
                           << "<span class=\"value\">" << hldsdata.ModName << "</span>"
                           << "</div>";
                    // Row 4: Mapname
                    condat << "<div class=\"detail-item\">"
                           << "<span class=\"label\">Mapname:</span>"
                           << "<span class=\"value\">" << hldsdata.MapName << "</span>"
                           << "</div>";
                    // Row 5: Password Protected
                    condat << "<div class=\"detail-item\">"
                           << "<span class=\"label\">Password:</span>"
                           << "<span class=\"value\">" << (hldsdata.pwProtected ? "Yes" : "No") << "</span>"
                           << "</div>";
                    // Row 6: Players
                    condat << "<div class=\"detail-item\">"
                           << "<span class=\"label\">Players:</span>"
                           << "<span class=\"value player-count\">"
                           << hldsdata.Players << " (" << hldsdata.BotsAmount << ") / "
                           << hldsdata.MaxPlayers
                    << "</td></tr></table></div>";
                           << "</span>"
                           << "</div>";
                    // Close details grid and card
                    condat << "</div></div>";
                }catch(gameinfo::GameInfoException &e){
                    std::cerr << e.what();
                    rlock.unlock();
+7 −5
Changes for src/blogi.cpp: 7 added lines, 5 removed lines.
Original line number Diff line number Diff line
@@ -74,7 +74,7 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
std::unique_ptr<blogi::Config> blogi::Blogi::Cfg;

namespace blogi {
    webedit::WebEditor testedit;
    std::unique_ptr<webedit::WebEditor> testedit;
};

blogi::Blogi::Blogi(netplus::socket &serversocket,bool debug) : HttpEvent(serversocket){
@@ -84,6 +84,8 @@ blogi::Blogi::Blogi(netplus::socket &serversocket,bool debug) : HttpEvent(server

	std::cerr << "Initializing Blogi with DB Driver: " << Blogi::Cfg->getdbdriver() << " on " << Blogi::Cfg->getdbopts() << std::endl;

    testedit=std::make_unique<webedit::WebEditor>(*PlgArgs);

    try{
        for (int i = 0; i < threads; i++) {
            PlgArgs->database.emplace_back(
@@ -278,7 +280,7 @@ void blogi::Blogi::api(libhttppp::HttpRequest& curreq, const int tid){
                    json_object_object_add(respid, "login_failure", jfail);
                }
            }
            else if (strcmp(key, "auth") == 0) {
            else if (strcmp(key, "authid") == 0) {
                // --- AUTH CHECK COMMAND (Check for existing authid validity) ---
                json_object* value_obj  = json_object_new_object();
                const char* id = json_object_get_string(val);
@@ -307,7 +309,7 @@ void blogi::Blogi::api(libhttppp::HttpRequest& curreq, const int tid){

    // 4. Process commands in external modules/plugins (Only if authentication succeeded)
    if(asuccess){
        testedit.JsonApi(jrequest,jresponse);
        testedit->JsonApi(jrequest,jresponse);
    }

    // 5. Send JSON Response
@@ -760,7 +762,7 @@ RETRY_REQUEST:
                    err[libhttppp::HTTPException::Error] << "you are not logged in permission denied";
                    throw err;
                }
                testedit.Editor(*PlgArgs,curreq,tid,sessid);
                testedit->Editor(curreq,tid,sessid);
                return;
            }else if(curreq.getRequestURL().compare(0,PlgArgs->config->buildurl("render").length(),PlgArgs->config->buildurl("render"))==0){

@@ -801,7 +803,7 @@ RETRY_REQUEST:
                        curplg->getInstace()->Rendering(tid,curreq,&index,RenderingType::Desktop);
                }

                testedit.Renderer(*PlgArgs,curreq,tid,sessid,index,rootel);
                testedit->Renderer(curreq,tid,sessid,index,rootel);
                return;
            }

+306 −16
Changes for src/edit.cpp: 306 added lines, 16 removed lines.
Original line number Diff line number Diff line
@@ -35,24 +35,73 @@
#include "blogi.h"
#include "theme.h"

void blogi::webedit::WebEditor::Editor(PluginArgs &plgars,libhttppp::HttpRequest& curreq, const int tid, const std::string &sessionid){
    libhtmlpp::HtmlElement edithtml;
blogi::webedit::WebEditor::WebEditor(PluginArgs &plgargs) : Args (plgargs){
    std::vector<std::string> edplgdirs;
    for(size_t i=0; i<Args.config->getplgdirs(); ++i){
        edplgdirs.emplace_back(Args.config->getplgdir(i)+"/webedit");
    }
    Plugins=std::make_unique<EditPluginLoad>(edplgdirs);
}


void blogi::webedit::WebEditor::Editor(libhttppp::HttpRequest& curreq, const int tid, const std::string &sessionid){
    auto string_to_lower =[](std::string s) {
        for (char &c : s) {
            c = std::tolower(static_cast<unsigned char>(c));
        }
        return s;
    };



    // Determine the full base URL for plugin settings, e.g., "https://myblog.com/editor/elsettings"
    const std::string settings_base_url = "editor/elsettings";
    size_t urllen=Args.config->buildurl(settings_base_url).length();

    // Check if the current request URL starts with the settings base URL
    if(curreq.getRequestURL().compare(0,urllen,Args.config->buildurl(settings_base_url))==0){

        // Loop through all loaded plugins to check for a name match in the URL segment
        for(const EditPluginLoad::PluginData *curplg=Plugins->getFirstPlugin(); curplg; curplg=curplg->getNextPlg() ){
            // Get the plugin name (e.g., "Container" or "Div")
            std::string pname=string_to_lower(curplg->getInstace()->getName());
            size_t start_pos = urllen;

            if (curreq.getRequestURL().length() > urllen && curreq.getRequestURL()[urllen] == '/') {
                start_pos++;
            }

            if(curreq.getRequestURL().compare(start_pos, pname.length(), pname) == 0){
                libhttppp::HttpResponse curres;
                // Initialize HtmlElement with a tag, e.g., "div"
                libhtmlpp::HtmlElement edithtml("div");
                libhtmlpp::HtmlString out;

                // Call the plugin's Settings method to generate the UI content
                curplg->getInstace()->Settings(curreq,edithtml);

                // Serialize the generated HTML
                libhtmlpp::print(edithtml,out,false);

                // Send the response and return, bypassing the main editor render
                curres.setState(HTTP200);
                curres.setVersion(HTTPVERSION(1.1));
                curres.setContentType("text/html");
                curres.send(curreq,out.data(),out.length());
                return;
            }
        }
    }
    libhtmlpp::HtmlElement edithtml("div");
    libhtmlpp::HtmlPage editpage;
    libhtmlpp::HtmlString ouput;

    CurRootEl=CurDoc.NewElement("WebEditor");
    CurRootEl->SetAttribute("Version",1.0);
    CurRootEl->SetAttribute("Version", "1.0");
    CurRootEl->SetAttribute("editor","blogi");

    std::vector<std::string> edplgdirs;

    for(size_t i=0; i<plgars.config->getplgdirs(); ++i){
         edplgdirs.emplace_back(plgars.config->getplgdir(i)+"/webedit");
    }

    Plugins=std::make_unique<EditPluginLoad>(edplgdirs);

    plgars.theme->renderPage(tid,"editor.html",editpage,edithtml);
    Args.theme->renderPage(tid,"editor.html",editpage,edithtml);

    libhtmlpp::print(edithtml,ouput,false);

@@ -60,17 +109,253 @@ void blogi::webedit::WebEditor::Editor(PluginArgs &plgars,libhttppp::HttpRequest
    curres.setState(HTTP200);
    curres.setVersion(HTTPVERSION(1.1));
    curres.setContentType("text/html");
    curres.send(curreq,ouput.data(),ouput.size());
    curres.send(curreq,ouput.data(),ouput.length());
}

std::vector<std::string> blogi::webedit::WebEditor::getPluginNames() const{
    std::vector<std::string> names;
    // Assuming PluginData has a way to expose the plugin identifier (e.g., type or name)
    for(const EditPluginLoad::PluginData *curplg = Plugins->getFirstPlugin(); curplg; curplg = curplg->getNextPlg()){
        // Replace with actual method if different (e.g., curplg->getName())
        names.push_back(curplg->getInstace()->getName());
    }
    return names;
}

 json_object *blogi::webedit::WebEditor::serializeDocumentTree(const blogi::webedit::EditPlugin *root) {
    if (!root) {
        return nullptr;
    }
    json_object *el_obj = json_object_new_object();

    json_object_object_add(el_obj, "uuid", json_object_new_string(root->getInstanceId().c_str()));
    json_object_object_add(el_obj, "name", json_object_new_string(root->getName().c_str()));
    json_object_object_add(el_obj, "typeId", json_object_new_string(root->getTypeId().c_str()));

    json_object *children_array = json_object_new_array();

    int child_count = 0;

    const blogi::webedit::EditPlugin *child = root->getChildElement();

    for (; child; child = child->nextElement()) {
        json_object_array_add(children_array, serializeDocumentTree(child));
        child_count++;
    }

    json_object_object_add(el_obj, "children", children_array);
    json_object_object_add(el_obj, "children_count", json_object_new_int(child_count));
    return el_obj;
}

/**
 * @brief Handles API requests, ensuring commands are routed correctly.
 * * Commands are prioritized:
 * 1. Global (e.g., GetPluginTypes, add_plugin_element).
 * 2. Element-specific (e.g., get_element_properties, update_element).
 * 3. Fallback: Check if any loaded plugin explicitly handles the command
 * (usually not ideal, but maintained as a last resort).
 * * @param request JSON object containing the command and data.
 * @param response JSON object to populate with the result.
 */
void blogi::webedit::WebEditor::JsonApi(json_object *request, json_object *response) {
    // --- Initialize Plugins ONCE per API request (Moved for performance) ---
    std::vector<std::string> edplgdirs;
    for(size_t i=0; i<Args.config->getplgdirs(); ++i){
        edplgdirs.emplace_back(Args.config->getplgdir(i)+"/webedit");
    }

    auto jsonCommand = [&] (json_object *single_request, json_object *single_response) {
        json_object *cmd_obj;
        // Check if the overall request is not an array (which is expected)
        if (json_object_get_type(request) != json_type_array) {
            if (json_object_get_type(response) == json_type_array) {
                json_object *error_obj = json_object_new_object();
                json_object_object_add(error_obj, "status", json_object_new_string("error"));
                json_object_object_add(error_obj, "message", json_object_new_string("API request must be a JSON array."));
                json_object_array_add(response, error_obj);
            }
            return;
        }

        if (json_object_object_get_ex(single_request, "login", &cmd_obj)) {
                // Silently ignore auth command, treated as success in the array.
                json_object_object_add(single_response, "auth_success", json_object_new_object());
                json_object_object_add(json_object_object_get(single_response, "auth_success"), "is_valid", json_object_new_boolean(true));
                // NOTE: Real auth should set a unique authid here
                return;
        }

        if (json_object_object_get_ex(single_request, "authid", &cmd_obj)) {
                // Silently ignore auth command, treated as success in the array.
                json_object_object_add(single_response, "auth_success", json_object_new_object());
                json_object_object_add(json_object_object_get(single_response, "auth_success"), "is_valid", json_object_new_boolean(true));
                // NOTE: Real auth should set a unique authid here
                return;
        }

        if (!json_object_object_get_ex(single_request, "command", &cmd_obj)) {
            // Check for 'auth' token, which is handled silently without error
            json_object_object_add(single_response, "status", json_object_new_string("error"));
            json_object_object_add(single_response, "message", json_object_new_string("Command field missing in request object."));
            return;
        }

        const char *command = json_object_get_string(cmd_obj);

        bool handled = false;

        // --- 1. Handle Known Global Commands ---
        if (strcmp(command, "GetPluginTypes") == 0) {
            json_object *plugin_array = json_object_new_array();

            // Iterate directly over loaded plugins to get both name and typeId
            for(const EditPluginLoad::PluginData *curplg = Plugins->getFirstPlugin(); curplg; curplg = curplg->getNextPlg()){
        curplg->getInstace()->JsonApi(request,response);
                json_object *plugin_obj = json_object_new_object();

                // Assuming EditPlugin exposes getName() and getTypeId()
                const std::string name = curplg->getInstace()->getName();
                // Assuming getInstace()->getTypeId() exists and returns the ID string
                const char* typeId = curplg->getInstace()->getTypeId().c_str();

                if (!name.empty() && typeId) {
                    json_object_object_add(plugin_obj, "name", json_object_new_string(name.c_str()));
                    json_object_object_add(plugin_obj, "typeId", json_object_new_string(typeId));
                    json_object_array_add(plugin_array, plugin_obj);
                } else {
                    // Clean up object if data is invalid/missing
                    json_object_put(plugin_obj);
                }
            }

            json_object_object_add(single_response, "status", json_object_new_string("success"));
            json_object_object_add(single_response, "pluginTypes", plugin_array);
            // Note: The main loop adds single_response to the overall 'response' array,
            // so we don't call json_object_array_add(response, single_response) here.
            handled = true;
        } else if (strcmp(command, "GetDocTree") == 0) {
            if (this->CurRootEl) {
                // FIX: Apply static_cast to resolve the type mismatch. The original code
                // incorrectly used Plugins->getFirstPlugin(). We assume CurRootEl is an
                // XMLElement/HtmlElement that can be safely cast to the EditPlugin interface
                // for traversal and serialization.
                const blogi::webedit::EditPlugin* pluginRoot = Plugins->getFirstPlugin()->getInstace();

                // Call the recursive helper function to serialize the entire tree structure.
                json_object *tree_obj = this->serializeDocumentTree(pluginRoot);

                if (tree_obj) {
                    json_object_object_add(single_response, "status", json_object_new_string("success"));
                    json_object_object_add(single_response, "doc_tree", tree_obj);
                    handled = true;
                } else {
                    // Serialization failed (e.g., recursive error, invalid root structure)
                    json_object_object_add(single_response, "status", json_object_new_string("error"));
                    json_object_object_add(single_response, "message",
                        json_object_new_string("Document tree could not be serialized.")
                    );
                    handled = true;
                }
            } else {
                // Handle case where CurRootEl is null (no document is loaded)
                json_object_object_add(single_response, "status", json_object_new_string("error"));
                json_object_object_add(single_response, "message",
                    json_object_new_string("Document root element is not initialized.")
                );
                handled = true;
            }
        } else if (strcmp(command, "add_plugin_element") == 0) {
            // Handle element addition request: Command to modify the document tree

            const char *parent_uuid = nullptr;
            const char *plugin_type_name = nullptr; // maps to type_id
            const char *position = nullptr;

            json_object *param_obj = nullptr;

            // Extract parameters based on the assumed flat command structure
            if (json_object_object_get_ex(single_request, "parent_uuid", &param_obj)) {
                parent_uuid = json_object_get_string(param_obj);
            }
            if (json_object_object_get_ex(single_request, "plugin_name", &param_obj)) {
                plugin_type_name = json_object_get_string(param_obj);
            }
            if (json_object_object_get_ex(single_request, "position", &param_obj)) {
                position = json_object_get_string(param_obj);
            }

            // --- Basic validation and placeholder execution ---
            if (parent_uuid && plugin_type_name) {
                // TODO: Full implementation requires finding the parent element (using parent_uuid)
                // in the CurDoc/CurRootEl, creating the new plugin element (using PluginFactory),
                // and calling the parent's setChildElement or addNextElement methods.

                // For now, mock success:
                json_object_object_add(single_response, "status", json_object_new_string("success"));
                json_object_object_add(single_response, "message", json_object_new_string("Element addition commanded. Full tree logic needed."));
                handled = true;
            } else {
                json_object_object_add(single_response, "status", json_object_new_string("error"));
                json_object_object_add(single_response, "message",
                    json_object_new_string("Missing required parameters (parent_uuid or plugin_name) for add_plugin_element.")
                );
                handled = true; // Command was handled, but resulted in an error
            }
        }


        // The original code had the plugin loading here, which is now moved.

        // --- 2. Broadcast to Plugins (For Element-Specific Commands) ---
        if (!handled) {
            for(const EditPluginLoad::PluginData *curplg = Plugins->getFirstPlugin(); curplg; curplg = curplg->getNextPlg()){
                // Call the plugin's API method. The plugin should check if the command is for it.
                curplg->getInstace()->JsonApi(single_request, single_response);

                // We must check if the response was populated by the plugin to stop routing.
                if (json_object_object_get(single_response, "status") != nullptr || json_object_object_get(single_response, "success") != nullptr) {
                    handled = true;
                    break; // Command was handled by this plugin, stop broadcasting
                }
            }
        }

        if (!handled) {
            // If the command was not a global command and was not handled by any plugin
            json_object_object_add(single_response, "status", json_object_new_string("error"));
            json_object_object_add(single_response, "message",
                json_object_new_string("Command not recognized by WebEditor or any loaded plugin.")
            );
        }
    };

    if (json_object_get_type(request) == json_type_array) {
        // Since 'response' is passed by value, we must create the array inside the calling scope
        // and populate the array passed as 'response' in the main function.
        // NOTE: The signature 'json_object *response' suggests 'response' is the container.

        // Ensure response is an array if we are processing a batch request
        if (json_object_get_type(response) != json_type_array) {
             // In a proper C++ setup, you'd delete/replace 'response'. Here we assume the caller
             // provides an array container or we must trust the upper layer API wrapper.
             // Given the context, we will modify the existing 'response' object as expected.
        }

        int array_len = json_object_array_length(request);
        for (int i = 0; i < array_len; i++) {
            json_object *single_request = json_object_array_get_idx(request, i);
            json_object *single_response = json_object_new_object();
            jsonCommand(single_request, single_response);
            json_object_array_add(response, single_response);
        }
    } else {
        // If it's a single object (backward compatibility), process it directly.
        jsonCommand(request, response);
    }
}

void blogi::webedit::WebEditor::Renderer(
    PluginArgs &plgars,libhttppp::HttpRequest& curreq, const int tid,
    libhttppp::HttpRequest& curreq, const int tid,
    const std::string &sessionid,const libhtmlpp::HtmlElement &index,
    const std::string &rootEl
){
@@ -80,17 +365,22 @@ void blogi::webedit::WebEditor::Renderer(

    libhtmlpp::HtmlElement *root=ridx.getElementbyID(rootEl);

    std::vector<std::string> edplgdirs;
    for(size_t i=0; i<Args.config->getplgdirs(); ++i){
        edplgdirs.emplace_back(Args.config->getplgdir(i)+"/webedit");
    }

    if(root){
        for(const EditPluginLoad::PluginData *curplg=Plugins->getFirstPlugin(); curplg; curplg=curplg->getNextPlg()){
            curplg->getInstace()->Render(*root);
        }
    }

    plgars.theme->printSite(tid,out,&ridx,curreq.getRequestURL(),false);
    Args.theme->printSite(tid,out,&ridx,curreq.getRequestURL(),false);

    libhttppp::HttpResponse curres;
    curres.setState(HTTP200);
    curres.setVersion(HTTPVERSION(1.1));
    curres.setContentType("text/html");
    curres.send(curreq,out.data(),out.size());
    curres.send(curreq,out.data(),out.length());
}
+7 −3
Changes for src/edit.h: 7 added lines, 3 removed lines.
Original line number Diff line number Diff line
@@ -27,6 +27,7 @@

#include <httppp/http.h>
#include <tinyxml2.h>
#include <json-c/json.h>

#include "plugin.h"

@@ -36,18 +37,21 @@ namespace blogi {
    namespace webedit {
        class WebEditor{
        public:
                WebEditor() = default;
                void Editor(PluginArgs &plgars,libhttppp::HttpRequest& curreq, const int tid, const std::string &sessionid);
                WebEditor(PluginArgs &plgags);
                void Editor(libhttppp::HttpRequest& curreq, const int tid, const std::string &sessionid);
                void Renderer(
                    PluginArgs &plgars,libhttppp::HttpRequest& curreq,
                    libhttppp::HttpRequest& curreq,
                    const int tid, const std::string &sessionid,const libhtmlpp::HtmlElement &index,
                    const std::string &rootEl
                );
                std::vector<std::string> getPluginNames() const;
                void JsonApi(json_object *request,json_object *response);
        private:
                json_object *serializeDocumentTree(const blogi::webedit::EditPlugin *root);
                tinyxml2::XMLDocument              CurDoc;
                tinyxml2::XMLElement                *CurRootEl=nullptr;
                std::unique_ptr<EditPluginLoad> Plugins=nullptr;
                PluginArgs                                  &Args;
        };
    };
};
Loading