Skip to content

Commit

Permalink
fix: Fix issues with the plugin example crashing.
Browse files Browse the repository at this point in the history
  • Loading branch information
shdwmtr committed Oct 11, 2024
1 parent 46e7a68 commit 8624fab
Show file tree
Hide file tree
Showing 6 changed files with 53 additions and 34 deletions.
5 changes: 4 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -5,4 +5,7 @@
/vendor/python/python311.dll
/vendor/python/python311.lib
/vendor/python/python311_d.lib
/vendor/python/python311_d.dll
/vendor/python/python311_d.dll

# Ignore plugin example build assets
/examples/plugin/.millennium
23 changes: 13 additions & 10 deletions examples/plugin/backend/main.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,13 @@
import Millennium
import Millennium, PluginUtils # type: ignore
logger = PluginUtils.Logger("__plugin_name__")

import time
import json

class Backend:
@staticmethod
def receive_frontend_message(message: str, status: bool, count: int):
print(f"received: {[message, status, count]}")
logger.log(f"received: {[message, status, count]}")

# accepted return types [str, int, bool]
if count == 69:
Expand All @@ -15,7 +16,7 @@ def receive_frontend_message(message: str, status: bool, count: int):
return

def get_steam_path():
print("getting steam path")
logger.log("getting steam path")
return Millennium.steam_path()

class Plugin:
Expand All @@ -26,29 +27,31 @@ def _front_end_loaded(self):
# The front end has successfully mounted in the steam app.
# You can now use Millennium.call_frontend_method()

print("The front end has loaded!")
logger.log("The front end has loaded!")

start_time = time.time()
value = Millennium.call_frontend_method("classname.method", params=[18, "USA", False])
end_time = time.time()

print(f"classname.method says -> {value} [{round((end_time - start_time) * 1000, 3)}ms]")
logger.log(f"classname.method says -> {value} [{round((end_time - start_time) * 1000, 3)}ms]")


def _load(self):
# This code is executed when your plugin loads.
# notes: thread safe, running for entire lifespan of millennium

print(f"bootstrapping plugin, millennium v{Millennium.version()}")
print(f"Steam Path -> {Millennium.steam_path()}")
logger.log(f"bootstrapping plugin, millennium v{Millennium.version()}")
logger.log(f"Steam Path -> {Millennium.steam_path()}")

# print("pinging frontend")
try:
value = Millennium.call_frontend_method("classname.method", params=[18, "USA", False])
print(f"ponged message -> {value}")
logger.log(f"ponged message -> {value}")
except ConnectionError as error:
print(error) # "frontend is not loaded!"
logger.error(f"Failed to ping frontend, {error}")

Millennium.ready() # this is required to tell Millennium that the backend is ready.


def _unload(self):
print("unloading")
logger.log("unloading")
2 changes: 1 addition & 1 deletion src/core/ffi/ffi.h
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ namespace JavaScript {
// Deliver any missed messages
auto it = missedMessages.find(event);
if (it != missedMessages.end()) {
for (const auto& message : it->second) {
for (const auto message : it->second) {
handler(message, listenerId);
}
missedMessages.erase(it); // Clear missed messages once delivered
Expand Down
19 changes: 12 additions & 7 deletions src/core/ffi/javascript.cc
Original file line number Diff line number Diff line change
Expand Up @@ -30,23 +30,28 @@ const EvalResult ExecuteOnSharedJsContext(std::string javaScriptEval)

JavaScript::SharedJSMessageEmitter::InstanceRef().OnMessage("msg", [&](const nlohmann::json& eventMessage, int listenerId)
{
nlohmann::json response = eventMessage;
std::string method = response.value("method", std::string());

if (method.find("Debugger") != std::string::npos || method.find("Console") != std::string::npos)
{
return;
}

try
{
if (eventMessage.contains("id") && eventMessage["id"] != SHARED_JS_EVALUATE_ID)
if (response.contains("id") && !response["id"].is_null() && response["id"] != SHARED_JS_EVALUATE_ID)
{
return;
}

if (eventMessage["result"].contains("exceptionDetails"))
if (response["result"].contains("exceptionDetails"))
{
promise.set_value
({
eventMessage["result"]["exceptionDetails"]["exception"]["description"], false
});
promise.set_value({ response["result"]["exceptionDetails"]["exception"]["description"], false });
return;
}

promise.set_value({ eventMessage["result"]["result"], true });
promise.set_value({ response["result"]["result"], true });
JavaScript::SharedJSMessageEmitter::InstanceRef().RemoveListener("msg", listenerId);
}
catch (nlohmann::detail::exception& ex)
Expand Down
14 changes: 8 additions & 6 deletions src/core/loader.cc
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,6 @@ bool Sockets::PostShared(nlohmann::json data)
{
if (sharedJsContextSessionId.empty())
{
LOG_ERROR("not connected to shared js context, cant post message");
return false;
}

Expand All @@ -33,8 +32,8 @@ bool Sockets::PostShared(nlohmann::json data)

bool Sockets::PostGlobal(nlohmann::json data)
{
if (browserClient == nullptr) {
LOG_ERROR("not connected to steam, cant post message");
if (browserClient == nullptr)
{
return false;
}

Expand Down Expand Up @@ -98,17 +97,20 @@ class CEFBrowser
this->SetupSharedJSContext();
}
}

if (method == "Target.attachedToTarget")
{
sharedJsContextSessionId = json["params"]["sessionId"];
this->onSharedJsConnect();
}
if (method == "Console.messageAdded")
else if (method == "Console.messageAdded")
{
this->HandleConsoleMessage(json);
}

JavaScript::SharedJSMessageEmitter::InstanceRef().EmitMessage("msg", json);
else
{
JavaScript::SharedJSMessageEmitter::InstanceRef().EmitMessage("msg", json);
}
webKitHandler.DispatchSocketMessage(json);
}

Expand Down
24 changes: 15 additions & 9 deletions src/core/py_controller/logger.h
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,17 @@ class BackendLogger
return fmt::format("[{}-{}-{} @ {}:{}:{}]", year, month, day, hour, min, sec);
}

std::string GetPluginName()
{
const auto toUpper = [](const std::string& str) {
std::string result = str;
std::transform(result.begin(), result.end(), result.begin(), ::toupper);
return result;
};

return toUpper(pluginName);
}

public:
BackendLogger(const std::string& pluginName) : pluginName(pluginName)
{
Expand All @@ -57,14 +68,8 @@ class BackendLogger

void Log(const std::string& message)
{
const auto toUpper = [](const std::string& str) {
std::string result = str;
std::transform(result.begin(), result.end(), result.begin(), ::toupper);
return result;
};

fmt::print("{} ", GetLocalTime());
std::string formatted = fmt::format("{} ", toUpper(pluginName));
std::string formatted = fmt::format("{} ", GetPluginName());

fmt::print("\033[1m\033[34m{}\033[0m\033[0m", formatted);
fmt::print(fmt::format("{}\n", message));
Expand All @@ -74,7 +79,7 @@ class BackendLogger

void Warn(const std::string& message)
{
std::string formatted = fmt::format("{}{}{}\n", GetLocalTime(), fmt::format(" ({}) ", pluginName), message);
std::string formatted = fmt::format("{}{}{}\n", GetLocalTime(), fmt::format(" {} ", GetPluginName()), message);

fmt::print(fg(fmt::color::orange), formatted, "\n");
file << formatted;
Expand All @@ -83,10 +88,11 @@ class BackendLogger

void Error(const std::string& message)
{
std::string formatted = fmt::format("{}{}{}\n", GetLocalTime(), fmt::format(" ({}) ", pluginName), message);
std::string formatted = fmt::format("{}{}{}\n", GetLocalTime(), fmt::format(" {} ", GetPluginName()), message);

fmt::print(fg(fmt::color::red), formatted, "\n");
file << formatted;
file.flush();
}
};

Expand Down

0 comments on commit 8624fab

Please sign in to comment.