Пример #1
0
        private static string EngineReturnValue(Jint.Engine engine)
        {
            var returnitem = engine.GetCompletionValue();

            if (returnitem != null && !returnitem.IsNull())
            {
                var jsvalue = returnitem as JsValue;
                if (jsvalue != null)
                {
                    if (jsvalue.Type == Types.Null || jsvalue.Type == Types.None)
                    {
                        return(null);
                    }
                    else if (jsvalue.Type == Types.Object)
                    {
                        var obj = jsvalue.ToObject();
                        if (obj != null)
                        {
                            return(Lib.Helper.JsonHelper.Serialize(obj));
                        }
                    }
                    else
                    {
                        return(jsvalue.ToString());
                    }
                }
            }
            return(null);
        }
Пример #2
0
        public bool Process(FileInfo file)
        {
            Jint.Engine engine = new Jint.Engine(cfg => cfg.AllowClr(
                                                     Assembly.GetAssembly(typeof(TagLib.File))
                                                     ));
            engine.SetValue("file", file);

            var delegates = ProcessorExtensions.Delegates;

            foreach (Delegate dele in delegates)
            {
                engine.SetValue(dele.Method.Name, dele);
            }

            try
            {
                Jint.Engine proceed = engine.Execute(Script);
                return(proceed.GetCompletionValue().AsBoolean());
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine(ex.StackTrace);
                return(false);
            }
        }
Пример #3
0
        private static object EngineConfigReturnObject(Jint.Engine engine)
        {
            var returnitem = engine.GetCompletionValue();

            if (returnitem != null && !returnitem.IsNull())
            {
                var jsvalue = returnitem as JsValue;
                if (jsvalue != null)
                {
                    if (jsvalue.Type == Types.Object)
                    {
                        var obj = jsvalue.ToObject();
                        return(obj);
                    }
                }
            }
            return(null);
        }
Пример #4
0
 public void Execute(string code)
 {
     if (string.IsNullOrWhiteSpace(code))
     {
         return;
     }
     try
     {
         Jint.Engine engine = JsEngine.Execute(code);
         if (ComponentPlayer != null)
         {
             ComponentPlayer.ComponentGui.DisplaySmallMessage(engine.GetCompletionValue().ToString(), false, false);
         }
     }
     catch (Exception e)
     {
         ExceptionManager.ReportExceptionToUser("JS", e);
     }
     lastcode = code;
 }
Пример #5
0
        /// <summary>
        /// Runs a script with a different language inside the LoliScript.
        /// </summary>
        /// <param name="script">The script as a string with linebreaks</param>
        /// <param name="language">The language of the script</param>
        /// <param name="outputs">The variables that should be extracted from the script's scope and set into the BotData local variables</param>
        /// <param name="data">The BotData needed for variable replacement</param>
        private void RunScript(string script, ScriptingLanguage language, string outputs, BotData data, string jsFilePath = "")
        {
            // Set the console output to stringwriter
            var sw = new StringWriter();

            Console.SetOut(sw);
            Console.SetError(sw);

            jsFilePath = BlockBase.ReplaceValues(jsFilePath, data);

            if (jsFilePath != string.Empty && File.Exists(jsFilePath))
            {
                script += File.ReadAllText(jsFilePath);
            }

            // Parse variables to get out
            List <string> outVarList = new List <string>();

            if (outputs != string.Empty)
            {
                try { outVarList = outputs.Split(',').Select(x => x.Trim()).ToList(); }
                catch { }
            }

            var start = DateTime.Now;

            try
            {
                switch (language)
                {
                case ScriptingLanguage.JavaScript:

                    switch (jsEngine.ToLower())
                    {
                    case "jint":
                        InvokeJint();
                        break;

                    case "noesis":
                        InvokeNoesis();
                        break;

                    default:
                        InvokeJint();
                        break;
                    }

                    void InvokeNoesis()
                    {
                        var taskExecuteJs = Task.Run(() =>
                        {
                            object jsRetValue  = null;
                            bool disposeEngine = false;

                            JavascriptContext context = null;

                            if (disposeEngine = data.JsEngine == null)
                            {
                                context = new JavascriptContext();
                                JsEngine.SetParameter(context, data);
                            }
                            else
                            {
                                context = data.JsEngine.GetOrCreateEngine(data);
                            }

                            // Execute JS
                            try
                            {
                                jsRetValue = context.Run(script);
                            }
                            catch (JavascriptException ex)
                            {
                                throw new Exception($"Executing js error {ex.Message}\nline: {ex.Line}\nStart column:{ex.StartColumn}");
                            }

                            // Print results to log
                            data.Log(new LogEntry($"DEBUG LOG: {sw}", Colors.White));

                            // Get variables out
                            data.Log(new LogEntry($"Parsing {outVarList.Count} variables", Colors.White));
                            foreach (var name in outVarList)
                            {
                                try
                                {
                                    //Add it to the variables and print info
                                    var value   = context.GetParameter(name);
                                    var isArray = value.GetType().IsArray || value is string[] || value.GetType().Name.Contains("Dictionary");
                                    if (isArray)
                                    {
                                        try { data.Variables.Set(new CVar(name, CVar.VarType.List, (List <string>)value)); } catch (Exception ex) { data.Log(new LogEntry("[SET VARS] ERROR: " + ex.Message, Colors.Yellow)); }
                                    }
                                    else
                                    {
                                        data.Variables.Set(new CVar(name, CVar.VarType.Single, value.ToString()));
                                    }

                                    data.Log(new LogEntry($"SET VARIABLE {name} WITH VALUE {value}", Colors.Yellow));
                                }
                                catch { data.Log(new LogEntry($"COULD NOT FIND VARIABLE {name}", Colors.Tomato)); }
                            }
                            if (disposeEngine)
                            {
                                context.Dispose();
                            }

                            //Print other info
                            if (jsRetValue != null && !jsRetValue.GetType().Name.Contains("Dictionary"))
                            {
                                data.Log(new LogEntry($"Return value: {jsRetValue}", Colors.White));
                            }
                        });

                        taskExecuteJs.Wait();
                        taskExecuteJs.Dispose();
                    }

                    void InvokeJint()
                    {
                        // Redefine log() function
                        var jsEngine = new Jint.Engine().SetValue("log", new Action <object>(Console.WriteLine));

                        // Add in all the variables
                        foreach (var variable in data.Variables.All)
                        {
                            try
                            {
                                switch (variable.Type)
                                {
                                case CVar.VarType.List:
                                    jsEngine.SetValue(variable.Name, (variable.Value as List <string>).ToArray());
                                    break;

                                default:
                                    jsEngine.SetValue(variable.Name, variable.Value.ToString());
                                    break;
                                }
                            }
                            catch { }
                        }

                        // Execute JS
                        jsEngine.Execute(script);

                        // Print results to log
                        data.Log(new LogEntry($"DEBUG LOG: {sw.ToString()}", Colors.White));

                        // Get variables out
                        data.Log(new LogEntry($"Parsing {outVarList.Count} variables", Colors.White));
                        foreach (var name in outVarList)
                        {
                            try
                            {
                                // Add it to the variables and print info
                                var value   = jsEngine.Global.GetProperty(name).Value;
                                var isArray = value.IsArray();
                                if (isArray)
                                {
                                    data.Variables.Set(new CVar(name, CVar.VarType.List, value.TryCast <List <string> >()));
                                }
                                else
                                {
                                    data.Variables.Set(new CVar(name, CVar.VarType.Single, value.ToString()));
                                }
                                data.Log(new LogEntry($"SET VARIABLE {name} WITH VALUE {value.ToString()}", Colors.Yellow));
                            }
                            catch { data.Log(new LogEntry($"COULD NOT FIND VARIABLE {name}", Colors.Tomato)); }
                        }

                        // Print other info
                        if (jsEngine.GetCompletionValue() != null)
                        {
                            data.Log(new LogEntry($"Completion value: {jsEngine.GetCompletionValue()}", Colors.White));
                        }
                    }

                    break;

                case ScriptingLanguage.IronPython:

                    // Initialize the engine
                    var runtime  = Python.CreateRuntime();
                    var pyengine = runtime.GetEngine("py");
                    PythonCompilerOptions pco = (PythonCompilerOptions)pyengine.GetCompilerOptions();
                    pco.Module &= ~ModuleOptions.Optimized;
                    //var pyengine = Python.CreateEngine();
                    var scope = pyengine.CreateScope();
                    var code  = pyengine.CreateScriptSourceFromString(script);

                    // Add in all the variables
                    foreach (var variable in data.Variables.All)
                    {
                        try { scope.SetVariable(variable.Name, variable.Value); } catch { }
                    }

                    // Execute it
                    var result = code.Execute(scope);
                    //var result = pyengine.Execute(script, scope);

                    // Print the logs
                    data.Log(new LogEntry($"DEBUG LOG: {sw}", Colors.White));

                    // Get variables out
                    data.Log(new LogEntry($"Parsing {outVarList.Count} variables", Colors.White));
                    foreach (var name in outVarList)
                    {
                        try
                        {
                            // Add it to the variables and print info
                            var value = scope.GetVariable(name);
                            data.Variables.Set(new CVar(name, (value.GetType() == typeof(string[])) ? CVar.VarType.List : CVar.VarType.Single, value.ToString()));
                            data.Log(new LogEntry($"SET VARIABLE {name} WITH VALUE {value}", Colors.Yellow));
                        }
                        catch { data.Log(new LogEntry($"COULD NOT FIND VARIABLE {name}", Colors.Tomato)); }
                    }

                    // Print other info
                    if (result != null)
                    {
                        data.Log(new LogEntry($"Completion value: {result}", Colors.White));
                    }

                    break;

                default:
                    break;
                }

                data.Log(new LogEntry($"Execution completed in {(DateTime.Now - start).TotalSeconds} seconds", Colors.GreenYellow));
            }
            catch (Exception e)
            {
                data.Log(new LogEntry($"[ERROR] INFO: {e.Message}", Colors.White));
            }
            finally
            {
                var standardOutput = new StreamWriter(Console.OpenStandardOutput());
                var standardError  = new StreamWriter(Console.OpenStandardError());
                standardOutput.AutoFlush = true;
                standardError.AutoFlush  = true;
                Console.SetOut(standardOutput);
                Console.SetError(standardError);
            }
        }