public void AddResult(IMtgaOutputLogPartResult r)
        {
            try
            {
                switch (r)
                {
                case IgnoredResult _:
                case UnknownResult _:
                    return;

                case ITagMatchResult _:
                    AddMatchResult(r);
                    break;

                case AuthenticateResponseResult authenticateResponse:
                {
                    MyScreenName = authenticateResponse.Raw.authenticateResponse.screenName;
                    if (currentMatch != null)
                    {
                        currentMatch.StartDateTime = authenticateResponse.LogDateTime;
                    }
                    break;
                }

                default:
                    AddResultLobby(r);
                    break;
                }
            }
            catch (Exception ex)
            {
                ProduceError(ex, false);
            }
        }
예제 #2
0
        public void OnFileSizeChangedNewText(object sender, string newText)
        {
            vm.SetProblem(ProblemsFlags.LogFileNotFound, false);
            vm.SizeOfLogToSend = fileMonitor.LogContentToSend.Length;

            ICollection <IMtgaOutputLogPartResult> messages = new IMtgaOutputLogPartResult[0];

            using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(newText ?? "")))
            {
                messages = reader.ProcessIntoMessages(true, "local", ms);
            }

            //if (messages.Count == 20) System.Diagnostics.Debugger.Break();

            Action GoHome = () =>
            {
                SetMainWindowContext(MainWindowContextEnum.Home);
            };

            var mustUpload = false;

            foreach (var msg in messages)
            {
                if (msg is IResultCardPool msgCardPool)
                {
                    var isDrafting = true;
                    if (msg is GetEventPlayerCourseV2Result playerCourse)
                    {
                        if (playerCourse.Raw.payload.CurrentEventState == "PreMatch")
                        {
                            // Clear the drafting window
                            SetCardsDraft(new DraftPickProgress(new int[0]));
                        }

                        isDrafting = playerCourse.Raw.payload.InternalEventName.Contains("Draft") || playerCourse.Raw.payload.InternalEventName.Contains("Sealed");
                    }

                    if (isDrafting)
                    {
                        // Refresh the drafting window to show whole card pool
                        SetCardsDraft(new DraftPickProgress(msgCardPool.CardPool));
                        SetMainWindowContext(MainWindowContextEnum.Drafting);
                    }
                }
                else if (msg is IResultDraftPick msgDraftPack && msgDraftPack.Raw.payload.draftPack != null)
                {
                    // Refresh the drafting window to show the new picks
                    var draftInfo = Mapper.Map <DraftPickProgress>(msgDraftPack.Raw.payload);
                    SetCardsDraft(draftInfo);
                }
예제 #3
0
        private void AddMatchResult(IMtgaOutputLogPartResult r)
        {
            //if (configApp.IsFeatureEnabled(ConfigAppFeatureEnum.ParseMatches) == false)
            //    return;

            if (r is MatchCreatedResult mc)
            {
                CreateMatch(mc);
            }
            //else if (r is DuelSceneGameStopResult gameStop)
            else if (r is GameStateMessageResult gsm && gsm.Raw.gameStateMessage?.gameInfo?.stage == "GameStage_GameOver")
            {
                var winningTeamId = gsm.Raw.gameStateMessage.gameInfo.results.Last().winningTeamId;
                UpdateGame(winningTeamId);
            }
예제 #4
0
 public void SaveResult(IMtgaOutputLogPartResult r)
 {
     // Not in a match
     if (r is IgnoredResult || r is UnknownResult)
     {
         var resultsList = r.GetType() == typeof(IgnoredResult) ? Ignored : Unknown;
         if (resultsList.ContainsKey(r.Prefix) == false)
         {
             resultsList.Add(r.Prefix, new List <IMtgaOutputLogPartResult>());
         }
         resultsList[r.Prefix].Add(r);
     }
     else
     {
         if (Results.ContainsKey(r.GetType()) == false)
         {
             Results.Add(r.GetType(), new List <IMtgaOutputLogPartResult>());
         }
         Results[r.GetType()].Add(r);
     }
 }
예제 #5
0
        public void AddResult(IMtgaOutputLogPartResult r)
        {
            //if (r.Part.Contains("Event.GetPlayerCoursesV2")) System.Diagnostics.Debugger.Break();

            try
            {
                inGameTracker.ProcessMessage(r);

                switch (r)
                {
                case IgnoredResult _:
                case UnknownResult _:
                    return;

                case ITagMatchResult _:
                    AddMatchResult(r);
                    break;

                case AuthenticateResponseResult authenticateResponse:
                {
                    MyScreenName = authenticateResponse.Raw.authenticateResponse.screenName;
                    if (currentMatch != null)
                    {
                        currentMatch.StartDateTime = authenticateResponse.LogDateTime;
                    }
                    break;
                }

                default:
                    AddResultLobby(r);
                    break;
                }
            }
            catch (Exception ex)
            {
                ProduceError(ex, false);
            }
        }
예제 #6
0
        public ICollection <IMtgaOutputLogPartResult> ParseJsonMulti(string json)
        {
            var raw = JsonConvert.DeserializeObject <GreMatchToClientMessageRoot>(json);

            if (raw.greToClientEvent != null)
            {
                return(ParseGreToClientEvent(raw.timestamp, raw.greToClientEvent));
            }

            else if (raw.matchGameRoomStateChangedEvent != null)
            {
                return(ParseMatchGameRoomStateChangedEvent(raw.timestamp, raw.matchGameRoomStateChangedEvent)
                       .Cast <IMtgaOutputLogPartResult>()
                       .ToArray());
            }

            else if (json.Contains("MatchServiceErrorCode_UnknownServerError"))
            {
                return new[] { new IgnoredMatchResult() }
            }
            ;

            //throw new Exception("Unknown GreMatchToClientMessageRoot");
            Log.Warning("{outputLogError}: {json}", "OUTPUTLOG Unknown GreMatchToClientMessageRoot", json);
            return(new[] { new UnknownMatchResult() });
        }

        ICollection <IMtgaOutputLogPartResult> ParseGreToClientEvent(long timestamp, GreMatchToClientEvent raw)
        {
            //if (timestamp == 636899006015817784)
            //    System.Diagnostics.Debugger.Break();

            //if (raw.greToClientMessages.Any(i => i.gameStateId == 128))
            //    System.Diagnostics.Debugger.Break();

            string matchId = null;
            var    results = new List <IMtgaOutputLogPartResult>();

            foreach (var submsg in raw.greToClientMessages)
            {
                IMtgaOutputLogPartResult result = null;

                string type    = submsg.type;
                var    subjson = JsonConvert.SerializeObject(submsg);

                if (converters.ContainsKey(type))
                {
                    //try
                    //{
                    result           = converters[type].ParseJson(subjson);
                    result.Timestamp = timestamp;
                    result.SubPart   = subjson;
                    //}
                    //catch (Exception ex)
                    //{
                    //    System.Diagnostics.Debugger.Break();
                    //}
                }
                else if (IgnoredTypes.Contains(type))
                {
                    result = new IgnoredMatchResult(timestamp)
                    {
                        SubPart = subjson
                    };
                }
                else
                {
                    result = new UnknownMatchResult(timestamp)
                    {
                        SubPart = subjson
                    };
                }

                if (string.IsNullOrEmpty(result.MatchId) == false)
                {
                    matchId = result.MatchId;
                }

                results.Add(result);
            }

            foreach (var r in results)
            {
                r.MatchId = matchId;
            }

            return(results);
        }

        ICollection <IMtgaOutputLogPartResult <MatchGameRoomStateChangedEvent> > ParseMatchGameRoomStateChangedEvent(long timestamp, MatchGameRoomStateChangedEvent raw)
        {
            return(new[] { new MatchGameRoomStateChangedEventResult {
                               MatchId = raw.gameRoomInfo.gameRoomConfig.matchId,
                               Raw = raw,
                               Timestamp = timestamp,
                           } });
        }
    }
예제 #7
0
        public void ProcessMessage(IMtgaOutputLogPartResult message)
        {
            State.IsReset = false;

            switch (message)
            {
            case MatchCreatedResult matchCreated:
                Reset();
                State.OpponentScreenName = matchCreated.Raw.payload.opponentScreenName;
                return;

            case MatchGameRoomStateChangedEventResult gameRoom:
            {
                var opponentInfo = gameRoom.Raw.gameRoomInfo.gameRoomConfig.reservedPlayers?
                                   .FirstOrDefault(i => i.playerName.StartsWith(State.OpponentScreenName));
                if (opponentInfo != null)
                {
                    State.SetSeatIds(State.OpponentSeatId == 1 ? 2 : 1, opponentInfo.systemSeatId);
                    if (opponentInfo.playerName.Contains("#"))
                    {
                        State.OpponentScreenName = opponentInfo.playerName;
                    }
                }

                return;
            }

            case ConnectRespResult connectResp:
                State.SetSeatIds(connectResp.Raw.systemSeatIds.First());

                // only happens at start of game 1
                State.SetLibraryGrpIds(connectResp.Raw.connectResp.deckMessage.deckCards);
                State.SetSideboardGrpIds(connectResp.Raw.connectResp.deckMessage.sideboardCards);
                return;

            case GameStateMessageResult gsm:
            {
                var gameStateMessage = gsm.Raw.gameStateMessage;
                if (gameStateMessage.type == "GameStateType_Full" && zonesInfo == null)
                {
                    // Initialization of the state (beginning of the match)
                    zonesInfo = gameStateMessage.zones.ToDictionary(z => z.zoneId, GetZoneAndOwnerFromGameStateZone);
                    // first gameStateMessage should not be processed as mulligan info will get messed up
                }
                else if (gameStateMessage.type == "GameStateType_Full" || gameStateMessage.type == "GameStateType_Diff")
                {
                    var ti = gameStateMessage.turnInfo;
                    if (ti != null)
                    {
                        Log.Debug("=== game message t{t} {p}.{s} (p{p}) ===",
                                  ti.turnNumber, ti.phase, ti.step, ti.decisionPlayer);
                    }

                    AnalyzeDiff(gameStateMessage);
                }
                else
                {
                    Log.Information("gameStateMessage with type {type} encountered", gameStateMessage.type);
                }

                return;
            }

            case SelectNReqResult nReq when(nReq.AllowCancel == AllowCancel.AllowCancel_No || nReq.AllowCancel == AllowCancel.AllowCancel_Continue) &&
                nReq.SeatId == State.MySeatId &&
                nReq.IdType == IdType.IdType_InstanceId:
            {
                Log.Information("option type: {OptionType}", nReq.OptionType);
                State.SetInstIdsAboutToMove(nReq.Ids);
                return;
            }

            case GroupReqResult grpReq when grpReq.AllowCancel == AllowCancel.AllowCancel_No &&
                grpReq.SeatId == State.MySeatId:
                State.SetInstIdsAboutToMove(grpReq.InstanceIds);
                return;

            //case DuelSceneSideboardingStartResult _:
            case ClientToMatchResult <PayloadEnterSideboardingReq> submitDeckResp:
                State.IsSideboarding = true;
                return;

            case ClientToMatchResult <PayloadSubmitDeckResp> submitDeckResp:
            {
                State.IsSideboarding = false;
                Reset(true);
                // only happens after side boarding in BO3 matches, we need deck info from here in that case.
                var deckSubmitted = submitDeckResp.Raw.payload.submitDeckResp.deck;
                State.SetLibraryGrpIds(deckSubmitted.deckCards.Select(Convert.ToInt32));
                State.SetSideboardGrpIds(deckSubmitted.sideboardCards.Select(Convert.ToInt32));
                return;
            }
            }
        }
예제 #8
0
        public void AddResult(IMtgaOutputLogPartResult r)
        {
            //if (r.MatchId == "c84b04f4-16da-4abe-9968-4b7866176847") Debugger.Break();

            try
            {
                if (r is IgnoredResult || r is IgnoredMatchResult || r is UnknownResult || r is UnknownMatchResult)
                {
                    return;
                }

                //else if (r is MtgaOutputLogPartResultBase<string> resultNoJson)
                //{
                //    if (resultNoJson.Raw.Contains("MatchCompleted -> Disconnected"))
                //    {
                //        EndCurrentMatch();
                //    }
                //}

                else if (r is ITagMatchResult)
                {
                    //if (configApp.IsFeatureEnabled(ConfigAppFeatureEnum.ParseMatches) == false)
                    //    return;

                    if (r is MatchCreatedResult mc)
                    {
                        CreateMatch(mc);
                    }
                    //else if (r is DuelSceneGameStopResult gameStop)
                    else if (r is GameStateMessageResult gsm && gsm.Raw.gameStateMessage?.gameInfo?.stage == "GameStage_GameOver")
                    {
                        var winningTeamId = gsm.Raw.gameStateMessage.gameInfo.results.First().winningTeamId;
                        UpdateGame(winningTeamId);
                    }
                    //else if (r is DuelSceneSideboardingStopResult)
                    else if (r is ClientToMatchResult <PayloadEnterSideboardingReq> )
                    {
                        EndCurrentGame();
                        //CreateGame()
                    }
                    else if (r is MatchGameRoomStateChangedEventResult roomChanged)
                    {
                        if (roomChanged.Raw.gameRoomInfo.gameRoomConfig.reservedPlayers != null)
                        {
                            var opponentInfo = roomChanged.Raw.gameRoomInfo.gameRoomConfig.reservedPlayers.First(i => i.playerName != MyScreenName);
                            lastOpponentSystemId      = opponentInfo.systemSeatId;
                            OpponentNameWithTagNumber = opponentInfo.playerName;
                            CreateGame(roomChanged.LogDateTime, opponentInfo.systemSeatId, null);
                            //currentGameProgress.DeckUsed.Name = currentMatch.DeckUsed.Name;
                        }

                        if (roomChanged.Raw.gameRoomInfo.finalMatchResult != null)
                        {
                            EndCurrentMatch(roomChanged.Raw.gameRoomInfo.finalMatchResult);
                        }
                    }
                    else if (r is IntermissionReqResult intermission)
                    {
                        if (intermission.Raw.intermissionReq.result.reason == "ResultReason_Concede")
                        {
                            //currentGameProgress.Outcome = (intermission.Raw.intermissionReq.result.winningTeamId == currentGameProgress.systemSeatId) ? GameOutcomeEnum.Victory : GameOutcomeEnum.Defeat;
                            //EndCurrentGame();

                            var c = new CardForTurn
                            {
                                CardGrpId = default(int),
                                Player    = intermission.Raw.intermissionReq.result.winningTeamId == currentGameProgress.systemSeatId ? PlayerEnum.Opponent : PlayerEnum.Me,
                                Turn      = currentGameProgress.CurrentTurn,
                                Action    = CardForTurnEnum.Conceded,
                            };
                            currentGameProgress.AddCardTransfer(c);
                        }
                        else if (intermission.Raw.intermissionReq.result.reason == "ResultReason_Game" &&
                                 intermission.Raw.intermissionReq.result.result == "ResultType_Draw")
                        {
                            currentGameProgress.Outcome = GameOutcomeEnum.Draw;
                        }
                    }
                    else
                    {
                        UpdateMatch(r);
                    }
                }
                else if (r is AuthenticateResponseResult authenticateResponse)
                {
                    MyScreenName = authenticateResponse.Raw.authenticateResponse.screenName;
                    if (currentMatch != null)
                    {
                        currentMatch.StartDateTime = authenticateResponse.LogDateTime;
                    }
                }
                else
                {
                    AddResultLobby(r);
                }
            }
 public MessageWithMatch(IMtgaOutputLogPartResult msg, string matchId)
 {
     Message = msg;
     MatchId = matchId;
 }
        public ICollection <IMtgaOutputLogPartResult> ParsePart(string part)
        {
            //if (part.Contains("==> Event.JoinPodmaking"))
            //    System.Diagnostics.Debugger.Break();

            //var test = ignored.Where(i => part.Contains(i)).ToArray();

            if (skipped.Any(i => part.Contains(i)))
            {
                return(null);
            }

            if (ignoredMatch.Any(i => part.Contains(i)))
            {
                return new[] { new IgnoredMatchResult() }
            }
            ;

            var isIgnoredResult =
                //part.Contains(UnityCrossThreadLogger_DuelSceneGameStop) == false &&
                //part.Contains(UnityCrossThreadLogger_DuelSceneSideboardingStart) == false &&
                //part.Contains(UnityCrossThreadLogger_DuelSceneSideboardingStop) == false &&
                //part.Contains(UnityCrossThreadLogger_ClientConnected) == false &&
                ((part.Contains("==>") &&
                  part.Contains("==> Log") == false &&
                  part.Contains("==> Event.JoinPodmaking") == false &&
                  part.Contains("==> Event.MatchCreated") == false &&
                  part.Contains("==> Inventory.Updated") == false &&
                  part.Contains("==> PostMatch.Update") == false &&
                  part.Contains("==> Rank.Updated") == false
                  ) || ignored.Any(i => part.Contains(i)));

            if (isIgnoredResult)
            {
                return(part.Contains("==>")
                    ? new[] { new IgnoredResultRequestToServer() }
                    : new[] { new IgnoredResult() });
            }

            var(converterKey, startIndex) = GetConverter(part);
            var reader = converters[converterKey];

            //if (part.Contains("Y2Q5IJ3TOVB63K5GQS6DJVJXZA to Match")) System.Diagnostics.Debugger.Break();

            if (reader.IsJson)
            {
                try
                {
                    var json = GetJson(part, startIndex);
                    ICollection <IMtgaOutputLogPartResult> ret = new IMtgaOutputLogPartResult[0];

                    if (reader is IReaderMtgaOutputLogJsonMulti readerMulti)
                    {
                        ret = readerMulti.ParseJsonMulti(json);
                    }
                    else if (reader is IReaderMtgaOutputLogJson readerSingle)
                    {
                        ret = new[] { readerSingle.ParseJson(json) }
                    }
                    ;

                    ret = ret
                          .Where(i => i.SubPart == null || skippedGRE.Any(x => i.SubPart.Contains(x)) == false)
                          .ToArray();

                    return(ret);

                    throw new InvalidOperationException("Converter not recognized");
                }
                catch (MtgaOutputLogInvalidJsonException ex)
                {
                    if (part.Contains("GetPlayerQuests") == false)
                    {
                        Log.Warning("JsonReader {jsonReader} could not find json in part: <<{part}>>", reader.GetType().ToString(), part);
                    }

                    return(new[] { new IgnoredResult() });
                }
                catch (Exception ex)
                {
                    var functioName = $"{reader.GetType()}.ParseJson";
                    //Log.Error(ex, "{outputLogError}: Error on {functioName} with json {json}", "OUTPUTLOG", functioName, json);
                    Log.Error(ex, "{outputLogError}: Error on {functioName} with json", "OUTPUTLOG", functioName);
                    return(new IMtgaOutputLogPartResult[0]);
                }
            }
            else
            {
                if (reader is StateChangedConverter)
                {
                    return new[] { new StateChangedResult {
                                       Raw = part
                                   } }
                }
                ;
                //else if (reader is ReaderIgnoredClientToMatch)
                //    return new[] { new IgnoredClientToMatchResult { Raw = part } };

                // Default
                return(new[] {
                    new MtgaOutputLogPartResultBase <string> {
                        Raw = part
                    }
                });
            }
        }

        (string converterKey, int startIndex) GetConverter(string part)
        {
            foreach (var converter in converters)
            {
                var startIndex = GetPartTypeIndex(part, converter.Key);
                if (startIndex >= 0)
                {
                    return(converter.Key, startIndex);
                }
            }

            throw new MtgaOutputLogUnknownMessageException(part);
        }
    }
}