Ejemplo n.º 1
0
        private static async void WebSocketClient_OnOpen()
        {
            try
            {
                Log.Information("WebSocketClient_OnOpen");
                TokenUser user = null;
                while (user == null)
                {
                    if (!string.IsNullOrEmpty(PluginConfig.tempjwt))
                    {
                        user = await global.webSocketClient.Signin(PluginConfig.tempjwt); if (user != null)
                        {
                            if (isService)
                            {
                                PluginConfig.jwt     = Base64Encode(PluginConfig.ProtectString(PluginConfig.tempjwt));
                                PluginConfig.tempjwt = null;
                                Config.Save();
                            }
                            Log.Information("Signed in as " + user.username);
                        }
                    }
                    else if (PluginConfig.jwt != null && PluginConfig.jwt.Length > 0)
                    {
                        user = await global.webSocketClient.Signin(PluginConfig.UnprotectString(Base64Decode(PluginConfig.jwt))); if (user != null)
                        {
                            Log.Information("Signed in as " + user.username);
                        }
                    }
                    else
                    {
                        Log.Error("Missing jwt from config, close down");
                        _ = global.webSocketClient.Close();
                        if (isService)
                        {
                            await manager.StopService();
                        }
                        if (!isService)
                        {
                            Environment.Exit(0);
                        }
                        return;
                    }
                }
                string computername = NativeMethods.GetHostName().ToLower();
                string computerfqdn = NativeMethods.GetFQDN().ToLower();
                var    servers      = await global.webSocketClient.Query <unattendedserver>("openrpa", "{'_type':'unattendedserver', 'computername':'" + computername + "', 'computerfqdn':'" + computerfqdn + "'}");

                unattendedserver server = servers.FirstOrDefault();
                if (servers.Length == 0)
                {
                    Log.Information("Adding new unattendedserver for " + computerfqdn);
                    server = new unattendedserver()
                    {
                        computername = computername, computerfqdn = computerfqdn, name = computerfqdn, enabled = true
                    };
                    server = await global.webSocketClient.InsertOne("openrpa", 1, false, server);
                }
                //var clients = await global.webSocketClient.Query<unattendedclient>("openrpa", "{'_type':'unattendedclient', 'computername':'" + computername + "', 'computerfqdn':'" + computerfqdn + "'}");
                //foreach (var c in clients) sessions.Add(new RobotUserSession(c));
                // Log.Information("Loaded " + sessions.Count + " sessions");
                // Create listener for robots to connect too
                if (pipe == null)
                {
                    PipeSecurity ps = new PipeSecurity();
                    ps.AddAccessRule(new PipeAccessRule("Users", PipeAccessRights.ReadWrite | PipeAccessRights.CreateNewInstance, System.Security.AccessControl.AccessControlType.Allow));
                    ps.AddAccessRule(new PipeAccessRule("CREATOR OWNER", PipeAccessRights.FullControl, System.Security.AccessControl.AccessControlType.Allow));
                    ps.AddAccessRule(new PipeAccessRule("SYSTEM", PipeAccessRights.FullControl, System.Security.AccessControl.AccessControlType.Allow));
                    pipe = new OpenRPA.NamedPipeWrapper.NamedPipeServer <RPAMessage>("openrpa_service", ps);
                    pipe.ClientConnected += Pipe_ClientConnected;
                    pipe.ClientMessage   += Pipe_ClientMessage;
                    pipe.Start();
                }

                if (reloadTimer == null)
                {
                    reloadTimer          = new System.Timers.Timer(PluginConfig.reloadinterval.TotalMilliseconds);
                    reloadTimer.Elapsed += async(o, e) =>
                    {
                        reloadTimer.Stop();
                        try
                        {
                            await ReloadConfig();
                        }
                        catch (Exception ex)
                        {
                            Log.Error(ex.ToString());
                        }
                        reloadTimer.Start();
                    };
                    reloadTimer.Start();
                }
            }
            catch (Exception ex)
            {
                Log.Error(ex.ToString());
            }
        }
Ejemplo n.º 2
0
        static void Main(string[] args)
        {
            System.Threading.Thread.Sleep(1000 * StartupWaitSeconds);
            // Don't mess with ProjectsDirectory if we need to reauth
            if (args.Length == 0)
            {
                AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
                try
                {
                    if (PluginConfig.usefreerdp)
                    {
                        using (var rdp = new FreeRDP.Core.RDP())
                        {
                        }
                    }
                }
                catch (Exception)
                {
                    Console.WriteLine("Failed initilizing FreeRDP, is Visual C++ Runtime installed ?");
                    // Console.WriteLine("https://support.microsoft.com/en-us/help/2977003/the-latest-supported-visual-c-downloads");
                    Console.WriteLine("https://www.microsoft.com/en-us/download/details.aspx?id=40784");
                    return;
                }
            }
            var parentProcess = NativeMethods.GetParentProcessId();

            isService = (parentProcess.ProcessName.ToLower() == "services");
            if (args.Length == 0)
            {
                // System.Threading.Thread.Sleep(1000 * StartupWaitSeconds);
                if (!manager.IsServiceInstalled)
                {
                    //Console.Write("Username (" + NativeMethods.GetProcessUserName() + "): ");
                    //var username = Console.ReadLine();
                    //if (string.IsNullOrEmpty(username)) username = NativeMethods.GetProcessUserName();
                    //Console.Write("Password: "******"";
                    //do
                    //{
                    //    ConsoleKeyInfo key = Console.ReadKey(true);
                    //    if (key.Key != ConsoleKey.Backspace && key.Key != ConsoleKey.Enter)
                    //    {
                    //        pass += key.KeyChar;
                    //        Console.Write("*");
                    //    }
                    //    else
                    //    {
                    //        if (key.Key == ConsoleKey.Backspace && pass.Length > 0)
                    //        {
                    //            pass = pass.Substring(0, (pass.Length - 1));
                    //            Console.Write("\b \b");
                    //        }
                    //        else if (key.Key == ConsoleKey.Enter)
                    //        {
                    //            break;
                    //        }
                    //    }
                    //} while (true);
                    //manager.InstallService(typeof(Program), new string[] { "username="******"password="******"****** BEGIN");
            if (args.Length > 0)
            {
                if (args[0].ToLower() == "auth" || args[0].ToLower() == "reauth")
                {
                    if (Config.local.jwt != null && Config.local.jwt.Length > 0)
                    {
                        Log.Information("Saving temporart jwt token, from local settings.json");
                        PluginConfig.tempjwt = new System.Net.NetworkCredential(string.Empty, Config.local.UnprotectString(Config.local.jwt)).Password;
                        PluginConfig.wsurl   = Config.local.wsurl;

                        PluginConfig.Save();
                        Config.Save();
                        Console.WriteLine("local  count: " + Config.local.properties.Count);
                        Console.WriteLine("Plugin count: " + PluginConfig.globallocal.properties.Count);
                    }
                    return;
                }
                else if (args[0].ToLower() == "uninstall" || args[0].ToLower() == "u")
                {
                    if (manager.IsServiceInstalled)
                    {
                        manager.UninstallService(typeof(Program));
                    }
                    return;
                }
                else
                {
                    Console.WriteLine("unknown command " + args[0]);
                    Console.WriteLine("try uninstall or reauth ");
                }
                return;
            }
            Console.WriteLine("****** isService: " + isService);
            if (isService)
            {
                System.ServiceProcess.ServiceBase.Run(new MyServiceBase(ServiceName, DoWork));
            }
            else
            {
                DoWork();
            }
        }
Ejemplo n.º 3
0
        private static void DoWork()
        {
            try
            {
                log("BEGIN::Set ProjectsDirectory");
                // Don't mess with ProjectsDirectory if we need to reauth
                if (args.Length == 0)
                {
                    Log.ResetLogPath(logpath);
                }

                log("Set UnhandledException");
                AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
                System.Threading.Thread.Sleep(1000 * StartupWaitSeconds);
                if (args.Length != 0)
                {
                    try
                    {
                        log("Get usefreerdp");
                        if (PluginConfig.usefreerdp)
                        {
                            log("Init Freerdp");
                            using (var rdp = new FreeRDP.Core.RDP())
                            {
                            }
                        }
                    }
                    catch (Exception)
                    {
                        Console.WriteLine("Failed initilizing FreeRDP, is Visual C++ Runtime installed ?");
                        // Console.WriteLine("https://support.microsoft.com/en-us/help/2977003/the-latest-supported-visual-c-downloads");
                        Console.WriteLine("https://www.microsoft.com/en-us/download/details.aspx?id=40784");
                        return;
                    }
                }
                if (args.Length == 0)
                {
                    log("Check IsServiceInstalled");
                    // System.Threading.Thread.Sleep(1000 * StartupWaitSeconds);
                    if (!manager.IsServiceInstalled)
                    {
                        //Console.Write("Username (" + NativeMethods.GetProcessUserName() + "): ");
                        //var username = Console.ReadLine();
                        //if (string.IsNullOrEmpty(username)) username = NativeMethods.GetProcessUserName();
                        //Console.Write("Password: "******"";
                        //do
                        //{
                        //    ConsoleKeyInfo key = Console.ReadKey(true);
                        //    if (key.Key != ConsoleKey.Backspace && key.Key != ConsoleKey.Enter)
                        //    {
                        //        pass += key.KeyChar;
                        //        Console.Write("*");
                        //    }
                        //    else
                        //    {
                        //        if (key.Key == ConsoleKey.Backspace && pass.Length > 0)
                        //        {
                        //            pass = pass.Substring(0, (pass.Length - 1));
                        //            Console.Write("\b \b");
                        //        }
                        //        else if (key.Key == ConsoleKey.Enter)
                        //        {
                        //            break;
                        //        }
                        //    }
                        //} while (true);
                        //manager.InstallService(typeof(Program), new string[] { "username="******"password="******"InstallService");
                        manager.InstallService(typeof(Program), new string[] { });
                    }
                }
                if (args.Length > 0)
                {
                    if (args[0].ToLower() == "auth" || args[0].ToLower() == "reauth")
                    {
                        if (Config.local.jwt != null && Config.local.jwt.Length > 0)
                        {
                            Log.Information("Saving temporart jwt token, from local settings.json");
                            PluginConfig.tempjwt = new System.Net.NetworkCredential(string.Empty, Config.local.UnprotectString(Config.local.jwt)).Password;
                            PluginConfig.wsurl   = Config.local.wsurl;
                            PluginConfig.Save();
                        }
                        return;
                    }
                    else if (args[0].ToLower() == "uninstall" || args[0].ToLower() == "u")
                    {
                        if (manager.IsServiceInstalled)
                        {
                            manager.UninstallService(typeof(Program));
                        }

                        var asm      = System.Reflection.Assembly.GetEntryAssembly();
                        var filepath = asm.CodeBase.Replace("file:///", "");
                        var exepath  = System.IO.Path.GetDirectoryName(filepath);
                        if (System.IO.File.Exists(System.IO.Path.Combine(exepath, "OpenRPA.RDServiceMonitor.exe")))
                        {
                            var process = System.Diagnostics.Process.Start(System.IO.Path.Combine(exepath, "OpenRPA.RDServiceMonitor.exe"), "uninstall");
                            process.WaitForExit();
                        }
                        return;
                    }
                    else
                    {
                        Console.WriteLine("unknown command " + args[0]);
                        Console.WriteLine("try uninstall or reauth ");
                    }
                    return;
                }


                log("Create Tracing");
                tracing = new Tracing(Console.Out);
                log("Add Tracing");
                System.Diagnostics.Trace.Listeners.Add(tracing);
                log("Override SetOut");
                Console.SetOut(new ConsoleDecorator(Console.Out));
                log("Override SetError");
                Console.SetError(new ConsoleDecorator(Console.Out, true));
                log("ResetLogPath");
                Log.ResetLogPath(logpath);
                Console.WriteLine("****** BEGIN");

                Task.Run(async() => {
                    try
                    {
                        Console.WriteLine("Connect to " + PluginConfig.wsurl);
                        global.webSocketClient                 = new WebSocketClient(PluginConfig.wsurl);
                        global.webSocketClient.OnOpen         += WebSocketClient_OnOpen;
                        global.webSocketClient.OnClose        += WebSocketClient_OnClose;
                        global.webSocketClient.OnQueueMessage += WebSocketClient_OnQueueMessage;
                        await global.webSocketClient.Connect();
                    }
                    catch (Exception ex)
                    {
                        Log.Error(ex.ToString());
                    }
                });
                // NativeMethods.AllocConsole();
                // if (System.Diagnostics.Debugger.IsAttached && !isService)
                if (!Monitormanager.IsServiceInstalled)
                {
                    var asm      = System.Reflection.Assembly.GetEntryAssembly();
                    var filepath = asm.CodeBase.Replace("file:///", "");
                    var exepath  = System.IO.Path.GetDirectoryName(filepath);
                    if (System.IO.File.Exists(System.IO.Path.Combine(exepath, "OpenRPA.RDServiceMonitor.exe")))
                    {
                        var process = System.Diagnostics.Process.Start(System.IO.Path.Combine(exepath, "OpenRPA.RDServiceMonitor.exe"));
                        process.WaitForExit();
                    }
                }
                if (!isService)
                {
                    Log.Information("******************************");
                    Log.Information("* Done                       *");
                    Log.Information("******************************");
                    Console.ReadLine();
                }
                else
                {
                    if (Monitormanager.IsServiceInstalled)
                    {
                        _ = Monitormanager.StartService();
                    }
                    while (MyServiceBase.isRunning)
                    {
                        System.Threading.Thread.Sleep(100);
                    }
                    if (Monitormanager.IsServiceInstalled)
                    {
                        // _ = Monitormanager.StopService();
                    }
                }
            }
            catch (Exception ex)
            {
                Log.Error(ex.ToString());
            }
        }