public GettingStarted(int startTab = 0) { InitializeComponent(); Thread.CurrentThread.Priority = ThreadPriority.Highest; FormClosed += delegate { if (MainProgram.aboutVersionAwaiting) { Properties.Settings.Default.LastKnownVersion = MainProgram.softwareVersion; new NewVersion().Show(); Properties.Settings.Default.Save(); } }; tabControl.Appearance = TabAppearance.FlatButtons; tabControl.ItemSize = new Size(0, 1); tabControl.SizeMode = TabSizeMode.Fixed; tabControl.BackColor = Color.Transparent; tabControl.SelectTab(startTab); tabControl.Selected += delegate { if (tabControl.SelectedIndex == 1) { //Clicked on recommended setup guide (HTML), can show "move on" popover now theWebBrowser.Document.InvokeScript("showHelpPopover"); } else if (tabControl.SelectedIndex == 2) { expert.Focus(); } }; //Auto-select "recommended" panel RecommendedClicked(null, null); finalOptionButton.FlatStyle = FlatStyle.Flat; finalOptionButton.FlatAppearance.BorderSize = 0; setupSelect.MouseHover += delegate { if (selectedPanel != recommendedPanel) { recommendedPanel.borderColor = Pens.Black; recommendedPanel.Refresh(); } if (selectedPanel != expertPanel) { expertPanel.borderColor = Pens.Black; expertPanel.Refresh(); } }; //Recommended panel recommendedPanel.MouseHover += RecommendedHovered; recommendedPanel.Click += RecommendedClicked; recommendedLabel.MouseHover += RecommendedHovered; recommendedLabel.Click += RecommendedClicked; recommendedLabel2.MouseHover += RecommendedHovered; recommendedLabel2.Click += RecommendedClicked; recommendedLabel3.MouseHover += RecommendedHovered; recommendedLabel3.Click += RecommendedClicked; recommendedImage.MouseHover += RecommendedHovered; recommendedImage.Click += RecommendedClicked; //Expert panel expertPanel.MouseHover += ExpertHovered; expertPanel.Click += ExpertClicked; expertLabel1.MouseHover += ExpertHovered; expertLabel1.Click += ExpertClicked; expertLabel2.MouseHover += ExpertHovered; expertLabel2.Click += ExpertClicked; expertLabel2.MouseHover += ExpertHovered; expertLabel2.Click += ExpertClicked; expertLabel3.MouseHover += ExpertHovered; expertLabel3.Click += delegate { Process.Start("https://acc.readme.io/v1.0/docs/application-advanced-settings-expert-setup"); }; tooltip.SetToolTip(expertLabel3, "This will open a link in your default browser"); expertLabel4.MouseHover += ExpertHovered; expertLabel4.Click += ExpertClicked; expertImage.MouseHover += ExpertHovered; expertImage.Click += ExpertClicked; //Further expert settings actionFolderPath.KeyDown += new KeyEventHandler(FreakingStopDingSound); actionFileExtension.KeyDown += new KeyEventHandler(FreakingStopDingSound); void FreakingStopDingSound(Object o, KeyEventArgs e) { if (e.KeyCode == Keys.Enter) { e.Handled = true; e.SuppressKeyPress = true; } } actionFolderPath.Text = MainProgram.CheckPath(); actionFileExtension.Text = Properties.Settings.Default.ActionFileExtension; actionFolderPath.KeyDown += delegate { MainProgram.SetCheckFolder(actionFolderPath.Text); actionFolderPath.Text = MainProgram.CheckPath(); }; actionFolderPath.KeyUp += delegate { MainProgram.SetCheckFolder(actionFolderPath.Text); actionFolderPath.Text = MainProgram.CheckPath(); }; actionFileExtension.KeyDown += delegate { MainProgram.SetCheckExtension(actionFileExtension.Text); }; actionFileExtension.KeyUp += delegate { MainProgram.SetCheckExtension(actionFileExtension.Text); }; expert.Click += delegate { expert.Focus(); }; customSetupInfo.Click += delegate { expert.Focus(); }; expertDoneButton.FlatStyle = FlatStyle.Flat; expertDoneButton.FlatAppearance.BorderSize = 0; closeWindowButton.FlatStyle = FlatStyle.Flat; closeWindowButton.FlatAppearance.BorderSize = 0; analyticsMoveOn.FlatStyle = FlatStyle.Flat; analyticsMoveOn.FlatAppearance.BorderSize = 0; //Browser theWebBrowser = GuideWebBrowser; theWebBrowser.DocumentCompleted += BrowserDocumentCompleted; theWebBrowser.Navigating += BrowserNavigating; theWebBrowser.NewWindow += NewBrowserWindow; VisibleChanged += delegate { MainProgram.testingAction = Visible; MainProgram.gettingStarted = Visible ? this : null; }; FormClosed += delegate { MainProgram.testingAction = false; MainProgram.gettingStarted = null; }; }
public static void SetupAnalyticsAsync() { //Unique user-ID if (Properties.Settings.Default.UID == "" || Properties.Settings.Default.UID == null) { string newUID = Guid.NewGuid().ToString("N"); Properties.Settings.Default.UID = newUID; Properties.Settings.Default.Save(); MainProgram.DoDebug("Set UID to " + newUID); } else { MainProgram.DoDebug("UID; " + Properties.Settings.Default.UID); } if (Properties.Settings.Default.SendAnonymousAnalytics) { MainProgram.DoDebug("Setting up annonymous analytics..."); //Execution amounts if (Properties.Settings.Default.TotalActionsExecuted == null) { Properties.Settings.Default.TotalActionsExecuted = new int[actions.Length - 1]; Properties.Settings.Default.Save(); } int[] actionsExecuted = Properties.Settings.Default.TotalActionsExecuted; if (actions.Length != actionsExecuted.Length) { //MainProgram.DoDebug(actions.Length + " != " + actionsExecuted.Length); //New action most likely added int[] oldSettings = actionsExecuted , newSettings = new int[actions.Length]; //Populate new analytics array with old values int i = 0; foreach (int ac in oldSettings) { if (i != newSettings.Length) { newSettings[i] = ac; } i++; } Properties.Settings.Default.TotalActionsExecuted = newSettings; Properties.Settings.Default.Save(); } //Assistant type if (Properties.Settings.Default.AssistantType == null) { Properties.Settings.Default.AssistantType = new int[actions.Length - 1]; Properties.Settings.Default.Save(); } MainProgram.DoDebug("Annonymous analytics setup done"); } else { MainProgram.DoDebug("Annonymous analytics are not being shared"); } }
private bool EmptyCheck() { return(Directory.GetFiles(MainProgram.CheckPath()).Length > 0); }
private void skipGuide_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) { SetupDone(); MainProgram.DoDebug("Skipped setup guide"); Close(); }
private void TrayExit(object sender, EventArgs e) { TrayIcon.Visible = false; MainProgram.Exit(); }
public void ProcessFile(string file, bool tryingAgain = false) { //Custom 'file read delay' float fileReadDelay = Properties.Settings.Default.FileReadDelay; if (fileReadDelay > 0) { MainProgram.DoDebug("User has set file delay to " + fileReadDelay.ToString() + "s, waiting before processing..."); Thread.Sleep((int)fileReadDelay * 1000); } if (!File.Exists(file)) { MainProgram.DoDebug("File doesn't exist (anymore)."); return; } //Make sure the file isn't in use before trying to access it int tries = 0; while (FileInUse(file) || tries >= 20) { tries++; } if (tries >= 20 && FileInUse(file)) { MainProgram.DoDebug("File in use in use and can't be read. Try again."); return; } //Check unique file ID (dublicate check) ulong theFileUid = 0; bool gotFileUid = false; tries = 0; while (!gotFileUid || tries >= 30) { try { theFileUid = getFileUID(file); gotFileUid = true; } catch { Thread.Sleep(50); } } if (tries >= 30 && !gotFileUid) { MainProgram.DoDebug("File in use in use and can't be read. Try again."); return; } //Validate UID if (lastFileUid == 0) { lastFileUid = Properties.Settings.Default.LastActionFileUid; } if (lastFileUid == theFileUid && !tryingAgain) { //Often times this function is called three times per file - check if it has already been (or is being) processed return; } if (executedFiles.Contains(theFileUid) && !tryingAgain) { MainProgram.DoDebug("Tried to execute an already-executed file (UID " + theFileUid.ToString() + ")"); return; } lastFileUid = theFileUid; executedFiles.Add(theFileUid); Properties.Settings.Default.LastActionFileUid = lastFileUid; Properties.Settings.Default.Save(); MainProgram.DoDebug("Processing file..."); string originalFileName = file, fullContent = ""; if (!File.Exists(file)) { MainProgram.DoDebug("File no longer exists when trying to read file."); return; } //READ FILE if (new FileInfo(file).Length != 0) { try { string fileContent; fileContent = File.ReadAllText(file); fullContent = Regex.Replace(fileContent, @"\t|\r", ""); } catch (Exception e) { if (unsuccessfulReads < 20) { MainProgram.DoDebug("Failed to read file - trying again in 200ms... (trying max 20 times)"); unsuccessfulReads++; Thread.Sleep(200); ProcessFile(file, true); return; } else { MainProgram.DoDebug("Could not read file on final try; " + e); unsuccessfulReads = 0; return; } } MainProgram.DoDebug(" - Read complete, content: " + fullContent); } else { MainProgram.DoDebug(" - File is empty"); ErrorMessageBox("No action was set in the action file."); } //END READ //DateTime lastModified = File.GetCreationTime(file); DateTime lastModified = File.GetLastWriteTime(file); if (lastModified.AddSeconds(Properties.Settings.Default.FileEditedMargin) < DateTime.Now) { //if (File.GetLastWriteTime(file).AddSeconds(Properties.Settings.Default.FileEditedMargin) < DateTime.Now) { //Extra security - sometimes the "creation" time is a bit behind, but the "modify" timestamp is usually right. MainProgram.DoDebug("File creation time: " + lastModified.ToString()); MainProgram.DoDebug("Local time: " + DateTime.Now.ToString()); if (GettingStarted.isConfiguringActions) { //Possibly configure an offset - if this always happens Console.WriteLine("File is actually too old, but configuring the software to maybe set an offset"); isConfiguringOffset = true; if (lastModifiedOffsets == null) { lastModifiedOffsets = new List <double>(); } lastModifiedOffsets.Add((DateTime.Now - lastModified).TotalSeconds); if (lastModifiedOffsets.Count >= 3) { int average = (int)(lastModifiedOffsets.Average()); Console.WriteLine("File Margin fixed offset set to; " + average.ToString()); Properties.Settings.Default.AutoFileMarginFixer = average; Properties.Settings.Default.Save(); } } else { bool isGood = false; if (Properties.Settings.Default.AutoFileMarginFixer != 0) { //if (lastModified.AddSeconds(-Properties.Settings.Default.AutoFileMarginFixer) < DateTime.Now) { var d1 = lastModified.AddSeconds(-Properties.Settings.Default.FileEditedMargin); var d2 = DateTime.Now.AddSeconds(-Properties.Settings.Default.AutoFileMarginFixer); if (d1 < d2) { isGood = true; MainProgram.DoDebug("File timestamp is actually more than " + Properties.Settings.Default.FileEditedMargin.ToString() + "s old, but the software is configured to have an auto-file-margin fix for " + Properties.Settings.Default.AutoFileMarginFixer.ToString() + "s"); } else { //MainProgram.DoDebug(d1.ToString()); //MainProgram.DoDebug(d2.ToString()); MainProgram.DoDebug("The " + Properties.Settings.Default.AutoFileMarginFixer.ToString() + "s didn't fix it"); } } if (!isGood) { MainProgram.DoDebug("The file is more than " + Properties.Settings.Default.FileEditedMargin.ToString() + "s old, meaning it won't be executed."); new CleanupService().Start(); return; } } //} } MainProgram.DoDebug("\n[ -- DOING ACTION(S) -- ]"); MainProgram.DoDebug(" - " + file + " UID; " + theFileUid); MainProgram.DoDebug(" - File exists, checking the content..."); //Process the file using (StringReader reader = new StringReader(fullContent)) { string theLine = string.Empty; do { theLine = reader.ReadLine(); if (theLine != null) { MainProgram.DoDebug("\n[EXECUTING ACTION]"); CheckAction(theLine, file); } } while (theLine != null); } MainProgram.DoDebug("[ -- DONE -- ]"); }
private void doSetupAgain_Click(object sender, EventArgs e) { MainProgram.ShowGettingStarted(); }
public void SetODtype(string type) { MainProgram.DoDebug("Setting OneDrive type to " + type); MainProgram.SetCheckFolder(Environment.GetEnvironmentVariable(type)); }
public void CloudServiceChosen(string service = "") { switch (service) { case "dropbox": case "onedrive": case "googledrive": backgroundCheckerServiceName = service; break; default: return; } if (CloudServiceFunctions.GetCloudServicePath(backgroundCheckerServiceName) != "") { //Cloud service found MainProgram.DoDebug("Cloud service " + backgroundCheckerServiceName + " is installed"); if (backgroundCheckerServiceName == "googledrive") { bool partial = CloudServiceFunctions.GetGoogleDriveFolder() != String.Empty; if (theWebBrowser != null) { if (theWebBrowser.Handle != null) { theWebBrowser.Document.InvokeScript("CloudServiceInstalled", new Object[2] { true, partial }); } } if (partial) { CheckLocalGoogleDrive(); } } else { if (theWebBrowser != null) { if (theWebBrowser.Handle != null) { theWebBrowser.Document.InvokeScript("CloudServiceInstalled", new Object[1] { true }); } } } } else { //Not found new Thread(() => { Thread.CurrentThread.IsBackground = true; string checkValue = ""; stopCheck = false; MainProgram.DoDebug("Could not find cloud service. Running loop to check"); while (checkValue == "" && !stopCheck) { checkValue = CloudServiceFunctions.GetCloudServicePath(backgroundCheckerServiceName); Thread.Sleep(1000); } if (stopCheck) { stopCheck = false; return; } //Cloud service has been installed since we last checked! MainProgram.DoDebug("Cloud service has been installed since last check. Proceed."); if (theWebBrowser != null) { if (theWebBrowser.Handle != null) { theWebBrowser.Invoke(new Action(() => { if (backgroundCheckerServiceName == "googledrive") { bool partial = CloudServiceFunctions.GetGoogleDriveFolder() != String.Empty; theWebBrowser.Document.InvokeScript("CloudServiceInstalled", new Object[2] { true, partial }); if (partial) { CheckLocalGoogleDrive(); } } else { theWebBrowser.Document.InvokeScript("CloudServiceInstalled", new Object[1] { true }); } })); } } }).Start(); } }
static public void FileFound(object source, FileSystemEventArgs e) { string file = e.FullPath; if (!MainProgram.isPerformingAction) { MainProgram.isPerformingAction = true; MainProgram.DoDebug("File exists, checking the content..."); while (FileInUse(file)) { ; } if (new FileInfo(file).Length != 0) { MainProgram.DoDebug("Action set. File is not empty..."); string line = File.ReadAllText(file); MainProgram.DoDebug("Read complete, content: " + line); DateTime lastModified = File.GetLastWriteTime(file); string action = line; string parameter = null; string timeParam = null; if (lastModified.AddSeconds(Properties.Settings.Default.FileEditedMargin) > DateTime.Now) { //If file has been modified recently - check for action MainProgram.DoDebug("File modified within the last " + Properties.Settings.Default.FileEditedMargin + " seconds..."); //Check for timestamp param - for future use (possibly) to calculate how long the request took - //however Google Assistant doesn't return second-stamp, only hour and minute, so unless they implement it; can't be used if (line.Contains("[") && line.Contains("]")) { action = line.Split('[')[0]; timeParam = line.Split('[')[1]; timeParam.Replace("]", ""); if (timeParam.Contains("time;")) { timeParam = timeParam.Split(';')[1]; MainProgram.DoDebug("Action has time parameter; " + timeParam); } } if (action.Contains(":")) { //Contains a parameter action = line.Split(':')[0]; parameter = line.Split(':')[1]; if (parameter == "") { parameter = null; } } if (MainProgram.testingAction) { MainProgram.DoDebug("Test went through: " + action); } switch (action) { case "shutdown": //Shuts down the computer string shutdownParameters = "/s /t 0"; if (parameter != null) { if (parameter == "abort") { shutdownParameters = "abort"; } else { if (parameter.Contains("/t")) { shutdownParameters = !parameter.Contains("/s") ? "/s " : "" + parameter; } else { shutdownParameters = !parameter.Contains("/s") ? "/s " : "" + parameter + " /t 0"; } } } if (MainProgram.testingAction) { MainProgram.testActionMessage = shutdownParameters; } else { if (shutdownParameters != "abort") { MainProgram.DoDebug("Shutting down computer..."); successMessage = "Shutting down"; Process.Start("shutdown", shutdownParameters); } else { MainProgram.DoDebug("Cancelling shutdown..."); Process.Start("shutdown", "/a"); successMessage = "Aborted shutdown"; } } break; case "restart": //Restart the computer string restartParameters = "/r /t 0"; if (parameter != null) { if (parameter == "abort") { restartParameters = "abort"; } else { if (parameter.Contains("/t")) { restartParameters = !parameter.Contains("/r") ? "/r " : "" + parameter; } else { restartParameters = !parameter.Contains("/r") ? "/r " : "" + parameter + " /t 0"; } } } if (MainProgram.testingAction) { MainProgram.testActionMessage = restartParameters; } else { if (restartParameters != "abort") { MainProgram.DoDebug("Restarting computer..."); successMessage = "Restarting"; Process.Start("shutdown", restartParameters); } else { MainProgram.DoDebug("Cancelling restart..."); Process.Start("shutdown", "/a"); successMessage = "Aborted restart"; } } break; case "sleep": //Puts computer to sleep if (MainProgram.testingAction) { } MainProgram.DoDebug("Putting computer to sleep..."); if (parameter == null) { Application.SetSuspendState(PowerState.Suspend, true, true); } else { bool doForce = true; switch (parameter) { case "true": doForce = true; break; case "false": doForce = false; break; default: MainProgram.DoDebug("ERROR: Parameter (" + parameter + ") is invalid for \"" + action + "\". Accepted parameters: \"true\" and \"false\""); MainProgram.errorMessage = "Parameter \"" + parameter + "\" is invalid for the \"" + action + "\" action. Accepted parameters: \"true\" and \"false\")"; break; } Application.SetSuspendState(PowerState.Suspend, doForce, true); } successMessage = "Put computer to sleep"; break; case "logout": //Logs out of the current user MainProgram.DoDebug("Logging out of user..."); ExitWindowsEx(0, 0); successMessage = "Logged out of user"; break; case "lock": //Lock computer if (MainProgram.testingAction) { successMessage = "Simulated PC lock"; } else { MainProgram.DoDebug("Locking computer..."); LockWorkStation(); successMessage = "Locked pc"; } break; case "mute": //Mutes windows //Parameter optional (true/false) bool doMute = true; if (parameter == null) { //No parameter - toggle doMute = !AudioManager.GetMasterVolumeMute(); } else { //Parameter set; switch (parameter) { case "true": doMute = true; break; case "false": doMute = false; break; default: MainProgram.DoDebug("ERROR: Parameter (" + parameter + ") is invalid for \"" + action + "\". Accepted parameters: \"true\" and \"false\""); MainProgram.errorMessage = "Parameter \"" + parameter + "\" is invalid for the \"" + action + "\" action. Accepted parameters: \"true\" and \"false\")"; break; } } AudioManager.SetMasterVolumeMute(doMute); successMessage = (doMute ? "Muted " : "Unmuted") + "pc"; break; case "set_volume": //Sets volume to a specific percent //Requires parameter (percent, int) if (requireParameter(parameter)) { if (double.TryParse(parameter, out double volumeLevel)) { if (volumeLevel >= 0 && volumeLevel <= 100) { if (Properties.Settings.Default.UnmuteOnVolumeChange) { AudioManager.SetMasterVolumeMute(false); } AudioManager.SetMasterVolume((float)volumeLevel); if (AudioManager.GetMasterVolume() != volumeLevel) { //Something went wrong... Audio not set to parameter-level MainProgram.DoDebug("ERROR: Volume was not sat"); MainProgram.errorMessage = "Something went wrong when setting the volume"; } else { successMessage = "Set volume to " + volumeLevel + "%"; } } else { MainProgram.DoDebug("ERROR: Parameter is an invalid number, range; 0-100 (" + volumeLevel + ")"); MainProgram.errorMessage = "Can't set volume to " + volumeLevel + "%, has to be a number from 0-100"; } } else { MainProgram.DoDebug("ERROR: Parameter (" + parameter + ") not convertable to double"); MainProgram.errorMessage = "Not a valid parameter (has to be a number)"; } } break; case "music": if (requireParameter(parameter)) { switch (parameter) { case "previous": keybd_event(VK_MEDIA_PREV_TRACK, 0, KEYEVENTF_EXTENTEDKEY, 0); successMessage = "MUSIC: Skipped song"; break; /*case "previousx2": //WIP * keybd_event(VK_MEDIA_PREV_TRACK, 0, KEYEVENTF_EXTENTEDKEY, 0); * keybd_event(VK_MEDIA_PREV_TRACK, 0, KEYEVENTF_EXTENTEDKEY, 0); * success_message = "MUSIC: Skipped song (x2)"; * break;*/ case "next": keybd_event(VK_MEDIA_NEXT_TRACK, 0, KEYEVENTF_EXTENTEDKEY, 0); successMessage = "MUSIC: Next song"; break; case "play_pause": keybd_event(VK_MEDIA_PLAY_PAUSE, 0, KEYEVENTF_EXTENTEDKEY, 0); successMessage = "MUSIC: Played/Paused"; break; default: MainProgram.DoDebug("ERROR: Unknown parameter"); MainProgram.errorMessage = "Unknown parameter \"" + parameter + "\""; break; } } break; case "open": if (requireParameter(parameter)) { string fileLocation = Path.Combine(MainProgram.shortcutLocation, parameter); if (File.Exists(fileLocation)) { Process.Start(fileLocation); successMessage = "OPEN: opened file; " + fileLocation; } else { MainProgram.DoDebug("ERROR: file doesn't exist (" + fileLocation + ")"); MainProgram.errorMessage = "File doesn't exist (" + fileLocation + ")"; } } break; case "die": //Exit ACC Application.Exit(); break; default: //Unknown action MainProgram.DoDebug("ERROR: Unknown action"); MainProgram.errorMessage = "Unknown action \"" + action + "\""; break; } if (successMessage != "") { MainProgram.DoDebug("\nSUCCESS: " + successMessage + "\n"); } if (MainProgram.testingAction) { MainProgram.testActionWindow.ActionExecuted(successMessage, MainProgram.errorMessage, action, parameter); } successMessage = ""; } else { MainProgram.DoDebug("No action set within the last " + Properties.Settings.Default.FileEditedMargin + " seconds. File last edited; " + lastModified + ". PC time; " + DateTime.Now); MainProgram.errorMessage = "No action set lately"; } } else { MainProgram.DoDebug("File is empty"); MainProgram.errorMessage = "No action set (file is empty)"; } MainProgram.ClearFile(file); if (MainProgram.errorMessage.Length != 0 && !MainProgram.debug) { MessageBox.Show(MainProgram.errorMessage, "Error | " + MainProgram.messageBoxTitle); MainProgram.errorMessage = ""; } MainProgram.isPerformingAction = false; } else { MainProgram.DoDebug("Already performing an action"); } }
public void SkipGuide() { MainProgram.gettingStarted.SetupDone(); MainProgram.DoDebug("Skipped setup guide"); MainProgram.gettingStarted.Close(); }
static public void ProcessFile(string file, bool tryingAgain = false) { MainProgram.DoDebug("Processing file..."); string originalFileName = file; float fileReadDelay = Properties.Settings.Default.FileReadDelay; if (fileReadDelay > 0) { MainProgram.DoDebug("User has set file delay to " + fileReadDelay.ToString() + "s, waiting before processing..."); Thread.Sleep((int)fileReadDelay * 1000); } if (!File.Exists(file)) { MainProgram.DoDebug("File doesn't exist (anymore)."); return; } bool hidden = (File.GetAttributes(file) & FileAttributes.Hidden) == FileAttributes.Hidden; if (hidden && !tryingAgain) { MainProgram.DoDebug("File is hidden and has therefore (most likely) already been processed and executed. Ignoring it..."); return; } //DateTime lastModified = File.GetCreationTime(file); DateTime lastModified = File.GetLastWriteTime(file); if (lastModified == lastActionModified && !tryingAgain) { MainProgram.DoDebug("File has the exact same 'last modified' timestamp as the previous action - most likely a dublicate; ignoring"); return; } lastActionModified = lastModified; if (lastModified.AddSeconds(Properties.Settings.Default.FileEditedMargin) < DateTime.Now) { //if (File.GetLastWriteTime(file).AddSeconds(Properties.Settings.Default.FileEditedMargin) < DateTime.Now) { //Extra security - sometimes the "creation" time is a bit behind, but the "modify" timestamp is usually right. MainProgram.DoDebug("The file is more than " + Properties.Settings.Default.FileEditedMargin.ToString() + "s old, meaning it won't be executed."); MainProgram.DoDebug("File creation time: " + lastModified.ToString()); MainProgram.DoDebug("Local time: " + DateTime.Now.ToString()); new CleanupService().Start(); return; //} } MainProgram.DoDebug("\n[ -- DOING ACTION(S) -- ]"); MainProgram.DoDebug(" - " + file); MainProgram.DoDebug(" - File exists, checking the content..."); try { File.SetAttributes(file, FileAttributes.Hidden); } catch { MainProgram.DoDebug("Failed to set attribute; hidden on action file"); } if (new FileInfo(file).Length != 0) { string fullContent = ""; //Sentry issue @804439508 int tries = 0; while (FileInUse(file) || tries >= 20) { tries++; } if (tries >= 20 && FileInUse(file)) { MainProgram.DoDebug("File still in use and can't be read. Try again."); return; } try { string fileContent; fileContent = File.ReadAllText(file); fullContent = Regex.Replace(fileContent, @"\t|\r", ""); } catch (Exception e) { if (unsuccessfulReads < 20) { MainProgram.DoDebug("Failed to read file - trying again in 200ms... (trying max 20 times)"); unsuccessfulReads++; Thread.Sleep(200); ProcessFile(file, true); return; } else { MainProgram.DoDebug("Could not read file on final try; " + e); unsuccessfulReads = 0; return; } } MainProgram.DoDebug(" - Read complete, content: " + fullContent); using (StringReader reader = new StringReader(fullContent)) { string theLine = string.Empty; do { theLine = reader.ReadLine(); if (theLine != null) { MainProgram.DoDebug("\n[EXECUTING ACTION]"); CheckAction(theLine, file); } } while (theLine != null); } } else { MainProgram.DoDebug(" - File is empty"); MainProgram.errorMessage = "No action set (file is empty)"; if ((File.GetAttributes(file) & FileAttributes.Hidden) != FileAttributes.Hidden) { try { File.SetAttributes(file, FileAttributes.Hidden); } catch { // } } } MainProgram.DoDebug("[ -- DONE -- ]"); if (MainProgram.errorMessage.Length != 0) { MessageBox.Show(MainProgram.errorMessage, "Error | " + MainProgram.messageBoxTitle); MainProgram.errorMessage = ""; } }
public static void ExecuteAction(string action, string line, string parameter, string assistantParam) { Actions actionExecution = new Actions(); switch (action.ToLower()) { 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; default: //Unknown action MainProgram.DoDebug("ERROR: Unknown action \"" + action + "\""); MainProgram.errorMessage = "Unknown action \"" + action + "\""; break; } successMessage = actionExecution.successMessage; lastActionWasFatal = actionExecution.wasFatal; actionExecution.wasFatal = false; if (successMessage != "") { MainProgram.DoDebug("\nSUCCESS: " + successMessage + "\n"); } if (MainProgram.testingAction) { MainProgram.testActionWindow.ActionExecuted(successMessage, MainProgram.errorMessage, action, parameter, line); } successMessage = ""; }
private static void CheckAction(string theLine, string theFile) { string action = theLine , parameter = null , fullContent = null; action = theLine; fullContent = theLine; string assistantParam = null; //Whether it's Google Assistant or Amazon Alexa (included in the default IFTTT applets) if (theLine.Contains("[") && theLine.Contains("]")) { action = theLine.Split('[')[0]; assistantParam = theLine.Split('[')[1]; assistantParam = assistantParam.Split(']')[0]; MainProgram.DoDebug(" - Executing using; " + assistantParam); } if (action.Contains(":")) { //Contains a parameter string[] splitAction = action.Split(':'); parameter = splitAction[1]; action = splitAction[0]; if (splitAction.Length > 1) { int i = 0; foreach (string moreParam in splitAction) { if (i != 0 && i != 1) { parameter += ":" + moreParam; } i++; } } if (parameter == "") { parameter = null; } } if (MainProgram.testingAction) { MainProgram.DoDebug(" - Test went through: " + action); } MainProgram.DoDebug(" - Action: " + action); MainProgram.DoDebug(" - Parameter: " + parameter); MainProgram.DoDebug(" - Full line: " + theLine); lastActionWasFatal = false; ExecuteAction(action, theLine, parameter, assistantParam); if (!lastActionWasFatal) { MainProgram.DoDebug("Non-fatal action. Starting cleanup service."); new CleanupService().Start(); } }
private void saveActionFolder_Click(object sender, EventArgs e) { MainProgram.SetCheckFolder(actionFolderPath.Text); }
public GettingStarted(int startTab = 0) { InitializeComponent(); Thread.CurrentThread.Priority = ThreadPriority.Highest; theTabControl = tabControl; FormClosed += delegate { if (MainProgram.aboutVersionAwaiting) { Properties.Settings.Default.LastKnownVersion = MainProgram.softwareVersion; new NewVersion().Show(); Properties.Settings.Default.Save(); } }; tabControl.Appearance = TabAppearance.FlatButtons; tabControl.ItemSize = new Size(0, 1); tabControl.SizeMode = TabSizeMode.Fixed; tabControl.BackColor = Color.Transparent; tabControl.SelectTab(startTab); tabControl.Selected += delegate { if (tabControl.SelectedIndex == 1) { //Clicked on recommended setup guide (HTML), can show "move on" popover now //theWebBrowser.Document.InvokeScript("showHelpPopover"); // Why would I do this...? } else if (tabControl.SelectedIndex == 2) { expert.Focus(); } }; //Set GettingStarted web-browser things string fileName = Path.Combine(MainProgram.currentLocation, "WebFiles/GettingStarted.html"); if (File.Exists(fileName)) { string fileLoc = "file:///" + fileName; Uri theUri = new Uri(fileLoc); GettingStartedWebBrowser.Url = theUri; } else { GettingStartedWebBrowser.Visible = false; } GettingStartedWebBrowser.ObjectForScripting = new WebBrowserHandler(); theWebBrowser = GettingStartedWebBrowser; theWebBrowser.DocumentCompleted += BrowserDocumentCompleted; theWebBrowser.Navigating += BrowserNavigating; theWebBrowser.NewWindow += NewBrowserWindow; //Further expert settings actionFolderPath.KeyDown += new KeyEventHandler(FreakingStopDingSound); actionFileExtension.KeyDown += new KeyEventHandler(FreakingStopDingSound); void FreakingStopDingSound(Object o, KeyEventArgs e) { if (e.KeyCode == Keys.Enter) { e.Handled = true; e.SuppressKeyPress = true; } } actionFolderPath.Text = MainProgram.CheckPath(); actionFileExtension.Text = Properties.Settings.Default.ActionFileExtension; actionFolderPath.KeyDown += delegate { MainProgram.SetCheckFolder(actionFolderPath.Text); actionFolderPath.Text = MainProgram.CheckPath(); }; actionFolderPath.KeyUp += delegate { MainProgram.SetCheckFolder(actionFolderPath.Text); actionFolderPath.Text = MainProgram.CheckPath(); }; actionFileExtension.KeyDown += delegate { MainProgram.SetCheckExtension(actionFileExtension.Text); }; actionFileExtension.KeyUp += delegate { MainProgram.SetCheckExtension(actionFileExtension.Text); }; expert.Click += delegate { expert.Focus(); }; customSetupInfo.Click += delegate { expert.Focus(); }; expertDoneButton.FlatStyle = FlatStyle.Flat; expertDoneButton.FlatAppearance.BorderSize = 0; closeWindowButton.FlatStyle = FlatStyle.Flat; closeWindowButton.FlatAppearance.BorderSize = 0; VisibleChanged += delegate { MainProgram.testingAction = Visible; MainProgram.gettingStarted = Visible ? this : null; }; FormClosed += delegate { MainProgram.testingAction = false; MainProgram.gettingStarted = null; }; this.HandleCreated += delegate { Invoke(new Action(() => { FlashWindow.Flash(this); if (Application.OpenForms[this.Name] != null) { Application.OpenForms[this.Name].Activate(); Application.OpenForms[this.Name].Focus(); } })); }; }
//Execute mod public static void ExecuteModAction(string name, string parameter = "", string secondaryParameter = "") { MainProgram.DoDebug("\nRunning MOD ACTION!\n"); string modLocation = Path.Combine(MainProgram.actionModsPath, modActions[name]), infoJsonFile = Path.Combine(modLocation, "info.json"); if (File.Exists(infoJsonFile)) { string modFileContent = ReadInfoFile(infoJsonFile); if (modFileContent != null) { try { dynamic jsonTest = JsonConvert.DeserializeObject <dynamic>(modFileContent); if (jsonTest != null) { if (ValidateInfoJson(jsonTest)) { //JSON is valid - get script file string scriptFile = jsonTest["options"]["file_name"], scriptFileLocation = Path.Combine(modLocation, scriptFile); if (File.Exists(scriptFileLocation)) { try { ProcessStartInfo p = new ProcessStartInfo { UseShellExecute = false, CreateNoWindow = true, RedirectStandardOutput = true, RedirectStandardError = true }; string theExtension = Path.GetExtension(scriptFile); if (theExtension == ".ps1") { //Is powershell - open it correctly p.FileName = "powershell.exe"; p.Arguments = $"-WindowStyle Hidden -file \"{scriptFileLocation}\" \"{Path.Combine(MainProgram.CheckPath(), "*")}\" \"*.{Properties.Settings.Default.ActionFileExtension}\""; } else if (theExtension == ".py") { //Python - open it correctly MainProgram.DoDebug("Is python!"); string minPythonVersion = (jsonTest["options"]["min_python_version"] != null ? jsonTest["options"]["min_python_version"] : ""), maxPythonVersion = (jsonTest["options"]["max_python_version"] != null ? jsonTest["options"]["max_python_version"] : ""), pythonPath = GetPythonPath(minPythonVersion, maxPythonVersion); if (pythonPath != "") { MainProgram.DoDebug("Python path; " + pythonPath); p.FileName = GetPythonPath(); p.Arguments = scriptFileLocation; } else { //No python version (or one with the min-max requirements) not found. if (minPythonVersion == "" && maxPythonVersion == "") { //Python just not found MessageBox.Show("We could not locate Python on your computer. Please either download Python or specify its path in the ACC settings if it's already installed.", MainProgram.messageBoxTitle); } else { if (minPythonVersion != "" && maxPythonVersion != "") { //Both min & max set MessageBox.Show("We could not locate a version of Python between v" + minPythonVersion + " and v" + maxPythonVersion + ". Please either download a version of Python in between the specified versions, or specify its path in the ACC settings if it's already installed.", MainProgram.messageBoxTitle); } else { if (minPythonVersion != "") { //Min only MessageBox.Show("We could not locate a version of Python greater than v" + minPythonVersion + ". Please either download Python (min version " + minPythonVersion + ") or specify its path in the ACC settings if it's already installed.", MainProgram.messageBoxTitle); } else { //Max only MessageBox.Show("We could not locate a version of Python lower than v" + maxPythonVersion + ". Please either download Python (max version " + maxPythonVersion + ") or specify its path in the ACC settings if it's already installed.", MainProgram.messageBoxTitle); } } } return; } } else { //"Other" filetype. Simply open file. p.FileName = scriptFileLocation; p.Arguments = "how to do dis?"; } Process theP = Process.Start(p); string output = theP.StandardOutput.ReadToEnd(); theP.WaitForExit(); Console.WriteLine(output); } catch (Exception e) { //Process init failed - it shouldn't, but better safe than sorry MainProgram.DoDebug("6"); Console.WriteLine(e); } } else { //Script file doesn't exist MainProgram.DoDebug("5"); } } else { //JSON is not valid; validateErrMsg MainProgram.DoDebug("4"); } } else { //JSON is invalid or failed MainProgram.DoDebug("3"); } } catch (Exception e) { //Failed to parse MainProgram.DoDebug("2"); Console.WriteLine(e.Message); } } else { //Couldn't read file MainProgram.DoDebug("1"); } } else { MainProgram.DoDebug("0; " + modLocation); } MainProgram.DoDebug("\n\n"); }
public static void TaskSchedulerSetup() { //Create "Task Scheduler" service; cleanup ACC on startup, log on, workstation unlock var ps1File = Path.Combine(MainProgram.currentLocation, "ExtraCleanupper.ps1"); try { var userId = WindowsIdentity.GetCurrent().Name; using (var ts = new TaskService()) { var td = ts.NewTask(); td.RegistrationInfo.Author = "Albert MN. | AssistantComputerControl"; td.RegistrationInfo.Description = "AssistantComputerControl cleanup - clears the action folder to prevent the same action being executed twice"; td.Actions.Add(new ExecAction("powershell.exe", $"-WindowStyle Hidden -file \"{ps1File}\" \"{Path.Combine(MainProgram.CheckPath(), "*")}\" \"*.{Properties.Settings.Default.ActionFileExtension}\"", null)); td.Triggers.Add(new LogonTrigger { UserId = userId, }); ts.RootFolder.RegisterTaskDefinition(@"AssistantComputerControl cleanup", td); } } catch (Exception e) { DoDebug("Failed to create / update cleanup Task Scheduler service; " + e.Message); Console.WriteLine(e); } }
private static void CheckAction(string theLine, string theFile) { string action = theLine , parameter = null , fullContent = null; action = theLine; fullContent = theLine; bool isDefaultComputer = Properties.Settings.Default.DefaultComputer; string theComputerName = null, thisComputerName = Properties.Settings.Default.ComputerName; //COMPUTER NAME! //PREVIOUSLY; Whether it's Google Assistant or Amazon Alexa (included in the default IFTTT applets) if (theLine.Contains("[") && theLine.Contains("]")) { action = theLine.Split('[')[0]; theComputerName = theLine.Split('[')[1]; theComputerName = theComputerName.Split(']')[0]; if (theComputerName == "google" || theComputerName == "alexa") { MainProgram.DoDebug(" - The targetted 'PC name' is set to 'google' or 'alexa' - this is the old format; these names are reserved and cannot be used as 'Computer name'"); } else { MainProgram.DoDebug(" - Targetted computer is; " + theComputerName); if (thisComputerName == theComputerName) { MainProgram.DoDebug(" - This computer is the target!"); } else { //Not this computer! MainProgram.DoDebug(" - Computer name \"" + theComputerName + "\" does not match \"" + thisComputerName + "\""); return; } } } else { if (thisComputerName == String.Empty) { if (!isDefaultComputer) { MainProgram.DoDebug(" - Applet has not specified a computer name, this computer has no computer name and is NOT a 'default computer' - ignoring"); return; } else { MainProgram.DoDebug(" - Applet has not specified a computer name, this computer has no computer name BUT it's a 'default computer' - executing"); } } else { if (!isDefaultComputer) { MainProgram.DoDebug(" - Applet has not specified a computer name, this computer HAS a computer name and is NOT a 'default computer' - ignoring"); return; } else { MainProgram.DoDebug(" - Applet has not specified a computer name, this computer HAS a computer name and IS a 'default computer' - executing"); } } } if (action.Contains(":")) { //Contains a parameter string[] splitAction = action.Split(':'); parameter = splitAction[1]; action = splitAction[0]; if (splitAction.Length > 1) { int i = 0; foreach (string moreParam in splitAction) { if (i != 0 && i != 1) { parameter += ":" + moreParam; } i++; } } if (parameter == "") { parameter = null; } } if (MainProgram.testingAction) { MainProgram.DoDebug(" - Test went through: " + action); } MainProgram.DoDebug(" - Action: " + action); MainProgram.DoDebug(" - Parameter: " + parameter); MainProgram.DoDebug(" - Full line: " + theLine); Actions theActionExecution = ExecuteAction(action, theLine, parameter); if (!theActionExecution.wasFatal) { MainProgram.DoDebug("Non-fatal action. Starting cleanup service."); new CleanupService().Start(); } if (!String.IsNullOrEmpty(theActionExecution.errorMessage)) { MainProgram.DoDebug("[ERROR]: " + theActionExecution.errorMessage); ErrorMessageBox(theActionExecution.errorMessage, "Action Error " + MainProgram.messageBoxTitle); } else { if (!String.IsNullOrEmpty(theActionExecution.successMessage)) { MainProgram.DoDebug("\nSUCCESS: " + theActionExecution.successMessage + "\n"); } else { MainProgram.DoDebug("\nSUCCESS (got no success message)\n"); } } }
public static void TaskSchedulerSetup() { //Create "Task Scheduler" service; cleanup ACC on startup, log on, workstation unlock try { using (TaskService ts = new TaskService()) { var ps1File = Path.Combine(MainProgram.currentLocation, "ExtraCleanupper.ps1"); TaskDefinition td = ts.NewTask(); td.Principal.LogonType = TaskLogonType.S4U; td.RegistrationInfo.Author = "Albert MN. | AssistantComputerControl"; td.RegistrationInfo.Description = "AssistantComputerControl cleanup - clears the action folder to prevent the same action being executed twice"; td.Triggers.Add(new BootTrigger()); td.Triggers.Add(new LogonTrigger()); td.Triggers.Add(new SessionStateChangeTrigger { StateChange = TaskSessionStateChangeType.SessionUnlock }); td.Actions.Add(new ExecAction("powershell.exe", $"-WindowStyle Hidden -file \"{ps1File}\" \"{Path.Combine(MainProgram.CheckPath(), "*")}\" \"*.{Properties.Settings.Default.ActionFileExtension}\"", null)); //Register the task in the root folder ts.RootFolder.RegisterTaskDefinition(@"AssistantComputerControl cleanup", td); } } catch { DoDebug("Failed to create / update Task Scheduler service"); } }
public GettingStarted() { InitializeComponent(); tabControl.Appearance = TabAppearance.FlatButtons; tabControl.ItemSize = new Size(0, 1); tabControl.SizeMode = TabSizeMode.Fixed; tabControl.BackColor = Color.Transparent; tabControl.Selected += delegate { if (tabControl.SelectedIndex == 1) { //Clicked on recommended setup guide (HTML), can show "move on" popover now theWebBrowser.Document.InvokeScript("showHelpPopover"); } else if (tabControl.SelectedIndex == 2) { expert.Focus(); } }; //Auto-select "recommended" panel RecommendedClicked(null, null); finalOptionButton.FlatStyle = FlatStyle.Flat; finalOptionButton.FlatAppearance.BorderSize = 0; setupSelect.MouseHover += delegate { if (selectedPanel != recommendedPanel) { recommendedPanel.borderColor = Pens.Black; recommendedPanel.Refresh(); } if (selectedPanel != expertPanel) { expertPanel.borderColor = Pens.Black; expertPanel.Refresh(); } }; //Recommended panel recommendedPanel.MouseHover += RecommendedHovered; recommendedPanel.Click += RecommendedClicked; recommendedLabel.MouseHover += RecommendedHovered; recommendedLabel.Click += RecommendedClicked; recommendedLabel2.MouseHover += RecommendedHovered; recommendedLabel2.Click += RecommendedClicked; recommendedLabel3.MouseHover += RecommendedHovered; recommendedLabel3.Click += RecommendedClicked; recommendedImage.MouseHover += RecommendedHovered; recommendedImage.Click += RecommendedClicked; //Expert panel expertPanel.MouseHover += ExpertHovered; expertPanel.Click += ExpertClicked; expertLabel1.MouseHover += ExpertHovered; expertLabel1.Click += ExpertClicked; expertLabel2.MouseHover += ExpertHovered; expertLabel2.Click += ExpertClicked; expertLabel2.MouseHover += ExpertHovered; expertLabel2.Click += ExpertClicked; expertLabel3.MouseHover += ExpertHovered; expertLabel3.Click += delegate { Process.Start("https://github.com/AlbertMN/AssistantComputerControl/wiki/Application-advanced-settings-expert-setup"); }; tooltip.SetToolTip(expertLabel3, "This will open a link in your default browser"); expertLabel4.MouseHover += ExpertHovered; expertLabel4.Click += ExpertClicked; expertImage.MouseHover += ExpertHovered; expertImage.Click += ExpertClicked; //Further expert settings actionFolderPath.KeyDown += new KeyEventHandler(FreakingStopDingSound); actionFileExtension.KeyDown += new KeyEventHandler(FreakingStopDingSound); void FreakingStopDingSound(Object o, KeyEventArgs e) { if (e.KeyCode == Keys.Enter) { e.Handled = true; e.SuppressKeyPress = true; } } actionFolderPath.Text = MainProgram.CheckPath(); actionFileExtension.Text = Properties.Settings.Default.ActionFileExtension; actionFolderPath.KeyDown += delegate { MainProgram.SetCheckFolder(actionFolderPath.Text); }; actionFolderPath.KeyUp += delegate { MainProgram.SetCheckFolder(actionFolderPath.Text); }; actionFileExtension.KeyDown += delegate { MainProgram.SetCheckExtension(actionFileExtension.Text); }; actionFileExtension.KeyUp += delegate { MainProgram.SetCheckExtension(actionFileExtension.Text); }; expert.Click += delegate { expert.Focus(); }; customSetupInfo.Click += delegate { expert.Focus(); }; expertDoneButton.FlatStyle = FlatStyle.Flat; expertDoneButton.FlatAppearance.BorderSize = 0; closeWindowButton.FlatStyle = FlatStyle.Flat; closeWindowButton.FlatAppearance.BorderSize = 0; //Browser theWebBrowser = GuideWebBrowser; string tes = "http://acc.albe.pw/recommended_setup.html?" + new Random().Next(10000); Console.WriteLine(tes); //theWebBrowser.Url = new Uri(tes); theWebBrowser.DocumentCompleted += BrowserDocumentCompleted; theWebBrowser.Navigating += BrowserNavigating; theWebBrowser.NewWindow += NewBrowserWindow; VisibleChanged += delegate { MainProgram.testingAction = Visible; MainProgram.gettingStarted = Visible ? this : null; }; FormClosed += delegate { MainProgram.testingAction = false; MainProgram.gettingStarted = null; }; }
//Baisc things private void Error(string errorMsg, string debugMsg = null) { MainProgram.DoDebug("ERROR: " + (String.IsNullOrEmpty(debugMsg) ? errorMsg : debugMsg)); //MainProgram.errorMessage = errorMsg; errorMessage = errorMsg; }
public void InitializeComponent() { TrayIcon = new NotifyIcon(); //System tray creation TrayIcon = new NotifyIcon() { Text = MainProgram.appName + " v" + MainProgram.softwareVersion, Icon = Properties.Resources.ACC_loading_light_icon }; //Add tray menu items trayMenu.MenuItems.Add(Translator.__("settings_title", "tray_menu"), delegate { MainProgram.ShowSettings(); }); trayMenu.MenuItems.Add(Translator.__("help_title", "tray_menu"), new EventHandler(TrayOpenHelp)); trayMenu.MenuItems.Add(Translator.__("exit_title", "tray_menu"), new EventHandler(TrayExit)); TrayIcon.ContextMenu = trayMenu; TrayIcon.DoubleClick += new System.EventHandler(this.TrayShowSettings); }
public void KeyShortcut(string parameter) { /* * Added by: Joshua Miller * How to use it: * - To seperate keys please use '+' (to use '+' do {ADD}) * - Things like ctrl will be converted to control key */ // Split up commands char splitChar = '+'; String[] keyCombinationInput = parameter.Split(splitChar); // Will be added onto to make what to type String keyCombinationPress = ""; // Put commands into correct form for (int index = 0; index < keyCombinationInput.Length; index++) { // Get current command String command = keyCombinationInput[index]; // If not empty if (command != "") { // If one character (not command) if (command.Length == 1) { // Add to the out keyCombinationPress = keyCombinationPress + command.ToLower(); } else { // If it is a command (probably) // Check if it is a possible command and needs to be changed bool foundYet = false; for (int countInCharacterArray = 0; countInCharacterArray < charactersType.GetLength(0) && foundYet == false; countInCharacterArray++) { String characterTestNow = charactersType[countInCharacterArray, 0]; if (Equals(command.ToUpper(), characterTestNow)) { keyCombinationPress += charactersType[countInCharacterArray, 1]; foundYet = true; } else if (Equals(command.ToUpper(), charactersType[countInCharacterArray, 1])) { keyCombinationPress += charactersType[countInCharacterArray, 1]; foundYet = true; } } if (foundYet == false) { MainProgram.DoDebug("KeyShortcut Action - Warning: A command " + command.ToUpper() + " was not identified, please be weary as this may not work"); MainProgram.DoDebug("KeyShortcut Action - Warning: Adding Anyway"); keyCombinationPress += command; } } } else { MainProgram.DoDebug("KeyShortcut Action - Warning: A character inside the paramater was blank"); } } // Is it testing? if (MainProgram.testingAction) { successMessage = ("Simulated sending the combination: " + keyCombinationPress); } else { // Try pressing keys bool keysPressedSuccess = true; try { SendKeys.SendWait(keyCombinationPress); } catch (ArgumentException) { Error("Key combination is not valid"); keysPressedSuccess = false; } if (keysPressedSuccess) { successMessage = ("Sending the combination: " + keyCombinationPress); } } }
private void TrayShowSettings(object sender, EventArgs e) { MainProgram.ShowSettings(); }
public void DeleteFile(string parameter) { string fileLocation = parameter; if (File.Exists(fileLocation) || Directory.Exists(fileLocation)) { FileAttributes attr = File.GetAttributes(fileLocation); bool succeeded = true; MainProgram.DoDebug("Deleting file/folder at " + fileLocation); try { string toDelete; if (attr.HasFlag(FileAttributes.Directory)) { //Is folder MainProgram.DoDebug("Deleting folder..."); DirectoryInfo d = new DirectoryInfo(fileLocation); bool doDelete = true; if (d.GetFiles().Length > Properties.Settings.Default.MaxDeleteFiles && Properties.Settings.Default.WarnWhenDeletingManyFiles) { //Has more than x files - do warning DialogResult dialogResult = MessageBox.Show("You're about to delete more than " + Properties.Settings.Default.MaxDeleteFiles.ToString() + " files at " + fileLocation + " - are you sure you wish to proceed?", "Are you sure?", MessageBoxButtons.YesNo); if (dialogResult == DialogResult.Yes) { } else if (dialogResult == DialogResult.No) { doDelete = false; } } if (doDelete) { if (MainProgram.testingAction) { //Make test-folder and delete it to test if has permission toDelete = Path.Combine(Directory.GetParent(fileLocation).FullName, "acc_testfolder"); Directory.CreateDirectory(toDelete); Directory.Delete(toDelete); } else { //Actually delete folder Directory.Delete(fileLocation); MainProgram.DoDebug("Deleted directory at " + fileLocation); } } } else { //Is file if (MainProgram.testingAction) { //Make test-file and delete it to test if has permission MainProgram.DoDebug("(Fake) Deleting file..."); toDelete = Path.Combine(fileLocation, "acc_testfile.txt"); File.Create(toDelete); File.Delete(toDelete); } else { //Actually delete file MainProgram.DoDebug("Deleting file..."); File.Delete(fileLocation); } } } catch (Exception exc) { succeeded = false; Error("Couldn't access file/folder - file might be in use or locked. Try running ACC as administrator.", exc.Message); } if (succeeded) { if (!MainProgram.testingAction) { successMessage = "Deleted file/folder at " + fileLocation; } else { successMessage = "Simulated deleting file/folder at " + fileLocation; } } } else { Error("File or folder doesn't exist"); } }
public bool Check(bool debug = false) { if (MainProgram.isCheckingForUpdate) { return(false); } MainProgram.isCheckingForUpdate = true; MainProgram.DoDebug("Checking for updates..."); string latestReleaseJson = null; string latestBetaJson = null; //Check and get latest if (RemoteFileExists(releaseJsonUrl)) { using (WebClient client = new WebClient()) { latestReleaseJson = client.DownloadString(releaseJsonUrl); } if (latestReleaseJson == string.Empty) { latestReleaseJson = null; } } //Check and get beta if (Properties.Settings.Default.BetaProgram && RemoteFileExists(betaJsonUrl)) { using (WebClient client = new WebClient()) { latestBetaJson = client.DownloadString(betaJsonUrl); } if (latestBetaJson == string.Empty) { latestBetaJson = null; } } if (latestReleaseJson != null || latestBetaJson != null) { Version newVersion = null , latestRelease , latestBeta; if (latestReleaseJson != null && latestBetaJson != null) { //Beta program enabled; check both release and beta for newest update latestRelease = JsonConvert.DeserializeObject <Version>(latestReleaseJson); latestBeta = JsonConvert.DeserializeObject <Version>(latestBetaJson); if (DateTime.Parse(latestRelease.datetime) > DateTime.Parse(MainProgram.releaseDate) || DateTime.Parse(latestBeta.datetime) > DateTime.Parse(MainProgram.releaseDate)) { //Both latest release and beta is ahead of this current build if (DateTime.Parse(latestRelease.datetime) > DateTime.Parse(latestBeta.datetime)) { //Release is newest newVersion = latestRelease; } else { //Beta is newest newVersion = latestBeta; } } else { //None of them are newer. Nothing new MainProgram.DoDebug("Software up to date (beta program enabled)"); MainProgram.isCheckingForUpdate = false; return(false); } } else if (latestReleaseJson != null && latestBetaJson == null) { //Only check latest latestRelease = JsonConvert.DeserializeObject <Version>(latestReleaseJson); if (DateTime.Parse(latestRelease.datetime) > DateTime.Parse(MainProgram.releaseDate) && latestRelease.version != MainProgram.softwareVersion) { //Newer build newVersion = latestRelease; } else { //Not new, move on MainProgram.DoDebug("Software up to date"); MainProgram.isCheckingForUpdate = false; return(false); } } else if (latestReleaseJson == null && latestBetaJson != null) { //Couldn't reach "latest" update, but beta-updates are enabled latestBeta = JsonConvert.DeserializeObject <Version>(latestBetaJson); if (latestBeta != null) { if (DateTime.Parse(latestBeta.datetime) > DateTime.Parse(MainProgram.releaseDate)) { //Newer build newVersion = latestBeta; } else { //Not new, move on MainProgram.DoDebug("Software up to date (beta program enabled)"); MainProgram.isCheckingForUpdate = false; return(false); } } } else { MainProgram.DoDebug("Both release and beta is NULL, no new updates, or no contact to the server."); } if (newVersion != null && newVersion.version != MainProgram.softwareVersion) { //New version available MainProgram.DoDebug("New software version found (" + newVersion.version + ") [" + newVersion.type + "], current; " + MainProgram.softwareVersion); DialogResult dialogResult = MessageBox.Show("A new version of " + MainProgram.messageBoxTitle + " is available (v" + newVersion.version + " [" + newVersion.type + "]), do you wish to install it?", "New update found | " + MainProgram.messageBoxTitle, MessageBoxButtons.YesNo); if (dialogResult == DialogResult.Yes) { MainProgram.DoDebug("User chose \"yes\" to install update"); DownloadFile(newVersion.installpath + "&upgrade=true"); } else if (dialogResult == DialogResult.No) { MainProgram.DoDebug("User did not want to install update"); } MainProgram.isCheckingForUpdate = false; return(true); } else { MainProgram.DoDebug("Software up to date"); if (debug) { MessageBox.Show("No new update found. You're up to date!", "Check for update | " + MainProgram.messageBoxTitle); } } } else { MainProgram.DoDebug("Could not reach the webserver (both 'release' and 'beta' json files couldn't be reached)"); if (debug) { MessageBox.Show("Could not reach the ACC webservers - try again later", "Check for update | " + MainProgram.messageBoxTitle); } } MainProgram.isCheckingForUpdate = false; return(false); }
public void AppendText(string parameter) { string fileLocation = ActionChecker.GetSecondaryParam(parameter)[0], toAppend = ActionChecker.GetSecondaryParam(parameter).Length > 1 ? ActionChecker.GetSecondaryParam(parameter)[1] : null; MainProgram.DoDebug("Appending \"" + toAppend + "\" to " + fileLocation); if (fileLocation != null && toAppend != null) { if (toAppend != "") { if (File.Exists(fileLocation)) { string parentPath = Path.GetDirectoryName(fileLocation); bool succeeded = true; try { //Is file if (MainProgram.testingAction) { //Write empty string to file to test permission using (StreamWriter w = File.AppendText(fileLocation)) { w.Write(String.Empty); } } else { //Actually write to file using (StreamWriter w = File.AppendText(fileLocation)) { //string[] lines = toAppend.Split(new string[] { "\n" }, StringSplitOptions.None); string[] lines = toAppend.Split(new string[] { "\\n" }, StringSplitOptions.None); MainProgram.DoDebug(lines.Length.ToString()); int i = 0; foreach (string appendChild in lines) { if (i == 0) { w.Write(appendChild); } else { w.WriteLine(String.Empty); w.Write(appendChild); } i++; } } } } catch (Exception exc) { succeeded = false; Error("Couldn't create file - folder might be locked. Try running ACC as administrator.", exc.Message); } if (succeeded) { if (!MainProgram.testingAction) { successMessage = "Appended \"" + toAppend + "\" to file at " + fileLocation; } else { successMessage = "Simulated appending \"" + toAppend + "\" to file at " + fileLocation; } } } else { Error("File doesn't exists"); } } else { Error("Can't append nothing"); } } else { Error("Parameter doesn't contain a string to append"); } }
//public static List<string> cleanedFiles = new List<string>(); public void Start() { new Thread(() => { Thread.CurrentThread.IsBackground = true; MainProgram.DoDebug("[CLEANUP] Service started"); Thread.Sleep(150); if (isCleaning) { MainProgram.DoDebug("[CLEANUP] Another cleanup service in progress. Waiting..."); while (isCleaning) { Thread.Sleep(200); } MainProgram.DoDebug("[CLEANUP] Other cleanup service done - starting check..."); } isCleaning = true; if (AllHiddenCheck() != 0 && EmptyCheck()) { int tries = 0; while (!Check() && tries <= 10) { tries++; Thread.Sleep(1000); } if (tries >= 10) { MainProgram.DoDebug("[CLEANUP] Timeout. Failed to remove files in action folder."); } else { int filesAmount = AllHiddenCheck(); if (filesAmount != 0) { MainProgram.DoDebug("[CLEANUP] Did not timeout, but action folder is still not empty (" + filesAmount.ToString() + " non-hidden files in folder) - not supposed to happen Emtpy check returns " + (EmptyCheck() ? "true" : "false")); } else { MainProgram.DoDebug("[CLEANUP] Successful"); } } } else { MainProgram.DoDebug("[CLEANUP] Action folder is completely empty"); } /* Launch a follow-up investigation */ new Thread(() => { Thread.CurrentThread.IsBackground = true; void ExtraCleanup() { MainProgram.DoDebug("[CLEANUP] Running extra cleanup (followup)"); try { var ps1File = Path.Combine(MainProgram.currentLocation, "ExtraCleanupper.ps1"); Process p = new Process(); p.StartInfo.FileName = "powershell.exe"; p.StartInfo.Arguments = $"-WindowStyle Hidden -file \"{ps1File}\" \"{Path.Combine(MainProgram.CheckPath(), "*")}\" \"*.{Properties.Settings.Default.ActionFileExtension}\""; p.StartInfo.UseShellExecute = false; p.StartInfo.CreateNoWindow = true; p.Start(); } catch { MainProgram.DoDebug("[CLEANUP] Extra checkup failed"); } } Thread.Sleep(5000); ExtraCleanup(); Thread.Sleep(25000); ExtraCleanup(); }).Start(); isCleaning = false; }).Start(); }
private bool CheckSetPath(string chosenService) { bool t = false; if (customSetPath != String.Empty) { if (Directory.Exists(customSetPath)) { if (!customSetPath.Contains("AssistantComputerControl") && !customSetPath.Contains("assistantcomputercontrol")) { customSetPath = Path.Combine(customSetPath, "AssistantComputerControl"); MainProgram.DoDebug("Changed path to include 'AssistantComputerControl': " + customSetPath); if (!Directory.Exists(customSetPath)) { Directory.CreateDirectory(customSetPath); } } Properties.Settings.Default.ActionFilePath = customSetPath; Properties.Settings.Default.Save(); MainProgram.SetupListener(); t = true; } } else { string checkPath = CloudServiceFunctions.GetCloudServicePath(chosenService); MainProgram.DoDebug("Checking: " + checkPath); if (!String.IsNullOrEmpty(checkPath)) { if (Directory.Exists(checkPath)) { if (!checkPath.Contains("AssistantComputerControl") && !checkPath.Contains("assistantcomputercontrol")) { checkPath = Path.Combine(checkPath, "AssistantComputerControl"); MainProgram.DoDebug("Changed path to include 'AssistantComputerControl': " + checkPath); if (!Directory.Exists(checkPath)) { Directory.CreateDirectory(checkPath); } } Properties.Settings.Default.ActionFilePath = checkPath; Properties.Settings.Default.Save(); MainProgram.SetupListener(); t = true; } } } if (Properties.Settings.Default.ActionFilePath == MainProgram.currentLocation) { MainProgram.DefaultPathIssue(); } return(t); }