Exemplo n.º 1
0
        /// <summary>Construct a trade from an existing position</summary>
        public Trade(Instrument instr, Position pos, EResult result = EResult.Open)
            : this(instr, pos.TradeType, pos.Label, pos.EntryPrice, pos.StopLoss, pos.TakeProfit, pos.Volume, comment : pos.Comment)
        {
            CAlgoId = pos.Id;
            Result  = result;

            EntryIndex = instr.IndexAt(pos.EntryTime) - instr.IdxFirst;
            ExitIndex  = instr.IndexAt(instr.Bot.UtcNow) - instr.IdxFirst;

            NetProfit   = pos.NetProfit;
            GrossProfit = pos.GrossProfit;

            // Buy at the bid price, then: loss = EP - ask, profit = ask - EP
            // Sell at the ask price, then: loss = bid - EP, profit = EP - bid
            MaxFavourableExcursion = 0.0;
            MaxAdverseExcursion    = 0.0;
            for (var i = (int)EntryIndex; i != (int)ExitIndex; ++i)
            {
                var hi = Instrument.Data.High[i];
                var lo = Instrument.Data.Low [i];
                if (Sign > 0)
                {
                    MaxAdverseExcursion    = Math.Max(MaxAdverseExcursion, EP - lo);
                    MaxFavourableExcursion = Math.Max(MaxFavourableExcursion, hi - EP);
                }
                else
                {
                    MaxAdverseExcursion    = Math.Max(MaxAdverseExcursion, hi - EP);
                    MaxFavourableExcursion = Math.Max(MaxFavourableExcursion, EP - lo);
                }
            }
        }
Exemplo n.º 2
0
 internal SetLobbyOwnerCallback(JobID jobId, uint appId, EResult res, SteamID lobbySteamId)
 {
     JobID        = jobId;
     AppID        = appId;
     Result       = res;
     LobbySteamID = lobbySteamId;
 }
Exemplo n.º 3
0
        private async Task UpdateCMStatus(Monitor monitor, EResult result, string lastAction)
        {
            var keyName = ServerRecordToString(monitor.Server);

            Log.WriteStatus($"> {keyName,40} | { monitor.Server.ProtocolTypes,10} | {result,20} | {lastAction}");

            if (monitor.LastReportedStatus == result)
            {
                return;
            }

            try
            {
                await using var db = await GetConnection();

                await db.ExecuteAsync(
                    "INSERT INTO `CMs` (`Address`, `IsWebSocket`, `Status`) VALUES(@IP, @IsWebSocket, @Status) ON DUPLICATE KEY UPDATE `Status` = VALUES(`Status`)",
                    new
                {
                    IP          = keyName,
                    IsWebSocket = (monitor.Server.ProtocolTypes & ProtocolTypes.WebSocket) > 0,
                    Status      = (int)result
                }
                    );

                monitor.LastReportedStatus = result;
            }
            catch (MySqlException e)
            {
                Log.WriteError($"Failed to update status of {keyName}: {e.Message}");
            }
        }
Exemplo n.º 4
0
    void OnCreateItemResult(CreateItemResult_t p, bool ioFailure)
    {
        bool ok = true;

        this.lastResult = p.m_eResult;

        if (ioFailure)
        {
            SetError("Create Item failed, IO Failure!");
            ok = false;
        }
        else if (p.m_eResult != EResult.k_EResultOK)
        {
            SetError("Create Item failed, error: " + p.m_eResult.ToString());
            ok = false;
        }
        else
        {
            this.needsToAcceptWorkshopLegalAgreement = p.m_bUserNeedsToAcceptWorkshopLegalAgreement;

            this.currentItem       = new WorkshopItem(p.m_nPublishedFileId);
            this.currentItem.title = "My new item";
        }

        if (OnCreateItemDone != null)
        {
            OnCreateItemDone(ok, p.m_nPublishedFileId);
        }

        SignalStateChanged();
    }
Exemplo n.º 5
0
    void OnSubmitItemResult(SubmitItemUpdateResult_t p, bool ioFailure)
    {
        bool ok = true;

        this.lastResult = p.m_eResult;

        this.isUpdatingItem = false;

        if (ioFailure)
        {
            SetError("Submit Item failed, IO Failure!");
            ok = false;
        }
        else if (p.m_eResult != EResult.k_EResultOK)
        {
            SetError("Submit Item failed, error: " + p.m_eResult.ToString());
            ok = false;
        }
        else
        {
            this.needsToAcceptWorkshopLegalAgreement = p.m_bUserNeedsToAcceptWorkshopLegalAgreement;
            Debug.Log("Item was successfully uploaded!");
        }

        if (OnSubmitItemDone != null)
        {
            OnSubmitItemDone(ok);
        }

        SignalStateChanged();
    }
    private void Update()
    {
        if (!Global.isSteamActive || !m_waitForResult)
        {
            return;
        }
        EResult resultStatus = SteamInventory.GetResultStatus(m_resultHandle);

        switch (resultStatus)
        {
        case EResult.k_EResultPending:
            return;

        case EResult.k_EResultOK:
        {
            uint punOutItemsArraySize = 0u;
            if (SteamInventory.GetResultItems(m_resultHandle, null, ref punOutItemsArraySize) && punOutItemsArraySize != 0)
            {
                SteamItemDetails_t[] array = new SteamItemDetails_t[punOutItemsArraySize];
                SteamInventory.GetResultItems(m_resultHandle, array, ref punOutItemsArraySize);
                m_itemDetails.AddRange(array);
            }
            EquipSteamInventoryItems();
            break;
        }

        default:
            Debug.Log("SteamInventoryHandler.cs: Couldn't get inventory: " + resultStatus);
            break;
        }
        SteamInventory.DestroyResult(m_resultHandle);
        m_waitForResult = false;
    }
Exemplo n.º 7
0
 internal CreateLobbyCallback(JobID jobId, uint appId, EResult res, SteamID lobbySteamId)
 {
     JobID        = jobId;
     AppID        = appId;
     Result       = res;
     LobbySteamID = lobbySteamId;
 }
Exemplo n.º 8
0
            internal PurchaseResponseCallback(JobID jobID, CMsgClientPurchaseResponse msg)
            {
                JobID = jobID;

                if (msg == null)
                {
                    return;
                }

                Result         = (EResult)msg.eresult;
                PurchaseResult = (EPurchaseResult)msg.purchase_result_details;

                ReceiptInfo = new KeyValue();
                using (MemoryStream ms = new MemoryStream(msg.purchase_receipt_info)) {
                    if (!ReceiptInfo.TryReadAsBinary(ms))
                    {
                        return;
                    }

                    List <KeyValue> lineItems = ReceiptInfo["lineitems"].Children;
                    Items = new Dictionary <uint, string>(lineItems.Count);

                    foreach (KeyValue lineItem in lineItems)
                    {
                        uint   appID    = (uint)lineItem["PackageID"].AsUnsignedLong();
                        string gameName = lineItem["ItemDescription"].AsString();
                        gameName = WebUtility.UrlDecode(gameName);                         // Apparently steam expects client to decode sent HTML
                        Items.Add(appID, gameName);
                    }
                }
            }
Exemplo n.º 9
0
        public Steam(Action <bool> OnLogOn, Action <EPurchaseResultDetail, string> OnKeyRedeem)
        {
            this.onLogOn     = OnLogOn;
            this.onKeyRedeem = OnKeyRedeem;

            if (File.Exists("auth.json"))
            {
                Program.Context.Log("Using saved auth details.");

                logOnDetails = JsonConvert.DeserializeObject <SteamUser.LogOnDetails>(File.ReadAllText("auth.json"));
            }

            if (logOnDetails.Username != null && (logOnDetails.Password != null || logOnDetails.LoginKey != null))
            {
                EResult logInResult = AttemptLogIn();

                if (logInResult == EResult.OK)
                {
                    loggedOn = true;
                    OnLogOn(true);
                    return;
                }
                else
                {
                    Console.WriteLine(logInResult);
                }
            }

            previousResult = EResult.OK;

            askForm = new GetLogonDetails(HandleFormResponse);
            askForm.Show();
        }
Exemplo n.º 10
0
 public void ConfirmResult(EResult mEResult)
 {
     if (mEResult != EResult.k_EResultOK)
     {
         throw new FailedOperationException("Failed with result " + mEResult, mEResult);
     }
 }
Exemplo n.º 11
0
 public ModUpdateResult(ModDownloadStatus status, Mod mod, EResult result)
 {
     Status = status;
     Mod    = mod ?? throw new ArgumentNullException("mod");
     Result = result;
     Title  = mod.label.title;
 }
Exemplo n.º 12
0
 static bool Prefix(ZSteamSocket __instance, Queue <byte[]> ___m_sendQueue, ref int ___m_totalSent, HSteamNetConnection ___m_con)
 {
     if (!__instance.IsConnected())
     {
         return(false);
     }
     while (___m_sendQueue.Count > 0)
     {
         byte[] source = ___m_sendQueue.Peek();
         IntPtr num    = Marshal.AllocHGlobal(source.Length);
         Marshal.Copy(source, 0, num, source.Length);
         // This was k_nSteamNetworkingSend_ReliableNoNagle before
         EResult connection = SteamNetworkingSockets.SendMessageToConnection(___m_con, num, (uint)source.Length, Constants.k_nSteamNetworkingSend_Reliable, out long _);
         Marshal.FreeHGlobal(num);
         if (connection == EResult.k_EResultOK)
         {
             ___m_totalSent += source.Length;
             ___m_sendQueue.Dequeue();
         }
         else
         {
             ZLog.Log("Failed to send data " + connection);
             break;
         }
     }
     return(false);
 }
Exemplo n.º 13
0
 private void Update()
 {
     if (Global.isSteamActive && this.m_waitForResult)
     {
         EResult resultStatus = SteamInventory.GetResultStatus(this.m_resultHandle);
         if (resultStatus != EResult.k_EResultPending)
         {
             if (resultStatus == EResult.k_EResultOK)
             {
                 uint num = 0U;
                 if (SteamInventory.GetResultItems(this.m_resultHandle, null, ref num) && num > 0U)
                 {
                     SteamItemDetails_t[] array = new SteamItemDetails_t[num];
                     SteamInventory.GetResultItems(this.m_resultHandle, array, ref num);
                     this.m_itemDetails.AddRange(array);
                 }
                 this.EquipSteamInventoryItems();
             }
             else
             {
                 Debug.Log("SteamInventoryHandler.cs: Couldn't get inventory: " + resultStatus.ToString());
             }
             SteamInventory.DestroyResult(this.m_resultHandle);
             this.m_waitForResult = false;
         }
     }
 }
Exemplo n.º 14
0
        private void HandleCreateLobbyResponse(IPacketMsg packetMsg)
        {
            var createResponse = new ClientMsgProtobuf <CMsgClientMMSCreateLobbyResponse>(packetMsg);

            EResult result = (EResult)createResponse.Body.eresult;

            if (result == EResult.OK)
            {
                ulong lobbyId = createResponse.Body.steam_id_lobby;
                CSGOClient.lobbyId = lobbyId;

                SetLobbyData(0, 1, 1, 1);
                SetLobbyData(0, 1, 2, 0);
                SetLobbyData(0, 1, 2, 0);
                SetLobbyOwner(CSGOClient.steamId);
                SetLobbyData(0, 10, 2, 0);
                SetLobbyData(0, 10, 2, 0);
                SetLobbyData(0, 10, 2, 0);

                RegisterLobbyParty();
                CSGOClient.UpdateRichPresence();
                //ClientGamesPlayedWithDataBlob(3);

                string log = string.Format("Lobby created with lobbyId : {0}", lobbyId);

                form.ToggleLobby(true);
                form.AddMessage(log);
                form.AddLog(log);
            }
        }
Exemplo n.º 15
0
        PsScript(PsScriptMgr mgr)
        {
            mMgr    = mgr;
            mVarMgr = new VariableMgr();

            Result = EResult.Max;
        }
    // CALLBACKS

    private void OnUserStatsReceived(UserStatsReceived_t i_CallbackParams)
    {
        if (m_AchievementsManager == null)
        {
            return;
        }

        if (i_CallbackParams.m_nGameID == ((ulong)m_GameId))
        {
            EResult callbackResult = i_CallbackParams.m_eResult;
            if (callbackResult == EResult.k_EResultOK)
            {
                for (int achievementIndex = 0; achievementIndex < m_AchievementsManager.achievementsCount; ++achievementIndex)
                {
                    Achievement achievement = m_AchievementsManager.GetAchievementByIndex(achievementIndex);
                    if (achievement != null)
                    {
                        string achievementSteamId = achievement.steamId;
                        bool   achieved           = false;
                        if (SteamUserStats.GetAchievement(achievementSteamId, out achieved))
                        {
                            achievement.SetAchieved(achieved);
                        }
                    }
                }
            }
        }
    }
Exemplo n.º 17
0
        IEnumerator CoWaitForKeys(EResult accept, EResult cancel)
        {
            while (true)
            {
                if (defaultAcceptValid && (InputManager.GetKeyState(InputKey.Return).down ||
                                           InputManager.GetKeyState(InputKey.KeypadEnter).down))
                {
                    InputManager.FlushKeyState(InputKey.Return);
                    InputManager.FlushKeyState(InputKey.KeypadEnter);
                    if (Close(accept))
                    {
                        break;
                    }
                }
                if (InputManager.GetKeyState(InputKey.Escape).down)
                {
                    if (Close(cancel))
                    {
                        break;
                    }
                }

                yield return(null);
            }
        }
Exemplo n.º 18
0
        private void OnUploadLeaderboardScoreCallCompleted(string p_leaderboardName, int p_score, LeaderboardScoreUploaded_t p_callback, bool p_bIOFailure)
        {
            EResult callResultType = p_callback.m_bSuccess == 1 ? EResult.k_EResultOK : EResult.k_EResultUnexpectedError;

            if (CheckAndLogResult <LeaderboardScoreUploaded_t, LeaderboardsUploadedScoreEventArgs>("OnUploadLeaderboardScoreCallCompleted", callResultType, p_bIOFailure, GetEventNameForOnUploadedScore(p_leaderboardName, p_score), ref OnUploadedScore))
            {
                // inform listeners
                if (OnUploadedScore != null)
                {
                    ELeaderboardDisplayType scoreType = SteamUserStats.GetLeaderboardDisplayType(p_callback.m_hSteamLeaderboard);
                    InvokeEventHandlerSafely(OnUploadedScore, new LeaderboardsUploadedScoreEventArgs()
                    {
                        LeaderboardName    = p_leaderboardName,
                        Score              = p_callback.m_nScore,
                        ScoreString        = FormatScore(p_callback.m_nScore, scoreType),
                        ScoreType          = scoreType,
                        IsScoreChanged     = p_callback.m_bScoreChanged == 1,
                        GlobalRankNew      = p_callback.m_nGlobalRankNew,
                        GlobalRankPrevious = p_callback.m_nGlobalRankPrevious,
                        SteamNative        = new LeaderboardsUploadedScoreEventArgs.SteamNativeData(p_callback.m_hSteamLeaderboard)
                    });
                    ClearSingleShotEventHandlers(GetEventNameForOnUploadedScore(p_leaderboardName, p_score), ref OnUploadedScore);
                }
            }
        }
Exemplo n.º 19
0
        private void OnUploadScoreFindOrCreateLeaderboardCallCompleted(string p_leaderboardName, int p_score, ELeaderboardSortMethod p_scoreSorting, ELeaderboardDisplayType p_scoreType, int[] p_scoreDetails, LeaderboardFindResult_t p_callbackFind, bool p_bIOFailureFind)
        {
            EResult callResultType = p_callbackFind.m_bLeaderboardFound == 1 ? EResult.k_EResultOK : EResult.k_EResultFileNotFound;

            if (CheckAndLogResult <LeaderboardFindResult_t, LeaderboardsUploadedScoreEventArgs>("OnUploadScoreFindOrCreateLeaderboardCallCompleted", callResultType, p_bIOFailureFind, GetEventNameForOnUploadedScore(p_leaderboardName, p_score), ref OnUploadedScore))
            {
                // compare sort and type -> warning on mismatch
                ELeaderboardSortMethod sorting = SteamUserStats.GetLeaderboardSortMethod(p_callbackFind.m_hSteamLeaderboard);
                if (sorting != p_scoreSorting)
                {
                    Debug.LogWarning("UploadScore: sorting mismatch for leaderboard '" + p_leaderboardName + "' sort mode on Steam is '" + sorting + "', expected '" + p_scoreSorting + "'!");
                }
                ELeaderboardDisplayType type = SteamUserStats.GetLeaderboardDisplayType(p_callbackFind.m_hSteamLeaderboard);
                if (type != p_scoreType)
                {
                    Debug.LogWarning("UploadScore: type mismatch for leaderboard '" + p_leaderboardName + "' type on Steam is '" + type + "', expected '" + p_scoreType + "'!");
                }
                // upload score
                if (p_scoreDetails == null)
                {
                    p_scoreDetails = new int[0];
                }
                Execute <LeaderboardScoreUploaded_t>(SteamUserStats.UploadLeaderboardScore(p_callbackFind.m_hSteamLeaderboard, m_scoreUploadMethod, p_score, p_scoreDetails, Mathf.Min(64, p_scoreDetails.Length)), (p_callbackUpload, p_bIOFailureUpload) => OnUploadLeaderboardScoreCallCompleted(p_leaderboardName, p_score, p_callbackUpload, p_bIOFailureUpload));
                if (IsDebugLogEnabled)
                {
                    Debug.Log("UploadScore: leaderboard '" + p_leaderboardName + "' found, starting score upload");
                }
            }
        }
Exemplo n.º 20
0
 internal GetLobbyListCallback(JobID jobId, uint appId, EResult res, List <Lobby> lobbies)
 {
     JobID   = jobId;
     AppID   = appId;
     Result  = res;
     Lobbies = lobbies;
 }
        internal PurchaseResponseCallback(JobID jobID, CMsgClientPurchaseResponse msg)
        {
            JobID = jobID;
            PurchaseResultDetail = (EPurchaseResultDetail)msg.purchase_result_details;
            Result = (EResult)msg.eresult;

            if (msg.purchase_receipt_info == null)
            {
                return;
            }

            var receiptInfo = new KeyValue();

            using (var ms = new MemoryStream(msg.purchase_receipt_info))
            {
                if (!receiptInfo.TryReadAsBinary(ms))
                {
                    return;
                }
            }

            var lineItems = receiptInfo["lineitems"].Children;

            foreach (var lineItem in lineItems)
            {
                var packageID = lineItem["PackageID"].AsUnsignedInteger();
                var name      = lineItem["ItemDescription"].Value;

                if (packageID > 0)
                {
                    Packages.Add(packageID, name);
                }
            }
        }
        public static EResult TryRead(String accName, out MAccountFile?accFile)
        {
            EResult err = EResult.NO_ERROR;

            accFile = null;

            try
            {
                byte[] rawAcc = File.ReadAllBytes(String.Format("{0}/{1}/{2}.bin",
                                                                PersistencyBasics.DB_ROOT_PATH, accName.Substring(0, 1).ToUpper(), accName.ToUpper()));

                accFile = W2Marshal.GetStructure <MAccountFile>(rawAcc);
            }
            catch (FileNotFoundException)
            {
                err = EResult.ACC_NOT_FOUND;
            }
            catch (DirectoryNotFoundException)
            {
                err = EResult.ACC_NOT_FOUND;
            }
            catch (Exception)
            {
                err = EResult.UNKNOWN;
            }

            return(err);
        }
Exemplo n.º 23
0
        private void ItemUpdated(EResult Result)
        {
            bIsUploadInProgress = false;
            ulong bytesProcessed;
            ulong bytesTotal;

            CSteamInterface.GetUpdateItemProgress(out bytesProcessed, out bytesTotal);
            if (bytesTotal != 0)
            {
                workshopTextBox1.PrintLineAtLineStart(string.Format("  Uploaded {0:n0} of {1:n0} bytes", bytesProcessed, bytesTotal));
            }
            workshopTextBox1.PrintNewLine();
            if (Result == EResult.k_EResultOK)
            {
                workshopTextBox1.PrintLine("  Workshop item updated.");
            }
            else
            {
                workshopTextBox1.PrintLine(string.Format("  Steam error updating item: Error code = {0}", Result));
            }
            workshopTextBox1.PrintNewLine();
            if (!bDontDeleteTempFiles)
            {
                CConfig.DeleteDirectory(TempFolder);
            }
            workshopTextBox1.PrintPrompt();
        }
Exemplo n.º 24
0
        /// <summary>
        /// Load a Cry Binary XML buffer into memory and return the NodeRef for the root element
        /// </summary>
        /// <param name="filename">The byte buffer to read</param>
        /// <param name="result">Read result</param>
        /// <returns>The NodeRef of the root element or NULL</returns>
        public CryXmlNodeRef LoadFromBuffer(byte[] binBuffer, out EResult result)
        {
            m_errorDescription = "";
            result             = EResult.Error;

            UInt32 fileSize = ( UInt32 )binBuffer.Length;

            try {
                if (fileSize < CryXMLHeader.MySize( ))
                {
                    result = EResult.NotBinXml;
                    SetErrorDescription("File is not a binary XML file (file size is too small).");
                    return(null);
                }

                // read from binary file and map the content into the memory
                CryXmlBinContext pData = Create(binBuffer, out result);

                if (result != EResult.Success)
                {
                    return(null);                     // Well...
                }
                // Return first node
                CryXmlNodeRef n = pData.pBinaryNodes[0];
                return(n);
            } catch {
                result = EResult.NotBinXml;
                SetErrorDescription("Exception in buffer reader");
                return(null);
            }
        }
Exemplo n.º 25
0
        private async Task UpdateCMStatus(Monitor monitor, EResult result, string lastAction)
        {
            var keyName = ServerRecordToString(monitor.Server);

            Log.WriteInfo("CM", "{0,40} | {1,10} | {2,20} | {3}", keyName, monitor.Server.ProtocolTypes, result, lastAction);

            try
            {
                using var db = await GetConnection();

                await db.ExecuteAsync(
                    "INSERT INTO `CMs` (`Address`, `IsWebSocket`, `Status`, `LastAction`) VALUES(@IP, @IsWebSocket, @Status, @LastAction) ON DUPLICATE KEY UPDATE `Status` = VALUES(`Status`), `LastAction` = VALUES(`LastAction`)",
                    new
                {
                    IP          = keyName,
                    IsWebSocket = (monitor.Server.ProtocolTypes & ProtocolTypes.WebSocket) > 0,
                    Status      = result.ToString(),
                    LastAction  = lastAction
                }
                    );
            }
            catch (MySqlException e)
            {
                Log.WriteError("UpdateCM", "Failed to update status of {0}: {1}", keyName, e.Message);
            }
        }
Exemplo n.º 26
0
        public void RequireStop(EResult eResult)
        {
            Result = eResult;
            mTriggerGroup.RequireStop();

            Debug.Log(this + " require stop.");
            InternalEvent.Instance.EmitScriptEnd(this);
        }
Exemplo n.º 27
0
 static void OnLoggedOff(SteamUser.LoggedOffCallback callback)
 {
     LastLogOnResult     = callback.Result;
     IsLoggedIn          = false;
     CurrentPersonaState = 0;
     Console.WriteLine("[" + Program.BOTNAME + "] - Logged off of Steam: {0}", callback.Result);
     InfoForm.InfoHelper.CustomMessageBox.Show("Error", "Logged off of Steam:" + callback.Result);
 }
Exemplo n.º 28
0
            internal ServiceMethodResponse(JobID jobID, EResult result, CMsgClientServiceMethodLegacyResponse resp)
            {
                JobID = jobID;

                Result      = result;
                ResponseRaw = resp.serialized_method_response;
                MethodName  = resp.method_name ?? string.Empty;
            }
Exemplo n.º 29
0
 /// <summary>
 /// Creates an exception out of a Steam Result.
 /// </summary>
 /// <param name="result">the error code of the error.</param>
 /// <returns>an exception representing the error, null if no error.</returns>
 public static Exception ThrowIfError(EResult result)
 {
     if (result == EResult.k_EResultOK)
     {
         return(null);
     }
     throw new Exception($"Steam Error: {result}");
 }
Exemplo n.º 30
0
 /// <summary>
 /// Creates error logs for a given error code.
 /// Does nothing if there is no error.
 /// </summary>
 /// <param name="result">the error code of the error.</param>
 public static void LogIfError(EResult result)
 {
     if (result == EResult.k_EResultOK)
     {
         return;
     }
     Debug.LogError($"Steam Error: {result}");
 }
Exemplo n.º 31
0
			internal ParseTradeResult(ulong tradeID, EResult result) {
				if ((tradeID == 0) || (result == EResult.Unknown)) {
					throw new ArgumentNullException(nameof(tradeID) + " || " + nameof(result));
				}

				TradeID = tradeID;
				Result = result;
			}
Exemplo n.º 32
0
            internal LoggedOnCallback( JobID jobID, EResult result )
            {
                JobID = jobID;

                Result = result;
            }
Exemplo n.º 33
0
 internal ConnectedCallback( EResult result )
 {
     this.Result = result;
 }
Exemplo n.º 34
0
            internal LoggedOffCallback( CMsgClientLoggedOff resp )
#endif
            {
                this.Result = ( EResult )resp.eresult;
            }
Exemplo n.º 35
0
 // generally we don't want user code to instantiate callback objects,
 // but rather only let handlers create them
 internal MyCallback( EResult res )
 {
     Result = res;
 }
Exemplo n.º 36
0
            internal IgnoreFriendCallback( JobID jobID, MsgClientSetIgnoreFriendResponse response )
            {
                this.JobID = jobID;

                this.Result = response.Result;
            }
Exemplo n.º 37
0
 public UGCJobResult( JobID id, EResult result )
 {
     this.ID = id;
     this.Result = result;
 }
Exemplo n.º 38
0
		public MsgClientOGSEndSessionResponse()
		{
			Result = 0;
		}
Exemplo n.º 39
0
		public static extern bool ISteamUnifiedMessages_GetMethodResponseInfo(ClientUnifiedMessageHandle hHandle, out uint punResponseSize, out EResult peResult);
		/// <summary>
		/// <para> Gets the size of the response and the EResult. Returns false if the response is not ready yet.</para>
		/// </summary>
		public static bool GetMethodResponseInfo(ClientUnifiedMessageHandle hHandle, out uint punResponseSize, out EResult peResult) {
			InteropHelp.TestIfAvailableClient();
			return NativeMethods.ISteamUnifiedMessages_GetMethodResponseInfo(hHandle, out punResponseSize, out peResult);
		}
Exemplo n.º 41
0
 internal LoggedOnCallback( CMsgClientUFSLoginResponse body )
 {
     Result = ( EResult )body.eresult;
 }
Exemplo n.º 42
0
			internal PurchaseResponseCallback(JobID jobID, CMsgClientPurchaseResponse msg) {
				JobID = jobID;

				if (msg == null) {
					return;
				}

				Result = (EResult) msg.eresult;
				PurchaseResult = (EPurchaseResult) msg.purchase_result_details;

				if (msg.purchase_receipt_info == null) {
					return;
				}

				ReceiptInfo = new KeyValue();
				using (MemoryStream ms = new MemoryStream(msg.purchase_receipt_info)) {
					if (!ReceiptInfo.TryReadAsBinary(ms)) {
						return;
					}

					List<KeyValue> lineItems = ReceiptInfo["lineitems"].Children;
					Items = new Dictionary<uint, string>(lineItems.Count);

					foreach (KeyValue lineItem in lineItems) {
						uint appID = (uint) lineItem["PackageID"].AsUnsignedLong();
						string gameName = lineItem["ItemDescription"].AsString();
						gameName = WebUtility.UrlDecode(gameName); // Apparently steam expects client to decode sent HTML
						Items.Add(appID, gameName);
					}
				}
			}
Exemplo n.º 43
0
 internal SendGuestPassCallback( MsgClientSendGuestPassResponse msg )
 {
     Result = msg.Result;
 }
Exemplo n.º 44
0
 internal IgnoreFriendCallback( MsgClientSetIgnoreFriendResponse response )
 {
     this.Result = response.Result;
 }
Exemplo n.º 45
0
            internal LoggedOnCallback( JobID jobID, CMsgClientUFSLoginResponse body )
            {
                JobID = jobID;

                Result = ( EResult )body.eresult;
            }
Exemplo n.º 46
0
		public MsgClientSetIgnoreFriendResponse()
		{
			Unknown = 0;
			Result = 0;
		}
Exemplo n.º 47
0
        public async void NotifyCMOffline( Monitor monitor, EResult result = EResult.Invalid )
        {
            string keyName = monitor.Server.ToString();

            ServerInfo serverInfo = ServerInfo.DeserializeFromBytes( await redis.Hashes.Get( 10, "steamstatus:servers", keyName ) );

            serverInfo.IsOnline = false;

            if ( result != EResult.Invalid )
            {
                serverInfo.Result = result.ToString();
            }

            var task = redis.Hashes.Set( 10, "steamstatus:servers", keyName, serverInfo.SerializeToBytes() );
        }
Exemplo n.º 48
0
		public MsgClientSendGuestPassResponse()
		{
			Result = 0;
		}
 private void buttonOverwrite_Click(object sender, RoutedEventArgs e)
 {
     Result = EResult.Overwrite;
     Close();
 }
Exemplo n.º 50
0
		public MsgClientGenericResponse()
		{
			Result = 0;
		}
Exemplo n.º 51
0
 internal LoggedOffCallback( EResult result )
 {
     this.Result = result;
 }
Exemplo n.º 52
0
		public MsgChannelEncryptResult()
		{
			Result = EResult.Invalid;
		}
Exemplo n.º 53
0
 internal LoggedOnCallback( EResult result )
 {
     Result = result;
 }
Exemplo n.º 54
0
		public void Deserialize( Stream stream )
		{
			BinaryReader br = new BinaryReader( stream );

			Result = (EResult)br.ReadInt32();
		}
Exemplo n.º 55
0
 internal LoggedOffCallback( SteamClient client, EResult result )
     : base( client )
Exemplo n.º 56
0
		private async void OnDisconnected(SteamClient.DisconnectedCallback callback) {
			if (callback == null) {
				Logging.LogNullError(nameof(callback), BotName);
				return;
			}

			EResult lastLogOnResult = LastLogOnResult;
			LastLogOnResult = EResult.Invalid;

			Logging.LogGenericInfo("Disconnected from Steam!", BotName);

			ArchiWebHandler.OnDisconnected();
			CardsFarmer.OnDisconnected();
			Trading.OnDisconnected();

			FirstTradeSent = false;
			HandledGifts.ClearAndTrim();

			// If we initiated disconnect, do not attempt to reconnect
			if (callback.UserInitiated) {
				return;
			}

			switch (lastLogOnResult) {
				case EResult.Invalid:
					// Invalid means that we didn't get OnLoggedOn() in the first place, so Steam is down
					// Always reset one-time-only access tokens in this case, as OnLoggedOn() didn't do that for us
					AuthCode = TwoFactorCode = null;
					break;
				case EResult.InvalidPassword:
					// If we didn't use login key, it's nearly always rate limiting
					if (string.IsNullOrEmpty(BotDatabase.LoginKey)) {
						goto case EResult.RateLimitExceeded;
					}

					BotDatabase.LoginKey = null;
					Logging.LogGenericInfo("Removed expired login key", BotName);
					break;
				case EResult.NoConnection:
				case EResult.ServiceUnavailable:
				case EResult.Timeout:
				case EResult.TryAnotherCM:
					await Task.Delay(5000).ConfigureAwait(false);
					break;
				case EResult.RateLimitExceeded:
					Logging.LogGenericInfo("Will retry after 25 minutes...", BotName);
					await Task.Delay(25 * 60 * 1000).ConfigureAwait(false); // Captcha disappears after around 20 minutes, so we make it 25
					break;
			}

			if (!KeepRunning || SteamClient.IsConnected) {
				return;
			}

			Logging.LogGenericInfo("Reconnecting...", BotName);
			await Connect().ConfigureAwait(false);
		}
Exemplo n.º 57
0
		private async void OnLoggedOn(SteamUser.LoggedOnCallback callback) {
			if (callback == null) {
				Logging.LogNullError(nameof(callback), BotName);
				return;
			}

			// Always reset one-time-only access tokens
			AuthCode = TwoFactorCode = null;

			// Keep LastLogOnResult for OnDisconnected()
			LastLogOnResult = callback.Result;

			switch (callback.Result) {
				case EResult.AccountLogonDenied:
					AuthCode = Program.GetUserInput(SharedInfo.EUserInputType.SteamGuard, BotName);
					if (string.IsNullOrEmpty(AuthCode)) {
						Stop();
					}

					break;
				case EResult.AccountLoginDeniedNeedTwoFactor:
					if (BotDatabase.MobileAuthenticator == null) {
						TwoFactorCode = Program.GetUserInput(SharedInfo.EUserInputType.TwoFactorAuthentication, BotName);
						if (string.IsNullOrEmpty(TwoFactorCode)) {
							Stop();
						}
					} else {
						Logging.LogGenericWarning("2FA code was invalid despite of using ASF 2FA. Invalid authenticator or bad timing?", BotName);
					}

					break;
				case EResult.OK:
					Logging.LogGenericInfo("Successfully logged on!", BotName);

					// Old status for these doesn't matter, we'll be notified in callback if needed
					LibraryLockedBySteamID = 0;
					PlayingBlocked = false;

					if ((callback.CellID != 0) && (Program.GlobalDatabase.CellID != callback.CellID)) {
						Program.GlobalDatabase.CellID = callback.CellID;
					}

					if (BotDatabase.MobileAuthenticator == null) {
						// Support and convert SDA files
						string maFilePath = Path.Combine(SharedInfo.ConfigDirectory, callback.ClientSteamID.ConvertToUInt64() + ".maFile");
						if (File.Exists(maFilePath)) {
							ImportAuthenticator(maFilePath);
						}
					}

					if (string.IsNullOrEmpty(BotConfig.SteamParentalPIN)) {
						BotConfig.SteamParentalPIN = Program.GetUserInput(SharedInfo.EUserInputType.SteamParentalPIN, BotName);
						if (string.IsNullOrEmpty(BotConfig.SteamParentalPIN)) {
							Stop();
							return;
						}
					}

					if (!await ArchiWebHandler.Init(callback.ClientSteamID, SteamClient.ConnectedUniverse, callback.WebAPIUserNonce, BotConfig.SteamParentalPIN).ConfigureAwait(false)) {
						if (!await RefreshSession().ConfigureAwait(false)) {
							return;
						}
					}

					InitializeFamilySharing().Forget();

					if (BotConfig.DismissInventoryNotifications) {
						ArchiWebHandler.MarkInventory().Forget();
					}

					if (BotConfig.SteamMasterClanID != 0) {
						Task.Run(async () => {
							await ArchiWebHandler.JoinGroup(BotConfig.SteamMasterClanID).ConfigureAwait(false);
							JoinMasterChat();
						}).Forget();
					}
					await ArchiWebHandler.SetAvatar().ConfigureAwait(false);
					if (Program.GlobalConfig.Statistics) {
						ArchiWebHandler.JoinGroup(BotConfig.SteamMasterClanID).Forget();
					}

					Trading.CheckTrades().Forget();
					break;
				case EResult.InvalidPassword:
				case EResult.NoConnection:
				case EResult.RateLimitExceeded:
				case EResult.ServiceUnavailable:
				case EResult.Timeout:
				case EResult.TryAnotherCM:
				case EResult.TwoFactorCodeMismatch:
					Logging.LogGenericWarning("Unable to login to Steam: " + callback.Result + " / " + callback.ExtendedResult, BotName);
					break;
				default: // Unexpected result, shutdown immediately
					Logging.LogGenericError("Unable to login to Steam: " + callback.Result + " / " + callback.ExtendedResult, BotName);
					Stop();
					break;
			}
		}
Exemplo n.º 58
0
			internal RedeemGuestPassResponseCallback(JobID jobID, CMsgClientRedeemGuestPassResponse msg) {
				if ((jobID == null) || (msg == null)) {
					throw new ArgumentNullException(nameof(jobID) + " || " + nameof(msg));
				}

				JobID = jobID;
				Result = (EResult) msg.eresult;
			}