/// <summary> /// Runs async so the previous function can return, and an error isn't thrown with the Blazor function timeout /// </summary> private static void FinishBackup(string tempFolder) { var folderSize = Globals.FolderSizeString(tempFolder); _ = GeneralInvocableFuncs.ShowToast("info", Lang["Toast_BackupCompress", new { size = folderSize }], duration: 3000, renderTo: "toastarea"); var zipFile = Path.Join("Backups", (tempFolder.Contains("\\") ? tempFolder.Split("\\")[1] : tempFolder) + ".7z"); var backupWatcher = new Thread(() => CompressionUpdater(zipFile)); backupWatcher.Start(); try { Globals.CompressFolder(tempFolder, zipFile); } catch (Exception e) { if (e is FileNotFoundException && e.ToString().Contains("7z.dll")) { _ = GeneralInvocableFuncs.ShowToast("error", Lang["Error_RequiredFileVerify"], "Stylesheet error", "toastarea"); } } Globals.RecursiveDelete(tempFolder, false); _ = GeneralInvocableFuncs.ShowToast("success", Lang["Toast_BackupComplete", new { size = folderSize, compressedSize = Globals.FileSizeString(zipFile) }], renderTo: "toastarea"); _currentlyBackingUp = false; }
// BUTTON: Check account VAC status public static void ClearVacStatus() { Globals.DebugWriteLine(@"[ButtonClicked:Steam\Settings.razor.cs.ClearVacStatus]"); _ = Globals.DeleteFile(Data.Settings.Steam.VacCacheFile) ? GeneralInvocableFuncs.ShowToast("success", Lang["Toast_Steam_VacCleared"], renderTo: "toastarea") : GeneralInvocableFuncs.ShowToast("error", Lang["Toast_Steam_CantDeleteVacCache"], Lang["Error"], "toastarea"); }
public static IHostBuilder CreateHostBuilder(string[] args) { var port = ""; foreach (var arg in args) { if (!arg.Contains("--url")) { continue; } port = Regex.Match(arg, @"[\d]+", RegexOptions.IgnoreCase).Value; Console.WriteLine("Using port (from --url arg): " + port); } if (string.IsNullOrEmpty(port)) { FindOpenPort(); port = AppSettings.ServerPort.ToString(); Console.WriteLine("Using saved/random port: " + port); } // Start browser - if not started with nobrowser if (!args.Contains("nobrowser")) { GeneralInvocableFuncs.OpenLinkInBrowser($"http://localhost:{port}"); } return(Host.CreateDefaultBuilder(args) .ConfigureWebHostDefaults(webBuilder => { _ = webBuilder.UseStartup <Startup>() .UseUrls($"http://localhost:{port}"); })); }
/// <summary> /// Keeps the user updated with compression progress /// </summary> private static void CompressionUpdater(string zipFile) { Thread.Sleep(3500); while (_currentlyBackingUp) { _ = GeneralInvocableFuncs.ShowToast("info", Lang["Toast_BackupProgress", new { compressedSize = Globals.FileSizeString(zipFile) }], duration: 1000, renderTo: "toastarea"); Thread.Sleep(2000); } }
public static void SwapBasicAccounts(string accId = "", string args = "") { Globals.DebugWriteLine(@"[Func:Basic\BasicSwitcherFuncs.SwapBasicAccounts] Swapping to: hidden."); // Handle args: if (CurrentPlatform.ExeExtraArgs != "") { args = CurrentPlatform.ExeExtraArgs + (args == "" ? "" : " " + args); } LoadAccountIds(); var accName = GetNameFromId(accId); if (!KillGameProcesses()) { return; } // Add currently logged in account if there is a way of checking unique ID. // If saved, and has unique key: Update if (CurrentPlatform.UniqueIdFile is not null) { string uniqueId; if (CurrentPlatform.UniqueIdMethod is "REGKEY" && !string.IsNullOrEmpty(CurrentPlatform.UniqueIdFile)) { _ = ReadRegistryKeyWithErrors(CurrentPlatform.UniqueIdFile, out uniqueId); } else { uniqueId = GetUniqueId(); } // UniqueId Found >> Save! if (File.Exists(CurrentPlatform.IdsJsonPath)) { if (!string.IsNullOrEmpty(uniqueId) && AccountIds.ContainsKey(uniqueId)) { if (accId == uniqueId) { _ = GeneralInvocableFuncs.ShowToast("info", Lang["Toast_AlreadyLoggedIn"], renderTo: "toastarea"); if (Globals.StartProgram(BasicSettings.Exe(), BasicSettings.Admin, args)) { _ = GeneralInvocableFuncs.ShowToast("info", Lang["Status_StartingPlatform", new { platform = CurrentPlatform.SafeName }], renderTo: "toastarea"); } else { _ = GeneralInvocableFuncs.ShowToast("error", Lang["Toast_StartingPlatformFailed", new { platform = CurrentPlatform.SafeName }], renderTo: "toastarea"); } return; } BasicAddCurrent(AccountIds[uniqueId]); } } }
public static void SteamOpenUserdata(string steamId) { var steamId32 = new Converters.SteamIdConvert(steamId); var folder = Path.Join(Data.Settings.Steam.FolderPath, $"userdata\\{steamId32.Id32}"); if (Directory.Exists(folder)) { _ = Process.Start("explorer.exe", folder); } else { _ = GeneralInvocableFuncs.ShowToast("error", Lang["Toast_NoFindSteamUserdata"], Lang["Failed"], "toastarea"); } }
/// <summary> /// Verify updater files and start update /// </summary> public void UpdateNow() { try { if (Globals.InstalledToProgramFiles() && !IsAdmin() || !Globals.HasFolderAccess(Globals.AppDataFolder)) { _ = GeneralInvocableFuncs.ShowModal("notice:RestartAsAdmin"); return; } Directory.SetCurrentDirectory(Globals.AppDataFolder); // Download latest hash list var hashFilePath = Path.Join(Globals.UserDataFolder, "hashes.json"); Globals.DownloadFile("https://tcno.co/Projects/AccSwitcher/latest/hashes.json", hashFilePath); // Verify updater files var verifyDictionary = JsonConvert.DeserializeObject <Dictionary <string, string> >(Globals.ReadAllText(hashFilePath)); if (verifyDictionary == null) { _ = GeneralInvocableFuncs.ShowToast("error", Lang["Toast_UpdateVerifyFail"]); return; } var updaterDict = verifyDictionary.Where(pair => pair.Key.StartsWith("updater")).ToDictionary(pair => pair.Key, pair => pair.Value); // Download and replace broken files Globals.RecursiveDelete("newUpdater", false); foreach (var(key, value) in updaterDict) { if (key == null) { continue; } if (File.Exists(key) && value == GeneralFuncs.GetFileMd5(key)) { continue; } Globals.DownloadFile("https://tcno.co/Projects/AccSwitcher/latest/" + key.Replace('\\', '/'), key); } AutoStartUpdaterAsAdmin(); } catch (Exception e) { _ = GeneralInvocableFuncs.ShowToast("error", Lang["Toast_FailedUpdateCheck"]); Globals.WriteToLog("Failed to check for updates:" + e); } Directory.SetCurrentDirectory(Globals.UserDataFolder); }
public void Check(string platform) { Globals.DebugWriteLine($@"[Func:Index.Check] platform={platform}"); switch (platform) { case "BattleNet": if (!GeneralFuncs.CanKillProcess(BattleNetSettings.Processes, BattleNetSettings.ClosingMethod)) { return; } if (Directory.Exists(BattleNetSettings.FolderPath) && File.Exists(BattleNetSettings.Exe())) { AppData.ActiveNavMan.NavigateTo("/BattleNet/"); } else { _ = GeneralInvocableFuncs.ShowModal("find:BattleNet:Battle.net.exe:BattleNetSettings"); } break; case "Steam": if (!GeneralFuncs.CanKillProcess(SteamSettings.Processes, SteamSettings.ClosingMethod)) { return; } if (!Directory.Exists(SteamSettings.FolderPath) || !File.Exists(SteamSettings.Exe())) { _ = GeneralInvocableFuncs.ShowModal("find:Steam:Steam.exe:SteamSettings"); return; } if (SteamSwitcherFuncs.SteamSettingsValid()) { AppData.ActiveNavMan.NavigateTo("/Steam/"); } else { _ = GeneralInvocableFuncs.ShowModal(Lang["Toast_Steam_CantLocateLoginusers"]); } break; default: if (BasicPlatforms.PlatformExistsFromShort(platform)) // Is a basic platform! { BasicPlatforms.SetCurrentPlatformFromShort(platform); if (!GeneralFuncs.CanKillProcess(CurrentPlatform.ExesToEnd, BasicSettings.ClosingMethod)) { return; } if (Directory.Exists(BasicSettings.FolderPath) && File.Exists(BasicSettings.Exe())) { AppData.ActiveNavMan.NavigateTo("/Basic/"); } else { _ = GeneralInvocableFuncs.ShowModal($"find:{CurrentPlatform.SafeName}:{CurrentPlatform.ExeName}:{CurrentPlatform.SafeName}"); } } break; } }
// BUTTON: Pick folder public void PickFolder() { Globals.DebugWriteLine(@"[ButtonClicked:Steam\Settings.razor.cs.PickFolder]"); _ = GeneralInvocableFuncs.ShowModal("find:Steam:Steam.exe:SteamSettings"); }
/// <summary> /// Main function for Battle.net Account Switcher. Run on load. /// Prepares HTML Elements string for insertion into the account switcher GUI. /// </summary> public static async Task LoadProfiles() { Globals.DebugWriteLine(@"[Func:BattleNet\BattleNetSwitcherFuncs.LoadProfiles] Loading BattleNet profiles"); LoadImportantData(); BattleNetSettings.LoadAccounts(); // Check if accounts file exists if (!File.Exists(BattleNetRoaming + "\\Battle.net.config")) { _ = GeneralInvocableFuncs.ShowToast("error", Lang["Toast_BNet_CantLoadNotFound"], "toastarea"); return; } // Read lines in accounts file var file = await File.ReadAllTextAsync(BattleNetRoaming + "\\Battle.net.config").ConfigureAwait(false); if (JsonConvert.DeserializeObject(file) is not JObject accountsFile) { _ = GeneralInvocableFuncs.ShowToast("error", Lang["Toast_BNet_CantLoadConfigCorrupt"], "toastarea"); return; } // Verify that there are accounts to iterate over var savedAccountsList = accountsFile.SelectToken("Client.SavedAccountNames"); if (savedAccountsList == null) { _ = GeneralInvocableFuncs.ShowToast("error", Lang["Toast_BNet_CantLoadEmpty"], "toastarea"); return; } foreach (var mail in savedAccountsList.ToString().Split(',')) { if (string.IsNullOrEmpty(mail) || string.IsNullOrWhiteSpace(mail)) { continue; // Ignores blank emails sometimes added: ".com, , asdf@..." } try { if (BattleNetSettings.Accounts.Count == 0 || BattleNetSettings.Accounts.All(x => x.Email != mail) && !BattleNetSettings.IgnoredAccounts.Contains(mail) && mail != " ") { BattleNetSettings.Accounts.Add(new BattleNetSwitcherBase.BattleNetUser { Email = mail }); } } catch (NullReferenceException) { BattleNetSettings.Accounts.Add(new BattleNetSwitcherBase.BattleNetUser { Email = mail }); } } // Order if (File.Exists("LoginCache\\BattleNet\\order.json")) { var savedOrder = JsonConvert.DeserializeObject <List <string> >(await File.ReadAllTextAsync("LoginCache\\BattleNet\\order.json").ConfigureAwait(false)); if (savedOrder != null) { var index = 0; if (savedOrder is { Count : > 0 })
public bool FetchRank() { if (!BattleNetSwitcherFuncs.ValidateBTag(BTag)) { return(false); } var split = BTag.Split("#"); var req = WebRequest.Create($"https://playoverwatch.com/en-us/career/pc/{split[0]}-{split[1]}/"); req.Method = "GET"; var doc = new HtmlDocument(); var responseStream = req.GetResponse().GetResponseStream(); if (responseStream == null) { _ = GeneralInvocableFuncs.ShowToast("error", Lang["Toast_BNet_StatsFail", new { BTag = BTag }], renderTo: "toastarea"); return(false); } using (var reader = new StreamReader(responseStream)) { doc.LoadHtml(reader.ReadToEnd()); } // If the PlayOverwatch site is overloaded if (doc.DocumentNode.SelectSingleNode("/html/body/section[1]/section/div/h1") != null) { _ = GeneralInvocableFuncs.ShowToast("error", Lang["Toast_BNet_StatsFail", new { BTag = BTag }], renderTo: "toastarea"); return(false); } // If the Profile is private if (doc.DocumentNode.SelectSingleNode( "/html/body/section[1]/div[1]/section/div/div/div/div/div[1]/p")?.InnerHtml == "Private Profile") { ImgUrl = doc.DocumentNode .SelectSingleNode("/html/body/section[1]/div[1]/section/div/div/div/div/div[2]/img") .Attributes["src"].Value; _ = GeneralInvocableFuncs.ShowToast("warning", Lang["Toast_BNet_Private", new { BTag = BTag }], renderTo: "toastarea"); _ = BattleNetSwitcherFuncs.DownloadImage(Email, ImgUrl); LastTimeChecked = DateTime.Now - TimeSpan.FromMinutes(1435); // 23 Hours 55 Minutes return(false); } // If BattleTag is invalid if (doc.DocumentNode.SelectSingleNode( "/html/body/section[1]/section/div/h1")?.InnerHtml == "PROFILE NOT FOUND") { _ = GeneralInvocableFuncs.ShowToast("error", Lang["Toast_ItemNotFound", new { item = BTag }], renderTo: "toastarea"); return(false); } LastTimeChecked = DateTime.Now; ImgUrl = doc.DocumentNode .SelectSingleNode("/html/body/section[1]/div[1]/section/div/div[2]/div/div/div[2]/img") .Attributes["src"].Value; _ = BattleNetSwitcherFuncs.DownloadImage(Email, ImgUrl); var ranks = doc.DocumentNode.SelectNodes( "/html/body/section[1]/div[1]/section/div/div[2]/div/div/div[2]/div/div[3]"); foreach (var node in ranks.Elements()) { if (!int.TryParse(node.LastChild.LastChild.InnerHtml, out var sr)) { continue; } switch (node.LastChild.FirstChild.Attributes["data-ow-tooltip-text"].Value.Split(" ").First()) { case "Tank": OwTankSr = sr; break; case "Damage": OwDpsSr = sr; break; case "Support": OwSupportSr = sr; break; default: continue; } } return(true); }
private async void RestoreFile(InputFileChangeEventArgs e) { if (!_currentlyRestoring) { _currentlyRestoring = true; } else { _ = GeneralInvocableFuncs.ShowToast("error", Lang["Toast_RestoreBusy"], renderTo: "toastarea"); return; } foreach (var file in e.GetMultipleFiles(1)) { try { if (!file.Name.EndsWith("7z")) { continue; } _ = GeneralInvocableFuncs.ShowToast("info", Lang["Toast_RestoreExt"], renderTo: "toastarea"); var outputFolder = Path.Join("Restore", Path.GetFileNameWithoutExtension(file.Name)); Directory.CreateDirectory(outputFolder); var tempFile = Path.Join("Restore", file.Name); // Import 7z var s = file.OpenReadStream(4294967296); // 4 GB as bytes var fs = File.Create(tempFile); await s.CopyToAsync(fs); fs.Close(); // Decompress and remove temp file Globals.DecompressZip(tempFile, outputFolder); File.Delete(tempFile); _ = GeneralInvocableFuncs.ShowToast("info", Lang["Toast_RestoreCopying"], renderTo: "toastarea"); // Move files and folders back foreach (var(toPath, fromPath) in CurrentPlatform.BackupPaths) { var fullFromPath = Path.Join(outputFolder, fromPath); if (Globals.IsFile(fullFromPath)) { Globals.CopyFile(fullFromPath, toPath); } else if (Globals.IsFolder(fullFromPath)) { Globals.CopyFilesRecursive(fullFromPath, toPath, true); } } _ = GeneralInvocableFuncs.ShowToast("info", Lang["Toast_RestoreDeleting"], renderTo: "toastarea"); // Remove temp files Globals.RecursiveDelete(outputFolder, false); _ = GeneralInvocableFuncs.ShowToast("success", Lang["Toast_RestoreComplete"], renderTo: "toastarea"); } catch (Exception ex) { Globals.WriteToLog("Failed to restore from file: " + file.Name, ex); _ = GeneralInvocableFuncs.ShowToast("error", Lang["Status_FailedLog"], renderTo: "toastarea"); } _currentlyRestoring = false; } }
// BUTTON: Pick folder public void PickFolder() { Globals.DebugWriteLine(@"[ButtonClicked:Basic\Settings.razor.cs.PickFolder]"); _ = GeneralInvocableFuncs.ShowModal("find:Basic:BasicGamesLauncher.exe:BasicSettings"); }
/// <summary> /// Backs up platform folders, settings, etc - as defined in the platform settings json /// </summary> private void BackupButton(bool everything = false) { if (!_currentlyBackingUp) { _currentlyBackingUp = true; } else { _ = GeneralInvocableFuncs.ShowToast("error", Lang["Toast_BackupBusy"], renderTo: "toastarea"); return; } // Let user know it's copying files to a temp location _ = GeneralInvocableFuncs.ShowToast("info", Lang["Toast_BackupCopy"], renderTo: "toastarea"); // Generate temporary folder: var tempFolder = $"BackupTemp\\Backup_{CurrentPlatform.FullName}_{DateTime.Now:dd-MM-yyyy_hh-mm-ss}"; Directory.CreateDirectory("Backups\\BackupTemp"); if (!everything) { foreach (var(f, t) in CurrentPlatform.BackupPaths) { var fExpanded = BasicSwitcherFuncs.ExpandEnvironmentVariables(f); var dest = Path.Join(tempFolder, t); // Handle file entry if (Globals.IsFile(f)) { Globals.CopyFile(f, dest); continue; } if (!Directory.Exists(fExpanded)) { continue; } // Handle folder entry if (CurrentPlatform.BackupFileTypesInclude.Count > 0) { Globals.CopyFilesRecursive(fExpanded, dest, true, CurrentPlatform.BackupFileTypesInclude, true); } else if (CurrentPlatform.BackupFileTypesIgnore.Count > 0) { Globals.CopyFilesRecursive(fExpanded, dest, true, CurrentPlatform.BackupFileTypesIgnore, false); } } } else { foreach (var(f, t) in CurrentPlatform.BackupPaths) { var fExpanded = BasicSwitcherFuncs.ExpandEnvironmentVariables(f); var dest = Path.Join(tempFolder, t); // Handle file entry if (Globals.IsFile(f)) { Globals.CopyFile(f, dest); continue; } if (!Directory.Exists(fExpanded)) { continue; } // Handle folder entry Globals.CopyFilesRecursive(fExpanded, dest, true); } } var backupThread = new Thread(() => FinishBackup(tempFolder)); backupThread.Start(); }
// BUTTON: Pick folder public void PickFolder() { Globals.DebugWriteLine(@"[ButtonClicked:BattleNet\Settings.razor.cs.PickFolder]"); _ = GeneralInvocableFuncs.ShowModal("find:BattleNet:Battle.net.exe:BattleNetSettings"); }