public SingleReplayWindow()
        {
            InitializeComponent();

            Dispatcher.UnhandledException += (object sender, DispatcherUnhandledExceptionEventArgs e) =>
            {
                _log.Error(e.Exception.ToString());
                _log.WriteLog();
            };

            _log = new RiZhi()
            {
                FilePrefix = "ReplayBookLog"
            };

            _settingsManager = new SettingsManager(_log);

            _files    = new FileManager(_settingsManager.Settings, _log);
            _requests = new RequestManager(_settingsManager.Settings, _log);

            var context = new MainWindowViewModel(_files, _requests, _settingsManager, _log);

            this.DataContext = context;

            var version = Assembly.GetEntryAssembly().GetName().Version.ToString(2);

            _log.Error($"Log files are generated for each run while in prerelease. Prerelease version: {version}");

            // Decide to show welcome window
            context.ShowWelcomeWindow();
        }
        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);
        }
        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)
            {
                UpdateExecutableVersion(executable);
            }
        }
Exemple #4
0
        public MainWindow(RiZhi log, SettingsManager settingsManager, RequestManager requests, FileManager files, ReplayPlayer player)
        {
            InitializeComponent();

            _log             = log;
            _settingsManager = settingsManager;
            _requests        = requests;
            _files           = files;
            _player          = player;

            _lastSelection = null;

            Dispatcher.UnhandledException += (object sender, DispatcherUnhandledExceptionEventArgs e) =>
            {
                _log.Error(e.Exception.ToString());
                _log.WriteLog();
            };

            var context = new MainWindowViewModel(_files, _requests, _settingsManager, _player, _log);

            this.DataContext = context;

            // Decide to show welcome window
            context.ShowWelcomeWindow();
            context.ShowMissingReplayFoldersMessageBox();
        }
Exemple #5
0
        private async void Window_Loaded(object sender, RoutedEventArgs e)
        {
            if (!(this.DataContext is MainWindowViewModel context))
            {
                return;
            }

            var replay = await _files.GetSingleFile(ReplayFileLocation).ConfigureAwait(true);

            if (replay == null)
            {
                _log.Error($"Failed to load file {ReplayFileLocation}");
                MessageBox.Show((string)TryFindResource("FailedToLoadReplayText"),
                                (string)TryFindResource("ErrorTitle"),
                                MessageBoxButton.OK,
                                MessageBoxImage.Error);

                Application.Current.Shutdown();
            }
            else
            {
                // Let the view model know about the replay
                var previewReplay = context.AddReplay(replay);
                var replayDetail  = new ReplayDetail(replay, previewReplay);
                DetailView.DataContext = replayDetail;
                (DetailView.FindName("BlankContent") as Grid).Visibility  = Visibility.Hidden;
                (DetailView.FindName("ReplayContent") as Grid).Visibility = Visibility.Visible;

                await context.LoadItemThumbnails(replayDetail).ConfigureAwait(true);

                await context.LoadSinglePreviewPlayerThumbnails(previewReplay).ConfigureAwait(true);
            }
        }
Exemple #6
0
        private void CreateCommonObjects()
        {
            // Create common objects
            var assemblyName = Assembly.GetEntryAssembly()?.GetName();

            _log = new RiZhi()
            {
                FilePrefix      = "ReplayBookLog",
                AssemblyName    = assemblyName.Name,
                AssemblyVersion = assemblyName.Version.ToString(2)
            };

            try
            {
                _settingsManager = new SettingsManager(_log);
                _files           = new FileManager(_settingsManager.Settings, _log);
                _requests        = new RequestManager(_settingsManager.Settings, _log);
                _player          = new ReplayPlayer(_files, _settingsManager, _log);
            }
            catch (Exception ex)
            {
                _log.Error(ex.ToString());
                _log.WriteLog();
                throw;
            }
        }
Exemple #7
0
        private async void Application_Startup(object sender, StartupEventArgs e)
        {
            CreateCommonObjects();

            // Apply appearence theme
            ApplyThemeSetting();

            // Apply language setting
            LanguageHelper.SetProgramLanguage(_settingsManager.Settings.ProgramLanguage);

            // Load data
            RuneHelper.LoadRunes(_settingsManager.Settings.ProgramLanguage);

#if DEBUG
            _log.Error("Debug mode, writing log");
#endif

            if (e.Args.Length == 1)
            {
                var selectedFile = e.Args[0];
                // 0 = directly play, 1 = open in replaybook
                if (_settingsManager.Settings.FileAction == Settings.Models.FileAction.Play)
                {
                    StartDialogHost();
                    await _player.PlayReplay(selectedFile).ConfigureAwait(true);

                    Application.Current.Shutdown();
                }
                else if (_settingsManager.Settings.FileAction == Settings.Models.FileAction.Open)
                {
                    StartSingleReplayWindow(selectedFile);
                }
                else
                {
                }
            }
            else
            {
                StartMainWindow();
            }
        }
Exemple #8
0
        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();
        }
Exemple #9
0
        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);
        }
Exemple #10
0
        /// <summary>
        /// Get an array of all appropriate DataDragon versions
        /// </summary>
        /// <returns></returns>
        public async Task <string[]> GetDataDragonVersionStringsAsync()
        {
            const string url = @"https://ddragon.leagueoflegends.com/api/versions.json";

            HttpResponseMessage response;

            using (var request = new HttpRequestMessage(HttpMethod.Get, url))
            {
                request.Headers.UserAgent.ParseAdd(UserAgent);
                request.Headers.Accept.ParseAdd("text/json");

                try
                {
                    response = await _httpClient.SendAsync(request).ConfigureAwait(true);
                }
                catch (HttpRequestException)
                {
                    _log.Error($"Unable to send HTTP request to {url}");
                    return(null);
                }
            }

            if (response.IsSuccessStatusCode)
            {
                _log.Information($"Made successful HTTP request {url}");

                var json = await response.Content.ReadAsStringAsync().ConfigureAwait(true);

                return(JArray.Parse(json).ToObject <string[]>());
            }
            else
            {
                _log.Error($"HTTP request failed {(int)response.StatusCode} {url}");
                return(null);
            }
        }
Exemple #11
0
        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 <Process> PlayReplay(string path)
        {
            var replay = await _files.GetSingleFile(path).ConfigureAwait(true);

            var executables = _settingsManager.Executables.GetExecutablesByPatch(replay.ReplayFile.GameVersion);

            if (!executables.Any())
            {
                _log.Information($"No executables found to play replay");

                // No executable found that can be used to play
                await ShowUnsupportedDialog(replay.ReplayFile.GameVersion).ConfigureAwait(true);

                return(null);
            }

            LeagueExecutable target;

            if (executables.Count > 1)
            {
                _log.Information($"More than one possible executable, asking user...");
                // More than one?????
                target = await ShowChooseReplayDialog(executables).ConfigureAwait(true);

                if (target == null)
                {
                    return(null);
                }
            }
            else
            {
                target = executables.First();
            }

            if (_settingsManager.Settings.PlayConfirmation)
            {
                _log.Information($"Asking user for confirmation");

                // Only continue if the user pressed the yes button
                var dialogResult = await ShowConfirmationDialog().ConfigureAwait(true);

                if (dialogResult != ContentDialogResult.Primary)
                {
                    return(null);
                }
            }

            _log.Information($"Using {target.Name} to play replay {replay.FileInfo.Path}");

            Process gameHandle = null;

            try
            {
                gameHandle = target.PlayReplay(replay.FileInfo.Path);
            }
            catch (Exception ex)
            {
                await ShowExceptionDialog(ex).ConfigureAwait(true);

                _log.Error(ex.ToString());
            }

            return(gameHandle);
        }
        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
                });
            }
        }