public IEnumerable<FunctionDeclaration> GetSourceCodeGlobalFunctions() { JavaScriptParser parser = new JavaScriptParser(); foreach (FunctionDeclaration funcDecl in parser.Parse(Code).FunctionDeclarations) { yield return funcDecl; } }
public IScript Get(string content) { var parser = new JavaScriptParser(); var script = new Mock<IScript>(); script.SetupGet(s => s.File).Returns(_mockFile.FromString("js", content)); script.SetupGet(s => s.ExpressionTree).Returns(parser.Parse(content)); script.Name = content; return script.Object; }
public void Process() { try { var parser = new JavaScriptParser(); var program = parser.Parse(OriginalString); var visitor = new RequireVisitor(); var result = visitor.Visit(program, RelativeFileName); var lines = GetScriptLines(OriginalString); var flattenedResults = result.GetFlattened(); var deps = flattenedResults.SelectMany(r => r.Dependencies) .Where(r => !r.Contains("!")) .Except(new List<string> { "require", "module", "exports" }); Dependencies = deps.Select(r => GetModulePath(r)).ToList(); var shim = this.GetShim(RelativeFileName); if (shim != null) { Dependencies.AddRange(shim.Dependencies.Select(r => this.GetModulePath(r.Dependency))); } Dependencies = Dependencies.Distinct().ToList(); flattenedResults.ForEach( x => { EnsureHasRange(x.ParentNode.Node, lines); EnsureHasRange(x.DependencyArrayNode, lines); EnsureHasRange(x.ModuleDefinitionNode, lines); EnsureHasRange(x.ModuleIdentifierNode, lines); EnsureHasRange(x.SingleDependencyNode, lines); var arguments = x.ParentNode.Node.As<CallExpression>().Arguments; foreach (var arg in arguments) { EnsureHasRange(arg, lines); } }); var transformations = this.GetTransformations(result, flattenedResults); var text = OriginalString; transformations.ExecuteAll(ref text); ProcessedString = text; } catch (Exception ex) { throw new Exception(string.Format("Error while processing {0}: {1}", RelativeFileName, ex.Message), ex); } }
/// <summary>Rewrites the given program code.</summary> /// <param name="programcode">The jscript code to rewrite.</param> public void RewriteProgram(string programcode) { var parser = new JavaScriptParser(); try { var ast = parser.Parse(programcode); Emit(ast); } catch(ParserException ex) { Log.Trace("jscript parsing error: {0}\n{1}", ex.Message, ex.Source); throw ex; } }
static void Main(string[] args) { var filePath = GetPath(@"Scripts\BForms\Bundles\js\components.js"); var minimalPath = GetPath(@"Scripts\minimal.js"); var initUIPath = GetPath(@"Scripts\BForms\Plugins\UI\bforms.initUI.js"); var text = File.ReadAllText(initUIPath); var parser = new JavaScriptParser(); var program = parser.Parse(text); var visitor = new RequireVisitor(); var result = visitor.Visit(program, initUIPath); var lines = GetScriptLines(text); var flattenedResults = result.GetFlattened(); flattenedResults.ForEach( x => { EnsureHasRange(x.ParentNode.Node, lines); EnsureHasRange(x.DependencyArrayNode, lines); EnsureHasRange(x.ModuleDefinitionNode, lines); EnsureHasRange(x.ModuleIdentifierNode, lines); EnsureHasRange(x.SingleDependencyNode, lines); var arguments = x.ParentNode.Node.As<CallExpression>().Arguments; foreach (var arg in arguments) { EnsureHasRange(arg, lines); } }); var reqLines = flattenedResults.Select(x => GetTextFromFullScript(x.ParentNode.Node.Range, text)).ToList(); var modifiedString = text; var transformCollection = new TransformationCollection(); foreach (var req in flattenedResults) { transformCollection.Add(ToDefineTransformation.Create(req)); if (req.Type != RequireCallType.Define) { transformCollection.Add(AddIdentifierTransformation.Create(req, "gogu")); } } transformCollection.ExecuteAll(ref modifiedString); }
internal static CompiledScript Compile(string script, bool isGlobal) { CommonTokenStream tokens = new CommonTokenStream(); JavaScriptLexer lexer = new JavaScriptLexer(new ANTLRStringStream(script)); tokens.TokenSource = lexer; ScriptSource Source = new ScriptSource(script); JavaScriptParser parser = new JavaScriptParser(tokens); TopStatementList r = (TopStatementList) parser.program().Tree; r.ConstructionComplete(); if (JSContext.DebugOutput) { DumpTree(r, 0); } if (JSContext.OutputAssembly && isGlobal) { GenerateExternalAssembly(r); r.Reset(); } return GenerateMethod(r, Source); }
public JavascriptOperation( string outKey, string script, Dictionary<string, Script> scripts, IParameters parameters, ILogger logger) : base(string.Empty, outKey) { _script = script; _parameters = parameters; _addSelf = !parameters.Any(); foreach (var pair in scripts) { logger.Debug("Running script {0}.", pair.Value.File); try { var program = new JavaScriptParser().Parse(pair.Value.Content, new ParserOptions { Tolerant = true}); if (program.Errors != null && program.Errors.Count > 0) { logger.Warn("Javascript Parse Failed. Script: {0}.", pair.Value.Name); foreach (var error in program.Errors) { logger.Warn(error.Description); } } else { _scriptAppender.AppendLine(pair.Value.Content); } } catch (Exception e) { logger.Error("Javascript Parse Failed. Name: {0}. Script: {1}.", pair.Value.Name, pair.Value.Content); logger.Error(e.Message); } } var externalScripts = _scriptAppender.ToString(); if (externalScripts.Equals(string.Empty)) return; logger.Debug("Loading scripts into Javascript engine..."); logger.Debug(externalScripts.Replace("{","{{").Replace("}","}}")); _jint.Execute(externalScripts); Name = string.Format("Javascript({0}=>{1})", InKey, OutKey); }
public void ShouldParseScriptFile(string file, string version) { const string prefix = "Jint.Tests.Parser.Scripts."; var assembly = Assembly.GetExecutingAssembly(); var scriptPath = prefix + file; var sw = new Stopwatch(); using (var stream = assembly.GetManifestResourceStream(scriptPath)) { if (stream != null) { using (var sr = new StreamReader(stream)) { var source = sr.ReadToEnd(); sw.Restart(); var parser = new JavaScriptParser(); var program = parser.Parse(source); Console.WriteLine("Parsed {0} {1} ({3} KB) in {2} ms", file, version, sw.ElapsedMilliseconds, (int)source.Length/1024); Assert.NotNull(program); } } } }
/// <summary> /// Get student infos from the JavaScript variables in the schedule page. /// </summary> /// <returns></returns> public Dictionary<string, object> GetStudentInfoFromSchedulePage() { var schedulePageHtml = WebClientEx.Instance.Get(Constants.SCHEDULE_PAGE_URL); HtmlDocument htmlDoc = new HtmlDocument(); htmlDoc.LoadHtml(schedulePageHtml); var docNode = htmlDoc.DocumentNode; var scriptNodes = docNode.QuerySelectorAll("script"); List<HtmlNode> targetNodes = new List<HtmlNode>(); foreach (var node in scriptNodes) { if (node.Attributes["src"] == null) { if (!node.InnerHtml.Trim().StartsWith("debug") && node.InnerHtml.Length >= 100) { targetNodes.Add(node); } } } Dictionary<string, object> Variables = new Dictionary<string, object>(); if (targetNodes != null && targetNodes.Count >= 1) { foreach (var targetNode in targetNodes) { JavaScriptParser par = new JavaScriptParser(); var jsObj = par.Parse(targetNode.InnerHtml); var jsBody = jsObj.Body; foreach (var body in jsBody) { if (body is VariableDeclaration) { var var = body as VariableDeclaration; foreach (var dec in var.Declarations) { var name = dec.Id.Name; var value = dec.Init.As<Literal>().Value; Variables.Add(name, value); } } } } } Core.StudentInfo = Variables; return Variables; }
private void ValidateJavascript() { //TODO: extract interface and inject parser try { var program = new JavaScriptParser().Parse(Script, new ParserOptions() { Tolerant = true }); if (program.Errors == null) return; foreach (var parserError in program.Errors) { Error("Javascript parse error. {0}", parserError.Message); } } catch (Exception ex) { Error("Javascript parse error. {0}", ex.Message); } }
public ObjectInstance Construct(JsValue[] arguments) { var argCount = arguments.Length; string p = ""; string body = ""; if (argCount == 1) { body = TypeConverter.ToString(arguments[0]); } else if (argCount > 1) { var firstArg = arguments[0]; p = TypeConverter.ToString(firstArg); for (var k = 1; k < argCount - 1; k++) { var nextArg = arguments[k]; p += "," + TypeConverter.ToString(nextArg); } body = TypeConverter.ToString(arguments[argCount - 1]); } var parameters = this.ParseArgumentNames(p); var parser = new JavaScriptParser(); FunctionExpression function; try { var functionExpression = "function(" + p + ") { " + body + "}"; function = parser.ParseFunctionExpression(functionExpression); } catch (ParserException) { throw new JavaScriptException(Engine.SyntaxError); } // todo: check if there is not a way to use the FunctionExpression directly instead of creating a FunctionDeclaration var functionObject = new ScriptFunctionInstance( Engine, new FunctionDeclaration { Type = SyntaxNodes.FunctionDeclaration, Body = new BlockStatement { Type = SyntaxNodes.BlockStatement, Body = new [] { function.Body } }, Parameters = parameters.Select(x => new Identifier { Type = SyntaxNodes.Identifier, Name = x }).ToArray(), FunctionDeclarations = function.FunctionDeclarations, VariableDeclarations = function.VariableDeclarations }, LexicalEnvironment.NewDeclarativeEnvironment(Engine, Engine.ExecutionContext.LexicalEnvironment), function.Strict ) { Extensible = true }; return(functionObject); }
public void ExecuteTestCase(string fixture) { var options = new ParserOptions { Tokens = true }; string treeFilePath, failureFilePath, moduleFilePath; var jsFilePath = Path.Combine(GetFixturesPath(), "Fixtures", fixture); if (jsFilePath.EndsWith(".source.js")) { treeFilePath = Path.Combine(Path.GetDirectoryName(jsFilePath), Path.GetFileNameWithoutExtension(Path.GetFileNameWithoutExtension(jsFilePath))) + ".tree.json"; failureFilePath = Path.Combine(Path.GetDirectoryName(jsFilePath), Path.GetFileNameWithoutExtension(Path.GetFileNameWithoutExtension(jsFilePath))) + ".failure.json"; moduleFilePath = Path.Combine(Path.GetDirectoryName(jsFilePath), Path.GetFileNameWithoutExtension(Path.GetFileNameWithoutExtension(jsFilePath))) + ".module.json"; } else { treeFilePath = Path.Combine(Path.GetDirectoryName(jsFilePath), Path.GetFileNameWithoutExtension(jsFilePath)) + ".tree.json"; failureFilePath = Path.Combine(Path.GetDirectoryName(jsFilePath), Path.GetFileNameWithoutExtension(jsFilePath)) + ".failure.json"; moduleFilePath = Path.Combine(Path.GetDirectoryName(jsFilePath), Path.GetFileNameWithoutExtension(jsFilePath)) + ".module.json"; } var script = File.ReadAllText(jsFilePath); if (jsFilePath.EndsWith(".source.js")) { var parser = new JavaScriptParser(script); var program = parser.ParseScript(); var source = program.Body.First().As <VariableDeclaration>().Declarations.First().As <VariableDeclarator>().Init.As <Literal>().StringValue; script = source; } var expected = ""; var invalid = false; var filename = Path.GetFileNameWithoutExtension(jsFilePath); var isModule = filename.Contains("module") || filename.Contains("export") || filename.Contains("import"); if (!filename.Contains(".module")) { isModule &= !jsFilePath.Contains("dynamic-import") && !jsFilePath.Contains("script"); } var sourceType = isModule ? SourceType.Module : SourceType.Script; #pragma warning disable 162 if (File.Exists(moduleFilePath)) { sourceType = SourceType.Module; expected = File.ReadAllText(moduleFilePath); if (WriteBackExpectedTree) { var actual = ParseAndFormat(sourceType, script, options); if (!CompareTreesInternal(actual, expected)) { File.WriteAllText(moduleFilePath, actual); } } } else if (File.Exists(treeFilePath)) { expected = File.ReadAllText(treeFilePath); if (WriteBackExpectedTree) { var actual = ParseAndFormat(sourceType, script, options); if (!CompareTreesInternal(actual, expected)) { File.WriteAllText(treeFilePath, actual); } } } else if (File.Exists(failureFilePath)) { invalid = true; expected = File.ReadAllText(failureFilePath); if (WriteBackExpectedTree) { var actual = ParseAndFormat(sourceType, script, options); if (!CompareTreesInternal(actual, expected)) { File.WriteAllText(failureFilePath, actual); } } #pragma warning restore 162 } else { // cannot compare return; } invalid |= filename.Contains("error") || filename.Contains("invalid") && !filename.Contains("invalid-yield-object-"); if (!invalid) { options.Tolerant = true; var actual = ParseAndFormat(sourceType, script, options); CompareTrees(actual, expected, jsFilePath); } else { options.Tolerant = false; // TODO: check the accuracy of the message and of the location Assert.Throws <ParserException>(() => ParseAndFormat(sourceType, script, options)); } }
public void ProcessRequest(MIGClientRequest request, MIGInterfaceCommand migCommand) { switch (migCommand.Command) { case "Interfaces.List": migCommand.Response = "[ "; foreach (var kv in homegenie.Interfaces) { var migInterface = kv.Value; var ifaceConfig = homegenie.SystemConfiguration.MIGService.GetInterface(migInterface.Domain); if (ifaceConfig == null || !ifaceConfig.IsEnabled) { continue; } migCommand.Response += "{ \"Domain\" : \"" + migInterface.Domain + "\", \"IsConnected\" : \"" + migInterface.IsConnected + "\" },"; } if (homegenie.UpdateChecker != null && homegenie.UpdateChecker.IsUpdateAvailable) { migCommand.Response += "{ \"Domain\" : \"" + Domains.HomeGenie_UpdateChecker + "\", \"IsConnected\" : \"True\" }"; migCommand.Response += " ]"; } else { migCommand.Response = migCommand.Response.Substring(0, migCommand.Response.Length - 1) + " ]"; } // break; //TODO: should this be moved somewhere to MIG? case "Interfaces.Configure": switch (migCommand.GetOption(0)) { case "Hardware.SerialPorts": if (Environment.OSVersion.Platform == PlatformID.Unix) { var serialPorts = System.IO.Ports.SerialPort.GetPortNames(); var portList = new List <string>(); for (int p = serialPorts.Length - 1; p >= 0; p--) { if (serialPorts[p].Contains("/ttyS") || serialPorts[p].Contains("/ttyUSB")) { portList.Add(serialPorts[p]); } } if (Raspberry.Board.Current.IsRaspberryPi) { if (!portList.Contains("/dev/ttyAMA0")) { portList.Add("/dev/ttyAMA0"); // RaZberry } if (!portList.Contains("/dev/ttyACM0")) { portList.Add("/dev/ttyACM0"); // ZME_UZB1 } } migCommand.Response = JsonHelper.GetSimpleResponse(JsonConvert.SerializeObject(portList)); } else { var portNames = System.IO.Ports.SerialPort.GetPortNames(); migCommand.Response = JsonHelper.GetSimpleResponse(JsonConvert.SerializeObject(portNames)); } break; } break; case "System.Configure": if (migCommand.GetOption(0) == "Service.Restart") { Program.Quit(true); migCommand.Response = JsonHelper.GetSimpleResponse("OK"); } else if (migCommand.GetOption(0) == "UpdateManager.UpdatesList") { migCommand.Response = JsonConvert.SerializeObject(homegenie.UpdateChecker.RemoteUpdates); } else if (migCommand.GetOption(0) == "UpdateManager.Check") { homegenie.UpdateChecker.Check(); migCommand.Response = JsonHelper.GetSimpleResponse("OK"); } else if (migCommand.GetOption(0) == "UpdateManager.DownloadUpdate") { var resultMessage = "ERROR"; bool success = homegenie.UpdateChecker.DownloadUpdateFiles(); if (success) { if (homegenie.UpdateChecker.IsRestartRequired) { resultMessage = "RESTART"; } else { resultMessage = "OK"; } } migCommand.Response = JsonHelper.GetSimpleResponse(resultMessage); } else if (migCommand.GetOption(0) == "UpdateManager.InstallUpdate") //UpdateManager.InstallProgramsCommit") { string resultMessage = "OK"; if (!homegenie.UpdateChecker.InstallFiles()) { resultMessage = "ERROR"; } else { if (homegenie.UpdateChecker.IsRestartRequired) { resultMessage = "RESTART"; Utility.RunAsyncTask(() => { Thread.Sleep(2000); Program.Quit(true); }); } else { homegenie.LoadConfiguration(); homegenie.MigService.ClearWebCache(); homegenie.UpdateChecker.Check(); } } migCommand.Response = JsonHelper.GetSimpleResponse(resultMessage); } else if (migCommand.GetOption(0) == "HttpService.SetWebCacheEnabled") { if (migCommand.GetOption(1) == "1") { homegenie.MigService.IsWebCacheEnabled = true; homegenie.SystemConfiguration.MIGService.EnableWebCache = "true"; } else { homegenie.MigService.IsWebCacheEnabled = false; homegenie.SystemConfiguration.MIGService.EnableWebCache = "false"; } homegenie.SystemConfiguration.Update(); migCommand.Response = JsonHelper.GetSimpleResponse("OK"); } else if (migCommand.GetOption(0) == "HttpService.GetWebCacheEnabled") { migCommand.Response = JsonHelper.GetSimpleResponse(homegenie.MigService.IsWebCacheEnabled ? "1" : "0"); } else if (migCommand.GetOption(0) == "HttpService.GetPort") { migCommand.Response = JsonHelper.GetSimpleResponse(homegenie.SystemConfiguration.HomeGenie.ServicePort.ToString()); } else if (migCommand.GetOption(0) == "HttpService.SetPort") { try { homegenie.SystemConfiguration.HomeGenie.ServicePort = int.Parse(migCommand.GetOption(1)); homegenie.SystemConfiguration.Update(); } catch { } } else if (migCommand.GetOption(0) == "Statistics.GetStatisticsDatabaseMaximumSize") { migCommand.Response = JsonHelper.GetSimpleResponse(homegenie.SystemConfiguration.HomeGenie.Statistics.MaxDatabaseSizeMBytes.ToString()); } else if (migCommand.GetOption(0) == "Statistics.SetStatisticsDatabaseMaximumSize") { try { homegenie.SystemConfiguration.HomeGenie.Statistics.MaxDatabaseSizeMBytes = int.Parse(migCommand.GetOption(1)); homegenie.SystemConfiguration.Update(); } catch { } } else if (migCommand.GetOption(0) == "SystemLogging.DownloadCsv") { string csvlog = ""; string logpath = Path.Combine("log", "homegenie.log"); if (migCommand.GetOption(1) == "1") { logpath = Path.Combine("log", "homegenie.log.bak"); } if (File.Exists(logpath)) { using (var fs = new FileStream(logpath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) using (var sr = new StreamReader(fs, Encoding.Default)) { csvlog = sr.ReadToEnd(); } } (request.Context as HttpListenerContext).Response.AddHeader("Content-Disposition", "attachment;filename=homegenie_log_" + migCommand.GetOption(1) + ".csv"); migCommand.Response = csvlog; } else if (migCommand.GetOption(0) == "SystemLogging.Enable") { SystemLogger.Instance.OpenLog(); homegenie.SystemConfiguration.HomeGenie.EnableLogFile = "true"; homegenie.SystemConfiguration.Update(); } else if (migCommand.GetOption(0) == "SystemLogging.Disable") { SystemLogger.Instance.CloseLog(); homegenie.SystemConfiguration.HomeGenie.EnableLogFile = "false"; homegenie.SystemConfiguration.Update(); } else if (migCommand.GetOption(0) == "SystemLogging.IsEnabled") { migCommand.Response = JsonHelper.GetSimpleResponse((homegenie.SystemConfiguration.HomeGenie.EnableLogFile.ToLower().Equals("true") ? "1" : "0")); } else if (migCommand.GetOption(0) == "Security.SetPassword") { // password only for now, with fixed user login 'admin' string pass = migCommand.GetOption(1) == "" ? "" : MIG.Utility.Encryption.SHA1.GenerateHashString(migCommand.GetOption(1)); homegenie.MigService.SetWebServicePassword(pass); homegenie.SystemConfiguration.HomeGenie.UserPassword = pass; // regenerate encrypted files homegenie.SystemConfiguration.Update(); homegenie.UpdateModulesDatabase(); } else if (migCommand.GetOption(0) == "Security.ClearPassword") { homegenie.MigService.SetWebServicePassword(""); homegenie.SystemConfiguration.HomeGenie.UserPassword = ""; // regenerate encrypted files homegenie.SystemConfiguration.Update(); homegenie.UpdateModulesDatabase(); } else if (migCommand.GetOption(0) == "Security.HasPassword") { migCommand.Response = JsonHelper.GetSimpleResponse((homegenie.SystemConfiguration.HomeGenie.UserPassword != "" ? "1" : "0")); } else if (migCommand.GetOption(0) == "System.ConfigurationRestore") { // file uploaded by user string archivename = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "tmp", "homegenie_restore_config.zip"); if (!Directory.Exists("tmp")) { Directory.CreateDirectory("tmp"); } try { var downloadedMessageInfo = new DirectoryInfo("tmp"); foreach (var file in downloadedMessageInfo.GetFiles()) { file.Delete(); } foreach (DirectoryInfo directory in downloadedMessageInfo.GetDirectories()) { directory.Delete(true); } } catch { } // try { var encoding = (request.Context as HttpListenerContext).Request.ContentEncoding; string boundary = MIG.Gateways.WebServiceUtility.GetBoundary((request.Context as HttpListenerContext).Request.ContentType); MIG.Gateways.WebServiceUtility.SaveFile(encoding, boundary, request.InputStream, archivename); Utility.UncompressZip(archivename, Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "tmp")); File.Delete(archivename); } catch { } } else if (migCommand.GetOption(0) == "System.ConfigurationRestoreS1") { var serializer = new XmlSerializer(typeof(List <ProgramBlock>)); var reader = new StreamReader(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "tmp", "programs.xml")); var newProgramsData = (List <ProgramBlock>)serializer.Deserialize(reader); reader.Close(); var newProgramList = new List <ProgramBlock>(); foreach (ProgramBlock program in newProgramsData) { if (program.Address >= ProgramEngine.USER_SPACE_PROGRAMS_START) { ProgramBlock p = new ProgramBlock(); p.Address = program.Address; p.Name = program.Name; p.Description = program.Description; newProgramList.Add(p); } } newProgramList.Sort(delegate(ProgramBlock p1, ProgramBlock p2) { string c1 = p1.Address.ToString(); string c2 = p2.Address.ToString(); return(c1.CompareTo(c2)); }); migCommand.Response = JsonConvert.SerializeObject(newProgramList); } else if (migCommand.GetOption(0) == "System.ConfigurationRestoreS2") { var serializer = new XmlSerializer(typeof(List <Group>)); var reader = new StreamReader(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "tmp", "automationgroups.xml")); var automationGroups = (List <Group>)serializer.Deserialize(reader); reader.Close(); // foreach (var automationGroup in automationGroups) { if (homegenie.AutomationGroups.Find(g => g.Name == automationGroup.Name) == null) { homegenie.AutomationGroups.Add(automationGroup); } } // homegenie.UpdateGroupsDatabase("Automation"); // //File.Copy(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "tmp", "automationgroups.xml"), "./automationgroups.xml", true); File.Copy(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "tmp", "groups.xml"), Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "groups.xml"), true); File.Copy(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "tmp", "lircconfig.xml"), Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "lircconfig.xml"), true); File.Copy(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "tmp", "modules.xml"), Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "modules.xml"), true); File.Copy(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "tmp", "scheduler.xml"), Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "scheduler.xml"), true); File.Copy(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "tmp", "systemconfig.xml"), Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "systemconfig.xml"), true); // homegenie.LoadConfiguration(); // // Restore automation programs string selectedPrograms = migCommand.GetOption(1); serializer = new XmlSerializer(typeof(List <ProgramBlock>)); reader = new StreamReader(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "tmp", "programs.xml")); var newProgramsData = (List <ProgramBlock>)serializer.Deserialize(reader); reader.Close(); foreach (var program in newProgramsData) { var currentProgram = homegenie.ProgramEngine.Programs.Find(p => p.Address == program.Address); program.IsRunning = false; // Only restore user space programs if (selectedPrograms.Contains("," + program.Address.ToString() + ",") && program.Address >= ProgramEngine.USER_SPACE_PROGRAMS_START) { int oldPid = program.Address; if (currentProgram == null) { var newPid = ((currentProgram != null && currentProgram.Address == program.Address) ? homegenie.ProgramEngine.GeneratePid() : program.Address); try { File.Copy(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "tmp", "programs", program.Address + ".dll"), Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "programs", newPid + ".dll"), true); } catch { } program.Address = newPid; homegenie.ProgramEngine.ProgramAdd(program); } else if (currentProgram != null) { homegenie.ProgramEngine.ProgramRemove(currentProgram); try { File.Copy(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "tmp", "programs", program.Address + ".dll"), Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "programs", program.Address + ".dll"), true); } catch { } homegenie.ProgramEngine.ProgramAdd(program); } // Restore Arduino program folder ... // TODO: this is untested yet... if (program.Type.ToLower() == "arduino") { string sourceFolder = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "tmp", "programs", "arduino", oldPid.ToString()); string arduinoFolder = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "programs", "arduino", program.Address.ToString()); if (Directory.Exists(arduinoFolder)) { Directory.Delete(arduinoFolder, true); } Directory.CreateDirectory(arduinoFolder); foreach (string newPath in Directory.GetFiles(sourceFolder)) { File.Copy(newPath, newPath.Replace(sourceFolder, arduinoFolder), true); } } } else if (currentProgram != null && program.Address < ProgramEngine.USER_SPACE_PROGRAMS_START) { // Only restore Enabled/Disabled status of system programs currentProgram.IsEnabled = program.IsEnabled; } } // homegenie.UpdateProgramsDatabase(); // // regenerate encrypted files homegenie.UpdateModulesDatabase(); homegenie.SystemConfiguration.Update(); } else if (migCommand.GetOption(0) == "System.ConfigurationReset") { homegenie.RestoreFactorySettings(); } else if (migCommand.GetOption(0) == "System.ConfigurationBackup") { homegenie.BackupCurrentSettings(); (request.Context as HttpListenerContext).Response.Redirect("/hg/html/homegenie_backup_config.zip"); } else if (migCommand.GetOption(0) == "System.ConfigurationLoad") { homegenie.LoadConfiguration(); } break; case "Modules.Get": try { var module = homegenie.Modules.Find(m => m.Domain == migCommand.GetOption(0) && m.Address == migCommand.GetOption(1)); migCommand.Response = Utility.Module2Json(module, false); } catch (Exception ex) { migCommand.Response = JsonHelper.GetSimpleResponse("ERROR: \n" + ex.Message + "\n\n" + ex.StackTrace); } break; case "Modules.List": try { homegenie.modules_Sort(); migCommand.Response = homegenie.GetJsonSerializedModules(migCommand.GetOption(0).ToLower() == "short"); } catch (Exception ex) { migCommand.Response = JsonHelper.GetSimpleResponse("ERROR: \n" + ex.Message + "\n\n" + ex.StackTrace); } break; case "Modules.RoutingReset": try { for (int m = 0; m < homegenie.Modules.Count; m++) { homegenie.Modules[m].RoutingNode = ""; } migCommand.Response = JsonHelper.GetSimpleResponse("OK"); } catch (Exception ex) { migCommand.Response = JsonHelper.GetSimpleResponse("ERROR: \n" + ex.Message + "\n\n" + ex.StackTrace); } break; case "Modules.Save": string body = new StreamReader(request.InputStream).ReadToEnd(); var newModules = JsonConvert.DeserializeObject(body) as JArray; for (int i = 0; i < newModules.Count; i++) { try { var module = homegenie.Modules.Find(m => m.Address == newModules[i]["Address"].ToString() && m.Domain == newModules[i]["Domain"].ToString()); module.Name = newModules[i]["Name"].ToString(); // try { module.DeviceType = (MIG.ModuleTypes)Enum.Parse(typeof(MIG.ModuleTypes), newModules[i]["DeviceType"].ToString(), true); } catch { // TODO: check what's wrong here... } // var moduleProperties = newModules[i]["Properties"] as JArray; for (int p = 0; p < moduleProperties.Count; p++) { string propertyName = moduleProperties[p]["Name"].ToString(); string propertyValue = moduleProperties[p]["Value"].ToString(); ModuleParameter parameter = null; parameter = module.Properties.Find(delegate(ModuleParameter mp) { return(mp.Name == propertyName); }); // if (propertyName == ModuleParameters.MODPAR_VIRTUALMETER_WATTS) { try { propertyValue = double.Parse(propertyValue.Replace(",", "."), System.Globalization.CultureInfo.InvariantCulture).ToString(); } catch { propertyValue = "0"; } } // if (parameter == null) { module.Properties.Add(new ModuleParameter() { Name = propertyName, Value = propertyValue }); } else { if (moduleProperties[p]["NeedsUpdate"] != null && moduleProperties[p]["NeedsUpdate"].ToString() == "true") { parameter.Value = propertyValue; } } } } catch (Exception) { //TODO: notify exception? } } homegenie.UpdateModulesDatabase();//write modules break; case "Modules.Update": string streamContent = new StreamReader(request.InputStream).ReadToEnd(); var newModule = JsonConvert.DeserializeObject <Module>(streamContent); var currentModule = homegenie.Modules.Find(p => p.Domain == newModule.Domain && p.Address == newModule.Address); // if (currentModule == null) { homegenie.Modules.Add(newModule); } else { currentModule.Name = newModule.Name; currentModule.Description = newModule.Description; currentModule.DeviceType = newModule.DeviceType; foreach (var newParameter in newModule.Properties) { var currentParameter = currentModule.Properties.Find(mp => mp.Name == newParameter.Name); if (currentParameter == null) { currentModule.Properties.Add(newParameter); } else if (newParameter.NeedsUpdate) { currentParameter.Value = newParameter.Value; } } // look for deleted properties var deletedParameters = new List <ModuleParameter>(); foreach (var parameter in currentModule.Properties) { var currentParameter = newModule.Properties.Find(mp => mp.Name == parameter.Name); if (currentParameter == null) { deletedParameters.Add(parameter); } } foreach (var parameter in deletedParameters) { currentModule.Properties.Remove(parameter); } deletedParameters.Clear(); } // homegenie.UpdateModulesDatabase(); break; case "Modules.Delete": var deletedModule = homegenie.Modules.Find(m => m.Domain == migCommand.GetOption(0) && m.Address == migCommand.GetOption(1)); if (deletedModule != null) { homegenie.Modules.Remove(deletedModule); } migCommand.Response = JsonHelper.GetSimpleResponse("OK"); // homegenie.UpdateModulesDatabase(); break; case "Groups.ModulesList": var theGroup = homegenie.Groups.Find(z => z.Name.ToLower() == migCommand.GetOption(0).Trim().ToLower()); if (theGroup != null) { string jsonmodules = "["; for (int m = 0; m < theGroup.Modules.Count; m++) { var groupModule = homegenie.Modules.Find(mm => mm.Domain == theGroup.Modules[m].Domain && mm.Address == theGroup.Modules[m].Address); if (groupModule != null) { jsonmodules += Utility.Module2Json(groupModule, false) + ",\n"; } } jsonmodules = jsonmodules.TrimEnd(',', '\n'); jsonmodules += "]"; migCommand.Response = jsonmodules; } break; case "Groups.List": try { migCommand.Response = JsonConvert.SerializeObject(homegenie.GetGroups(migCommand.GetOption(0))); } catch (Exception ex) { migCommand.Response = JsonHelper.GetSimpleResponse("ERROR: \n" + ex.Message + "\n\n" + ex.StackTrace); } break; case "Groups.Rename": string oldName = migCommand.GetOption(1); string newName = new StreamReader(request.InputStream).ReadToEnd(); var currentGroup = homegenie.GetGroups(migCommand.GetOption(0)).Find(g => g.Name == oldName); var newGroup = homegenie.GetGroups(migCommand.GetOption(0)).Find(g => g.Name == newName); // ensure that the new group name is not already defined if (newGroup == null && currentGroup != null) { currentGroup.Name = newName; homegenie.UpdateGroupsDatabase(migCommand.GetOption(0)); //cmd.response = JsonHelper.GetSimpleResponse("OK"); } else { migCommand.Response = JsonHelper.GetSimpleResponse("New name already in use."); } break; case "Groups.Sort": using (var reader = new StreamReader(request.InputStream)) { var newGroupList = new List <Group>(); string[] newPositionOrder = reader.ReadToEnd().Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries); for (int i = 0; i < newPositionOrder.Length; i++) { newGroupList.Add(homegenie.GetGroups(migCommand.GetOption(0))[int.Parse(newPositionOrder[i])]); } homegenie.GetGroups(migCommand.GetOption(0)).Clear(); homegenie.GetGroups(migCommand.GetOption(0)).RemoveAll(g => true); homegenie.GetGroups(migCommand.GetOption(0)).AddRange(newGroupList); homegenie.UpdateGroupsDatabase(migCommand.GetOption(0)); } // try { migCommand.Response = JsonConvert.SerializeObject(homegenie.GetGroups(migCommand.GetOption(0))); } catch (Exception ex) { migCommand.Response = JsonHelper.GetSimpleResponse("ERROR: \n" + ex.Message + "\n\n" + ex.StackTrace); } break; case "Groups.SortModules": using (var reader = new StreamReader(request.InputStream)) { string groupName = migCommand.GetOption(1); Group sortGroup = null; try { sortGroup = homegenie.GetGroups(migCommand.GetOption(0)).Find(zn => zn.Name == groupName); } catch { } // if (sortGroup != null) { var newModulesReference = new List <ModuleReference>(); string[] newPositionOrder = reader.ReadToEnd().Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries); for (int i = 0; i < newPositionOrder.Length; i++) { newModulesReference.Add(sortGroup.Modules[int.Parse(newPositionOrder[i])]); } sortGroup.Modules.Clear(); sortGroup.Modules = newModulesReference; homegenie.UpdateGroupsDatabase(migCommand.GetOption(0)); } } try { migCommand.Response = JsonConvert.SerializeObject(homegenie.GetGroups(migCommand.GetOption(0))); } catch (Exception ex) { migCommand.Response = JsonHelper.GetSimpleResponse("ERROR: \n" + ex.Message + "\n\n" + ex.StackTrace); } break; case "Groups.Add": string newGroupName = new StreamReader(request.InputStream).ReadToEnd(); homegenie.GetGroups(migCommand.GetOption(0)).Add(new Group() { Name = newGroupName }); homegenie.UpdateGroupsDatabase(migCommand.GetOption(0));//write groups break; case "Groups.Delete": string deletedGroupName = new StreamReader(request.InputStream).ReadToEnd(); Group deletedGroup = null; try { deletedGroup = homegenie.GetGroups(migCommand.GetOption(0)).Find(zn => zn.Name == deletedGroupName); } catch { } // if (deletedGroup != null) { homegenie.GetGroups(migCommand.GetOption(0)).Remove(deletedGroup); homegenie.UpdateGroupsDatabase(migCommand.GetOption(0));//write groups if (migCommand.GetOption(0).ToLower() == "automation") { var groupPrograms = homegenie.ProgramEngine.Programs.FindAll(p => p.Group.ToLower() == deletedGroup.Name.ToLower()); if (groupPrograms != null) { // delete group association from programs foreach (ProgramBlock program in groupPrograms) { program.Group = ""; } } } } break; case "Groups.Save": string jsonGroups = new StreamReader(request.InputStream).ReadToEnd(); var newGroups = JsonConvert.DeserializeObject <List <Group> >(jsonGroups); for (int i = 0; i < newGroups.Count; i++) { try { var group = homegenie.Groups.Find(z => z.Name == newGroups[i].Name); group.Modules.Clear(); group.Modules = newGroups[i].Modules; } catch { } } homegenie.UpdateGroupsDatabase(migCommand.GetOption(0));//write groups break; case "Widgets.List": List <string> widgetsList = new List <string>(); var groups = Directory.GetDirectories(widgetBasePath); for (int d = 0; d < groups.Length; d++) { var categories = Directory.GetDirectories(groups[d]); for (int c = 0; c < categories.Length; c++) { var widgets = Directory.GetFiles(categories[c], "*.js"); var group = groups[d].Replace(widgetBasePath, "").Substring(1); var category = categories[c].Replace(groups[d], "").Substring(1); for (int w = 0; w < widgets.Length; w++) { widgetsList.Add(group + "/" + category + "/" + Path.GetFileNameWithoutExtension(widgets[w])); } } } migCommand.Response = JsonConvert.SerializeObject(widgetsList); break; case "Widgets.Add": { string response = "ERROR"; string widgetPath = migCommand.GetOption(0); // eg. homegenie/generic/dimmer string[] widgetParts = widgetPath.Split('/'); widgetParts[0] = new String(widgetParts[0].Where(Char.IsLetter).ToArray()).ToLower(); widgetParts[1] = new String(widgetParts[1].Where(Char.IsLetter).ToArray()).ToLower(); widgetParts[2] = new String(widgetParts[2].Where(Char.IsLetter).ToArray()).ToLower(); if (!String.IsNullOrWhiteSpace(widgetParts[0]) && !String.IsNullOrWhiteSpace(widgetParts[1]) && !String.IsNullOrWhiteSpace(widgetParts[2])) { string filePath = Path.Combine(widgetBasePath, widgetParts[0], widgetParts[1]); if (!Directory.Exists(filePath)) { Directory.CreateDirectory(filePath); } // copy widget template into the new widget var htmlFile = Path.Combine(filePath, widgetParts[2] + ".html"); var jsFile = Path.Combine(filePath, widgetParts[2] + ".js"); if (!File.Exists(htmlFile) && !File.Exists(jsFile)) { File.Copy(Path.Combine(widgetBasePath, "template.html"), htmlFile); File.Copy(Path.Combine(widgetBasePath, "template.js"), jsFile); response = "OK"; } } migCommand.Response = JsonHelper.GetSimpleResponse(response); } break; case "Widgets.Save": { string response = "ERROR"; string widgetData = new StreamReader(request.InputStream).ReadToEnd(); string fileType = migCommand.GetOption(0); string widgetPath = migCommand.GetOption(1); // eg. homegenie/generic/dimmer string[] widgetParts = widgetPath.Split('/'); string filePath = Path.Combine(widgetBasePath, widgetParts[0], widgetParts[1]); if (!Directory.Exists(filePath)) { Directory.CreateDirectory(filePath); } switch (fileType) { // html/javascript source case "html": case "js": using (TextWriter widgetWriter = new StreamWriter(Path.Combine(filePath, widgetParts[2] + "." + fileType))) { widgetWriter.Write(widgetData); } response = "OK"; break; // style sheet file case "css": break; // locale file case "json": break; // image file case "jpg": case "png": case "gif": break; } migCommand.Response = JsonHelper.GetSimpleResponse(response); } break; case "Widgets.Delete": { string response = "ERROR"; string widgetPath = migCommand.GetOption(0); // eg. homegenie/generic/dimmer string[] widgetParts = widgetPath.Split('/'); string filePath = Path.Combine(widgetBasePath, widgetParts[0], widgetParts[1], widgetParts[2] + "."); if (File.Exists(filePath + "html")) { File.Delete(filePath + "html"); response = "OK"; } if (File.Exists(filePath + "js")) { File.Delete(filePath + "js"); response = "OK"; } migCommand.Response = JsonHelper.GetSimpleResponse(response); } break; case "Widgets.Export": { string widgetPath = migCommand.GetOption(0); // eg. homegenie/generic/dimmer string[] widgetParts = widgetPath.Split('/'); string widgetBundle = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "tmp", "export", widgetPath.Replace('/', '_') + ".zip"); if (File.Exists(widgetBundle)) { File.Delete(widgetBundle); } else if (!Directory.Exists(Path.GetDirectoryName(widgetBundle))) { Directory.CreateDirectory(Path.GetDirectoryName(widgetBundle)); } string inputPath = Path.Combine(widgetBasePath, widgetParts[0], widgetParts[1]); string outputPath = Path.Combine(widgetParts[0], widgetParts[1]); string infoFilePath = Path.Combine(inputPath, "widget.info"); File.WriteAllText(infoFilePath, "HomeGenie exported widget."); Utility.AddFileToZip(widgetBundle, infoFilePath, "widget.info"); Utility.AddFileToZip(widgetBundle, Path.Combine(inputPath, widgetParts[2] + ".html"), Path.Combine(outputPath, widgetParts[2] + ".html")); Utility.AddFileToZip(widgetBundle, Path.Combine(inputPath, widgetParts[2] + ".js"), Path.Combine(outputPath, widgetParts[2] + ".js")); // byte[] bundleData = File.ReadAllBytes(widgetBundle); (request.Context as HttpListenerContext).Response.AddHeader("Content-Disposition", "attachment; filename=\"" + widgetPath.Replace('/', '_') + ".zip\""); (request.Context as HttpListenerContext).Response.OutputStream.Write(bundleData, 0, bundleData.Length); } break; case "Widgets.Import": { var encoding = (request.Context as HttpListenerContext).Request.ContentEncoding; string boundary = MIG.Gateways.WebServiceUtility.GetBoundary((request.Context as HttpListenerContext).Request.ContentType); string archiveFile = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "tmp", "import_widget.zip"); string importPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "tmp", "import"); if (Directory.Exists(importPath)) { Directory.Delete(importPath, true); } MIG.Gateways.WebServiceUtility.SaveFile(encoding, boundary, request.InputStream, archiveFile); // TODO: should extract to temporary folder and look for widget.info data file before copying anything List <string> extractedFiles = Utility.UncompressZip(archiveFile, importPath); if (File.Exists(Path.Combine(importPath, "widget.info"))) { foreach (string f in extractedFiles) { if (f.EndsWith(".html") || f.EndsWith(".js")) { string destFolder = Path.Combine(widgetBasePath, Path.GetDirectoryName(f)); if (!Directory.Exists(destFolder)) { Directory.CreateDirectory(destFolder); } File.Copy(Path.Combine(importPath, f), Path.Combine(widgetBasePath, f), true); } } //migCommand.Response = JsonHelper.GetSimpleResponse("OK"); } else { //migCommand.Response = JsonHelper.GetSimpleResponse("ERROR"); } } break; case "Widgets.Parse": { string widgetData = new StreamReader(request.InputStream).ReadToEnd(); var parser = new JavaScriptParser(); try { migCommand.Response = JsonHelper.GetSimpleResponse("OK"); parser.Parse(widgetData); } catch (Jint.Parser.ParserException e) { migCommand.Response = JsonHelper.GetSimpleResponse("ERROR (" + e.LineNumber + "," + e.Column + "): " + e.Description); } } break; } }
public ObjectInstance Construct(JsValue[] arguments) { var argCount = arguments.Length; string p = ""; string body = ""; if (argCount == 1) { body = TypeConverter.ToString(arguments[0]); } else if (argCount > 1) { var firstArg = arguments[0]; p = TypeConverter.ToString(firstArg); for (var k = 1; k < argCount - 1; k++) { var nextArg = arguments[k]; p += "," + TypeConverter.ToString(nextArg); } body = TypeConverter.ToString(arguments[argCount-1]); } var parameters = this.ParseArgumentNames(p); var parser = new JavaScriptParser(); FunctionExpression function; try { var functionExpression = "function(" + p + ") { " + body + "}"; function = parser.ParseFunctionExpression(functionExpression); } catch (ParserException) { throw new JavaScriptException(Engine.SyntaxError); } // todo: check if there is not a way to use the FunctionExpression directly instead of creating a FunctionDeclaration var functionObject = new ScriptFunctionInstance( Engine, new FunctionDeclaration { Type = SyntaxNodes.FunctionDeclaration, Body = new BlockStatement { Type = SyntaxNodes.BlockStatement, Body = new [] { function.Body } }, Parameters = parameters.Select(x => new Identifier { Type = SyntaxNodes.Identifier, Name = x }).ToArray(), FunctionDeclarations = function.FunctionDeclarations, VariableDeclarations = function.VariableDeclarations }, LexicalEnvironment.NewDeclarativeEnvironment(Engine, Engine.ExecutionContext.LexicalEnvironment), function.Strict ) { Extensible = true }; return functionObject; }
public static Dictionary<string, object> JsSeriaize(string js) { var parser = new JavaScriptParser(); var program = parser.Parse(js); return JsObjectSerialize(program) as Dictionary<string, object>; }
/// <summary> /// Import entry from javascript property /// </summary> /// <returns></returns> public static bool ImportB(string jsPath) { if (!File.Exists(jsPath)) { return(false); } // Parse 'javascript' file string rawString = File.ReadAllText(jsPath); JavaScriptParser parser = new JavaScriptParser(false); Program program = parser.Parse(rawString); ExpressionStatement expression = program.Body.First() as ExpressionStatement; AssignmentExpression assignment = expression.Expression as AssignmentExpression; ArrayExpression topArray = assignment.Right as ArrayExpression; // Rebuild entry foreach (ObjectExpression tokenObject in topArray.Elements) { Property nameProperty = PropertyFromObject(tokenObject, Config.JsNameKey); Property keywordProperty = PropertyFromObject(tokenObject, Config.JsKeywordKey); Property tagProperty = PropertyFromObject(tokenObject, Config.JsTagKey); string name = (nameProperty == null) ? null : (nameProperty.Value as Literal).Value as string; List <string> keywords = StringsFromProperty(keywordProperty); List <string> tags = StringsFromProperty(tagProperty); Entry tokenEntry = new Entry(); if (name != null) { tokenEntry.Name = name; } if (keywords.Count > 0) { tokenEntry.Keywords = keywords.OrderBy(x => x).ToList(); } if (tags.Count > 0) { tokenEntry.Tags = tags.OrderBy(x => x).ToList(); } Entry overlappedEntry = Core.Meta.Entries.ToList().Find(x => x.Name == tokenEntry.Name); if (overlappedEntry == null) { tokenEntry.ID = Core.PushID(); Core.Meta.Entries.Add(tokenEntry); } else { overlappedEntry.Tags.AddRange(tokenEntry.Tags); overlappedEntry.Tags = new List <string>(overlappedEntry.Tags.Distinct().OrderBy(x => x)); overlappedEntry.Keywords.AddRange(tokenEntry.Keywords); overlappedEntry.Keywords = new List <string>(overlappedEntry.Keywords.Distinct()); } } return(true); Property PropertyFromObject(ObjectExpression @object, string key) { return(@object.Properties.First(x => (x.Key as Identifier).Name == key)); } List <string> StringsFromProperty(Property property) { return((property == null) ? new List <string>() : (property.Value as ArrayExpression).Elements .ToList() .ConvertAll(x => (x as Literal).Value as string)); } }
public void ThrowsErrorForDeepRecursionParsing() { var parser = new JavaScriptParser("if ((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((true)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))) { } "); Assert.Throws <ParserException>(() => parser.ParseScript()); }
public void ThrowsErrorForInvalidRegExFlags() { var parser = new JavaScriptParser("/'/o//'///C//ÿ"); Assert.Throws <ParserException>(() => parser.ParseScript()); }
public void CanParseDot(string script) { var parser = new JavaScriptParser(script); Assert.Throws <ParserException>(() => parser.ParseScript()); }
public void CanParseInvalidCurly() { var parser = new JavaScriptParser("if (1}=1) eval('1');"); Assert.Throws <ParserException>(() => parser.ParseScript()); }
public void ExecuteTestCase(string fixture) { var options = new ParserOptions { Range = true, Loc = true, Tokens = true }; string treeFilePath, failureFilePath, moduleFilePath; var jsFilePath = Path.Combine(GetFixturesPath(), "Fixtures", fixture); if (jsFilePath.EndsWith(".source.js")) { treeFilePath = Path.Combine(Path.GetDirectoryName(jsFilePath), Path.GetFileNameWithoutExtension((Path.GetFileNameWithoutExtension(jsFilePath)))) + ".tree.json"; failureFilePath = Path.Combine(Path.GetDirectoryName(jsFilePath), Path.GetFileNameWithoutExtension((Path.GetFileNameWithoutExtension(jsFilePath)))) + ".failure.json"; moduleFilePath = Path.Combine(Path.GetDirectoryName(jsFilePath), Path.GetFileNameWithoutExtension((Path.GetFileNameWithoutExtension(jsFilePath)))) + ".module.json"; } else { treeFilePath = Path.Combine(Path.GetDirectoryName(jsFilePath), Path.GetFileNameWithoutExtension(jsFilePath)) + ".tree.json"; failureFilePath = Path.Combine(Path.GetDirectoryName(jsFilePath), Path.GetFileNameWithoutExtension(jsFilePath)) + ".failure.json"; moduleFilePath = Path.Combine(Path.GetDirectoryName(jsFilePath), Path.GetFileNameWithoutExtension(jsFilePath)) + ".module.json"; } // Convert to LF to match the number of chars the parser finds, but some tests expect to check Windows // TODO should be based on .gitattributes var script = File.ReadAllText(jsFilePath); if (!jsFilePath.EndsWith("primary\\literal\\string\\migrated_0017.js") && !jsFilePath.EndsWith("expression\\binary\\multiline_string_literal.js")) { script = script.Replace(Environment.NewLine, "\n"); } if (jsFilePath.EndsWith(".source.js")) { var parser = new JavaScriptParser(script); var program = parser.ParseScript(); var source = program.Body.First().As <VariableDeclaration>().Declarations.First().As <VariableDeclarator>().Init.As <Literal>().StringValue; script = source; } string expected = ""; bool invalid = false; var filename = Path.GetFileNameWithoutExtension(jsFilePath); var isModule = filename.Contains("module") || filename.Contains("export") || filename.Contains("import"); if (!filename.Contains(".module")) { isModule &= !jsFilePath.Contains("dynamic-import") && !jsFilePath.Contains("script"); } var sourceType = isModule ? SourceType.Module : SourceType.Script; if (File.Exists(moduleFilePath)) { sourceType = SourceType.Module; expected = File.ReadAllText(moduleFilePath); } else if (File.Exists(treeFilePath)) { expected = File.ReadAllText(treeFilePath); } else if (File.Exists(failureFilePath)) { invalid = true; expected = File.ReadAllText(failureFilePath); } else { // cannot compare return; } invalid |= filename.Contains("error") || (filename.Contains("invalid") && !filename.Contains("invalid-yield-object-")); if (!invalid) { options.Tolerant = true; var actual = ParseAndFormat(sourceType, script, options); Assert.True(CompareTrees(actual, expected), jsFilePath); } else { options.Tolerant = false; // TODO: check the accuracy of the message and of the location Assert.Throws <ParserException>(() => ParseAndFormat(sourceType, script, options)); } }
public Engine Execute(string source, ParserOptions parserOptions) { var parser = new JavaScriptParser(); return Execute(parser.Parse(source, parserOptions)); }
public ObjectInstance Construct(JsValue[] arguments, JsValue newTarget) { var argCount = arguments.Length; string p = ""; string body = ""; if (argCount == 1) { body = TypeConverter.ToString(arguments[0]); } else if (argCount > 1) { var firstArg = arguments[0]; p = TypeConverter.ToString(firstArg); for (var k = 1; k < argCount - 1; k++) { var nextArg = arguments[k]; p += "," + TypeConverter.ToString(nextArg); } body = TypeConverter.ToString(arguments[argCount - 1]); } IFunction function; try { string functionExpression; if (argCount == 0) { functionExpression = "function f(){}"; } else { functionExpression = "function f("; if (p.IndexOf('/') != -1) { // ensure comments don't screw up things functionExpression += "\n" + p + "\n"; } else { functionExpression += p; } functionExpression += ")"; if (body.IndexOf('/') != -1) { // ensure comments don't screw up things functionExpression += "{\n" + body + "\n}"; } else { functionExpression += "{" + body + "}"; } } var parser = new JavaScriptParser(functionExpression, ParserOptions); function = (IFunction)parser.ParseScript().Body[0]; } catch (ParserException) { return(ExceptionHelper.ThrowSyntaxError <ObjectInstance>(_engine)); } var functionObject = new ScriptFunctionInstance( Engine, function, _engine.GlobalEnvironment, function.Strict); // the function is not actually a named function functionObject.SetFunctionName(_functionNameAnonymous, force: true); return(functionObject); }
public void ExecuteTestCase(string fixture) { var options = new ParserOptions { Range = true, Loc = true, Tokens = true, SourceType = SourceType.Script }; string treeFilePath, failureFilePath, moduleFilePath; var jsFilePath = Path.Combine(GetFixturesPath(), "Fixtures", fixture); if (jsFilePath.EndsWith(".source.js")) { treeFilePath = Path.Combine(Path.GetDirectoryName(jsFilePath), Path.GetFileNameWithoutExtension((Path.GetFileNameWithoutExtension(jsFilePath)))) + ".tree.json"; failureFilePath = Path.Combine(Path.GetDirectoryName(jsFilePath), Path.GetFileNameWithoutExtension((Path.GetFileNameWithoutExtension(jsFilePath)))) + ".failure.json"; moduleFilePath = Path.Combine(Path.GetDirectoryName(jsFilePath), Path.GetFileNameWithoutExtension((Path.GetFileNameWithoutExtension(jsFilePath)))) + ".module.json"; } else { treeFilePath = Path.Combine(Path.GetDirectoryName(jsFilePath), Path.GetFileNameWithoutExtension(jsFilePath)) + ".tree.json"; failureFilePath = Path.Combine(Path.GetDirectoryName(jsFilePath), Path.GetFileNameWithoutExtension(jsFilePath)) + ".failure.json"; moduleFilePath = Path.Combine(Path.GetDirectoryName(jsFilePath), Path.GetFileNameWithoutExtension(jsFilePath)) + ".module.json"; } // Convert to LF to match the number of chars the parser finds var script = File.ReadAllText(jsFilePath); script = script.Replace(Environment.NewLine, "\n"); if (jsFilePath.EndsWith(".source.js")) { var parser = new JavaScriptParser(script); var program = parser.ParseProgram(); var source = program.Body.First().As <VariableDeclaration>().Declarations.First().As <VariableDeclarator>().Init.As <Literal>().StringValue; script = source; } string expected = ""; bool invalid = false; var filename = Path.GetFileNameWithoutExtension(jsFilePath); var isModule = filename.Contains("module") || filename.Contains("export") || filename.Contains("import"); options.SourceType = isModule ? SourceType.Module : SourceType.Script; if (File.Exists(moduleFilePath)) { options.SourceType = SourceType.Module; expected = File.ReadAllText(moduleFilePath); } else if (File.Exists(treeFilePath)) { expected = File.ReadAllText(treeFilePath); } else if (File.Exists(failureFilePath)) { invalid = true; expected = File.ReadAllText(failureFilePath); } invalid |= filename.Contains("error") || filename.Contains("invalid"); if (!invalid) { options.Tolerant = true; var actual = ParseAndFormat(script, options); Assert.True(CompareTrees(actual, expected), jsFilePath); } else { options.Tolerant = false; // TODO: check the accuracy of the message and of the location Assert.Throws <ParserException>(() => ParseAndFormat(script, options)); } }
public void ShouldParseScriptFile(string file, string version, bool compareTrees) { const string prefix = "Escape.Tests.Scripts."; var assembly = Assembly.GetExecutingAssembly(); var scriptPath = prefix + file; var sw = new Stopwatch(); var tempFilePath = NodePath != null ? Path.GetTempFileName() : null; try { using (var stream = assembly.GetManifestResourceStream(scriptPath)) { Assert.True(stream != null, string.Format("Script resource '{0}' not found", scriptPath)); using (var sr = new StreamReader(stream)) { var source = sr.ReadToEnd(); sw.Reset(); sw.Start(); var parser = new JavaScriptParser(); var program = parser.Parse(source); var bsfp = new ByteSizeFormatProvider(); Console.WriteLine("Parsed {0} {1} ({3}) in {2} ms", file, version, sw.ElapsedMilliseconds, bsfp.Format("SZ1", source.Length, null)); Assert.NotNull(program); if (!compareTrees) { Console.WriteLine("WARNING! AST compairson skipped for {0} {1}.", file, version); return; } if (tempFilePath == null) { Console.WriteLine( "If Node.js is installed in the system path " + "then a more comprehensive test can be carried " + "out comparing Esprima's and Escape's AST."); return; } File.WriteAllText(tempFilePath, source); sw.Restart(); var esparseOutput = Esparse(tempFilePath); Console.WriteLine( "Esparse.js for {0} {1} took {2} ms, producing {3} of pretty-printed AST JSON", file, version, sw.ElapsedMilliseconds, bsfp.Format("SZ1", esparseOutput.Length, null)); var sb = new StringBuilder(esparseOutput.Length * 110 / 100); var esw = new StringWriter(sb); JsonEncoder.Encode(program, false, esw); esw.WriteLine(); Assert.Equal(esparseOutput.Length, sb.Length); Assert.True(esparseOutput == sb.ToString(), "AST JSON mismatch"); } } } finally { if (tempFilePath != null) { File.Delete(tempFilePath); } } }
public void ShouldSymbolPropertyKey() { var parser = new JavaScriptParser("var a = { [Symbol.iterator]: undefined }"); var program = parser.ParseScript(); }
public EngineConstructionBenchmark() { var parser = new JavaScriptParser("return [].length + ''.length"); _program = parser.ParseScript(); }
static void Main(string[] args) { bool show_tree = false; bool show_tokens = false; bool old = false; bool two_byte = false; string file_name = null; string input = null; System.Text.Encoding encoding = null; for (int i = 0; i < args.Length; ++i) { if (args[i].Equals("-tokens")) { show_tokens = true; continue; } else if (args[i].Equals("-two-byte")) { two_byte = true; continue; } else if (args[i].Equals("-old")) { old = true; continue; } else if (args[i].Equals("-tree")) { show_tree = true; continue; } else if (args[i].Equals("-input")) { input = args[++i]; } else if (args[i].Equals("-file")) { file_name = args[++i]; } else if (args[i].Equals("-encoding")) { ++i; encoding = Encoding.GetEncoding( args[i], new EncoderReplacementFallback("(unknown)"), new DecoderReplacementFallback("(error)")); if (encoding == null) { throw new Exception(@"Unknown encoding. Must be an Internet Assigned Numbers Authority (IANA) code page name. https://www.iana.org/assignments/character-sets/character-sets.xhtml"); } } } ICharStream str = null; if (input == null && file_name == null) { str = CharStreams.fromStream(System.Console.OpenStandardInput()); } else if (input != null) { str = CharStreams.fromString(input); } else if (file_name != null) { if (two_byte) { str = new TwoByteCharStream(file_name); } else if (old) { FileStream fs = new FileStream(file_name, FileMode.Open); str = new Antlr4.Runtime.AntlrInputStream(fs); } else if (encoding == null) { str = CharStreams.fromPath(file_name); } else { str = CharStreams.fromPath(file_name, encoding); } } var lexer = new JavaScriptLexer(str); if (show_tokens) { StringBuilder new_s = new StringBuilder(); for (int i = 0; ; ++i) { var ro_token = lexer.NextToken(); var token = (CommonToken)ro_token; token.TokenIndex = i; new_s.AppendLine(token.ToString()); if (token.Type == Antlr4.Runtime.TokenConstants.EOF) { break; } } System.Console.Error.WriteLine(new_s.ToString()); lexer.Reset(); } var tokens = new CommonTokenStream(lexer); var parser = new JavaScriptParser(tokens); var listener_lexer = new ErrorListener <int>(); var listener_parser = new ErrorListener <IToken>(); lexer.AddErrorListener(listener_lexer); parser.AddErrorListener(listener_parser); DateTime before = DateTime.Now; var tree = parser.program(); DateTime after = DateTime.Now; System.Console.Error.WriteLine("Time: " + (after - before)); if (listener_lexer.had_error || listener_parser.had_error) { System.Console.Error.WriteLine("Parse failed."); } else { System.Console.Error.WriteLine("Parse succeeded."); } if (show_tree) { System.Console.Error.WriteLine(tree.ToStringTree(parser)); } System.Environment.Exit(listener_lexer.had_error || listener_parser.had_error ? 1 : 0); }
/// <summary> /// https://tc39.es/ecma262/#sec-performeval /// </summary> public JsValue PerformEval(JsValue x, Realm callerRealm, bool strictCaller, bool direct) { if (!x.IsString()) { return(x); } var evalRealm = _realm; _engine._host.EnsureCanCompileStrings(callerRealm, evalRealm); var inFunction = false; var inMethod = false; var inDerivedConstructor = false; if (direct) { var thisEnvRec = _engine.ExecutionContext.GetThisEnvironment(); if (thisEnvRec is FunctionEnvironmentRecord functionEnvironmentRecord) { var F = functionEnvironmentRecord._functionObject; inFunction = true; inMethod = thisEnvRec.HasSuperBinding(); if (F._constructorKind == ConstructorKind.Derived) { inDerivedConstructor = true; } } } var parser = new JavaScriptParser(x.ToString(), ParserOptions); Script script = null; try { script = parser.ParseScript(strictCaller); } catch (ParserException e) { if (e.Description == Messages.InvalidLHSInAssignment) { ExceptionHelper.ThrowReferenceError(callerRealm, (string)null); } else { ExceptionHelper.ThrowSyntaxError(callerRealm, e.Message); } } var body = script.Body; if (body.Count == 0) { return(Undefined); } if (!inFunction) { // if body Contains NewTarget, throw a SyntaxError exception. } if (!inMethod) { // if body Contains SuperProperty, throw a SyntaxError exception. } if (!inDerivedConstructor) { // if body Contains SuperCall, throw a SyntaxError exception. } var strictEval = script.Strict || _engine._isStrict; var ctx = _engine.ExecutionContext; using (new StrictModeScope(strictEval)) { EnvironmentRecord lexEnv; EnvironmentRecord varEnv; PrivateEnvironmentRecord privateEnv; if (direct) { lexEnv = JintEnvironment.NewDeclarativeEnvironment(_engine, ctx.LexicalEnvironment); varEnv = ctx.VariableEnvironment; privateEnv = ctx.PrivateEnvironment; } else { lexEnv = JintEnvironment.NewDeclarativeEnvironment(_engine, evalRealm.GlobalEnv); varEnv = evalRealm.GlobalEnv; privateEnv = null; } if (strictEval) { varEnv = lexEnv; } // If ctx is not already suspended, suspend ctx. Engine.EnterExecutionContext(lexEnv, varEnv, evalRealm, privateEnv); try { Engine.EvalDeclarationInstantiation(script, varEnv, lexEnv, privateEnv, strictEval); var statement = new JintScript(script); var result = statement.Execute(_engine._activeEvaluationContext); var value = result.GetValueOrDefault(); if (result.Type == CompletionType.Throw) { var ex = new JavaScriptException(value).SetCallstack(_engine, result.Location); throw ex; } else { return(value); } } finally { Engine.LeaveExecutionContext(); } } }
public JsValue Call(JsValue thisObject, JsValue[] arguments, bool directCall) { if (arguments.At(0).Type != Types.String) { return arguments.At(0); } var code = TypeConverter.ToString(arguments.At(0)); try { var parser = new JavaScriptParser(StrictModeScope.IsStrictModeCode); var program = parser.Parse(code); using (new StrictModeScope(program.Strict)) { using (new EvalCodeScope()) { LexicalEnvironment strictVarEnv = null; try { if (!directCall) { Engine.EnterExecutionContext(Engine.GlobalEnvironment, Engine.GlobalEnvironment, Engine.Global); } if (StrictModeScope.IsStrictModeCode) { strictVarEnv = LexicalEnvironment.NewDeclarativeEnvironment(Engine, Engine.ExecutionContext.LexicalEnvironment); Engine.EnterExecutionContext(strictVarEnv, strictVarEnv, Engine.ExecutionContext.ThisBinding); } Engine.DeclarationBindingInstantiation(DeclarationBindingType.EvalCode, program.FunctionDeclarations, program.VariableDeclarations, this, arguments); var result = _engine.ExecuteStatement(program); if (result.Type == Completion.Throw) { throw new JavaScriptException(result.GetValueOrDefault()); } else { return result.GetValueOrDefault(); } } finally { if (strictVarEnv != null) { Engine.LeaveExecutionContext(); } if (!directCall) { Engine.LeaveExecutionContext(); } } } } } catch (ParserException) { throw new JavaScriptException(Engine.SyntaxError); } }
public ParseTree Parse(TextFile sourceFile, out TimeSpan parserTimeSpan) { if (sourceFile.Data == null) { return(null); } var errorHandler = new JavaScriptEsprimaErrorHandler(sourceFile) { Logger = Logger, Offset = Offset, OriginFile = OriginFile }; try { var parserOptions = new ParserOptions(sourceFile.FullName) { Range = true, Comment = true, Tolerant = true, ErrorHandler = errorHandler }; var parser = new JavaScriptParser(sourceFile.Data, parserOptions); var stopwatch = Stopwatch.StartNew(); Program ast = parser.ParseProgram(JavaScriptType == JavaScriptType.Strict); stopwatch.Stop(); parserTimeSpan = stopwatch.Elapsed; var scanner = new Scanner(sourceFile.Data, parserOptions); errorHandler.Scanner = scanner; errorHandler.Logger = DummyLogger.Instance; // Ignore errors on tokenization because of the first stage var comments = new Collections.List <Comment>(); stopwatch.Restart(); Token token; do { comments.AddRange(scanner.ScanComments()); try { token = scanner.Lex(); } catch (Exception ex) when(!(ex is ThreadAbortException)) { // TODO: handle the end of the stream without exception Logger.LogError(new ParsingException(sourceFile, ex)); break; } }while (token.Type != TokenType.EOF); stopwatch.Stop(); TimeSpan lexerTimeSpan = stopwatch.Elapsed; // TODO: store lexer time // TODO: comments handling without scanner, https://github.com/sebastienros/esprima-dotnet/issues/39 var result = new JavaScriptEsprimaParseTree(ast, comments); result.SourceFile = sourceFile; return(result); } catch (Exception ex) when(!(ex is ThreadAbortException)) { ParsingException exception = ex is ParserException parserException ? errorHandler.CreateException(parserException.Index, parserException.Message) : ex is ParsingException parsingException ? parsingException : new ParsingException(sourceFile, ex); Logger.LogError(exception); return(null); } }
public void ParseProgram() { var parser = new JavaScriptParser(files[FileName]); parser.ParseProgram(); }
public void Awake() { // Loading var engine = new Jint.Engine(); //var logic = new Interpreter(); Registers = new Dictionary <Type, Action <BlockBehaviour, KeyInputController> >(); Unregisters = new Dictionary <Type, Action <BlockBehaviour> >(); ModConsole.RegisterCommand("script", args => { var text = string.Join(" ", args); //var func = logic.PrepareScript(text); //logic.AddExtFunc(func, "print", (ctx, x) => { ModConsole.Log(x[0]?.ToString()); return null; }, true); //logic.SetScript(func); //var res = logic.ContinueScript(1000); Func <JsValue, JsValue[], JsValue> printCb = (thiz, x) => { ModConsole.Log(x[0]?.ToObject().ToString()); return(x[0]); }; JsValue curV = null; Func <JsValue, JsValue[], JsValue> irqv = (thiz, x) => { curV = x[0]; return(null); }; var script = new JavaScriptParser(text, Jint.Engine.DefaultParserOptions).ParseScript(); engine.SetValue("print", printCb); engine.SetValue("irqv", irqv); engine.SetScript(script); engine.Executor.OnLog = (x) => ModConsole.Log(x?.ToString()); bool cli = false; engine.Executor.OnNextStatement = () => { if (cli) { return; } cli = true; try { if (curV != null) { engine.Invoke(curV); } } finally { cli = false; } }; var res = engine.ContinueScript(1000); ModConsole.Log(res?.ToString()); }, "exec script"); ModConsole.RegisterCommand("cpuapi", args => { foreach (var line in SingleInstance <Blocks.Api.CpuApi> .Instance.GetHelp()) { ModConsole.Log(line); } }, "print cpu api list"); ModConsole.RegisterCommand("sensordbg", args => { DrawSensorDebug = args.Length < 1 ? false : args[0] == "true"; }, "print sensor debug points"); CpuBlock.Create(this); // These creator functions find corresponding block in game prefabs // and replace it with inheritor ExtLogicGate.Create(this); ExtAltimeterBlock.Create(this); ExtSpeedometerBlock.Create(this); ExtAnglometerBlock.Create(this); ExtSensorBlock.Create(this); ModConsole.Log($"Logic mod Awake"); Events.OnMachineSimulationToggle += Events_OnMachineSimulationToggle; LineMaterial = new Material(Shader.Find("Hidden/Internal-Colored")); LineMaterial.hideFlags = HideFlags.HideAndDontSave; LineMaterial.SetInt("_SrcBlend", (int)UnityEngine.Rendering.BlendMode.SrcAlpha); LineMaterial.SetInt("_DstBlend", (int)UnityEngine.Rendering.BlendMode.OneMinusSrcAlpha); LineMaterial.SetInt("_Cull", (int)UnityEngine.Rendering.CullMode.Off); LineMaterial.SetInt("_ZWrite", 0); Camera.onPostRender += DrawConnectingLines; Events.OnBlockInit += InitBlock; CpuInfoMessage = ModNetworking.CreateMessageType(new DataType[] { DataType.Block, DataType.ByteArray }); CpuLogMessage = ModNetworking.CreateMessageType(new DataType[] { DataType.Block, DataType.String }); ModNetworking.Callbacks[CpuInfoMessage] += (Action <Message>)((msg) => { Player localPlayer = Player.GetLocalPlayer(); if (msg == null || localPlayer == null || !localPlayer.IsHost) { return; } var block = msg.GetData(0) as Modding.Blocks.Block; if (!(block?.BlockScript is CpuBlock cpu)) { return; } if (block.Machine == localPlayer.Machine) { return; // don't read updates for MY machine! } cpu.AfterEdit_ServerRecv((byte[])msg.GetData(1)); }); ModNetworking.Callbacks[CpuLogMessage] += (Action <Message>)((msg) => { if (msg == null) { return; } var block = msg.GetData(0) as Modding.Blocks.Block; if (!(block?.BlockScript is CpuBlock cpu)) { return; } cpu.LogMessage((string)msg.GetData(1)); }); }
public void Process() { try { var parser = new JavaScriptParser(); var program = parser.Parse(OriginalString); var visitor = new RequireVisitor(); var result = visitor.Visit(program, RelativeFileName); var lines = GetScriptLines(OriginalString); var flattenedResults = result.GetFlattened(); var deps = flattenedResults .SelectMany(r => r.Dependencies) .Where(r => !r.Contains("!")) .Except(new List<string> { "require", "module", "exports" }); //Make existing relative paths relative to the Scripts folder var scriptPath = System.IO.Path.GetDirectoryName(RelativeFileName).Replace(@"\", "/") + "/"; deps = deps.Select(r => { if (r.StartsWith(".")) { r = scriptPath + r; } return r; }); //Expand named paths relative to the scripts folder Dependencies = deps.Select(r => ExpandPaths(r, configuration)).ToList(); var shim = this.GetShim(RelativeFileName); if (shim != null) { Dependencies.AddRange(shim.Dependencies.Select(r => ExpandPaths(r.Dependency, configuration))); } Dependencies = Dependencies.Distinct().ToList(); flattenedResults.ForEach( x => { EnsureHasRange(x.ParentNode.Node, lines); EnsureHasRange(x.DependencyArrayNode, lines); EnsureHasRange(x.ModuleDefinitionNode, lines); EnsureHasRange(x.ModuleIdentifierNode, lines); EnsureHasRange(x.SingleDependencyNode, lines); var arguments = x.ParentNode.Node.As<CallExpression>().Arguments; foreach (var arg in arguments) { EnsureHasRange(arg, lines); } }); var transformations = this.GetTransformations(result, flattenedResults); var text = OriginalString; transformations.ExecuteAll(ref text); ProcessedString = text; } catch (Exception ex) { throw new Exception(string.Format("Error while processing {0}: {1}", RelativeFileName, ex.Message), ex); } }
private static void ValidateScript(string script) { var javaScriptParser = new JavaScriptParser(script); javaScriptParser.ParseProgram(); }
private static Esprima.Ast.Program ValidateScript(string script) { var javaScriptParser = new JavaScriptParser(script); return(javaScriptParser.ParseProgram()); }
/// <summary> /// https://tc39.es/ecma262/#sec-performeval /// </summary> public JsValue Call(JsValue thisObject, JsValue[] arguments, bool direct) { if (!(arguments.At(0) is JsString x)) { return(arguments.At(0)); } var parser = new JavaScriptParser(x.ToString(), ParserOptions); Script script; try { script = parser.ParseScript(StrictModeScope.IsStrictModeCode); } catch (ParserException e) { return(e.Description == Messages.InvalidLHSInAssignment ? ExceptionHelper.ThrowReferenceError <JsValue>(_engine) : ExceptionHelper.ThrowSyntaxError <JsValue>(_engine)); } var body = script.Body; if (body.Count == 0) { return(Undefined); } var strictEval = script.Strict || _engine._isStrict; var ctx = _engine.ExecutionContext; using (new StrictModeScope(strictEval)) { LexicalEnvironment lexEnv; LexicalEnvironment varEnv; if (direct) { lexEnv = LexicalEnvironment.NewDeclarativeEnvironment(_engine, ctx.LexicalEnvironment); varEnv = ctx.VariableEnvironment; } else { lexEnv = LexicalEnvironment.NewDeclarativeEnvironment(_engine, Engine.GlobalEnvironment); varEnv = Engine.GlobalEnvironment; } if (strictEval) { varEnv = lexEnv; } // If ctx is not already suspended, suspend ctx. Engine.EnterExecutionContext(lexEnv, varEnv); try { Engine.EvalDeclarationInstantiation(script, varEnv, lexEnv, strictEval); var statement = new JintScript(_engine, script); var result = statement.Execute(); var value = result.GetValueOrDefault(); if (result.Type == CompletionType.Throw) { var ex = new JavaScriptException(value).SetCallstack(_engine, result.Location); throw ex; } else { return(value); } } finally { Engine.LeaveExecutionContext(); } } }
public Engine Execute(string source) { var parser = new JavaScriptParser(); return Execute(parser.Parse(source)); }
public async Task <Task> InvokeAsync(HttpContext httpContext, ExpressionConverterResolver expressionConverterResolver, IEnumerable <IExtensionMethodsProvider> extensionMethodsProviders, IEnumerable <IStaticMethodsProvider> staticMethodsProviders, IQueryProviderProvider queryProviderProvider, IEnumerable <IIdentifier> Identifiers, IEnumerable <IIdentifierProvider> identifierProviders, JsonSerializer jsonSerializer, IEnumerable <IRuleMapsProvider> ruleMapsProviders, IEnumerable <IRuleMap> ruleMaps, IEnumerable <ICustomMethodCallExpressionConverter> customMethodCallExpressionConverters, IIdentityProvider identityProvider, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) { Esprima.Ast.Expression jsExpression = null; string payload = null; using (var reader = new StreamReader(httpContext.Request.Body)) { payload = await reader.ReadToEndAsync(); var parser = new JavaScriptParser(payload, new ParserOptions() { Range = true }); jsExpression = parser.ParseExpression(); } // The context holds the converters // Building the expression var currentUser = identityProvider.GetIdentity().User; // The context olds the factories ruleMaps = ruleMaps.Union(ruleMapsProviders.SelectMany(rmp => rmp.RuleMaps)); var expressionConvertersContext = new ExpressionConverterContext() { ExpressionConverterResolver = expressionConverterResolver, ExtensionMethods = extensionMethodsProviders.SelectMany(emp => emp.Methods), StaticMethods = staticMethodsProviders.SelectMany(emp => emp.Methods), RuleMapRegistry = new RuleMapRegistry(ruleMaps, Enumerable.Empty <IRuleMapsProvider>()), RuleMaps = ruleMaps, CustomMethodCallExpressionConverters = customMethodCallExpressionConverters, securityContext = new Context() { User = currentUser }, Source = payload }; var identifiers = new Dictionary <string, System.Linq.Expressions.Expression>(); foreach (var identifierProvider in identifierProviders) { foreach (var identifier in identifierProvider.Identifiers) { identifiers[identifier.Key] = identifier.Value; } } foreach (var identifier in Identifiers) { identifiers[identifier.Name] = identifier.Expression; } // The scope olds the target type, the generic parameter map and varibales set. // Note that the target type is null since we cannot predict it at this stage. // Note that the generic parameter map is null since we cannot predict it at this stage var expressionConvertersScope = new ExpressionConverterScope(null, null) { Variables = identifiers }; var expression = expressionConverterResolver.Convert(jsExpression, expressionConvertersContext, expressionConvertersScope, false); if (expression.Type != typeof(void) && expression.Type != typeof(Task)) { Func <Task <object> > asyncFunction = null; if (expression.Type.IsGenericType && expression.Type.GetGenericTypeDefinition() == typeof(Task <>)) { var f = System.Linq.Expressions.Expression.Lambda <Func <Task> >(expression).Compile(); asyncFunction = async() => { var task = f(); await task; return((object)((dynamic)task).Result); }; } else { var function = System.Linq.Expressions.Expression.Lambda <Func <object> >(System.Linq.Expressions.Expression.Convert(expression, typeof(object))).Compile(); asyncFunction = new Func <Task <object> >(() => Task.FromResult(function())); } var result = await asyncFunction(); httpContext.Response.Headers.Add("Content-Type", "application/json"); httpContext.Response.Headers.Add("charset", "utf8"); var queryable = result as IQueryable <object>; if (queryable != null) { result = queryable.ToArray(); } using (var streamWriter = new StreamWriter(httpContext.Response.Body)) { using (var jsonWriter = new JsonTextWriter(streamWriter)) { jsonSerializer.Serialize(jsonWriter, result); } } } else { Func <Task> asyncAction = null; if (expression.Type == typeof(Task)) { asyncAction = System.Linq.Expressions.Expression.Lambda <Func <Task> >(expression).Compile(); } else { var a = System.Linq.Expressions.Expression.Lambda <Action>(expression).Compile(); asyncAction = new Func <Task>(() => { a(); return(Task.CompletedTask); }); } await asyncAction(); } return(Task.CompletedTask); }
public void ProcessRequest(MigClientRequest request) { var migCommand = request.Command; string response = ""; switch (migCommand.Command) { case "Interfaces.List": response = "[ "; foreach (var migInterface in homegenie.Interfaces) { var ifaceConfig = homegenie.SystemConfiguration.MigService.GetInterface(migInterface.GetDomain()); if (ifaceConfig == null || !ifaceConfig.IsEnabled) { continue; } response += "{ \"Domain\" : \"" + migInterface.GetDomain() + "\", \"IsConnected\" : \"" + migInterface.IsConnected + "\" },"; } if (homegenie.UpdateChecker != null && homegenie.UpdateChecker.IsUpdateAvailable) { response += "{ \"Domain\" : \"" + Domains.HomeGenie_UpdateChecker + "\", \"IsConnected\" : \"True\" }"; response += " ]"; } else { response = response.Substring(0, response.Length - 1) + " ]"; } request.ResponseData = response; break; case "Interfaces.ListConfig": response = "[ "; foreach (var migInterface in homegenie.Interfaces) { var ifaceConfig = homegenie.SystemConfiguration.MigService.GetInterface(migInterface.GetDomain()); if (ifaceConfig == null) continue; response += JsonConvert.SerializeObject(ifaceConfig) + ","; } response = response.Substring(0, response.Length - 1) + " ]"; request.ResponseData = response; break; //TODO: should this be moved somewhere to MIG? case "Interfaces.Configure": switch (migCommand.GetOption(0)) { case "Hardware.SerialPorts": if (Environment.OSVersion.Platform == PlatformID.Unix) { var serialPorts = System.IO.Ports.SerialPort.GetPortNames(); var portList = new List<string>(); for (int p = serialPorts.Length - 1; p >= 0; p--) { if (serialPorts[p].Contains("/ttyS") || serialPorts[p].Contains("/ttyUSB") || serialPorts[p].Contains("/ttyAMA") // RaZberry || serialPorts[p].Contains("/ttyACM")) // ZME_UZB1 { portList.Add(serialPorts[p]); } } request.ResponseData = portList; } else { var portNames = System.IO.Ports.SerialPort.GetPortNames(); request.ResponseData = portNames; } break; } break; case "Interface.Import": string downloadUrl = migCommand.GetOption(0); response = ""; string ifaceFileName = Path.Combine(tempFolderPath, "mig_interface_import.zip"); string outputFolder = Path.Combine(tempFolderPath, "mig"); Utility.FolderCleanUp(outputFolder); try { if (String.IsNullOrWhiteSpace(downloadUrl)) { // file uploaded by user MIG.Gateways.WebServiceUtility.SaveFile(request.RequestData, ifaceFileName); } else { // download file from url using (var client = new WebClient()) { client.DownloadFile(downloadUrl, ifaceFileName); client.Dispose(); } } } catch { // TODO: report exception } try { if (!Directory.Exists(outputFolder)) { Directory.CreateDirectory(outputFolder); } Utility.UncompressZip(ifaceFileName, outputFolder); File.Delete(ifaceFileName); var migInt = GetInterfaceConfig(Path.Combine(outputFolder, "configuration.xml")); if (migInt != null) { response = String.Format("{0} ({1})\n{2}\n", migInt.Domain, migInt.AssemblyName, migInt.Description); // Check for README notes and append them to the response var readmeFile = Path.Combine(outputFolder, "README.TXT"); if (File.Exists(readmeFile)) { response += File.ReadAllText(readmeFile); } request.ResponseData = new ResponseText(response); } else { request.ResponseData = new ResponseText("NOT A VALID ADD-ON PACKAGE"); } } catch { // TODO: report exception } break; case "Interface.Install": // install the interface package from the unpacked archive folder if (InterfaceInstall(Path.Combine(tempFolderPath, "mig"))) request.ResponseData = new ResponseText("OK"); else request.ResponseData = new ResponseText("NOT A VALID ADD-ON PACKAGE"); break; case "System.GetVersion": request.ResponseData = homegenie.UpdateChecker.GetCurrentRelease(); break; case "System.Configure": if (migCommand.GetOption(0) == "Service.Restart") { Program.Quit(true); request.ResponseData = new ResponseText("OK"); } else if (migCommand.GetOption(0) == "UpdateManager.UpdatesList") { request.ResponseData = homegenie.UpdateChecker.RemoteUpdates; } else if (migCommand.GetOption(0) == "UpdateManager.Check") { homegenie.UpdateChecker.Check(); request.ResponseData = new ResponseText("OK"); } else if (migCommand.GetOption(0) == "UpdateManager.DownloadUpdate") { var resultMessage = "ERROR"; bool success = homegenie.UpdateChecker.DownloadUpdateFiles(); if (success) { if (homegenie.UpdateChecker.IsRestartRequired) { resultMessage = "RESTART"; } else { resultMessage = "OK"; } } request.ResponseData = new ResponseText(resultMessage); } else if (migCommand.GetOption(0) == "UpdateManager.InstallUpdate") //UpdateManager.InstallProgramsCommit") { string resultMessage = "OK"; homegenie.SaveData(); if (!homegenie.UpdateChecker.InstallFiles()) { resultMessage = "ERROR"; } else { if (homegenie.UpdateChecker.IsRestartRequired) { resultMessage = "RESTART"; Utility.RunAsyncTask(() => { Thread.Sleep(2000); Program.Quit(true); }); } else { homegenie.LoadConfiguration(); homegenie.UpdateChecker.Check(); } } request.ResponseData = new ResponseText(resultMessage); } else if (migCommand.GetOption(0) == "Statistics.GetStatisticsDatabaseMaximumSize") { request.ResponseData = new ResponseText(homegenie.SystemConfiguration.HomeGenie.Statistics.MaxDatabaseSizeMBytes.ToString()); } else if (migCommand.GetOption(0) == "Statistics.SetStatisticsDatabaseMaximumSize") { try { int sizeLimit = int.Parse(migCommand.GetOption(1)); homegenie.SystemConfiguration.HomeGenie.Statistics.MaxDatabaseSizeMBytes = sizeLimit; homegenie.SystemConfiguration.Update(); homegenie.Statistics.SizeLimit = sizeLimit * 1024 * 1024; } catch { } } else if (migCommand.GetOption(0) == "SystemLogging.DownloadCsv") { string csvlog = ""; string logpath = Path.Combine("log", "homegenie.log"); if (migCommand.GetOption(1) == "1") { logpath = Path.Combine("log", "homegenie.log.bak"); } if (File.Exists(logpath)) { using (var fs = new FileStream(logpath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) using (var sr = new StreamReader(fs, Encoding.Default)) { csvlog = sr.ReadToEnd(); } } (request.Context.Data as HttpListenerContext).Response.AddHeader("Content-Disposition", "attachment;filename=homegenie_log_" + migCommand.GetOption(1) + ".csv"); request.ResponseData = csvlog; } else if (migCommand.GetOption(0) == "SystemLogging.Enable") { SystemLogger.Instance.OpenLog(); homegenie.SystemConfiguration.HomeGenie.EnableLogFile = "true"; homegenie.SystemConfiguration.Update(); } else if (migCommand.GetOption(0) == "SystemLogging.Disable") { SystemLogger.Instance.CloseLog(); homegenie.SystemConfiguration.HomeGenie.EnableLogFile = "false"; homegenie.SystemConfiguration.Update(); } else if (migCommand.GetOption(0) == "SystemLogging.IsEnabled") { request.ResponseData = new ResponseText((homegenie.SystemConfiguration.HomeGenie.EnableLogFile.ToLower().Equals("true") ? "1" : "0")); } else if (migCommand.GetOption(0) == "Security.SetPassword") { // password only for now, with fixed user login 'admin' string pass = migCommand.GetOption(1) == "" ? "" : MIG.Utility.Encryption.SHA1.GenerateHashString(migCommand.GetOption(1)); homegenie.MigService.GetGateway("WebServiceGateway").SetOption("Password", pass); homegenie.SaveData(); } else if (migCommand.GetOption(0) == "Security.ClearPassword") { homegenie.MigService.GetGateway("WebServiceGateway").SetOption("Password", ""); homegenie.SaveData(); } else if (migCommand.GetOption(0) == "Security.HasPassword") { var webGateway = homegenie.MigService.GetGateway("WebServiceGateway"); var password = webGateway.GetOption("Password"); request.ResponseData = new ResponseText((password == null || String.IsNullOrEmpty(password.Value) ? "0" : "1")); } else if (migCommand.GetOption(0) == "HttpService.SetWebCacheEnabled") { if (migCommand.GetOption(1) == "1") { homegenie.MigService.GetGateway("WebServiceGateway").SetOption("EnableFileCaching", "true"); } else { homegenie.MigService.GetGateway("WebServiceGateway").SetOption("EnableFileCaching", "false"); } homegenie.SystemConfiguration.Update(); request.ResponseData = new ResponseText("OK"); } else if (migCommand.GetOption(0) == "HttpService.GetWebCacheEnabled") { var fileCaching = homegenie.MigService.GetGateway("WebServiceGateway").GetOption("EnableFileCaching"); request.ResponseData = new ResponseText(fileCaching != null ? fileCaching.Value : "false"); } else if (migCommand.GetOption(0) == "HttpService.GetPort") { var port = homegenie.MigService.GetGateway("WebServiceGateway").GetOption("Port"); request.ResponseData = new ResponseText(port != null ? port.Value : "8080"); } else if (migCommand.GetOption(0) == "HttpService.SetPort") { homegenie.MigService.GetGateway("WebServiceGateway").SetOption("Port", migCommand.GetOption(1)); homegenie.SystemConfiguration.Update(); } else if (migCommand.GetOption(0) == "HttpService.GetHostHeader") { var host = homegenie.MigService.GetGateway("WebServiceGateway").GetOption("Host"); request.ResponseData = new ResponseText(host != null ? host.Value : "*"); } else if (migCommand.GetOption(0) == "HttpService.SetHostHeader") { homegenie.MigService.GetGateway("WebServiceGateway").SetOption("Host", migCommand.GetOption(1)); homegenie.SystemConfiguration.Update(); } else if (migCommand.GetOption(0) == "System.ConfigurationRestore") { // file uploaded by user string archivename = Path.Combine(tempFolderPath, "homegenie_restore_config.zip"); Utility.FolderCleanUp(Utility.GetTmpFolder()); try { MIG.Gateways.WebServiceUtility.SaveFile(request.RequestData, archivename); Utility.UncompressZip(archivename, tempFolderPath); File.Delete(archivename); request.ResponseData = new ResponseStatus(Status.Ok); } catch { request.ResponseData = new ResponseStatus(Status.Error); } } else if (migCommand.GetOption(0) == "System.ConfigurationRestoreS1") { var serializer = new XmlSerializer(typeof(List<ProgramBlock>)); var reader = new StreamReader(Path.Combine(tempFolderPath, "programs.xml")); var newProgramsData = (List<ProgramBlock>)serializer.Deserialize(reader); reader.Close(); var newProgramList = new List<ProgramBlock>(); foreach (ProgramBlock program in newProgramsData) { if (program.Address >= ProgramManager.USER_SPACE_PROGRAMS_START) { ProgramBlock p = new ProgramBlock(); p.Address = program.Address; p.Name = program.Name; p.Description = program.Description; newProgramList.Add(p); } } newProgramList.Sort(delegate(ProgramBlock p1, ProgramBlock p2) { string c1 = p1.Address.ToString(); string c2 = p2.Address.ToString(); return c1.CompareTo(c2); }); request.ResponseData = newProgramList; } else if (migCommand.GetOption(0) == "System.ConfigurationRestoreS2") { // Import automation groups var serializer = new XmlSerializer(typeof(List<Group>)); var reader = new StreamReader(Path.Combine(tempFolderPath, "automationgroups.xml")); var automationGroups = (List<Group>)serializer.Deserialize(reader); reader.Close(); foreach (var automationGroup in automationGroups) { if (homegenie.AutomationGroups.Find(g => g.Name == automationGroup.Name) == null) { homegenie.AutomationGroups.Add(automationGroup); } } homegenie.UpdateGroupsDatabase("Automation"); // Copy system configuration files File.Copy(Path.Combine(tempFolderPath, "groups.xml"), Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "groups.xml"), true); File.Copy(Path.Combine(tempFolderPath, "modules.xml"), Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "modules.xml"), true); File.Copy(Path.Combine(tempFolderPath, "scheduler.xml"), Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "scheduler.xml"), true); // TODO: add backward compatibility for systemconfig.xml from HG 1.0 < r494 UpdateSystemConfig(); // Copy MIG configuration files if present (from folder lib/mig/*.xml) string migLibFolder = Path.Combine(tempFolderPath, "lib", "mig"); if (Directory.Exists(migLibFolder)) { foreach (string f in Directory.GetFiles(migLibFolder, "*.xml")) { File.Copy(f, Path.Combine("lib", "mig", Path.GetFileName(f)), true); } } homegenie.SoftReload(); // Restore automation programs string selectedPrograms = migCommand.GetOption(1); serializer = new XmlSerializer(typeof(List<ProgramBlock>)); reader = new StreamReader(Path.Combine(tempFolderPath, "programs.xml")); var newProgramsData = (List<ProgramBlock>)serializer.Deserialize(reader); reader.Close(); foreach (var program in newProgramsData) { var currentProgram = homegenie.ProgramManager.Programs.Find(p => p.Address == program.Address); program.IsRunning = false; // Only restore user space programs if (selectedPrograms.Contains("," + program.Address.ToString() + ",") && program.Address >= ProgramManager.USER_SPACE_PROGRAMS_START) { int oldPid = program.Address; if (currentProgram == null) { var newPid = ((currentProgram != null && currentProgram.Address == program.Address) ? homegenie.ProgramManager.GeneratePid() : program.Address); try { File.Copy(Path.Combine(tempFolderPath, "programs", program.Address + ".dll"), Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "programs", newPid + ".dll"), true); } catch { } program.Address = newPid; homegenie.ProgramManager.ProgramAdd(program); } else if (currentProgram != null) { homegenie.ProgramManager.ProgramRemove(currentProgram); try { File.Copy(Path.Combine(tempFolderPath, "programs", program.Address + ".dll"), Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "programs", program.Address + ".dll"), true); } catch { } homegenie.ProgramManager.ProgramAdd(program); } // Restore Arduino program folder ... // TODO: this is untested yet... if (program.Type.ToLower() == "arduino") { string sourceFolder = Path.Combine(tempFolderPath, "programs", "arduino", oldPid.ToString()); string arduinoFolder = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "programs", "arduino", program.Address.ToString()); if (Directory.Exists(arduinoFolder)) Directory.Delete(arduinoFolder, true); Directory.CreateDirectory(arduinoFolder); foreach (string newPath in Directory.GetFiles(sourceFolder)) { File.Copy(newPath, newPath.Replace(sourceFolder, arduinoFolder), true); } } } else if (currentProgram != null && program.Address < ProgramManager.USER_SPACE_PROGRAMS_START) { // Only restore Enabled/Disabled status of system programs currentProgram.IsEnabled = program.IsEnabled; } } homegenie.UpdateProgramsDatabase(); homegenie.SaveData(); } else if (migCommand.GetOption(0) == "System.ConfigurationReset") { homegenie.RestoreFactorySettings(); } else if (migCommand.GetOption(0) == "System.ConfigurationBackup") { homegenie.BackupCurrentSettings(); (request.Context.Data as HttpListenerContext).Response.Redirect("/hg/html/homegenie_backup_config.zip"); } else if (migCommand.GetOption(0) == "System.ConfigurationLoad") { homegenie.SoftReload(); } break; case "Modules.Get": try { var module = homegenie.Modules.Find(m => m.Domain == migCommand.GetOption(0) && m.Address == migCommand.GetOption(1)); request.ResponseData = Utility.Module2Json(module, false); } catch (Exception ex) { request.ResponseData = new ResponseText("ERROR: \n" + ex.Message + "\n\n" + ex.StackTrace); } break; case "Modules.ParameterGet": try { var module = homegenie.Modules.Find(m => m.Domain == migCommand.GetOption(0) && m.Address == migCommand.GetOption(1)); var parameter = Utility.ModuleParameterGet(module, migCommand.GetOption(2)); if (parameter != null) request.ResponseData = JsonConvert.SerializeObject(parameter, Formatting.Indented); else request.ResponseData = new ResponseText("ERROR: Unknown parameter '" + migCommand.GetOption(2) + "'"); } catch (Exception ex) { request.ResponseData = new ResponseText("ERROR: \n" + ex.Message + "\n\n" + ex.StackTrace); } break; case "Modules.ParameterSet": try { var module = homegenie.Modules.Find(m => m.Domain == migCommand.GetOption(0) && m.Address == migCommand.GetOption(1)); var parameter = Utility.ModuleParameterSet(module, migCommand.GetOption(2), migCommand.GetOption(3)); request.ResponseData = new ResponseText("OK"); } catch (Exception ex) { request.ResponseData = new ResponseText("ERROR: \n" + ex.Message + "\n\n" + ex.StackTrace); } break; case "Modules.StatisticsGet": try { var module = homegenie.Modules.Find(m => m.Domain == migCommand.GetOption(0) && m.Address == migCommand.GetOption(1)); var parameter = Utility.ModuleParameterGet(module, migCommand.GetOption(2)); if (parameter != null) request.ResponseData = JsonConvert.SerializeObject(parameter.Statistics, Formatting.Indented); else request.ResponseData = new ResponseText("ERROR: Unknown parameter '" + migCommand.GetOption(2) + "'"); } catch (Exception ex) { request.ResponseData = new ResponseText("ERROR: \n" + ex.Message + "\n\n" + ex.StackTrace); } break; case "Modules.List": try { homegenie.modules_Sort(); request.ResponseData = homegenie.GetJsonSerializedModules(migCommand.GetOption(0).ToLower() == "short"); } catch (Exception ex) { request.ResponseData = new ResponseText("ERROR: \n" + ex.Message + "\n\n" + ex.StackTrace); } break; case "Modules.RoutingReset": try { for (int m = 0; m < homegenie.Modules.Count; m++) { homegenie.Modules[m].RoutingNode = ""; } request.ResponseData = new ResponseText("OK"); } catch (Exception ex) { request.ResponseData = new ResponseText("ERROR: \n" + ex.Message + "\n\n" + ex.StackTrace); } break; case "Modules.Save": string body = request.RequestText; var newModules = JsonConvert.DeserializeObject(body) as JArray; for (int i = 0; i < newModules.Count; i++) { try { var module = homegenie.Modules.Find(m => m.Address == newModules[i]["Address"].ToString() && m.Domain == newModules[i]["Domain"].ToString()); module.Name = newModules[i]["Name"].ToString(); // try { module.DeviceType = (MIG.ModuleTypes)Enum.Parse(typeof(MIG.ModuleTypes), newModules[i]["DeviceType"].ToString(), true); } catch { // TODO: check what's wrong here... } // var moduleProperties = newModules[i]["Properties"] as JArray; for (int p = 0; p < moduleProperties.Count; p++) { string propertyName = moduleProperties[p]["Name"].ToString(); string propertyValue = moduleProperties[p]["Value"].ToString(); ModuleParameter parameter = null; parameter = module.Properties.Find(delegate(ModuleParameter mp) { return mp.Name == propertyName; }); // if (propertyName == Properties.VirtualMeterWatts) { try { propertyValue = double.Parse(propertyValue.Replace(",", "."), System.Globalization.CultureInfo.InvariantCulture).ToString(); } catch { propertyValue = "0"; } } // if (parameter == null) { module.Properties.Add(new ModuleParameter() { Name = propertyName, Value = propertyValue }); } else { if (moduleProperties[p]["NeedsUpdate"] != null && moduleProperties[p]["NeedsUpdate"].ToString() == "true") { parameter.Value = propertyValue; } } } } catch (Exception) { //TODO: notify exception? } } homegenie.UpdateModulesDatabase();//write modules break; case "Modules.Update": string streamContent = request.RequestText; var newModule = JsonConvert.DeserializeObject<Module>(streamContent); var currentModule = homegenie.Modules.Find(p => p.Domain == newModule.Domain && p.Address == newModule.Address); // if (currentModule == null) { homegenie.Modules.Add(newModule); } else { currentModule.Name = newModule.Name; currentModule.Description = newModule.Description; currentModule.DeviceType = newModule.DeviceType; foreach (var newParameter in newModule.Properties) { var currentParameter = currentModule.Properties.Find(mp => mp.Name == newParameter.Name); if (currentParameter == null) { currentModule.Properties.Add(newParameter); } else if (newParameter.NeedsUpdate) { // reset current reporting Watts if VMWatts field is set to 0 if (newParameter.Name == Properties.VirtualMeterWatts && newParameter.DecimalValue == 0 && currentParameter.DecimalValue != 0) { homegenie.RaiseEvent( Domains.HomeGenie_System, currentModule.Domain, currentModule.Address, currentModule.Description, Properties.MeterWatts, "0.0" ); } currentParameter.Value = newParameter.Value; } } // look for deleted properties var deletedParameters = new List<ModuleParameter>(); foreach (var parameter in currentModule.Properties) { var currentParameter = newModule.Properties.Find(mp => mp.Name == parameter.Name); if (currentParameter == null) { deletedParameters.Add(parameter); } } foreach (var parameter in deletedParameters) { currentModule.Properties.Remove(parameter); } deletedParameters.Clear(); } // homegenie.UpdateModulesDatabase(); break; case "Modules.Delete": var deletedModule = homegenie.Modules.Find(m => m.Domain == migCommand.GetOption(0) && m.Address == migCommand.GetOption(1)); if (deletedModule != null) { homegenie.Modules.Remove(deletedModule); } request.ResponseData = new ResponseText("OK"); // homegenie.UpdateModulesDatabase(); break; case "Stores.List": { var module = homegenie.Modules.Find(m => m.Domain == migCommand.GetOption(0) && m.Address == migCommand.GetOption(1)); if (module != null) { //module.Stores response = "["; for (int s = 0; s < module.Stores.Count; s++) { response += "{ \"Name\": \"" + Utility.XmlEncode(module.Stores[s].Name) + "\", \"Description\": \"" + Utility.XmlEncode(module.Stores[s].Description) + "\" },"; } response = response.TrimEnd(',') + "]"; request.ResponseData = response; } } break; case "Stores.Delete": break; case "Stores.ItemList": { var module = homegenie.Modules.Find(m => m.Domain == migCommand.GetOption(0) && m.Address == migCommand.GetOption(1)); if (module != null) { response = "["; var store = new StoreHelper(module.Stores, migCommand.GetOption(2)); for (int p = 0; p < store.List.Count; p++) { response += "{ \"Name\": \"" + Utility.XmlEncode(store.List[p].Name) + "\", \"Description\": \"" + Utility.XmlEncode(store.List[p].Description) + "\" },"; } response = response.TrimEnd(',') + "]"; request.ResponseData = response; } } break; case "Stores.ItemDelete": { var module = homegenie.Modules.Find(m => m.Domain == migCommand.GetOption(0) && m.Address == migCommand.GetOption(1)); if (module != null) { var name = migCommand.GetOption(3); var store = new StoreHelper(module.Stores, migCommand.GetOption(2)); store.List.RemoveAll(i => i.Name == name); } } break; case "Stores.ItemGet": { var module = homegenie.Modules.Find(m => m.Domain == migCommand.GetOption(0) && m.Address == migCommand.GetOption(1)); if (module != null) { var store = new StoreHelper(module.Stores, migCommand.GetOption(2)); request.ResponseData = store.Get(migCommand.GetOption(3)); } } break; case "Stores.ItemSet": { // value is the POST body string itemData = request.RequestText; var module = homegenie.Modules.Find(m => m.Domain == migCommand.GetOption(0) && m.Address == migCommand.GetOption(1)); if (module != null) { var store = new StoreHelper(module.Stores, migCommand.GetOption(2)); store.Get(migCommand.GetOption(3)).Value = itemData; } } break; case "Groups.ModulesList": var theGroup = homegenie.Groups.Find(z => z.Name.ToLower() == migCommand.GetOption(0).Trim().ToLower()); if (theGroup != null) { string jsonmodules = "["; for (int m = 0; m < theGroup.Modules.Count; m++) { var groupModule = homegenie.Modules.Find(mm => mm.Domain == theGroup.Modules[m].Domain && mm.Address == theGroup.Modules[m].Address); if (groupModule != null) { jsonmodules += Utility.Module2Json(groupModule, false) + ",\n"; } } jsonmodules = jsonmodules.TrimEnd(',', '\n'); jsonmodules += "]"; request.ResponseData = jsonmodules; } break; case "Groups.List": try { request.ResponseData = homegenie.GetGroups(migCommand.GetOption(0)); } catch (Exception ex) { request.ResponseData = new ResponseText("ERROR: \n" + ex.Message + "\n\n" + ex.StackTrace); } break; case "Groups.Rename": string oldName = migCommand.GetOption(1); string newName = request.RequestText; var currentGroup = homegenie.GetGroups(migCommand.GetOption(0)).Find(g => g.Name == oldName); var newGroup = homegenie.GetGroups(migCommand.GetOption(0)).Find(g => g.Name == newName); // ensure that the new group name is not already defined if (newGroup == null && currentGroup != null) { currentGroup.Name = newName; homegenie.UpdateGroupsDatabase(migCommand.GetOption(0)); //cmd.response = JsonHelper.GetSimpleResponse("OK"); } else { request.ResponseData = new ResponseText("New name already in use."); } break; case "Groups.Sort": { var newGroupList = new List<Group>(); string[] newPositionOrder = request.RequestText.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries); for (int i = 0; i < newPositionOrder.Length; i++) { newGroupList.Add(homegenie.GetGroups(migCommand.GetOption(0))[int.Parse(newPositionOrder[i])]); } homegenie.GetGroups(migCommand.GetOption(0)).Clear(); homegenie.GetGroups(migCommand.GetOption(0)).RemoveAll(g => true); homegenie.GetGroups(migCommand.GetOption(0)).AddRange(newGroupList); homegenie.UpdateGroupsDatabase(migCommand.GetOption(0)); } try { request.ResponseData = homegenie.GetGroups(migCommand.GetOption(0)); } catch (Exception ex) { request.ResponseData = new ResponseText("ERROR: \n" + ex.Message + "\n\n" + ex.StackTrace); } break; case "Groups.SortModules": { string groupName = migCommand.GetOption(1); Group sortGroup = null; sortGroup = homegenie.GetGroups(migCommand.GetOption(0)).Find(zn => zn.Name == groupName); if (sortGroup != null) { var newModulesReference = new List<ModuleReference>(); string[] newPositionOrder = request.RequestText.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries); for (int i = 0; i < newPositionOrder.Length; i++) { newModulesReference.Add(sortGroup.Modules[int.Parse(newPositionOrder[i])]); } sortGroup.Modules.Clear(); sortGroup.Modules = newModulesReference; homegenie.UpdateGroupsDatabase(migCommand.GetOption(0)); } } try { request.ResponseData = homegenie.GetGroups(migCommand.GetOption(0)); } catch (Exception ex) { request.ResponseData = new ResponseText("ERROR: \n" + ex.Message + "\n\n" + ex.StackTrace); } break; case "Groups.Add": string newGroupName = request.RequestText; homegenie.GetGroups(migCommand.GetOption(0)).Add(new Group() { Name = newGroupName }); homegenie.UpdateGroupsDatabase(migCommand.GetOption(0));//write groups break; case "Groups.Delete": string deletedGroupName = request.RequestText; Group deletedGroup = null; try { deletedGroup = homegenie.GetGroups(migCommand.GetOption(0)).Find(zn => zn.Name == deletedGroupName); } catch { } // if (deletedGroup != null) { homegenie.GetGroups(migCommand.GetOption(0)).Remove(deletedGroup); homegenie.UpdateGroupsDatabase(migCommand.GetOption(0));//write groups if (migCommand.GetOption(0).ToLower() == "automation") { var groupPrograms = homegenie.ProgramManager.Programs.FindAll(p => p.Group.ToLower() == deletedGroup.Name.ToLower()); if (groupPrograms != null) { // delete group association from programs foreach (ProgramBlock program in groupPrograms) { program.Group = ""; } } } } break; case "Groups.Save": string jsonGroups = request.RequestText; var newGroups = JsonConvert.DeserializeObject<List<Group>>(jsonGroups); for (int i = 0; i < newGroups.Count; i++) { try { var group = homegenie.Groups.Find(z => z.Name == newGroups[i].Name); group.Modules.Clear(); group.Modules = newGroups[i].Modules; } catch { } } homegenie.UpdateGroupsDatabase(migCommand.GetOption(0));//write groups break; case "Groups.WallpaperList": List<string> wallpaperList = new List<string>(); var images = Directory.GetFiles(groupWallpapersPath); for (int i = 0; i < images.Length; i++) { wallpaperList.Add(Path.GetFileName(images[i])); } request.ResponseData = wallpaperList; break; case "Groups.WallpaperAdd": { string wallpaperFile = ""; try { wallpaperFile = MIG.Gateways.WebServiceUtility.SaveFile(request.RequestData, groupWallpapersPath); } catch { } request.ResponseData = new ResponseText(Path.GetFileName(wallpaperFile)); } break; case "Groups.WallpaperSet": { string wpGroupName = migCommand.GetOption(0); var wpGroup = homegenie.GetGroups(migCommand.GetOption(0)).Find(g => g.Name == wpGroupName); if (wpGroup != null) { wpGroup.Wallpaper = migCommand.GetOption(1); homegenie.UpdateGroupsDatabase("Control"); } } break; case "Groups.WallpaperDelete": { string wallpaperFile = migCommand.GetOption(0); wallpaperFile = Path.Combine(groupWallpapersPath, Path.GetFileName(wallpaperFile)); if (File.Exists(wallpaperFile)) { File.Delete(wallpaperFile); } request.ResponseData = new ResponseText("OK"); } break; case "Widgets.List": List<string> widgetsList = new List<string>(); var groups = Directory.GetDirectories(widgetBasePath); for (int d = 0; d < groups.Length; d++) { var categories = Directory.GetDirectories(groups[d]); for (int c = 0; c < categories.Length; c++) { var widgets = Directory.GetFiles(categories[c], "*.js"); var group = groups[d].Replace(widgetBasePath, "").Substring(1); var category = categories[c].Replace(groups[d], "").Substring(1); for (int w = 0; w < widgets.Length; w++) { widgetsList.Add(group + "/" + category + "/" + Path.GetFileNameWithoutExtension(widgets[w])); } } } request.ResponseData = widgetsList; break; case "Widgets.Add": { var status = Status.Error; string widgetPath = migCommand.GetOption(0); // eg. homegenie/generic/dimmer string[] widgetParts = widgetPath.Split('/'); widgetParts[0] = new String(widgetParts[0].Where(Char.IsLetter).ToArray()).ToLower(); widgetParts[1] = new String(widgetParts[1].Where(Char.IsLetter).ToArray()).ToLower(); widgetParts[2] = new String(widgetParts[2].Where(Char.IsLetter).ToArray()).ToLower(); if (!String.IsNullOrWhiteSpace(widgetParts[0]) && !String.IsNullOrWhiteSpace(widgetParts[1]) && !String.IsNullOrWhiteSpace(widgetParts[2])) { string filePath = Path.Combine(widgetBasePath, widgetParts[0], widgetParts[1]); if (!Directory.Exists(filePath)) { Directory.CreateDirectory(filePath); } // copy widget template into the new widget var htmlFile = Path.Combine(filePath, widgetParts[2] + ".html"); var jsFile = Path.Combine(filePath, widgetParts[2] + ".js"); if (!File.Exists(htmlFile) && !File.Exists(jsFile)) { File.Copy(Path.Combine(widgetBasePath, "template.html"), htmlFile); File.Copy(Path.Combine(widgetBasePath, "template.js"), jsFile); status = Status.Ok; } } request.ResponseData = new ResponseStatus(status); } break; case "Widgets.Save": { var status = Status.Error; string widgetData = request.RequestText; string fileType = migCommand.GetOption(0); string widgetPath = migCommand.GetOption(1); // eg. homegenie/generic/dimmer string[] widgetParts = widgetPath.Split('/'); string filePath = Path.Combine(widgetBasePath, widgetParts[0], widgetParts[1]); if (!Directory.Exists(filePath)) { Directory.CreateDirectory(filePath); } switch (fileType) { // html/javascript source case "html": case "js": using (TextWriter widgetWriter = new StreamWriter(Path.Combine(filePath, widgetParts[2] + "." + fileType))) { widgetWriter.Write(widgetData); } status = Status.Ok; break; // style sheet file case "css": break; // locale file case "json": break; // image file case "jpg": case "png": case "gif": break; } request.ResponseData = new ResponseStatus(status); } break; case "Widgets.Delete": { var status = Status.Error; string widgetPath = migCommand.GetOption(0); // eg. homegenie/generic/dimmer string[] widgetParts = widgetPath.Split('/'); string filePath = Path.Combine(widgetBasePath, widgetParts[0], widgetParts[1], widgetParts[2] + "."); if (File.Exists(filePath + "html")) { File.Delete(filePath + "html"); status = Status.Ok; } if (File.Exists(filePath + "js")) { File.Delete(filePath + "js"); status = Status.Ok; } request.ResponseData = new ResponseStatus(status); } break; case "Widgets.Export": { string widgetPath = migCommand.GetOption(0); // eg. homegenie/generic/dimmer string[] widgetParts = widgetPath.Split('/'); string widgetBundle = Path.Combine(tempFolderPath, "export", widgetPath.Replace('/', '_') + ".zip"); if (File.Exists(widgetBundle)) { File.Delete(widgetBundle); } else if (!Directory.Exists(Path.GetDirectoryName(widgetBundle))) { Directory.CreateDirectory(Path.GetDirectoryName(widgetBundle)); } string inputPath = Path.Combine(widgetBasePath, widgetParts[0], widgetParts[1]); string outputPath = Path.Combine(widgetParts[0], widgetParts[1]); string infoFilePath = Path.Combine(inputPath, "widget.info"); File.WriteAllText(infoFilePath, "HomeGenie exported widget."); Utility.AddFileToZip(widgetBundle, infoFilePath, "widget.info"); Utility.AddFileToZip(widgetBundle, Path.Combine(inputPath, widgetParts[2] + ".html"), Path.Combine(outputPath, widgetParts[2] + ".html")); Utility.AddFileToZip(widgetBundle, Path.Combine(inputPath, widgetParts[2] + ".js"), Path.Combine(outputPath, widgetParts[2] + ".js")); // byte[] bundleData = File.ReadAllBytes(widgetBundle); (request.Context.Data as HttpListenerContext).Response.AddHeader("Content-Disposition", "attachment; filename=\"" + widgetPath.Replace('/', '_') + ".zip\""); (request.Context.Data as HttpListenerContext).Response.OutputStream.Write(bundleData, 0, bundleData.Length); } break; case "Widgets.Import": { string archiveFile = Path.Combine(tempFolderPath, "import_widget.zip"); string importPath = Path.Combine(tempFolderPath, "import"); if (Directory.Exists(importPath)) Directory.Delete(importPath, true); MIG.Gateways.WebServiceUtility.SaveFile(request.RequestData, archiveFile); if (WidgetImport(archiveFile, importPath)) { request.ResponseData = new ResponseText("OK"); } else { request.ResponseData = new ResponseText("ERROR"); } } break; case "Widgets.Parse": { string widgetData = request.RequestText; var parser = new JavaScriptParser(); try { request.ResponseData = new ResponseText("OK"); parser.Parse(widgetData); } catch (Jint.Parser.ParserException e) { request.ResponseData = new ResponseText("ERROR (" + e.LineNumber + "," + e.Column + "): " + e.Description); } } break; case "Package.Install": { string pkgBaseUrl = migCommand.GetOption(0); string installFolder = Path.Combine(tempFolderPath, "pkg"); dynamic pkgData = null; bool success = true; // Download package specs homegenie.RaiseEvent( Domains.HomeGenie_System, Domains.HomeGenie_PackageInstaller, SourceModule.Master, "HomeGenie Package Installer", Properties.InstallProgressMessage, "= Downloading: package.json" ); using (var client = new WebClient()) { try { string pkgJson = "[" + client.DownloadString(pkgBaseUrl + "/package.json") + "]"; pkgData = (JsonConvert.DeserializeObject(pkgJson) as JArray)[0]; } catch { success = false; } client.Dispose(); } // Download and install package files if (success && pkgData != null) { // Import Automation Programs in package foreach (var program in pkgData.programs) { homegenie.RaiseEvent( Domains.HomeGenie_System, Domains.HomeGenie_PackageInstaller, SourceModule.Master, "HomeGenie Package Installer", Properties.InstallProgressMessage, "= Downloading: " + program.file.ToString() ); Utility.FolderCleanUp(installFolder); string programFile = Path.Combine(installFolder, program.file.ToString()); if (File.Exists(programFile)) File.Delete(programFile); using (var client = new WebClient()) { try { client.DownloadFile(pkgBaseUrl + "/" + program.file.ToString(), programFile); } catch { success = false; } client.Dispose(); } if (success) { homegenie.RaiseEvent( Domains.HomeGenie_System, Domains.HomeGenie_PackageInstaller, SourceModule.Master, "HomeGenie Package Installer", Properties.InstallProgressMessage, "= Installing: " + program.name.ToString() ); int pid = int.Parse(program.uid.ToString()); var oldProgram = homegenie.ProgramManager.ProgramGet(pid); if (oldProgram != null) { homegenie.RaiseEvent( Domains.HomeGenie_System, Domains.HomeGenie_PackageInstaller, SourceModule.Master, "HomeGenie Package Installer", Properties.InstallProgressMessage, "= Replacing: '" + oldProgram.Name + "' with pid " + pid ); homegenie.ProgramManager.ProgramRemove(oldProgram); } var programBlock = ProgramImport(homegenie, pid, programFile, program.group.ToString()); if (programBlock != null) { programBlock.IsEnabled = true; homegenie.RaiseEvent( Domains.HomeGenie_System, Domains.HomeGenie_PackageInstaller, SourceModule.Master, "HomeGenie Package Installer", Properties.InstallProgressMessage, "= Installed: '" + program.name.ToString() + "' as pid " + pid ); } else { // TODO: report error and stop the package install procedure success = false; } } } // Import Widgets in package foreach (var widget in pkgData.widgets) { homegenie.RaiseEvent( Domains.HomeGenie_System, Domains.HomeGenie_PackageInstaller, SourceModule.Master, "HomeGenie Package Installer", Properties.InstallProgressMessage, "= Downloading: " + widget.file.ToString() ); Utility.FolderCleanUp(installFolder); string widgetFile = Path.Combine(installFolder, widget.file.ToString()); if (File.Exists(widgetFile)) File.Delete(widgetFile); using (var client = new WebClient()) { try { client.DownloadFile(pkgBaseUrl + "/" + widget.file.ToString(), widgetFile); } catch { success = false; } client.Dispose(); } if (success && WidgetImport(widgetFile, installFolder)) { homegenie.RaiseEvent( Domains.HomeGenie_System, Domains.HomeGenie_PackageInstaller, SourceModule.Master, "HomeGenie Package Installer", Properties.InstallProgressMessage, "= Installed: '" + widget.name.ToString() + "'" ); } else { // TODO: report error and stop the package install procedure success = false; } } // Import MIG Interfaces in package foreach (var migface in pkgData.interfaces) { homegenie.RaiseEvent( Domains.HomeGenie_System, Domains.HomeGenie_PackageInstaller, SourceModule.Master, "HomeGenie Package Installer", Properties.InstallProgressMessage, "= Downloading: " + migface.file.ToString() ); Utility.FolderCleanUp(installFolder); string migfaceFile = Path.Combine(installFolder, migface.file.ToString()); if (File.Exists(migfaceFile)) File.Delete(migfaceFile); using (var client = new WebClient()) { try { client.DownloadFile(pkgBaseUrl + "/" + migface.file.ToString(), migfaceFile); Utility.UncompressZip(migfaceFile, installFolder); File.Delete(migfaceFile); } catch { success = false; } client.Dispose(); } if (success && InterfaceInstall(installFolder)) { homegenie.RaiseEvent( Domains.HomeGenie_System, Domains.HomeGenie_PackageInstaller, SourceModule.Master, "HomeGenie Package Installer", Properties.InstallProgressMessage, "= Installed: '" + migface.name.ToString() + "'" ); } else { // TODO: report error and stop the package install procedure success = false; } } } else { success = false; } if (success) { // TODO: add package info to the list of installed packages // TODO: this package file must be included in the backup file also // TODO: and the restore process should also download and install // TODO: all packages included in it homegenie.RaiseEvent( Domains.HomeGenie_System, Domains.HomeGenie_PackageInstaller, SourceModule.Master, "HomeGenie Package Installer", Properties.InstallProgressMessage, "= Status: Package Install Successful" ); } else { homegenie.RaiseEvent( Domains.HomeGenie_System, Domains.HomeGenie_PackageInstaller, SourceModule.Master, "HomeGenie Package Installer", Properties.InstallProgressMessage, "= Status: Package Install Error" ); } request.ResponseData = new ResponseText(success ? "OK" : "ERROR"); } break; } }
public Engine Execute(string source) { var parser = new JavaScriptParser(); return(Execute(parser.Parse(source))); }
public void ShouldParseScriptFile(string file, string version) { var parser = new JavaScriptParser(); var source = GetEmbeddedFile(file); var sw = new Stopwatch(); var program = parser.Parse(source); Console.WriteLine("Parsed {0} {1} ({3} KB) in {2} ms", file, version, sw.ElapsedMilliseconds, (int)source.Length/1024); Assert.NotNull(program); }
public static async Task <int> Main(string[] args) { var rootDirectory = Path.GetDirectoryName(Assembly.GetEntryAssembly()?.Location) ?? string.Empty; var projectRoot = Path.Combine(rootDirectory, "../../.."); var allowListFile = Path.Combine(projectRoot, "allow-list.txt"); var lines = await File.ReadAllLinesAsync(allowListFile); var knownFailing = new HashSet <string>(lines .Where(x => !string.IsNullOrWhiteSpace(x) && !x.StartsWith("#")) ); // this should be same in both Test262Harness.settings.json and here const string Sha = "08a9fc2b974f83a9835174cede20a7935f126015"; var stream = await Test262StreamExtensions.FromGitHub(Sha); // we materialize to give better feedback on progress var test262Files = new ConcurrentBag <Test262File>(); TestExecutionSummary?summary = null; AnsiConsole.Progress() .Columns( new TaskDescriptionColumn(), new ProgressBarColumn(), new PercentageColumn(), new SpinnerColumn(), new ElapsedTimeColumn() ) .Start(ctx => { var readTask = ctx.AddTask("Loading tests", maxValue: 90_000); readTask.StartTask(); test262Files = new ConcurrentBag <Test262File>(stream.GetTestFiles()); readTask.Value = 100; readTask.StopTask(); AnsiConsole.WriteLine(); AnsiConsole.MarkupLine("Found [green]{0}[/] test cases to test against", test262Files.Count); var testTask = ctx.AddTask("Running tests", maxValue: test262Files.Count); var options = new Test262RunnerOptions { Execute = static file => { var parser = new JavaScriptParser(file.Program); if (file.Type == ProgramType.Script) { parser.ParseScript(file.Strict); } else { parser.ParseModule(); } }, IsIgnored = file => knownFailing.Contains(file.ToString()), IsParseError = exception => exception is ParserException, ShouldThrow = file => file.NegativeTestCase?.Type == ExpectedErrorType.SyntaxError || file.NegativeTestCase?.Phase == TestingPhase.Parse, OnTestExecuted = _ => testTask.Increment(1) }; var executor = new Test262Runner(options); summary = executor.Run(test262Files); testTask.StopTask(); });
public void ProcessRequest(MIGClientRequest request, MIGInterfaceCommand migCommand) { string response = ""; switch (migCommand.Command) { case "Interfaces.List": migCommand.Response = "[ "; foreach (var kv in homegenie.Interfaces) { var migInterface = kv.Value; var ifaceConfig = homegenie.SystemConfiguration.MIGService.GetInterface(migInterface.Domain); if (ifaceConfig == null || !ifaceConfig.IsEnabled) { continue; } migCommand.Response += "{ \"Domain\" : \"" + migInterface.Domain + "\", \"IsConnected\" : \"" + migInterface.IsConnected + "\" },"; } if (homegenie.UpdateChecker != null && homegenie.UpdateChecker.IsUpdateAvailable) { migCommand.Response += "{ \"Domain\" : \"" + Domains.HomeGenie_UpdateChecker + "\", \"IsConnected\" : \"True\" }"; migCommand.Response += " ]"; } else { migCommand.Response = migCommand.Response.Substring(0, migCommand.Response.Length - 1) + " ]"; } break; case "Interfaces.ListConfig": migCommand.Response = "[ "; foreach (var kv in homegenie.Interfaces) { var migInterface = kv.Value; var ifaceConfig = homegenie.SystemConfiguration.MIGService.GetInterface(migInterface.Domain); if (ifaceConfig == null) continue; migCommand.Response += JsonConvert.SerializeObject(ifaceConfig) + ","; } migCommand.Response = migCommand.Response.Substring(0, migCommand.Response.Length - 1) + " ]"; break; //TODO: should this be moved somewhere to MIG? case "Interfaces.Configure": switch (migCommand.GetOption(0)) { case "Hardware.SerialPorts": if (Environment.OSVersion.Platform == PlatformID.Unix) { var serialPorts = System.IO.Ports.SerialPort.GetPortNames(); var portList = new List<string>(); for (int p = serialPorts.Length - 1; p >= 0; p--) { if (serialPorts[p].Contains("/ttyS") || serialPorts[p].Contains("/ttyUSB")) { portList.Add(serialPorts[p]); } } if (Raspberry.Board.Current.IsRaspberryPi) { if (!portList.Contains("/dev/ttyAMA0")) portList.Add("/dev/ttyAMA0"); // RaZberry if (!portList.Contains("/dev/ttyACM0")) portList.Add("/dev/ttyACM0"); // ZME_UZB1 } migCommand.Response = JsonHelper.GetSimpleResponse(JsonConvert.SerializeObject(portList)); } else { var portNames = System.IO.Ports.SerialPort.GetPortNames(); migCommand.Response = JsonHelper.GetSimpleResponse(JsonConvert.SerializeObject(portNames)); } break; } break; case "Interface.Import": string downloadUrl = migCommand.GetOption(0); response = ""; string ifaceFileName = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, Utility.GetTmpFolder(), "mig_interface_import.zip"); string outputFolder = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, Utility.GetTmpFolder(), "mig"); Utility.FolderCleanUp(outputFolder); try { if (String.IsNullOrWhiteSpace(downloadUrl)) { // file uploaded by user MIG.Gateways.WebServiceUtility.SaveFile(request.InputStream, ifaceFileName); } else { // download file from url var client = new WebClient(); client.DownloadFile(downloadUrl, ifaceFileName); client.Dispose(); } } catch { // TODO: report exception } try { if (!Directory.Exists(outputFolder)) { Directory.CreateDirectory(outputFolder); } Utility.UncompressZip(ifaceFileName, outputFolder); File.Delete(ifaceFileName); var migInt = GetInterfaceConfig(Path.Combine(outputFolder, "configuration.xml")); if (migInt != null) { response = String.Format("{0} ({1})\n{2}\n", migInt.Domain, migInt.AssemblyName, migInt.Description); // Check for README notes and append them to the response var readmeFile = Path.Combine(outputFolder, "README.TXT"); if (File.Exists(readmeFile)) { response += File.ReadAllText(readmeFile); } migCommand.Response = JsonHelper.GetSimpleResponse(response); } else { migCommand.Response = JsonHelper.GetSimpleResponse("NOT A VALID ADD-ON PACKAGE"); } } catch { } break; case "Interface.Install": // install the interface package string outFolder = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, Utility.GetTmpFolder(), "mig"); string configFile = Path.Combine(outFolder, "configuration.xml"); var iface = GetInterfaceConfig(configFile); if (iface != null) { File.Delete(configFile); // homegenie.MigService.RemoveInterface(iface.Domain); // string configletName = iface.Domain.Substring(iface.Domain.LastIndexOf(".") + 1).ToLower(); string configletPath = Path.Combine("html", "pages", "configure", "interfaces", "configlet", configletName + ".html"); if (File.Exists(configletPath)) { File.Delete(configletPath); } File.Move(Path.Combine(outFolder, "configlet.html"), configletPath); // string logoPath = Path.Combine("html", "images", "interfaces", configletName + ".png"); if (File.Exists(logoPath)) { File.Delete(logoPath); } File.Move(Path.Combine(outFolder, "logo.png"), logoPath); // copy other interface files to mig folder (dll and dependencies) string migFolder = "mig"; Utility.FolderCleanUp(migFolder); DirectoryInfo dir = new DirectoryInfo(outFolder); foreach (var f in dir.GetFiles()) { string destFile = Path.Combine(migFolder, Path.GetFileName(f.FullName)); if (File.Exists(destFile)) { File.Move(destFile, Path.Combine(destFile, ".old")); File.Delete(Path.Combine(destFile, ".old")); } File.Move(f.FullName, destFile); } // homegenie.SystemConfiguration.MIGService.Interfaces.RemoveAll(i => i.Domain == iface.Domain); homegenie.SystemConfiguration.MIGService.Interfaces.Add(iface); homegenie.SystemConfiguration.Update(); homegenie.MigService.AddInterface(iface.Domain, iface.AssemblyName); migCommand.Response = JsonHelper.GetSimpleResponse("OK"); } else { migCommand.Response = JsonHelper.GetSimpleResponse("NOT A VALID ADD-ON PACKAGE"); } break; case "System.Configure": if (migCommand.GetOption(0) == "Service.Restart") { Program.Quit(true); migCommand.Response = JsonHelper.GetSimpleResponse("OK"); } else if (migCommand.GetOption(0) == "UpdateManager.UpdatesList") { migCommand.Response = JsonConvert.SerializeObject(homegenie.UpdateChecker.RemoteUpdates); } else if (migCommand.GetOption(0) == "UpdateManager.Check") { homegenie.UpdateChecker.Check(); migCommand.Response = JsonHelper.GetSimpleResponse("OK"); } else if (migCommand.GetOption(0) == "UpdateManager.DownloadUpdate") { var resultMessage = "ERROR"; bool success = homegenie.UpdateChecker.DownloadUpdateFiles(); if (success) { if (homegenie.UpdateChecker.IsRestartRequired) { resultMessage = "RESTART"; } else { resultMessage = "OK"; } } migCommand.Response = JsonHelper.GetSimpleResponse(resultMessage); } else if (migCommand.GetOption(0) == "UpdateManager.InstallUpdate") //UpdateManager.InstallProgramsCommit") { string resultMessage = "OK"; if (!homegenie.UpdateChecker.InstallFiles()) { resultMessage = "ERROR"; } else { if (homegenie.UpdateChecker.IsRestartRequired) { resultMessage = "RESTART"; Utility.RunAsyncTask(() => { Thread.Sleep(2000); Program.Quit(true); }); } else { homegenie.LoadConfiguration(); homegenie.MigService.ClearWebCache(); homegenie.UpdateChecker.Check(); } } migCommand.Response = JsonHelper.GetSimpleResponse(resultMessage); } else if (migCommand.GetOption(0) == "HttpService.SetWebCacheEnabled") { if (migCommand.GetOption(1) == "1") { homegenie.MigService.IsWebCacheEnabled = true; homegenie.SystemConfiguration.MIGService.EnableWebCache = "true"; } else { homegenie.MigService.IsWebCacheEnabled = false; homegenie.SystemConfiguration.MIGService.EnableWebCache = "false"; } homegenie.SystemConfiguration.Update(); migCommand.Response = JsonHelper.GetSimpleResponse("OK"); } else if (migCommand.GetOption(0) == "HttpService.GetWebCacheEnabled") { migCommand.Response = JsonHelper.GetSimpleResponse(homegenie.MigService.IsWebCacheEnabled ? "1" : "0"); } else if (migCommand.GetOption(0) == "HttpService.GetPort") { migCommand.Response = JsonHelper.GetSimpleResponse(homegenie.SystemConfiguration.HomeGenie.ServicePort.ToString()); } else if (migCommand.GetOption(0) == "HttpService.SetPort") { try { homegenie.SystemConfiguration.HomeGenie.ServicePort = int.Parse(migCommand.GetOption(1)); homegenie.SystemConfiguration.Update(); } catch { } } else if (migCommand.GetOption(0) == "HttpService.GetHostHeader") { migCommand.Response = JsonHelper.GetSimpleResponse(homegenie.SystemConfiguration.HomeGenie.ServiceHost.ToString()); } else if (migCommand.GetOption(0) == "HttpService.SetHostHeader") { try { homegenie.SystemConfiguration.HomeGenie.ServiceHost = migCommand.GetOption(1); homegenie.SystemConfiguration.Update(); } catch { } } else if (migCommand.GetOption(0) == "Statistics.GetStatisticsDatabaseMaximumSize") { migCommand.Response = JsonHelper.GetSimpleResponse(homegenie.SystemConfiguration.HomeGenie.Statistics.MaxDatabaseSizeMBytes.ToString()); } else if (migCommand.GetOption(0) == "Statistics.SetStatisticsDatabaseMaximumSize") { try { homegenie.SystemConfiguration.HomeGenie.Statistics.MaxDatabaseSizeMBytes = int.Parse(migCommand.GetOption(1)); homegenie.SystemConfiguration.Update(); } catch { } } else if (migCommand.GetOption(0) == "SystemLogging.DownloadCsv") { string csvlog = ""; string logpath = Path.Combine("log", "homegenie.log"); if (migCommand.GetOption(1) == "1") { logpath = Path.Combine("log", "homegenie.log.bak"); } if (File.Exists(logpath)) { using (var fs = new FileStream(logpath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) using (var sr = new StreamReader(fs, Encoding.Default)) { csvlog = sr.ReadToEnd(); } } (request.Context as HttpListenerContext).Response.AddHeader("Content-Disposition", "attachment;filename=homegenie_log_" + migCommand.GetOption(1) + ".csv"); migCommand.Response = csvlog; } else if (migCommand.GetOption(0) == "SystemLogging.Enable") { SystemLogger.Instance.OpenLog(); homegenie.SystemConfiguration.HomeGenie.EnableLogFile = "true"; homegenie.SystemConfiguration.Update(); } else if (migCommand.GetOption(0) == "SystemLogging.Disable") { SystemLogger.Instance.CloseLog(); homegenie.SystemConfiguration.HomeGenie.EnableLogFile = "false"; homegenie.SystemConfiguration.Update(); } else if (migCommand.GetOption(0) == "SystemLogging.IsEnabled") { migCommand.Response = JsonHelper.GetSimpleResponse((homegenie.SystemConfiguration.HomeGenie.EnableLogFile.ToLower().Equals("true") ? "1" : "0")); } else if (migCommand.GetOption(0) == "Security.SetPassword") { // password only for now, with fixed user login 'admin' string pass = migCommand.GetOption(1) == "" ? "" : MIG.Utility.Encryption.SHA1.GenerateHashString(migCommand.GetOption(1)); homegenie.MigService.SetWebServicePassword(pass); homegenie.SystemConfiguration.HomeGenie.UserPassword = pass; // regenerate encrypted files homegenie.SystemConfiguration.Update(); homegenie.UpdateModulesDatabase(); } else if (migCommand.GetOption(0) == "Security.ClearPassword") { homegenie.MigService.SetWebServicePassword(""); homegenie.SystemConfiguration.HomeGenie.UserPassword = ""; // regenerate encrypted files homegenie.SystemConfiguration.Update(); homegenie.UpdateModulesDatabase(); } else if (migCommand.GetOption(0) == "Security.HasPassword") { migCommand.Response = JsonHelper.GetSimpleResponse((homegenie.SystemConfiguration.HomeGenie.UserPassword != "" ? "1" : "0")); } else if (migCommand.GetOption(0) == "System.ConfigurationRestore") { // file uploaded by user string archivename = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, Utility.GetTmpFolder(), "homegenie_restore_config.zip"); Utility.FolderCleanUp(Utility.GetTmpFolder()); try { MIG.Gateways.WebServiceUtility.SaveFile(request.InputStream, archivename); Utility.UncompressZip(archivename, Path.Combine(AppDomain.CurrentDomain.BaseDirectory, Utility.GetTmpFolder())); File.Delete(archivename); } catch { } } else if (migCommand.GetOption(0) == "System.ConfigurationRestoreS1") { var serializer = new XmlSerializer(typeof(List<ProgramBlock>)); var reader = new StreamReader(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, Utility.GetTmpFolder(), "programs.xml")); var newProgramsData = (List<ProgramBlock>)serializer.Deserialize(reader); reader.Close(); var newProgramList = new List<ProgramBlock>(); foreach (ProgramBlock program in newProgramsData) { if (program.Address >= ProgramEngine.USER_SPACE_PROGRAMS_START) { ProgramBlock p = new ProgramBlock(); p.Address = program.Address; p.Name = program.Name; p.Description = program.Description; newProgramList.Add(p); } } newProgramList.Sort(delegate(ProgramBlock p1, ProgramBlock p2) { string c1 = p1.Address.ToString(); string c2 = p2.Address.ToString(); return c1.CompareTo(c2); }); migCommand.Response = JsonConvert.SerializeObject(newProgramList); } else if (migCommand.GetOption(0) == "System.ConfigurationRestoreS2") { var serializer = new XmlSerializer(typeof(List<Group>)); var reader = new StreamReader(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, Utility.GetTmpFolder(), "automationgroups.xml")); var automationGroups = (List<Group>)serializer.Deserialize(reader); reader.Close(); // foreach (var automationGroup in automationGroups) { if (homegenie.AutomationGroups.Find(g => g.Name == automationGroup.Name) == null) { homegenie.AutomationGroups.Add(automationGroup); } } // homegenie.UpdateGroupsDatabase("Automation"); // //File.Copy(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "tmp", "automationgroups.xml"), "./automationgroups.xml", true); File.Copy(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, Utility.GetTmpFolder(), "groups.xml"), Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "groups.xml"), true); File.Copy(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, Utility.GetTmpFolder(), "lircconfig.xml"), Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "lircconfig.xml"), true); File.Copy(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, Utility.GetTmpFolder(), "modules.xml"), Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "modules.xml"), true); File.Copy(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, Utility.GetTmpFolder(), "scheduler.xml"), Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "scheduler.xml"), true); File.Copy(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, Utility.GetTmpFolder(), "systemconfig.xml"), Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "systemconfig.xml"), true); // homegenie.LoadConfiguration(); // // Restore automation programs string selectedPrograms = migCommand.GetOption(1); serializer = new XmlSerializer(typeof(List<ProgramBlock>)); reader = new StreamReader(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, Utility.GetTmpFolder(), "programs.xml")); var newProgramsData = (List<ProgramBlock>)serializer.Deserialize(reader); reader.Close(); foreach (var program in newProgramsData) { var currentProgram = homegenie.ProgramEngine.Programs.Find(p => p.Address == program.Address); program.IsRunning = false; // Only restore user space programs if (selectedPrograms.Contains("," + program.Address.ToString() + ",") && program.Address >= ProgramEngine.USER_SPACE_PROGRAMS_START) { int oldPid = program.Address; if (currentProgram == null) { var newPid = ((currentProgram != null && currentProgram.Address == program.Address) ? homegenie.ProgramEngine.GeneratePid() : program.Address); try { File.Copy(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, Utility.GetTmpFolder(), "programs", program.Address + ".dll"), Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "programs", newPid + ".dll"), true); } catch { } program.Address = newPid; homegenie.ProgramEngine.ProgramAdd(program); } else if (currentProgram != null) { homegenie.ProgramEngine.ProgramRemove(currentProgram); try { File.Copy(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, Utility.GetTmpFolder(), "programs", program.Address + ".dll"), Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "programs", program.Address + ".dll"), true); } catch { } homegenie.ProgramEngine.ProgramAdd(program); } // Restore Arduino program folder ... // TODO: this is untested yet... if (program.Type.ToLower() == "arduino") { string sourceFolder = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, Utility.GetTmpFolder(), "programs", "arduino", oldPid.ToString()); string arduinoFolder = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "programs", "arduino", program.Address.ToString()); if (Directory.Exists(arduinoFolder)) Directory.Delete(arduinoFolder, true); Directory.CreateDirectory(arduinoFolder); foreach (string newPath in Directory.GetFiles(sourceFolder)) { File.Copy(newPath, newPath.Replace(sourceFolder, arduinoFolder), true); } } } else if (currentProgram != null && program.Address < ProgramEngine.USER_SPACE_PROGRAMS_START) { // Only restore Enabled/Disabled status of system programs currentProgram.IsEnabled = program.IsEnabled; } } // homegenie.UpdateProgramsDatabase(); // // regenerate encrypted files homegenie.UpdateModulesDatabase(); homegenie.SystemConfiguration.Update(); } else if (migCommand.GetOption(0) == "System.ConfigurationReset") { homegenie.RestoreFactorySettings(); } else if (migCommand.GetOption(0) == "System.ConfigurationBackup") { homegenie.BackupCurrentSettings(); (request.Context as HttpListenerContext).Response.Redirect("/hg/html/homegenie_backup_config.zip"); } else if (migCommand.GetOption(0) == "System.ConfigurationLoad") { homegenie.LoadConfiguration(); } break; case "Modules.Get": try { var module = homegenie.Modules.Find(m => m.Domain == migCommand.GetOption(0) && m.Address == migCommand.GetOption(1)); migCommand.Response = Utility.Module2Json(module, false); } catch (Exception ex) { migCommand.Response = JsonHelper.GetSimpleResponse("ERROR: \n" + ex.Message + "\n\n" + ex.StackTrace); } break; case "Modules.List": try { homegenie.modules_Sort(); migCommand.Response = homegenie.GetJsonSerializedModules(migCommand.GetOption(0).ToLower() == "short"); } catch (Exception ex) { migCommand.Response = JsonHelper.GetSimpleResponse("ERROR: \n" + ex.Message + "\n\n" + ex.StackTrace); } break; case "Modules.RoutingReset": try { for (int m = 0; m < homegenie.Modules.Count; m++) { homegenie.Modules[m].RoutingNode = ""; } migCommand.Response = JsonHelper.GetSimpleResponse("OK"); } catch (Exception ex) { migCommand.Response = JsonHelper.GetSimpleResponse("ERROR: \n" + ex.Message + "\n\n" + ex.StackTrace); } break; case "Modules.Save": string body = new StreamReader(request.InputStream).ReadToEnd(); var newModules = JsonConvert.DeserializeObject(body) as JArray; for (int i = 0; i < newModules.Count; i++) { try { var module = homegenie.Modules.Find(m => m.Address == newModules[i]["Address"].ToString() && m.Domain == newModules[i]["Domain"].ToString()); module.Name = newModules[i]["Name"].ToString(); // try { module.DeviceType = (MIG.ModuleTypes)Enum.Parse(typeof(MIG.ModuleTypes), newModules[i]["DeviceType"].ToString(), true); } catch { // TODO: check what's wrong here... } // var moduleProperties = newModules[i]["Properties"] as JArray; for (int p = 0; p < moduleProperties.Count; p++) { string propertyName = moduleProperties[p]["Name"].ToString(); string propertyValue = moduleProperties[p]["Value"].ToString(); ModuleParameter parameter = null; parameter = module.Properties.Find(delegate(ModuleParameter mp) { return mp.Name == propertyName; }); // if (propertyName == ModuleParameters.MODPAR_VIRTUALMETER_WATTS) { try { propertyValue = double.Parse(propertyValue.Replace(",", "."), System.Globalization.CultureInfo.InvariantCulture).ToString(); } catch { propertyValue = "0"; } } // if (parameter == null) { module.Properties.Add(new ModuleParameter() { Name = propertyName, Value = propertyValue }); } else { if (moduleProperties[p]["NeedsUpdate"] != null && moduleProperties[p]["NeedsUpdate"].ToString() == "true") { parameter.Value = propertyValue; } } } } catch (Exception) { //TODO: notify exception? } } homegenie.UpdateModulesDatabase();//write modules break; case "Modules.Update": string streamContent = new StreamReader(request.InputStream).ReadToEnd(); var newModule = JsonConvert.DeserializeObject<Module>(streamContent); var currentModule = homegenie.Modules.Find(p => p.Domain == newModule.Domain && p.Address == newModule.Address); // if (currentModule == null) { homegenie.Modules.Add(newModule); } else { currentModule.Name = newModule.Name; currentModule.Description = newModule.Description; currentModule.DeviceType = newModule.DeviceType; foreach (var newParameter in newModule.Properties) { var currentParameter = currentModule.Properties.Find(mp => mp.Name == newParameter.Name); if (currentParameter == null) { currentModule.Properties.Add(newParameter); } else if (newParameter.NeedsUpdate) { // reset current reporting Watts if VMWatts field is set to 0 if (newParameter.Name == ModuleParameters.MODPAR_VIRTUALMETER_WATTS && newParameter.DecimalValue == 0 && currentParameter.DecimalValue != 0) { homegenie.migService_InterfacePropertyChanged(new InterfacePropertyChangedAction() { Domain = currentModule.Domain, SourceId = currentModule.Address, SourceType = currentModule.Description, Path = ModuleParameters.MODPAR_METER_WATTS, Value = "0.0" }); } currentParameter.Value = newParameter.Value; } } // look for deleted properties var deletedParameters = new List<ModuleParameter>(); foreach (var parameter in currentModule.Properties) { var currentParameter = newModule.Properties.Find(mp => mp.Name == parameter.Name); if (currentParameter == null) { deletedParameters.Add(parameter); } } foreach (var parameter in deletedParameters) { currentModule.Properties.Remove(parameter); } deletedParameters.Clear(); } // homegenie.UpdateModulesDatabase(); break; case "Modules.Delete": var deletedModule = homegenie.Modules.Find(m => m.Domain == migCommand.GetOption(0) && m.Address == migCommand.GetOption(1)); if (deletedModule != null) { homegenie.Modules.Remove(deletedModule); } migCommand.Response = JsonHelper.GetSimpleResponse("OK"); // homegenie.UpdateModulesDatabase(); break; case "Stores.List": { var module = homegenie.Modules.Find(m => m.Domain == migCommand.GetOption(0) && m.Address == migCommand.GetOption(1)); if (module != null) { //module.Stores migCommand.Response = "["; for (int s = 0; s < module.Stores.Count; s++) { migCommand.Response += "{ \"Name\": \"" + Utility.XmlEncode(module.Stores[s].Name) + "\", \"Description\": \"" + Utility.XmlEncode(module.Stores[s].Description) + "\" },"; } migCommand.Response = migCommand.Response.TrimEnd(',') + "]"; } } break; case "Stores.Delete": break; case "Stores.ItemList": { var module = homegenie.Modules.Find(m => m.Domain == migCommand.GetOption(0) && m.Address == migCommand.GetOption(1)); if (module != null) { migCommand.Response = "["; var store = new StoreHelper(module.Stores, migCommand.GetOption(2)); for (int p = 0; p < store.List.Count; p++) { migCommand.Response += "{ \"Name\": \"" + Utility.XmlEncode(store.List[p].Name) + "\", \"Description\": \"" + Utility.XmlEncode(store.List[p].Description) + "\" },"; } migCommand.Response = migCommand.Response.TrimEnd(',') + "]"; } } break; case "Stores.ItemDelete": { var module = homegenie.Modules.Find(m => m.Domain == migCommand.GetOption(0) && m.Address == migCommand.GetOption(1)); if (module != null) { var name = migCommand.GetOption(3); var store = new StoreHelper(module.Stores, migCommand.GetOption(2)); store.List.RemoveAll(i => i.Name == name); } } break; case "Stores.ItemGet": { var module = homegenie.Modules.Find(m => m.Domain == migCommand.GetOption(0) && m.Address == migCommand.GetOption(1)); if (module != null) { var store = new StoreHelper(module.Stores, migCommand.GetOption(2)); migCommand.Response += JsonConvert.SerializeObject(store.Get(migCommand.GetOption(3))); } } break; case "Stores.ItemSet": { // value is the POST body string itemData = new StreamReader(request.InputStream).ReadToEnd(); var module = homegenie.Modules.Find(m => m.Domain == migCommand.GetOption(0) && m.Address == migCommand.GetOption(1)); if (module != null) { var store = new StoreHelper(module.Stores, migCommand.GetOption(2)); store.Get(migCommand.GetOption(3)).Value = itemData; } } break; case "Groups.ModulesList": var theGroup = homegenie.Groups.Find(z => z.Name.ToLower() == migCommand.GetOption(0).Trim().ToLower()); if (theGroup != null) { string jsonmodules = "["; for (int m = 0; m < theGroup.Modules.Count; m++) { var groupModule = homegenie.Modules.Find(mm => mm.Domain == theGroup.Modules[m].Domain && mm.Address == theGroup.Modules[m].Address); if (groupModule != null) { jsonmodules += Utility.Module2Json(groupModule, false) + ",\n"; } } jsonmodules = jsonmodules.TrimEnd(',', '\n'); jsonmodules += "]"; migCommand.Response = jsonmodules; } break; case "Groups.List": try { migCommand.Response = JsonConvert.SerializeObject(homegenie.GetGroups(migCommand.GetOption(0))); } catch (Exception ex) { migCommand.Response = JsonHelper.GetSimpleResponse("ERROR: \n" + ex.Message + "\n\n" + ex.StackTrace); } break; case "Groups.Rename": string oldName = migCommand.GetOption(1); string newName = new StreamReader(request.InputStream).ReadToEnd(); var currentGroup = homegenie.GetGroups(migCommand.GetOption(0)).Find(g => g.Name == oldName); var newGroup = homegenie.GetGroups(migCommand.GetOption(0)).Find(g => g.Name == newName); // ensure that the new group name is not already defined if (newGroup == null && currentGroup != null) { currentGroup.Name = newName; homegenie.UpdateGroupsDatabase(migCommand.GetOption(0)); //cmd.response = JsonHelper.GetSimpleResponse("OK"); } else { migCommand.Response = JsonHelper.GetSimpleResponse("New name already in use."); } break; case "Groups.Sort": using (var reader = new StreamReader(request.InputStream)) { var newGroupList = new List<Group>(); string[] newPositionOrder = reader.ReadToEnd().Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries); for (int i = 0; i < newPositionOrder.Length; i++) { newGroupList.Add(homegenie.GetGroups(migCommand.GetOption(0))[int.Parse(newPositionOrder[i])]); } homegenie.GetGroups(migCommand.GetOption(0)).Clear(); homegenie.GetGroups(migCommand.GetOption(0)).RemoveAll(g => true); homegenie.GetGroups(migCommand.GetOption(0)).AddRange(newGroupList); homegenie.UpdateGroupsDatabase(migCommand.GetOption(0)); } // try { migCommand.Response = JsonConvert.SerializeObject(homegenie.GetGroups(migCommand.GetOption(0))); } catch (Exception ex) { migCommand.Response = JsonHelper.GetSimpleResponse("ERROR: \n" + ex.Message + "\n\n" + ex.StackTrace); } break; case "Groups.SortModules": using (var reader = new StreamReader(request.InputStream)) { string groupName = migCommand.GetOption(1); Group sortGroup = null; try { sortGroup = homegenie.GetGroups(migCommand.GetOption(0)).Find(zn => zn.Name == groupName); } catch { } // if (sortGroup != null) { var newModulesReference = new List<ModuleReference>(); string[] newPositionOrder = reader.ReadToEnd().Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries); for (int i = 0; i < newPositionOrder.Length; i++) { newModulesReference.Add(sortGroup.Modules[int.Parse(newPositionOrder[i])]); } sortGroup.Modules.Clear(); sortGroup.Modules = newModulesReference; homegenie.UpdateGroupsDatabase(migCommand.GetOption(0)); } } try { migCommand.Response = JsonConvert.SerializeObject(homegenie.GetGroups(migCommand.GetOption(0))); } catch (Exception ex) { migCommand.Response = JsonHelper.GetSimpleResponse("ERROR: \n" + ex.Message + "\n\n" + ex.StackTrace); } break; case "Groups.Add": string newGroupName = new StreamReader(request.InputStream).ReadToEnd(); homegenie.GetGroups(migCommand.GetOption(0)).Add(new Group() { Name = newGroupName }); homegenie.UpdateGroupsDatabase(migCommand.GetOption(0));//write groups break; case "Groups.Delete": string deletedGroupName = new StreamReader(request.InputStream).ReadToEnd(); Group deletedGroup = null; try { deletedGroup = homegenie.GetGroups(migCommand.GetOption(0)).Find(zn => zn.Name == deletedGroupName); } catch { } // if (deletedGroup != null) { homegenie.GetGroups(migCommand.GetOption(0)).Remove(deletedGroup); homegenie.UpdateGroupsDatabase(migCommand.GetOption(0));//write groups if (migCommand.GetOption(0).ToLower() == "automation") { var groupPrograms = homegenie.ProgramEngine.Programs.FindAll(p => p.Group.ToLower() == deletedGroup.Name.ToLower()); if (groupPrograms != null) { // delete group association from programs foreach (ProgramBlock program in groupPrograms) { program.Group = ""; } } } } break; case "Groups.Save": string jsonGroups = new StreamReader(request.InputStream).ReadToEnd(); var newGroups = JsonConvert.DeserializeObject<List<Group>>(jsonGroups); for (int i = 0; i < newGroups.Count; i++) { try { var group = homegenie.Groups.Find(z => z.Name == newGroups[i].Name); group.Modules.Clear(); group.Modules = newGroups[i].Modules; } catch { } } homegenie.UpdateGroupsDatabase(migCommand.GetOption(0));//write groups break; case "Groups.WallpaperList": List<string> wallpaperList = new List<string>(); var images = Directory.GetFiles(groupWallpapersPath); for (int i = 0; i < images.Length; i++) { wallpaperList.Add(Path.GetFileName(images[i])); } migCommand.Response = JsonConvert.SerializeObject(wallpaperList); break; case "Groups.WallpaperAdd": { string wallpaperFile = ""; try { wallpaperFile = MIG.Gateways.WebServiceUtility.SaveFile(request.InputStream, groupWallpapersPath); } catch { } migCommand.Response = JsonHelper.GetSimpleResponse(Path.GetFileName(wallpaperFile)); } break; case "Groups.WallpaperSet": { string wpGroupName = migCommand.GetOption(0); var wpGroup = homegenie.GetGroups(migCommand.GetOption(0)).Find(g => g.Name == wpGroupName); if (wpGroup != null) { wpGroup.Wallpaper = migCommand.GetOption(1); homegenie.UpdateGroupsDatabase("Control"); } } break; case "Groups.WallpaperDelete": { string wallpaperFile = migCommand.GetOption(0); wallpaperFile = Path.Combine(groupWallpapersPath, Path.GetFileName(wallpaperFile)); if (File.Exists(wallpaperFile)) { File.Delete(wallpaperFile); } migCommand.Response = JsonHelper.GetSimpleResponse("OK"); } break; case "Widgets.List": List<string> widgetsList = new List<string>(); var groups = Directory.GetDirectories(widgetBasePath); for (int d = 0; d < groups.Length; d++) { var categories = Directory.GetDirectories(groups[d]); for (int c = 0; c < categories.Length; c++) { var widgets = Directory.GetFiles(categories[c], "*.js"); var group = groups[d].Replace(widgetBasePath, "").Substring(1); var category = categories[c].Replace(groups[d], "").Substring(1); for (int w = 0; w < widgets.Length; w++) { widgetsList.Add(group + "/" + category + "/" + Path.GetFileNameWithoutExtension(widgets[w])); } } } migCommand.Response = JsonConvert.SerializeObject(widgetsList); break; case "Widgets.Add": { response = "ERROR"; string widgetPath = migCommand.GetOption(0); // eg. homegenie/generic/dimmer string[] widgetParts = widgetPath.Split('/'); widgetParts[0] = new String(widgetParts[0].Where(Char.IsLetter).ToArray()).ToLower(); widgetParts[1] = new String(widgetParts[1].Where(Char.IsLetter).ToArray()).ToLower(); widgetParts[2] = new String(widgetParts[2].Where(Char.IsLetter).ToArray()).ToLower(); if (!String.IsNullOrWhiteSpace(widgetParts[0]) && !String.IsNullOrWhiteSpace(widgetParts[1]) && !String.IsNullOrWhiteSpace(widgetParts[2])) { string filePath = Path.Combine(widgetBasePath, widgetParts[0], widgetParts[1]); if (!Directory.Exists(filePath)) { Directory.CreateDirectory(filePath); } // copy widget template into the new widget var htmlFile = Path.Combine(filePath, widgetParts[2] + ".html"); var jsFile = Path.Combine(filePath, widgetParts[2] + ".js"); if (!File.Exists(htmlFile) && !File.Exists(jsFile)) { File.Copy(Path.Combine(widgetBasePath, "template.html"), htmlFile); File.Copy(Path.Combine(widgetBasePath, "template.js"), jsFile); response = "OK"; } } migCommand.Response = JsonHelper.GetSimpleResponse(response); } break; case "Widgets.Save": { response = "ERROR"; string widgetData = new StreamReader(request.InputStream).ReadToEnd(); string fileType = migCommand.GetOption(0); string widgetPath = migCommand.GetOption(1); // eg. homegenie/generic/dimmer string[] widgetParts = widgetPath.Split('/'); string filePath = Path.Combine(widgetBasePath, widgetParts[0], widgetParts[1]); if (!Directory.Exists(filePath)) { Directory.CreateDirectory(filePath); } switch (fileType) { // html/javascript source case "html": case "js": using (TextWriter widgetWriter = new StreamWriter(Path.Combine(filePath, widgetParts[2] + "." + fileType))) { widgetWriter.Write(widgetData); } response = "OK"; break; // style sheet file case "css": break; // locale file case "json": break; // image file case "jpg": case "png": case "gif": break; } migCommand.Response = JsonHelper.GetSimpleResponse(response); } break; case "Widgets.Delete": { response = "ERROR"; string widgetPath = migCommand.GetOption(0); // eg. homegenie/generic/dimmer string[] widgetParts = widgetPath.Split('/'); string filePath = Path.Combine(widgetBasePath, widgetParts[0], widgetParts[1], widgetParts[2] + "."); if (File.Exists(filePath + "html")) { File.Delete(filePath + "html"); response = "OK"; } if (File.Exists(filePath + "js")) { File.Delete(filePath + "js"); response = "OK"; } migCommand.Response = JsonHelper.GetSimpleResponse(response); } break; case "Widgets.Export": { string widgetPath = migCommand.GetOption(0); // eg. homegenie/generic/dimmer string[] widgetParts = widgetPath.Split('/'); string widgetBundle = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, Utility.GetTmpFolder(), "export", widgetPath.Replace('/', '_') + ".zip"); if (File.Exists(widgetBundle)) { File.Delete(widgetBundle); } else if (!Directory.Exists(Path.GetDirectoryName(widgetBundle))) { Directory.CreateDirectory(Path.GetDirectoryName(widgetBundle)); } string inputPath = Path.Combine(widgetBasePath, widgetParts[0], widgetParts[1]); string outputPath = Path.Combine(widgetParts[0], widgetParts[1]); string infoFilePath = Path.Combine(inputPath, "widget.info"); File.WriteAllText(infoFilePath, "HomeGenie exported widget."); Utility.AddFileToZip(widgetBundle, infoFilePath, "widget.info"); Utility.AddFileToZip(widgetBundle, Path.Combine(inputPath, widgetParts[2] + ".html"), Path.Combine(outputPath, widgetParts[2] + ".html")); Utility.AddFileToZip(widgetBundle, Path.Combine(inputPath, widgetParts[2] + ".js"), Path.Combine(outputPath, widgetParts[2] + ".js")); // byte[] bundleData = File.ReadAllBytes(widgetBundle); (request.Context as HttpListenerContext).Response.AddHeader("Content-Disposition", "attachment; filename=\"" + widgetPath.Replace('/', '_') + ".zip\""); (request.Context as HttpListenerContext).Response.OutputStream.Write(bundleData, 0, bundleData.Length); } break; case "Widgets.Import": { string archiveFile = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, Utility.GetTmpFolder(), "import_widget.zip"); string importPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, Utility.GetTmpFolder(), "import"); if (Directory.Exists(importPath)) Directory.Delete(importPath, true); MIG.Gateways.WebServiceUtility.SaveFile(request.InputStream, archiveFile); if (WidgetImport(archiveFile, importPath)) { migCommand.Response = JsonHelper.GetSimpleResponse("OK"); } else { migCommand.Response = JsonHelper.GetSimpleResponse("ERROR"); } } break; case "Widgets.Parse": { string widgetData = new StreamReader(request.InputStream).ReadToEnd(); var parser = new JavaScriptParser(); try { migCommand.Response = JsonHelper.GetSimpleResponse("OK"); parser.Parse(widgetData); } catch (Jint.Parser.ParserException e) { migCommand.Response = JsonHelper.GetSimpleResponse("ERROR (" + e.LineNumber + "," + e.Column + "): " + e.Description); } } break; } }
public Engine Execute(string source, ParserOptions parserOptions, DebugInfo debugInfo = null) { var parser = new JavaScriptParser(this); return(Execute(parser.Parse(source, parserOptions), debugInfo)); }
public JsValue Call(JsValue thisObject, JsValue[] arguments, bool directCall) { if (arguments.At(0).Type != Types.String) { return(arguments.At(0)); } var code = TypeConverter.ToString(arguments.At(0)); try { var parser = new JavaScriptParser(StrictModeScope.IsStrictModeCode); var program = parser.Parse(code); using (new StrictModeScope(program.Strict)) { using (new EvalCodeScope()) { LexicalEnvironment strictVarEnv = null; try { if (!directCall) { Engine.EnterExecutionContext(Engine.GlobalEnvironment, Engine.GlobalEnvironment, Engine.Global); } if (StrictModeScope.IsStrictModeCode) { strictVarEnv = LexicalEnvironment.NewDeclarativeEnvironment(Engine, Engine.ExecutionContext.LexicalEnvironment); Engine.EnterExecutionContext(strictVarEnv, strictVarEnv, Engine.ExecutionContext.ThisBinding); } Engine.DeclarationBindingInstantiation(DeclarationBindingType.EvalCode, program.FunctionDeclarations, program.VariableDeclarations, this, arguments); var result = _engine.ExecuteStatement(program); if (result.Type == Completion.Throw) { throw result.Exception ?? new JavaScriptException(result.GetValueOrDefault()) .SetCallstack(_engine, result.Location); } else { return(result.GetValueOrDefault()); } } finally { if (strictVarEnv != null) { Engine.LeaveExecutionContext(); } if (!directCall) { Engine.LeaveExecutionContext(); } } } } } catch (ParserException) { throw new JavaScriptException(Engine.SyntaxError); } }
public void ShouldParseClassInheritance() { var parser = new JavaScriptParser("class Rectangle extends aggregation(Shape, Colored, ZCoord) { }"); var program = parser.ParseScript(); }
public Engine Execute(string source, ParserOptions parserOptions) { var parser = new JavaScriptParser(); return(Execute(parser.Parse(source, parserOptions))); }
public List<ProgramError> Compile() { List<ProgramError> errors = new List<ProgramError>(); JavaScriptParser jp = new JavaScriptParser(false); //ParserOptions po = new ParserOptions(); try { jp.Parse(programBlock.ScriptCondition); } catch (Exception e) { // TODO: parse error message if (e.Message.Contains(":")) { string[] error = e.Message.Split(':'); string message = error[1]; if (message != "hg is not defined") // TODO: find a better solution for this { int line = int.Parse(error[0].Split(' ')[1]); errors.Add(new ProgramError() { Line = line, ErrorMessage = message, CodeBlock = "TC" }); } } } // try { jp.Parse(programBlock.ScriptSource); } catch (Exception e) { // TODO: parse error message if (e.Message.Contains(":")) { string[] error = e.Message.Split(':'); string message = error[1]; if (message != "hg is not defined") // TODO: find a better solution for this { int line = int.Parse(error[0].Split(' ')[1]); errors.Add(new ProgramError() { Line = line, ErrorMessage = message, CodeBlock = "CR" }); } } } return errors; }