Beispiel #1
0
    // Use this for initialization
    void Start()
    {
        currentReplayStep = new ReplayReader.ReplayStep();

        alreadyGenerateStatistic = false;
        matchResults             = new List <uint>();

        grid       = gameObject.GetComponent <Grid>();
        scenarioId = grid.scenarioId;
        academy    = FindObjectOfType(typeof(BombermanAcademy)) as BombermanAcademy;

        playerManager = ServiceLocator.getManager(scenarioId).GetPlayerManager();
        bombManager   = ServiceLocator.getManager(scenarioId).GetBombManager();
        blocksManager = ServiceLocator.getManager(scenarioId).GetBlocksManager();

        playerManager.initInitialPositions(grid);

        ServiceLocator.getManager(scenarioId).GetLogManager().episodePrint(playerManager.getEpisodeCount());

        playerManager.setRandomizeIterationOfAgents(randomizeIterationOfAgents);

        //Vector3 monitorPosition = transform.position + new Vector3(-3, 4, 1); // scene sem imitação
        Vector3 monitorPosition = transform.position + new Vector3(-6.72f, 4, -4.51f);

        myMonitor = Instantiate(monitorPrefab, monitorPosition, Quaternion.identity, transform.parent);
        Monitor.Log("Last Result:", "draw", myMonitor.transform);
        Monitor.Log("Iteration:", "0 / " + maxIterationString, myMonitor.transform);
        Monitor.Log("Episode:", "1", myMonitor.transform);
        Monitor.Log("Scenario:", transform.parent.gameObject.name, myMonitor.transform);

        iterationWhereWasCreatedBombs = 0;
        numberOfBombsByCreation       = 1;

        // replay
        if (saveReplay)
        {
            replayWriter = new ReplayWriter(scenarioId);
        }

        if (followReplayFile)
        {
            replayReader = new ReplayReader(replayFileName);
            ReplayReader.ReplayStep rStep = replayReader.readStep(ReplayCommandLine.RCL_Episode);
            if (rStep.command == ReplayCommandLine.RCL_Episode)
            {
                currentReplayStep.epId = rStep.epId;
            }
            else
            {
                Debug.Log("Nao e pra entrar aqui. Leitura de episódio errada");
            }
        }

        //Debug.Log("Criando MapController");
        createAgents();
        initBlocks();

        wasInitialized = true;
        reseting       = false;
    }
Beispiel #2
0
        public void TestAthenaMatchStats0()
        {
            var data = $"AthenaMatchStats/matchstats0.dump";

            using var stream  = File.Open(data, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
            using var archive = new Unreal.Core.BinaryReader(stream);
            var reader = new ReplayReader();
            var result = reader.ParseMatchStats(archive, null);

            Assert.True(archive.AtEnd());

            var expected = new Stats
            {
                Info               = null,
                Unknown            = 0,
                Accuracy           = 24f,
                Eliminations       = 0,
                Assists            = 2,
                WeaponDamage       = 314,
                OtherDamage        = 14,
                Revives            = 0,
                DamageTaken        = 338,
                DamageToStructures = 1026,
                MaterialsGathered  = 28,
                MaterialsUsed      = 10,
                TotalTraveled      = 1,
            };

            AssertEqual(expected, result);
        }
Beispiel #3
0
        public static ReplayFile ReadFile(string filePath)
        {
            ReplayFile replayFile = new ReplayFile();

            using (_reader = new ReplayReader(File.Open(filePath, FileMode.Open)))
            {
                replayFile.Passed               = true;
                replayFile.Mode                 = _reader.ReadByte();
                replayFile.Version              = _reader.ReadInt32();
                replayFile.BeatmapHash          = _reader.ReadString();
                replayFile.PlayerName           = _reader.ReadString();
                replayFile.ReplayHash           = _reader.ReadString();
                replayFile.Count300             = _reader.ReadUInt16();
                replayFile.Count100             = _reader.ReadUInt16();
                replayFile.Count50              = _reader.ReadUInt16();
                replayFile.CountGeki            = _reader.ReadUInt16();
                replayFile.CountKatu            = _reader.ReadUInt16();
                replayFile.CountMiss            = _reader.ReadUInt16();
                replayFile.Score                = _reader.ReadInt32();
                replayFile.MaxCombo             = _reader.ReadUInt16();
                replayFile.FullCombo            = _reader.ReadBoolean();
                replayFile.UsedMods             = _reader.ReadInt32();
                replayFile.PerformanceGraphData = _reader.ReadString();
                replayFile.ReplayDate           = _reader.ReadDateTime();
                replayFile.Replay               = _reader.ReadByteArray();
                if (replayFile.Version >= 20140721)
                {
                    replayFile.Long0 = _reader.ReadInt64();
                }
            }

            return(replayFile);
        }
Beispiel #4
0
        private static FortniteReplay ReadReplay(FileInfo replayFile)
        {
            var reader = new ReplayReader();
            var replay = reader.ReadReplay(replayFile.FullName);

            return(replay);
        }
Beispiel #5
0
        private async void DetailForm_Load(object sender, EventArgs e)
        {
            var filename = DetailWindowManager.GetReplayFilename(replaypath);

            GeneralGameFileLabel.Text = filename;

            try
            {
                fileinfo = await ReplayReader.ReadReplayFileAsync(replaypath);

                ImageDownloader.SetDataDragonVersion(fileinfo.MatchMetadata.GameVersion.ToString());
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error Parsing Replay: " + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                Environment.Exit(1);
            }

            if (fileinfo != null)
            {
                DetailWindowManager.PopulatePlayerData(fileinfo.MatchMetadata, this);
                DetailWindowManager.PopulateGeneralReplayData(fileinfo, this);
            }
            else
            {
                MessageBox.Show("Error Parsing Replay", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                Environment.Exit(1);
            }

            // Set version text in about tab
            this.AboutVersionLabel.Text = RoflSettings.Default.VersionString;
        }
Beispiel #6
0
        public void TestAthenaMatchStats2()
        {
            var data = $"AthenaMatchStats/matchstats2.dump";

            using var stream  = File.Open(data, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
            using var archive = new Unreal.Core.BinaryReader(stream);
            var reader = new ReplayReader();
            var result = reader.ParseMatchStats(archive, null);

            Assert.True(archive.AtEnd());

            var expected = new Stats
            {
                Eliminations       = 3,
                Revives            = 0,
                Assists            = 4,
                Accuracy           = 22,
                MaterialsUsed      = 710,
                MaterialsGathered  = 2063,
                DamageTaken        = 839,
                WeaponDamage       = 753,
                OtherDamage        = 119,
                DamageToStructures = 43504,
                TotalTraveled      = 4,
            };

            AssertEqual(expected, result);
        }
Beispiel #7
0
        static void Main(string[] args)
        {
            var localAppDataFolder = Environment.GetFolderPath(SpecialFolder.LocalApplicationData);
            var replayFilesFolder  = Path.Combine(localAppDataFolder, @"FortniteGame\Saved\Demos");

            var replayFiles = Directory.EnumerateFiles(replayFilesFolder, "*.replay");

            foreach (var replayFile in replayFiles)
            {
                var replayReader = new ReplayReader(replayFile);
                var replayInfo   = replayReader.ReadReplayInfo();

                Console.WriteLine($"Name: {replayInfo.FriendlyName}");
                Console.WriteLine($"Date: {replayInfo.Timestamp:dd/MM/yyyy HH:mm:ss}");
                Console.WriteLine($"Total time: {replayInfo.TotalReplayTime}");
                Console.WriteLine($"Eliminations: {replayInfo.Eliminations}");
                Console.WriteLine($"Position: {replayInfo.Position}");
                Console.WriteLine($"Total players: {replayInfo.TotalPlayers}");

                foreach (var elimination in replayInfo.PlayerEliminations)
                {
                    System.Console.WriteLine($"Player {elimination.Eliminated} was eliminated by {elimination.Eliminator} with {elimination.GunType}");
                }
            }
        }
Beispiel #8
0
        private void ParseGeneric(int version, ReplayReader reader)
        {
            AllowToOverrideTime = false;

            if (version >= 14)
            {
                reader.Skip(8);

                WeatherId = reader.ReadString();

                /*if (!string.IsNullOrWhiteSpace(WeatherId)) {
                 *  ErrorIf(WeatherManager.Instance.GetWrapperById(WeatherId) == null,
                 *          AcErrorType.Replay_WeatherIsMissing, WeatherId);
                 * }*/

                TrackId            = reader.ReadString();
                TrackConfiguration = reader.ReadString();
            }
            else
            {
                TrackId = reader.ReadString();
            }

            CarId = reader.TryToReadNextString();
            try {
                DriverName = reader.ReadString();
                reader.ReadInt64();
                CarSkinId = reader.ReadString();
            } catch (Exception) {
                // ignored
            }
        }
Beispiel #9
0
        public static void Main(string[] args)
        {
            if (args.Length != 1)
            {
                Console.WriteLine("1:invalid argument(s)");
                Environment.Exit(1);
            }

            if (!File.Exists(args[0]))
            {
                Console.WriteLine("2:file does not exist");
                Environment.Exit(2);
            }

            try
            {
                var readTask = ReplayReader.ReadReplayFileAsync(args[0]).Result;

                ReturnData readData = new ReturnData()
                {
                    MatchId = readTask.MatchHeader.MatchId
                };
                readData.Players = readTask.MatchMetadata.Players.Select(x => new PlayerData((string)x["NAME"], (string)x["SKIN"], (ulong)x["ID"])).ToArray();

                Console.WriteLine(JsonConvert.SerializeObject(readData));
            }
            catch (Exception ex)
            {
                Console.WriteLine("3:exception - " + ex.Message + ex.StackTrace);
                Environment.Exit(3);
            }
        }
Beispiel #10
0
        public void TestAthenaMatchStats2()
        {
            byte[] rawData =
            {
                0x00, 0x00, 0x00, 0x00, 0x47, 0x6E, 0x64, 0x3E, 0x04, 0x00, 0x00, 0x00,
                0x03, 0x00, 0x00, 0x00, 0xF1, 0x02, 0x00, 0x00, 0x77, 0x00, 0x00, 0x00,
                0x00, 0x00, 0x00, 0x00, 0x47, 0x03, 0x00, 0x00, 0xF0, 0xA9, 0x00, 0x00,
                0x0F, 0x08, 0x00, 0x00, 0xC6, 0x02, 0x00, 0x00, 0x90, 0xAB, 0x05, 0x00
            };
            using var stream  = new MemoryStream(rawData);
            using var archive = new Unreal.Core.BinaryReader(stream);
            var reader = new ReplayReader();
            var result = reader.ParseMatchStats(archive, null);

            Assert.True(archive.AtEnd());
            Assert.False(archive.IsError);

            var expected = new Stats
            {
                Eliminations       = 3,
                Revives            = 0,
                Assists            = 4,
                Accuracy           = 22,
                MaterialsUsed      = 710,
                MaterialsGathered  = 2063,
                DamageTaken        = 839,
                WeaponDamage       = 753,
                OtherDamage        = 119,
                DamageToStructures = 43504,
                TotalTraveled      = 4,
            };

            AssertEqual(expected, result);
        }
Beispiel #11
0
        public void TestAthenaMatchStats1()
        {
            byte[] rawData =
            {
                0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
                0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
                0x00, 0x00, 0x00, 0x00, 0xDD, 0x00, 0x00, 0x00, 0xDE, 0x00, 0x00, 0x00,
                0x1B, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xEA, 0x14, 0x00, 0x00
            };

            using var stream  = new MemoryStream(rawData);
            using var archive = new Unreal.Core.BinaryReader(stream);
            var reader = new ReplayReader();
            var result = reader.ParseMatchStats(archive, null);

            Assert.True(archive.AtEnd());
            Assert.False(archive.IsError);

            var expected = new Stats
            {
                Eliminations       = 0,
                Revives            = 0,
                Assists            = 0,
                Accuracy           = 0,
                MaterialsUsed      = 0,
                MaterialsGathered  = 27,
                DamageTaken        = 221,
                WeaponDamage       = 0,
                OtherDamage        = 0,
                DamageToStructures = 222,
                TotalTraveled      = 1,
            };

            AssertEqual(expected, result);
        }
Beispiel #12
0
        public FileManager(ObservableSettings settings, RiZhi log)
        {
            _log = log ?? throw new ArgumentNullException(nameof(log));

            _fileSystem = new FolderRepository(settings, log);
            _db         = new DatabaseRepository(log);

            _reader = new ReplayReader(log);
        }
Beispiel #13
0
        public void Initialize(String XMLFile)
        {
            CommandRequester c = new CommandRequester();
            GameSimulator s = new GameSimulator();
            replayer = new ReplayReader(XMLFile);

            GameController.Initialize(XMLFile, false, _frame, null, s, null, c);
            GameController.connectAsInputSource(replayer);
        }
        public static async Task <bool> ShowReplay(GameStats game, bool showToast)
        {
            if (game == null)
            {
                return(false);
            }
            if (Config.Instance.ForceLocalReplayViewer)
            {
                ReplayReader.LaunchReplayViewer(game.ReplayFile, false);
                return(true);
            }
            Action <ReplayProgress> setToastStatus = null;

            if (game.HasReplayFile && !game.HsReplay.Uploaded)
            {
                if (showToast)
                {
                    setToastStatus = ToastManager.ShowReplayProgressToast();
                }
                var log = GetLogFromHdtReplay(game.ReplayFile).ToArray();
                var validationResult = LogValidator.Validate(log);
                if (validationResult.IsValid)
                {
                    await LogUploader.Upload(log, null, game);
                }
                else
                {
                    Log.Error("Invalid log: " + validationResult.Reason);
                    game.HsReplay.Unsupported = true;
                }
                if (DefaultDeckStats.Instance.DeckStats.Any(x => x.DeckId == game.DeckId))
                {
                    DefaultDeckStats.Save();
                }
                else
                {
                    DeckStatsList.Save();
                }
            }
            if (game.HsReplay?.Uploaded ?? false)
            {
                setToastStatus?.Invoke(ReplayProgress.Complete);
                Helper.TryOpenUrl(game.HsReplay?.Url);
            }
            else if (game.HasReplayFile)
            {
                setToastStatus?.Invoke(ReplayProgress.Error);
                ReplayReader.LaunchReplayViewer(game.ReplayFile, true);
            }
            else
            {
                setToastStatus?.Invoke(ReplayProgress.Error);
                return(false);
            }
            return(true);
        }
Beispiel #15
0
 private void ButtonShowReplay_OnClick(object sender, RoutedEventArgs e)
 {
     if (SelectedGame == null)
     {
         return;
     }
     if (SelectedGame.HasReplayFile)
     {
         ReplayReader.LaunchReplayViewer(SelectedGame.ReplayFile);
     }
 }
Beispiel #16
0
 public Worker(ILogger <Worker> logger)
 {
     _logger = logger;
     _reader = new ReplayReader();
     if (!File.Exists("config.json"))
     {
         File.Create("config.json");
         File.WriteAllText("config.json", "{ \"NewFileName\":\"<date> <map>\",\"MoveToThisFolder\":\"\"}");
     }
     _configBuilder = new ConfigurationBuilder().AddJsonFile("config.json").Build();
     _config        = _configBuilder.Get <Config>();
 }
        public void ParseAthenaTeamStatsTest(byte[] rawData, uint position, uint totalPlayers)
        {
            using var stream  = new MemoryStream(rawData);
            using var archive = new Unreal.Core.BinaryReader(stream);
            var reader = new ReplayReader();
            var result = reader.ParseTeamStats(archive, null);

            Assert.True(archive.AtEnd());
            Assert.False(archive.IsError);
            Assert.Equal(position, result.Position);
            Assert.Equal(totalPlayers, result.TotalPlayers);
        }
        static void Main(string[] args)
        {
            var serviceCollection = new ServiceCollection()
                                    .AddLogging(loggingBuilder => loggingBuilder
                                                .AddConsole()
                                                .SetMinimumLevel(LogLevel.Error));
            var provider = serviceCollection.BuildServiceProvider();
            var logger   = provider.GetService <ILogger <Program> >();

            //var localAppDataFolder = GetFolderPath(SpecialFolder.LocalApplicationData);
            //var replayFilesFolder = Path.Combine(localAppDataFolder, @"FortniteGame\Saved\Demos");
            var replayFilesFolder = @"F:\Projects\FortniteReplayCollection\_upload\season 11\";
            var replayFiles       = Directory.EnumerateFiles(replayFilesFolder, "*.replay");

            var  sw     = new Stopwatch();
            var  reader = new ReplayReader(logger, ParseMode.Full);
            long total  = 0;

            foreach (var replayFile in replayFiles)
            {
                sw.Restart();
                try
                {
                    var replay = reader.ReadReplay(replayFile);
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex);
                }
                sw.Stop();
                Console.WriteLine($"---- {replayFile} : done in {sw.ElapsedMilliseconds} milliseconds ----");
                total += sw.ElapsedMilliseconds;
            }
            Console.WriteLine($"total: {total / 1000} seconds ----");

            //var replayFile = "Replays/shootergame.replay";
            //var replayFile = "Replays/season6.10.replay";
            //var replayFile = "Replays/season11.11.replay";
            //var replayFile = "Replays/season11.31.replay";
            //var replayFile = "Replays/season11.replay";
            //var replayFile = "Replays/season12.replay";
            //var replayFile = "Replays/collectPickup.replay";

            //var sw = new Stopwatch();
            //sw.Start();
            //var reader = new ReplayReader(logger, ParseMode.Debug);
            //var replay = reader.ReadReplay(replayFile);
            //sw.Stop();

            //Console.WriteLine($"---- done in {(sw.ElapsedMilliseconds / 1000)} seconds ----");
            Console.ReadLine();
        }
Beispiel #19
0
        private bool ReadExtendedSection(ReplayReader reader, string name, int length)
        {
            if (name == @"CONFIG_RACE")
            {
                RaceIniConfig = Encoding.ASCII.GetString(reader.ReadBytes(length));
                CustomTime    = Game.ConditionProperties.GetSeconds(
                    IniFile.Parse(RaceIniConfig)["LIGHTING"].GetDoubleNullable("__CM_UNCLAMPED_SUN_ANGLE")
                    ?? IniFile.Parse(RaceIniConfig)["LIGHTING"].GetDouble("SUN_ANGLE", 80d)).RoundToInt();
                return(true);
            }

            return(false);
        }
Beispiel #20
0
        public void AthenaTeamStats1Test()
        {
            var data = $"AthenaTeamStats/teamstats1.dump";

            using var stream  = File.Open(data, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
            using var archive = new Unreal.Core.BinaryReader(stream);
            var reader = new ReplayReader();
            var result = reader.ParseTeamStats(archive, null);

            Assert.True(archive.AtEnd());
            Assert.Equal(2u, result.Position);
            Assert.Equal(99u, result.TotalPlayers);
        }
        public override void ReadObjectsIdsAndNames()
        {
            var entitiesCount = ReplayReader.ReadByte();
            var idToNames     = new Dictionary <int, string>();

            for (var i = 0; i < entitiesCount; i++)
            {
                var id   = ReplayReader.ReadInt32();
                var name = ReplayReader.ReadString();

                idToNames.Add(id, name);
            }
            InstantiateOrDestroyGameObjectsAtDeltaReplay(idToNames);
        }
Beispiel #22
0
        public void Season7Test()
        {
            var data = $"PlayerElims/season7.dump";

            using var stream  = File.Open(data, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
            using var archive = new Unreal.Core.BinaryReader(stream);
            var reader = new ReplayReader()
            {
                Branch = "++Fortnite+Release-7.10"
            };
            var result = reader.ParseElimination(archive, null);

            Assert.True(archive.AtEnd());
        }
Beispiel #23
0
        protected override async Task <Window> Load(ILoadingView loadingView)
        {
            try {
                var replayClient = new ReplayClient();
                Program.Client = replayClient;

                Program.IsHost = true;

                loadingView.UpdateStatus("Loading Replay..");
                ReplayReader reader = null;
                ReplayEngine engine = null;
                try {
                    reader = ReplayReader.FromStream(File.OpenRead(_replayPath));
                    engine = new ReplayEngine(reader, replayClient);

                    loadingView.UpdateStatus("Loading Game...");
                    var game = GameManager.Get().GetById(reader.Replay.GameId);

                    loadingView.UpdateStatus("Loading Game Engine...");
                    Program.CurrentOnlineGameName = game.Name;
                    Program.GameEngine            = new GameEngine(engine, game, reader.Replay.User);
                } catch {
                    reader?.Dispose();
                    engine?.Dispose();

                    throw;
                }

                var dispatcher = Dispatcher.CurrentDispatcher;

                Window window = null;
                await dispatcher.InvokeAsync(() => {
                    window = WindowManager.PlayWindow = new PlayWindow();

                    window.Closed += PlayWindow_Closed;

                    window.Show();
                }, DispatcherPriority.Background);

                return(window);
            } catch (UserMessageException) {
                throw;
            } catch (Exception e) {
                var msg = $"Error launching replay from {_replayPath}: {e.Message}";

                Log.Warn(msg, e);

                throw new UserMessageException(UserMessageExceptionMode.Blocking, msg, e);
            }
        }
 private void MenuItemReplayLastGame_OnClick(object sender, RoutedEventArgs e)
 {
     try
     {
         var newest = Directory.GetFiles(Config.Instance.ReplayDir).Select(x => new FileInfo(x)).OrderByDescending(x => x.CreationTime).FirstOrDefault();
         if (newest != null)
         {
             ReplayReader.Read(newest.FullName);
         }
     }
     catch (Exception ex)
     {
         Logger.WriteLine(ex.ToString());
     }
 }
        public override void ReadObjectsIdsAndNames()
        {
            var entitiesCount = ReplayReader.ReadInt32();
            var idToNames     = new Dictionary <int, (string, Vector3, Quaternion)>();

            for (var i = 0; i < entitiesCount; i++)
            {
                var id   = ReplayReader.ReadInt32();
                var name = ReplayReader.ReadString();
                var pos  = ReplayReader.ReadVector3();
                var rot  = ReplayReader.ReadQuaternion();
                idToNames.Add(id, (name, pos, rot));
            }

            InstantiateOrDestroyGameObjectsAtReplay(idToNames);
        }
Beispiel #26
0
        public void ParsePlayerElimTest(byte[] rawData, EngineNetworkVersionHistory version, string branch)
        {
            using var stream  = new MemoryStream(rawData);
            using var archive = new Unreal.Core.BinaryReader(stream)
                  {
                      EngineNetworkVersion = version
                  };
            var reader = new ReplayReader()
            {
                Branch = branch
            };

            reader.ParseElimination(archive, null);

            Assert.True(archive.AtEnd());
            Assert.False(archive.IsError);
        }
Beispiel #27
0
        public void Season9Test()
        {
            var data = $"PlayerElims/season9.dump";

            using var stream  = File.Open(data, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
            using var archive = new Unreal.Core.BinaryReader(stream)
                  {
                      EngineNetworkVersion = EngineNetworkVersionHistory.HISTORY_FAST_ARRAY_DELTA_STRUCT
                  };
            var reader = new ReplayReader()
            {
                Branch = "++Fortnite+Release-9.10"
            };
            var result = reader.ParseElimination(archive, null);

            Assert.True(archive.AtEnd());
        }
Beispiel #28
0
        public void Season11update11Test()
        {
            var data = $"PlayerElims/season11.11.dump";

            using var stream  = File.Open(data, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
            using var archive = new Unreal.Core.BinaryReader(stream)
                  {
                      EngineNetworkVersion = EngineNetworkVersionHistory.HISTORY_OPTIONALLY_QUANTIZE_SPAWN_INFO
                  };
            var reader = new ReplayReader()
            {
                Branch = "++Fortnite+Release-11.11"
            };
            var result = reader.ParseElimination(archive, null);

            Assert.True(archive.AtEnd());
        }
        public static async Task ShowReplay(string fileName, bool showToast)
        {
            if (Config.Instance.ForceLocalReplayViewer)
            {
                ReplayReader.LaunchReplayViewer(fileName, false);
                return;
            }
            Action <ReplayProgress> setToastStatus = null;
            var log = GetLogFromHdtReplay(fileName).ToArray();
            var validationResult = LogValidator.Validate(log);

            if (validationResult.IsValid)
            {
                if (showToast)
                {
                    setToastStatus = ToastManager.ShowReplayProgressToast();
                }
                setToastStatus?.Invoke(ReplayProgress.Uploading);
                var file     = new FileInfo(fileName);
                var hsBuild  = BuildDates.GetByDate(file.LastWriteTime);
                var metaData = hsBuild != null ? new GameMetaData()
                {
                    HearthstoneBuild = hsBuild
                } : null;
                var gameStats = hsBuild != null ? new GameStats()
                {
                    StartTime = file.LastWriteTime
                } : null;
                var success = await LogUploader.Upload(log.ToArray(), metaData, gameStats);

                if (success)
                {
                    Helper.TryOpenUrl(gameStats?.HsReplay?.Url);
                }
                else
                {
                    ReplayReader.LaunchReplayViewer(fileName, true);
                }
            }
            else
            {
                Log.Error("Invalid log: " + validationResult.Reason);
                ReplayReader.LaunchReplayViewer(fileName, true);
            }
            setToastStatus?.Invoke(ReplayProgress.Complete);
        }
Beispiel #30
0
        /// <summary>
        /// Given replay path, construct ReplayFile with all properties initialized
        /// </summary>
        /// <param name="replayPath"></param>
        /// <returns></returns>
        private static async Task <ReplayFile> SetupReplayFileAsync(string replayPath)
        {
            var fileInfo = new ReplayFile
            {
                Location = replayPath,
                Name     = Path.GetFileName(replayPath),
            };

            switch (Path.GetExtension(replayPath))
            {
            case ".rofl":
                fileInfo.Type = REPLAYTYPES.ROFL;
                break;

            case ".lrf":
                MessageBox.Show($"{fileInfo.Name} is a old LoLReplay file.\nROFLPlayer will try to open this file in compatibility mode, some data or features may be missing.", "Compatibility Mode", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                fileInfo.Type = REPLAYTYPES.LRF;
                break;

            case ".lpr":
                MessageBox.Show($"{fileInfo.Name} is a old BaronReplay file. ROFLPlayer does not support opening this file.", "Compatibility Mode", MessageBoxButtons.OK, MessageBoxIcon.Error);
                fileInfo.Type = REPLAYTYPES.LPR;
                Environment.Exit(1);
                break;

            default:
                MessageBox.Show($"{fileInfo.Name} is not a supported file type", "Unsupported File", MessageBoxButtons.OK, MessageBoxIcon.Error);
                Environment.Exit(1);
                break;
            }

            var replayReader = new ReplayReader();

            try
            {
                fileInfo = await replayReader.ReadFile(fileInfo);
            }
            catch (Exception ex)
            {
                MessageBox.Show($"Exception occured when parsing file:\n{ex.Message}", "Parsing Exception", MessageBoxButtons.OK, MessageBoxIcon.Error);
                Environment.Exit(1);
            }

            return(fileInfo);
        }