2using System.Diagnostics;
11using Jint.Native.Function;
26 public static TaskCompletionSource<HttpResponse>
httpResponse =
new();
27 public const string fName =
"JsInterface";
34 delegate(Options cfg) {
35 cfg.AllowClr(AppDomain.CurrentDomain.GetAssemblies());
39 string codeString =
null;
51 &&
int.TryParse(portString, out
int port)) {
55 SetHttpPort((DateTime.Now.Millisecond * 32749 + 8191) % 9000 + 1024,
true);
61 httpPassword = ((DateTime.Now.Millisecond * 49999 + 3067) % 9000 + 999).ToString();
65 &&
bool.Parse(enable)) {
71 List<Function> keyDownHandlers =
GetHandlers(
"keyDownHandlers");
72 if (keyDownHandlers !=
null
73 && keyDownHandlers.Count > 0) {
75 string keyString = key.ToString();
76 keyDownHandlers.ForEach(
function => {
Invoke(
function, keyString); });
79 List<Function> keyUpHandlers =
GetHandlers(
"keyUpHandlers");
80 if (keyUpHandlers !=
null
81 && keyUpHandlers.Count > 0) {
83 string keyString = key.ToString();
84 keyUpHandlers.ForEach(
function => {
Invoke(
function, keyString); });
87 List<Function> frameHandlers =
GetHandlers(
"frameHandlers");
88 if (frameHandlers !=
null
89 && frameHandlers.Count > 0) {
90 Window.Frame += delegate { frameHandlers.ForEach(
function => {
Invoke(
function); }); };
108 catch (Exception ex) {
113 public static void Execute(Prepared<Script> script) {
117 catch (Exception ex) {
124 return engine.Evaluate(str).ToString();
126 catch (Exception ex) {
127 string errors = ex.ToString();
133 public static string Evaluate(Prepared<Script> script) {
135 return engine.Evaluate(script).ToString();
137 catch (Exception ex) {
138 string errors = ex.ToString();
144 public static JsValue
Invoke(
string str, params
object[] arguments) {
146 return engine.Invoke(str, arguments);
148 catch (Exception ex) {
154 public static JsValue
Invoke(JsValue jsValue, params
object[] arguments) {
156 return engine.Invoke(jsValue, arguments);
158 catch (Exception ex) {
165 JsArray array =
engine.GetValue(str).AsArray();
166 if (array.IsNull()) {
169 List<Function> list = [];
170 foreach (JsValue item
in array) {
172 Function
function = item.AsFunctionInstance();
173 if (!
function.IsNull()) {
177 catch (Exception ex) {
189 List<Function> handlers =
GetHandlers($
"{handlesName}Handlers");
191 && handlers.Count > 0) {
196 catch (Exception ex) {
201 public static void SetHttpPort(
int port,
bool updateConfig =
false) {
207 httpListener.Prefixes.Add($
"http://{IPAddress.Loopback}:{port}/");
219 catch (Exception e) {
220 Log.
Error($
"Remote control server starts failed: {e}");
223 HttpListenerContext context = await
httpListener.GetContextAsync();
240 Stopwatch stopwatch = Stopwatch.StartNew();
245 success = !result.StartsWith(
"Jint.Runtime.JavaScriptException"), result = result, timeCosted = stopwatch.Elapsed
253 string responseString;
257 else if (context.Request.HttpMethod ==
"POST") {
259 || (context.Request.Headers.Get(
"password")?.Equals(
httpPassword) ??
false)) {
262 httpResponse =
new TaskCompletionSource<HttpResponse>();
264 using (Stream bodyStream = context.Request.InputStream) {
265 using (StreamReader reader =
new(bodyStream, context.Request.ContentEncoding)) {
266 string requestBody = reader.ReadToEnd();
267 if (requestBody.Length > 0) {
270 responseString = JsonSerializer.Serialize(await
httpResponse.Task);
278 catch (Exception e) {
287 else if (context.Request.HttpMethod ==
"ELEVATE") {
288#if !MOBILE && !BROWSER
289 Thread.CurrentThread.Priority = ThreadPriority.Highest;
291 responseString =
"Sucess";
296 HttpListenerResponse response = context.Response;
297 response.ContentType =
"application/json";
298 byte[] buffer = Encoding.UTF8.GetBytes(responseString);
299 response.ContentLength64 = buffer.Length;
300 Stream output = response.OutputStream;
301 await output.WriteAsync(buffer);
304 catch (Exception e) {
305 context.Response.Close();
311 JsonSerializer.Serialize(
new HttpResponse { success =
false, result = error, timeCosted = TimeSpan.Zero });
324using System.Diagnostics;
326using System.Runtime.InteropServices.JavaScript;
328using System.Text.Json;
329using System.Xml.Linq;
330using static System.Runtime.InteropServices.JavaScript.JSType;
334 private static JSContext jSContext;
336 private static JsModLoader
loader;
342 public static TaskCompletionSource<HttpResponse>
httpResponse =
new();
344 public const string fName =
"JsInterface";
348 jSContext =
new JSContext();
351 string codeString =
null;
353 if (Storage.FileExists(
"app:init.js")) {
354 codeString = Storage.ReadAllText(
"app:init.js");
358 Log.Warning(LanguageControl.Get(
fName,
"5"));
362 if (ModsManager.Configs.TryGetValue(
"RemoteControlPort", out
string portString)
363 &&
int.TryParse(portString, out
int port)) {
367 SetHttpPort((DateTime.Now.Millisecond * 32749 + 8191) % 9000 + 1024,
true);
369 if (ModsManager.Configs.TryGetValue(
"RemoteControlPassword", out
string password)) {
373 httpPassword = ((DateTime.Now.Millisecond * 49999 + 3067) % 9000 + 999).ToString();
374 ModsManager.SetConfig(
"RemoteControlPassword",
httpPassword);
376 if (ModsManager.Configs.TryGetValue(
"RemoteControlEnabled", out
string enable)
377 &&
bool.Parse(enable)) {
383 public static void SetHttpPort(
int port,
bool updateConfig =
false) {
389 httpListener.Prefixes.Add($
"http://{IPAddress.Loopback}:{port}/");
393 ModsManager.SetConfig(
"RemoteControlPort", port.ToString());
401 catch (Exception e) {
402 Log.Error($
"Remote control server starts failed: {e}");
405 HttpListenerContext context = await
httpListener.GetContextAsync();
411 public static JSValue
Invoke(
string str, params
object[] arguments) {
413 var jv = JSValue.CreateArray(jSContext);
414 JSValue[] jSValues =
new JSValue[arguments.Length];
415 for (
int i = 0; i < arguments.Length; i++) jSValues[i] = JSValue.From((NSObject)arguments[i],jSContext);
416 return jSContext.GlobalObject.GetProperty(str).Call(jSValues);
418 catch (Exception ex) {
425 var keyDownHandlers =
GetHandlers(
"keyDownHandlers");
426 if (keyDownHandlers !=
null
427 && keyDownHandlers.Count > 0) {
428 Keyboard.KeyDown += delegate (
Key key) {
429 string keyString = key.ToString();
430 keyDownHandlers.ForEach(keyDownEvt => { keyDownEvt.Call(
new JSValue[] { JSValue.From(keyString,jSContext) }); });
434 if (keyUpHandlers !=
null
435 && keyUpHandlers.Count > 0) {
436 Keyboard.KeyUp += delegate (
Key key) {
437 string keyString = key.ToString();
438 keyUpHandlers.ForEach(keyDownEvt => { keyDownEvt.Call(
new JSValue[] { JSValue.From(keyString, jSContext) }); });
442 if (frameHandlers !=
null
443 && frameHandlers.Count > 0) {
444 Window.Frame += delegate { frameHandlers.ForEach(frameEvt => { frameEvt.Call(
new JSValue[] { JSValue.From(
"", jSContext) }); }); };
447 loader = (JsModLoader)ModsManager.ModLoaders.Find(item => item is JsModLoader);
448 loader.JSContext = jSContext;
459 public static JSValue
Execute(
string str) {
461 return jSContext.EvaluateScript(str);
463 catch (Exception ex) {
469 public static List<JSValue>
GetHandlers(
string str) {
470 JSValue arrayValue = jSContext.GlobalObject.GetProperty(str);
471 if (!arrayValue.IsArray) {
474 List<JSValue> list =
new();
475 int length = arrayValue.GetProperty(
"length").ToInt32();
476 for (
int i=0;i<length;i++) {
477 list.Add(arrayValue.GetProperty(i.ToString()));
487 List<JSValue> handlers =
GetHandlers($
"{handlesName}Handlers");
489 && handlers.Count > 0) {
491 ModsManager.RegisterHook(handlesName,
loader);
494 catch (Exception ex) {
499 public static void Update() {
501 Stopwatch stopwatch = Stopwatch.StartNew();
507 result = result.ToString(),
508 timeCosted = stopwatch.Elapsed
516 string responseString;
520 else if (context.Request.HttpMethod ==
"POST") {
522 || (context.Request.Headers.Get(
"password")?.Equals(
httpPassword) ??
false)) {
525 httpResponse =
new TaskCompletionSource<HttpResponse>();
527 using (Stream bodyStream = context.Request.InputStream) {
528 using (StreamReader reader =
new(bodyStream, context.Request.ContentEncoding)) {
529 string requestBody = reader.ReadToEnd();
530 if (requestBody.Length > 0) {
533 responseString = JsonSerializer.Serialize(await
httpResponse.Task);
541 catch (Exception e) {
550 else if (context.Request.HttpMethod ==
"ELEVATE") {
551 responseString =
"Sucess";
556 HttpListenerResponse response = context.Response;
557 response.ContentType =
"application/json";
558 byte[] buffer = Encoding.UTF8.GetBytes(responseString);
559 response.ContentLength64 = buffer.Length;
560 Stream output = response.OutputStream;
561 await output.WriteAsync(buffer);
564 catch (Exception e) {
565 context.Response.Close();
579 JsonSerializer.Serialize(
new HttpResponse { success =
false, result = error, timeCosted = TimeSpan.Zero });
582 public bool success {
get;
set; }
583 public string result {
get;
set; }
static void Error(object message)
static void Warning(object message)
static bool FileExists(string path)
static string ReadAllText(string path)
static void StopHttpListener()
static void RegisterEvent()
static TaskCompletionSource< HttpResponse > httpResponse
static Dictionary< string, List< Function > > handlersDictionary
static string ErrorJsonResponse(string error)
static JsValue Invoke(string str, params object[] arguments)
static string Evaluate(Prepared< Script > script)
static List< Function > GetHandlers(string str)
static bool httpProcessing
static void SetHttpPort(int port, bool updateConfig=false)
static bool httpScriptPrepared
static async void HandleHttpRequest(HttpListenerContext context)
static string Evaluate(string str)
static string httpPassword
static Prepared< Script > httpScript
static void Execute(string str)
static JsModLoader loader
static HttpListener httpListener
static void GetAndRegisterHandlers(string handlesName)
static void Execute(Prepared< Script > script)
static JsValue Invoke(JsValue jsValue, params object[] arguments)
static async Task StartHttpListener()
static string Get(string className, int key)
获取在当前语言类名键对应的字符串
static List< ModLoader > ModLoaders
static void SetConfig(string key, string value)
static Dictionary< string, string > Configs
static void RegisterHook(string HookName, ModLoader modLoader)
注册Hook