public IList <LeagueExecutable> SearchFolderForExecutables(string startPath) { List <LeagueExecutable> foundExecutables = new List <LeagueExecutable>(); if (!Directory.Exists(startPath)) { _log.Warning($"Input path {startPath} does not exist"); throw new DirectoryNotFoundException($"Input path {startPath} does not exist"); } try { // Look for any and all league of legends executables var exeFiles = Directory.EnumerateFiles(startPath, "League of Legends.exe", SearchOption.AllDirectories); foreach (string exePath in exeFiles) { LeagueExecutable newExe = null; try { newExe = ExeTools.CreateNewLeagueExecutable(exePath); } catch (Exception ex) { _log.Error($"{ex.GetType()} trying to create executable for path = \"{exePath}\""); _log.Error(ex.ToString()); continue; } try { newExe.Locale = ExeTools.DetectExecutableLocale(exePath); } catch (Exception ex) { _log.Error($"{ex.GetType()} trying to find locale for path = \"{exePath}\""); _log.Error(ex.ToString()); newExe.Locale = LeagueLocale.EnglishUS; // do not stop operation } // Do we already have an exe with the same target? if (!foundExecutables.Exists(x => x.TargetPath.Equals(newExe.TargetPath, StringComparison.OrdinalIgnoreCase))) { foundExecutables.Add(newExe); } } } catch (Exception e) { _log.Error(e.ToString()); throw; } return(foundExecutables); }
// Window has been rendered to the screen private async void Window_ContentRendered(object sender, EventArgs e) { if (!_settingsManager.Settings.AutoUpdateCheck) { return; } string latestVersion; try { _log.Information("Checking for updates..."); latestVersion = await GithubConnection.GetLatestVersion().ConfigureAwait(true); } catch (HttpRequestException ex) { _log.Warning("Failed to check for updates - " + ex.ToString()); return; // keep in mind when adding anything to this function! } if (String.IsNullOrEmpty(latestVersion)) { _log.Warning("Failed to check for updates - github returned nothing or error code"); return; // keep in mind when adding anything to this function! } var assemblyName = Assembly.GetEntryAssembly()?.GetName(); var assemblyVersion = assemblyName.Version.ToString(3); if (latestVersion.Equals(assemblyVersion, StringComparison.OrdinalIgnoreCase)) { _settingsManager.TemporaryValues["UpdateAvailable"] = false; } else { _settingsManager.TemporaryValues["UpdateAvailable"] = true; var updateNotif = FlyoutHelper.CreateFlyout(true, true); updateNotif.SetFlyoutLabelText(TryFindResource("UpdateAvailableNotifText") as String); updateNotif.SetFlyoutButtonText(TryFindResource("UpdateAvailableNotifButton") as String); updateNotif.GetFlyoutButton().Click += (object e1, RoutedEventArgs a) => { Process.Start((TryFindResource("GitHubReleasesLink") as Uri).ToString()); }; updateNotif.Placement = ModernWpf.Controls.Primitives.FlyoutPlacementMode.Bottom; updateNotif.ShowAt(SettingsButton); } return; }
public IList <LeagueExecutable> SearchFolderForExecutables(string startPath) { List <LeagueExecutable> foundExecutables = new List <LeagueExecutable>(); if (!Directory.Exists(startPath)) { _log.Warning($"Input path {startPath} does not exist"); throw new DirectoryNotFoundException($"Input path {startPath} does not exist"); } try { // Look for any and all league of legends executables var exeFiles = Directory.EnumerateFiles(startPath, "League of Legends.exe", SearchOption.AllDirectories); foreach (string exePath in exeFiles) { LeagueExecutable newExe = ExeTools.CreateNewLeagueExecutable(exePath); // Set default locale newExe.Locale = Settings.DefaultLocale; // Do we already have an exe with the same target? if (!foundExecutables.Exists(x => x.TargetPath.Equals(newExe.TargetPath, StringComparison.OrdinalIgnoreCase))) { foundExecutables.Add(newExe); } } } catch (Exception e) { _log.Error(e.ToString()); throw; } return(foundExecutables); }
public DatabaseRepository(RiZhi log) { _log = log; try { InitializeDatabase(); } catch (Exception ex) { _log.Warning($"Database file is invalid, deleting and trying again... exception:{ex}"); File.Delete(_filePath); InitializeDatabase(); } }
private async Task <string> DownloadImage(string url, string location) { HttpResponseMessage response; using (var request = new HttpRequestMessage(HttpMethod.Get, url)) { request.Headers.UserAgent.ParseAdd(UserAgent); request.Headers.Accept.ParseAdd("image/png"); try { response = await _httpClient.SendAsync(request).ConfigureAwait(false); } catch (HttpRequestException) { _log.Error($"Unable to send HTTP request to {url}"); return(null); } } if (response.IsSuccessStatusCode) { _log.Information($"Made successful HTTP request {url}"); using (var s = await response.Content.ReadAsStreamAsync().ConfigureAwait(false)) { // Creates or overwrites the file if (!Directory.Exists(Path.GetDirectoryName(location))) { Directory.CreateDirectory(Path.GetDirectoryName(location)); } using (var file = File.Create(location)) { await s.CopyToAsync(file).ConfigureAwait(true); } } return(location); } else { _log.Warning($"HTTP request failed {(int) response.StatusCode} {url}"); return(null); } }
public ReplayFileInfo GetSingleReplayFileInfo(string path) { var file = new FileInfo(path); // If the file is not supported, skip it if (!(file.Name.EndsWith(".rofl", StringComparison.OrdinalIgnoreCase))) { _log.Warning($"File {path} is not supported, cannot get file info"); return(null); } return(new ReplayFileInfo() { Path = file.FullName, CreationTime = file.CreationTime, FileSizeBytes = file.Length, Name = Path.GetFileNameWithoutExtension(file.FullName) }); }
public string[] RemoveInvalidReplayPaths() { var missingList = new List <string>(); foreach (var path in Settings.SourceFolders) { if (!Directory.Exists(path)) { _log.Warning($"Replay folder {path} no longer exists, deleting..."); missingList.Add(path); } } foreach (var path in missingList) { Settings.SourceFolders.Remove(path); } return(missingList.ToArray()); }
/// <summary> /// Downloads image from url and returns bitmap /// </summary> /// <param name="url"></param> /// <param name="location"></param> /// <returns></returns> private async Task <byte[]> DownloadImage(string url, string location) { HttpResponseMessage response; using (var request = new HttpRequestMessage(HttpMethod.Get, url)) { request.Headers.UserAgent.ParseAdd(UserAgent); request.Headers.Accept.ParseAdd("image/png"); try { response = await _httpClient.SendAsync(request).ConfigureAwait(false); } catch (HttpRequestException) { _log.Error($"Unable to send HTTP request to {url}"); return(null); } } if (response.IsSuccessStatusCode) { // _log.Information($"Made successful HTTP request {url}"); var contentBytes = await response.Content.ReadAsByteArrayAsync().ConfigureAwait(false); // Create file directory if it does not exist if (!Directory.Exists(Path.GetDirectoryName(location))) { Directory.CreateDirectory(Path.GetDirectoryName(location)); } // Write bytes to file File.WriteAllBytes(location, contentBytes); return(contentBytes); } else { _log.Warning($"HTTP request failed {(int) response.StatusCode} {url}"); return(null); } }
public ExecutableManager(RiZhi log) { _log = log ?? throw new ArgumentNullException(nameof(log)); // Get the exeInfoFile or create new one _exeInfoFilePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "executablesettings.json"); if (!File.Exists(_exeInfoFilePath)) { // Exe file is missing, set up defaults _log.Information($"Executable file does not exist, creating"); Settings = new ExecutableSettings(); } else { // Exe file found, load it try { Settings = JsonConvert.DeserializeObject <ExecutableSettings>(File.ReadAllText(_exeInfoFilePath)); } catch (Exception parseEx) { // Failed loading, create new one instead _log.Error($"Error reading executable info file, creating new one. {parseEx}"); Settings = new ExecutableSettings(); } } // Refresh all known executables versions foreach (var executable in Settings.Executables) { if (File.Exists(executable.TargetPath)) { UpdateExecutableVersion(executable); } else { _log.Warning($"Target for executable '{executable.Name}' does not exist"); } } }
public static void Main(string[] args) { var log = new RiZhi { FilePrefix = "ExampleApp", AssemblyVersion = "1.0.0", AssemblyName = "Example Program" }; log.Debug("Debug message, appears first"); log.Information("Information message, appears second"); log.Warning($"Warning message, appears third. Error Flag = {log.ErrorFlag}"); log.Error("Error message, appears fourth"); if (log.ErrorFlag) { log.Debug($"Error was logged"); } log.WriteLog(); }
public async Task <ReplayFile> ReadFile(string filePath) { // Make sure file exists if (String.IsNullOrEmpty(filePath)) { _log.Error("File reference is null"); throw new ArgumentNullException($"File reference is null"); } if (!File.Exists(filePath)) { _log.Error("File path not found, does the file exist?"); throw new FileNotFoundException($"File path not found, does the file exist?"); } // Reads the first 4 bytes and tries to find out the replay type ReplayType type = await ParserHelpers.GetReplayTypeAsync(filePath); // Match parsers to file types ReplayFile result; switch (type) { case ReplayType.ROFL: // Official Replays result = await ReadROFL(filePath); break; //case ReplayType.LRF: // LOLReplay // file.Type = ReplayType.LRF; // file.Data = await ReadLRF(file.Location); // break; //case ReplayType.LPR: // BaronReplays // file.Type = ReplayType.LPR; // file.Data = null; // break; default: _log.Error($"File {filePath} is not an accepted format: rofl"); return(null); } // Make some educated guesses GameDetailsInferrer detailsInferrer = new GameDetailsInferrer(); result.Players = result.BluePlayers.Union(result.RedPlayers).ToArray(); try { result.MapId = detailsInferrer.InferMap(result.Players); } catch (ArgumentNullException ex) { _log.Warning("Could not infer map type\n" + ex.ToString()); result.MapId = MapCode.Unknown; } result.MapName = detailsInferrer.GetMapName(result.MapId); result.IsBlueVictorious = detailsInferrer.InferBlueVictory(result.BluePlayers, result.RedPlayers); foreach (var player in result.Players) { player.Id = $"{result.MatchId}_{player.PlayerID}"; } // Set the alternate name to the default result.AlternativeName = result.Name; return(result); }
public async Task LoadItemThumbnails(ReplayDetail replay) { _log.Information("Loading/downloading thumbnails for items..."); if (replay == null) { throw new ArgumentNullException(nameof(replay)); } var dataVersion = await RequestManager.GetLatestDataDragonVersionAsync().ConfigureAwait(true); var allItems = new List <Item>(); var itemTasks = new List <Task>(); allItems.AddRange(replay.BluePlayers.SelectMany(x => x.Items)); allItems.AddRange(replay.RedPlayers.SelectMany(x => x.Items)); _log.Information($"Processing {allItems.Count} item thumbnail requests"); foreach (var item in allItems) { // If an item does not exist, set it to nothing! if (item.ItemId == "0") { Application.Current.Dispatcher.Invoke((Action) delegate { item.ShowBorder = true; }); continue; } // Set default item image, to be replaced Application.Current.Dispatcher.Invoke((Action) delegate { item.OverlayIcon = ResourceTools.GetObjectFromResource <Geometry>("DownloadPathIcon"); }); itemTasks.Add(Task.Run(async() => { var response = await RequestManager.MakeRequestAsync(new ItemRequest { DataDragonVersion = dataVersion, ItemID = item.ItemId }).ConfigureAwait(true); if (response.IsFaulted) { _log.Warning($"Failed to load image for {(response.Request as ItemRequest).ItemID}"); Application.Current.Dispatcher.Invoke((Action) delegate { item.OverlayIcon = ResourceTools.GetObjectFromResource <Geometry>("ErrorPathIcon"); }); } else { if (response.FromCache) { Application.Current.Dispatcher.Invoke((Action) delegate { item.OverlayIcon = null; // hide overlay icons, if any item.ImageSource = ResourceTools.GetImageSourceFromPath(response.ResponsePath); }); } else { Application.Current.Dispatcher.Invoke((Action) delegate { item.OverlayIcon = null; // hide overlay icons, if any item.ImageSource = response.ResponseBytes.ToBitmapImage(); }); } } })); } await Task.WhenAll(itemTasks).ConfigureAwait(true); }
public async Task <ResponseBase> MakeRequestAsync(RequestBase request) { // This acts as the key to tell if a download is in progress string requestId = GetRequestIdentifier(request); if (requestId == "0" || requestId is null) { _log.Warning($"Invalid requestId: {requestId}"); return(new ResponseBase() { Exception = new Exception($"requestId is not valid: {requestId}"), Request = request, IsFaulted = true }); } // 1. If a download is in progress, use the same task to get the result if (_inProgressTasks.ContainsKey(requestId)) { // Get the matching in progress task Task <ResponseBase> responseTask = _inProgressTasks[requestId]; // If the task is complete, remove it if (responseTask.IsCompleted) { if (!_inProgressTasks.TryRemove(requestId, out _)) { _log.Warning($"Failed to remove in progress task {requestId}"); } } // Get the result of the task and return it ResponseBase result = await responseTask.ConfigureAwait(true); return(result); } // 2. A download is not in progress, is it cached? ResponseBase cacheResponse = _cacheClient.CheckImageCache(request); // Fault occurs if cache is unable to find the file, or if the file is corrupted if (!cacheResponse.IsFaulted) { return(cacheResponse); } // 3. Does not exist in cache, make download request try { Task <ResponseBase> responseTask = _downloadClient.DownloadIconImageAsync(request); if (!_inProgressTasks.TryAdd(requestId, responseTask)) { _log.Warning($"Failed to add in progress task {requestId}"); } ResponseBase result = await responseTask.ConfigureAwait(true); return(result); } catch (Exception ex) { _log.Error($"Failed to download {requestId}. Ex: {ex}"); return(new ResponseBase() { Exception = ex, Request = request, IsFaulted = true }); } }