Esempio n. 1
0
        public static Actions ExecuteAction(string action, string line, string parameter)
        {
            Actions actionExecution = new Actions();
            string  theAction       = action.ToLower();

            if (ActionMods.ModActionExists(theAction))
            {
                actionExecution.ModExecution(theAction, parameter);
            }
            else
            {
                switch (theAction)
                {
                case "shutdown":
                    //Shuts down the computer
                    actionExecution.Shutdown(parameter);
                    break;

                case "restart":
                    //Restart the computer
                    actionExecution.Restart(parameter);
                    break;

                case "sleep":
                    //Puts computer to sleep
                    actionExecution.Sleep(parameter);
                    break;

                case "hibernate":
                    //Hibernates computer
                    actionExecution.Hibernate(parameter);
                    break;

                case "logout":
                    //Logs out of the current user
                    actionExecution.Logout(parameter);
                    break;

                case "lock":
                    //Lock computer
                    actionExecution.Lock(parameter);
                    break;

                case "mute":
                    //Mutes windows
                    //Parameter optional (true/false)
                    actionExecution.Mute(parameter);
                    break;

                case "set_volume":
                    //Sets volume to a specific percent
                    //Requires parameter (percent, int)
                    if (RequireParameter(parameter))
                    {
                        actionExecution.SetVolume(parameter);
                    }
                    break;

                case "music":
                    if (RequireParameter(parameter))
                    {
                        switch (parameter)
                        {
                        case "previous":
                        case "previousx2":
                            break;

                        case "next":
                            break;

                        case "play_pause":
                            break;
                        }
                        actionExecution.Music(parameter);
                    }
                    break;

                case "open":
                    if (RequireParameter(parameter))
                    {
                        actionExecution.Open(parameter);
                    }
                    break;

                case "open_all":
                    if (RequireParameter(parameter))
                    {
                        actionExecution.OpenAll(parameter);
                    }
                    break;

                case "die":
                    //Exit ACC
                    actionExecution.Die(parameter);
                    break;

                case "monitors_off":
                    actionExecution.MonitorsOff(parameter);
                    break;

                case "key_shortcut":
                    if (RequireParameter(parameter))
                    {
                        actionExecution.KeyShortcut(parameter);
                    }
                    break;

                case "write_out":
                    if (RequireParameter(parameter))
                    {
                        actionExecution.WriteOut(parameter, line);
                    }
                    break;

                case "create_file":
                    if (RequireParameter(parameter))
                    {
                        actionExecution.CreateFile(parameter);
                    }
                    break;

                case "delete_file":
                    if (RequireParameter(parameter))
                    {
                        actionExecution.DeleteFile(parameter);
                    }
                    break;

                case "append_text":
                    if (RequireParameter(parameter))
                    {
                        actionExecution.AppendText(parameter);
                    }
                    break;

                case "message_box":
                    if (RequireParameter(parameter))
                    {
                        actionExecution.DoMessageBox(parameter);
                    }
                    break;

                case "move":
                    if (RequireParameter(parameter))
                    {
                        actionExecution.MoveSubject(parameter);
                    }
                    break;

                case "kill_process":
                    if (RequireParameter(parameter))
                    {
                        actionExecution.KillProcess(parameter);
                    }
                    break;

                case "minimize_all":
                    actionExecution.MinimizeAll();
                    break;

                case "maximize_all":
                    actionExecution.MaximizeAll();
                    break;

                case "move_mouse":
                    if (RequireParameter(parameter))
                    {
                        actionExecution.MoveMouse(parameter);
                    }
                    break;

                case "mouse_click":
                    actionExecution.MouseClick(parameter);
                    break;

                case "wait":
                    if (RequireParameter(parameter))
                    {
                        actionExecution.Wait(parameter);
                    }
                    break;

                default:
                    //Unknown action
                    actionExecution.errorMessage = "Unknown action \"" + action + "\"";
                    break;
                }
            }

            if (MainProgram.testingAction)
            {
                MainProgram.testActionWindow.ActionExecuted(actionExecution.successMessage, actionExecution.errorMessage, action, parameter, line);
            }

            return(actionExecution);
        }
Esempio n. 2
0
        static void Main(string[] args)
        {
            Console.WriteLine("Log location; " + logFilePath);
            CheckSettings();

            var config  = new NLog.Config.LoggingConfiguration();
            var logfile = new NLog.Targets.FileTarget("logfile")
            {
                FileName = logFilePath
            };
            var logconsole = new NLog.Targets.ConsoleTarget("logconsole");

            config.AddRule(LogLevel.Info, LogLevel.Fatal, logconsole);
            config.AddRule(LogLevel.Debug, LogLevel.Fatal, logfile);
            NLog.LogManager.Configuration = config;

            void ActualMain()
            {
                AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);

                //Upgrade settings
                if (Properties.Settings.Default.UpdateSettings)
                {
                    /* Copy old setting-files in case the Evidence type and Evidence Hash has changed (which it does sometimes) - easier than creating a whole new settings system */
                    try {
                        Configuration accConfiguration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.PerUserRoamingAndLocal);
                        string        currentFolder    = new DirectoryInfo(accConfiguration.FilePath).Parent.Parent.FullName;
                        string[]      directories      = Directory.GetDirectories(new DirectoryInfo(currentFolder).Parent.FullName);

                        foreach (string dir in directories)
                        {
                            if (dir != currentFolder.ToString())
                            {
                                var directoriesInDir = Directory.GetDirectories(dir);
                                foreach (string childDir in directoriesInDir)
                                {
                                    string checkPath = Path.Combine(currentFolder, Path.GetFileName(childDir));
                                    if (!Directory.Exists(checkPath))
                                    {
                                        string checkFile = Path.Combine(childDir, "user.config");
                                        if (File.Exists(checkFile))
                                        {
                                            bool xmlHasError = false;
                                            try {
                                                XmlDocument xml = new XmlDocument();
                                                xml.Load(checkFile);

                                                xml.Validate(null);
                                            } catch {
                                                xmlHasError = true;
                                                DoDebug("XML document validation failed (is invalid): " + checkFile);
                                            }

                                            if (!xmlHasError)
                                            {
                                                Directory.CreateDirectory(checkPath);
                                                File.Copy(checkFile, Path.Combine(checkPath, "user.config"), true);
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    } catch (Exception e) {
                        Console.WriteLine("Error getting settings from older versions of ACC" + e.Message);
                    }
                    /* End "copy settings" */

                    try {
                        Properties.Settings.Default.Upgrade();
                        Properties.Settings.Default.UpdateSettings = false;
                        Properties.Settings.Default.Save();
                    } catch {
                        DoDebug("Failed to upgrade from old settings file.");
                    }

                    Console.WriteLine("Upgraded settings to match last version");
                }

                if (Properties.Settings.Default.LastUpdated == DateTime.MinValue)
                {
                    Properties.Settings.Default.LastUpdated = DateTime.Now;
                }

                //Translator
                string tempDir = Path.Combine(currentLocation, "Translations");

                if (Directory.Exists(tempDir))
                {
                    Translator.translationFolder = Path.Combine(currentLocation, "Translations");
                    Translator.languagesArray    = Translator.GetLanguages();
                }
                else
                {
                    MessageBox.Show("Missing the translations folder. Reinstall the software to fix this issue.", messageBoxTitle);
                }

                string lang = Properties.Settings.Default.ActiveLanguage;

                if (Array.Exists(Translator.languagesArray, element => element == lang))
                {
                    DoDebug("ACC running with language \"" + lang + "\"");

                    Translator.SetLanguage(lang);
                }
                else
                {
                    DoDebug("Invalid language chosen (" + lang + ")");

                    Properties.Settings.Default.ActiveLanguage = "English";
                    Translator.SetLanguage("English");
                }
                //End translator
                sysIcon = new SysTrayIcon();

                Properties.Settings.Default.TimesOpened += 1;
                Properties.Settings.Default.Save();

                SetupDataFolder();
                if (File.Exists(logFilePath))
                {
                    try {
                        File.WriteAllText(logFilePath, string.Empty);
                    } catch {
                        // Don't let this being DENIED crash the software
                        Console.WriteLine("Failed to empty the log");
                    }
                }
                else
                {
                    Console.WriteLine("Trying to create log");
                    CreateLogFile();
                }

                //Check if software already runs, if so kill this instance
                var otherACCs = Process.GetProcessesByName(Path.GetFileNameWithoutExtension(currentLocationFull));

                if (otherACCs.Length > 1)
                {
                    //Try kill the _other_ process instead
                    foreach (Process p in otherACCs)
                    {
                        if (p.Id != Process.GetCurrentProcess().Id)
                        {
                            try {
                                p.Kill();
                                DoDebug("Other ACC instance was running. Killed it.");
                            } catch {
                                DoDebug("Could not kill other process of ACC; access denied");
                            }
                        }
                    }
                }

                Application.EnableVisualStyles();

                DoDebug("[ACC begun (v" + softwareVersion + ")]");

                if (Properties.Settings.Default.CheckForUpdates)
                {
                    if (HasInternet())
                    {
                        new Thread(() => {
                            new SoftwareUpdater().Check();
                        }).Start();
                    }
                    else
                    {
                        DoDebug("Couldn't check for new update as PC does not have access to the internet");
                    }
                }

                //On console close: hide NotifyIcon
                Application.ApplicationExit += new EventHandler(OnApplicationExit);
                handler = new ConsoleEventDelegate(ConsoleEventCallback);
                SetConsoleCtrlHandler(handler, true);

                //Check if software starts with Windows
                if (!ACCStartsWithWindows())
                {
                    sysIcon.AddOpenOnStartupMenu();
                }

                //Create shortcut folder if doesn't exist
                if (!Directory.Exists(shortcutLocation))
                {
                    Directory.CreateDirectory(shortcutLocation);
                }
                if (!File.Exists(Path.Combine(shortcutLocation, @"example.txt")))
                {
                    //Create example-file
                    try {
                        using (StreamWriter sw = File.CreateText(Path.Combine(shortcutLocation, @"example.txt"))) {
                            sw.WriteLine("This is an example file.");
                            sw.WriteLine("If you haven't already, make your assistant open this file!");
                        }
                    } catch {
                        DoDebug("Could not create or write to example file");
                    }
                }

                //Delete all old action files
                if (Directory.Exists(CheckPath()))
                {
                    DoDebug("Deleting all files in action folder");
                    foreach (string file in Directory.GetFiles(CheckPath(), "*." + Properties.Settings.Default.ActionFileExtension))
                    {
                        int timeout = 0;

                        if (File.Exists(file))
                        {
                            while (ActionChecker.FileInUse(file) && timeout < 5)
                            {
                                timeout++;
                                Thread.Sleep(500);
                            }
                            if (timeout >= 5)
                            {
                                DoDebug("Failed to delete file at " + file + " as file appears to be in use (and has been for 2.5 seconds)");
                            }
                            else
                            {
                                try {
                                    File.Delete(file);
                                } catch (Exception e) {
                                    DoDebug("Failed to delete file at " + file + "; " + e.Message);
                                }
                            }
                        }
                    }
                    DoDebug("Old action files removed - moving on...");
                }

                //SetupListener();
                watcher = new FileSystemWatcher()
                {
                    Path         = CheckPath(),
                    NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite
                                   | NotifyFilters.FileName | NotifyFilters.DirectoryName,
                    Filter = "*." + Properties.Settings.Default.ActionFileExtension,
                    EnableRaisingEvents = true
                };
                watcher.Changed += new FileSystemEventHandler(new ActionChecker().FileFound);
                watcher.Created += new FileSystemEventHandler(new ActionChecker().FileFound);
                watcher.Renamed += new RenamedEventHandler(new ActionChecker().FileFound);
                watcher.Deleted += new FileSystemEventHandler(new ActionChecker().FileFound);
                watcher.Error   += delegate { DoDebug("Something wen't wrong TEST"); };

                DoDebug("\n[" + messageBoxTitle + "] Initiated. \nListening in: \"" + CheckPath() + "\" for \"." + Properties.Settings.Default.ActionFileExtension + "\" extensions");

                sysIcon.TrayIcon.Icon = Properties.Resources.ACC_icon_light;

                RegistryKey key = Registry.CurrentUser.OpenSubKey("Software", true);

                if (Registry.GetValue(key.Name + @"\AssistantComputerControl", "FirstTime", null) == null)
                {
                    key.CreateSubKey("AssistantComputerControl");
                    key = key.OpenSubKey("AssistantComputerControl", true);
                    key.SetValue("FirstTime", false);

                    Properties.Settings.Default.HasCompletedTutorial = true;
                    Properties.Settings.Default.Save();

                    ShowGettingStarted();

                    DoDebug("Starting setup guide");
                }
                else
                {
                    if (!Properties.Settings.Default.HasCompletedTutorial)
                    {
                        ShowGettingStarted();
                        DoDebug("Didn't finish setup guide last time, opening again");
                    }
                }
                SetRegKey("ActionFolder", CheckPath());
                SetRegKey("ActionExtension", Properties.Settings.Default.ActionFileExtension);

                testActionWindow = new TestActionWindow();

                //If newly updated
                if (Properties.Settings.Default.LastKnownVersion != softwareVersion)
                {
                    //Up(or down)-grade, display version notes
                    Properties.Settings.Default.LastUpdated = DateTime.Now;
                    if (gettingStarted != null)
                    {
                        DoDebug("'AboutVersion' window awaits, as 'Getting Started' is showing");
                        aboutVersionAwaiting = true;
                    }
                    else
                    {
                        Properties.Settings.Default.LastKnownVersion = softwareVersion;
                        new NewVersion().Show();
                    }
                    Properties.Settings.Default.Save();
                }

                /* 'Evalufied' user feedback implementation */
                if ((DateTime.Now - Properties.Settings.Default.LastUpdated).TotalDays >= 7 && Properties.Settings.Default.TimesOpened >= 7 &&
                    gettingStarted == null &&
                    !Properties.Settings.Default.HasPromptedFeedback)
                {
                    //User has had the software/update for at least 7 days, and has opened the software more than 7 times - time to ask for feedback
                    //(also the "getting started" window is not showing)
                    if (HasInternet())
                    {
                        try {
                            WebRequest      request  = WebRequest.Create("https://evalufied.dk/");
                            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                            if (response == null || response.StatusCode != HttpStatusCode.OK)
                            {
                                DoDebug("'Evalufied' is down - won't show faulty feedback window");
                            }
                            else
                            {
                                DoDebug("Showing 'User Feedback' window");
                                Properties.Settings.Default.HasPromptedFeedback = true;
                                Properties.Settings.Default.Save();
                                new UserFeedback().Show();
                            }
                        } catch {
                            DoDebug("Failed to check for 'Evalufied'-availability");
                        }
                    }
                    else
                    {
                        DoDebug("No internet connection, not showing user feedback window");
                    }
                }

                //Action mods implementation
                ActionMods.CheckMods();
                TaskSchedulerSetup();

                SystemEvents.SessionSwitch += new SessionSwitchEventHandler(SystemEvents_SessionSwitch); //On wake up from sleep
                Application.Run();
            }

            if (sentryToken != "super_secret")
            {
                //Tracking issues with Sentry.IO - not forked from GitHub (official version)
                bool sentryOK = false;
                try {
                    if (Properties.Settings.Default.UID != "")
                    {
                        Properties.Settings.Default.UID = Guid.NewGuid().ToString();
                        Properties.Settings.Default.Save();
                    }

                    if (Properties.Settings.Default.UID != "")
                    {
                        SentrySdk.ConfigureScope(scope => {
                            scope.User = new Sentry.Protocol.User {
                                Id = Properties.Settings.Default.UID
                            };
                        });
                    }

                    using (SentrySdk.Init(sentryToken)) {
                        sentryOK = true;
                    }
                } catch {
                    //Sentry failed. Error sentry's side or invalid key - don't let this stop the app from running
                    DoDebug("Sentry initiation failed");
                    ActualMain();
                }

                if (sentryOK)
                {
                    try {
                        using (SentrySdk.Init(sentryToken)) {
                            DoDebug("Sentry initiated");
                            ActualMain();
                        }
                    } catch {
                        ActualMain();
                    }
                }
            }
            else
            {
                //Code is (most likely) forked - skip issue tracking
                ActualMain();
            }
        }