Esempio n. 1
0
        /// <summary>
        /// A result is a reply to a specific command
        /// </summary>
        private static void ProcessResult(CallbackMsg_t msg)
        {
            var result = msg.Data.ToType <SteamAPICallCompleted_t>();

            //
            // Do we have an entry added via OnCallComplete
            //
            if (!ResultCallbacks.TryGetValue(result.AsyncCall, out var callbackInfo))
            {
                //
                // This can happen if the callback result was immediately available
                // so we just returned that without actually going through the callback
                // dance. It's okay for this to fail.
                //

                //
                // But still let everyone know that this happened..
                //
                OnDebugCallback?.Invoke((CallbackType)result.Callback, $"[no callback waiting/required]", false);
                return;
            }

            // Remove it before we do anything, incase the continuation throws exceptions
            ResultCallbacks.Remove(result.AsyncCall);

            // At this point whatever async routine called this
            // continues running.
            callbackInfo.continuation();
        }
Esempio n. 2
0
        /// <summary>
        /// A callback is a general global message
        /// </summary>
        private static void ProcessCallback(CallbackMsg_t msg, bool isServer)
        {
            OnDebugCallback?.Invoke(msg.Type, CallbackToString(msg.Type, msg.Data, msg.DataSize), isServer);

            // Is this a special callback telling us that the call result is ready?
            if (msg.Type == CallbackType.SteamAPICallCompleted)
            {
                ProcessResult(msg);
                return;
            }

            if (Callbacks.TryGetValue(msg.Type, out var list))
            {
                actionsToCall.Clear();

                foreach (var item in list)
                {
                    if (item.server != isServer)
                    {
                        continue;
                    }

                    actionsToCall.Add(item.action);
                }

                foreach (var action in actionsToCall)
                {
                    action(msg.Data);
                }

                actionsToCall.Clear();
            }
        }
Esempio n. 3
0
        void UnhandledCallback(CallbackMsg_t msg)
        {
            txtCallbacks.Invoke((MethodInvoker) delegate
            {
                int iCall          = (msg.m_iCallback / 100) * 100;
                ECallbackType type = ( ECallbackType )iCall;

                txtCallbacks.AppendText("Unhandled callback: " + msg.m_iCallback + " Type: " + type + " Size: " + msg.m_cubParam + Environment.NewLine);

                txtCallbacks.ScrollToCaret();
            });
        }
Esempio n. 4
0
        /// <summary>
        /// Gets the last callback in steamclient's callback queue.
        /// </summary>
        /// <param name="pipe">The steam pipe.</param>
        /// <param name="message">A reference to a callback object to copy the callback to.</param>
        /// <returns>True if a callback was copied, or false if no callback was waiting, or an error occured.</returns>
        public static bool GetCallback(int pipe, ref CallbackMsg_t message)
        {
            if (_callSteamBGetCallback == null)
            {
                throw new InvalidOperationException($"Steam library is not been initialized({nameof(GetCallback)}).");
            }

            try
            {
                return(_callSteamBGetCallback(pipe, ref message));
            }
            catch
            {
                message = new CallbackMsg_t();
                return(false);
            }
        }
Esempio n. 5
0
        public string ActivateKey(string key)
        {
            if (Utils.ValidateCDKey(key))
            {
                if (connectToSteam())
                {
                    callbackHandlerThread = new Thread(() =>
                    {
                        _waitingForActivationResp = true;
                        CallbackMsg_t callbackMsg = new CallbackMsg_t();
                        while (callbackHandlerThread.ThreadState != ThreadState.AbortRequested && callbackHandlerThread.ThreadState != ThreadState.Aborted)
                        {
                            while (Steamworks.GetCallback(_pipe, ref callbackMsg) && callbackHandlerThread.ThreadState != ThreadState.AbortRequested && callbackHandlerThread.ThreadState != ThreadState.Aborted)
                            {
                                switch (callbackMsg.m_iCallback)
                                {
                                case PurchaseResponse_t.k_iCallback:
                                    onPurchaseResponse((PurchaseResponse_t)Marshal.PtrToStructure(callbackMsg.m_pubParam, typeof(PurchaseResponse_t)));
                                    break;
                                }

                                Steamworks.FreeLastCallback(_pipe);
                            }

                            Thread.Sleep(100);
                        }
                    }
                                                       );
                    callbackHandlerThread.Start();

                    _clientBilling.PurchaseWithActivationCode(key);

                    while (_waitingForActivationResp)
                    {
                        Thread.Sleep(100);
                    }

                    return(_result);
                }
            }
            return("Something went wrong");
        }
Esempio n. 6
0
        private void _callbacks_DoWork(object sender, DoWorkEventArgs e)
        {
            CallbackMsg_t callbackMsg = new CallbackMsg_t();

            while (!_callbackBwg.CancellationPending)
            {
                while (Steamworks.GetCallback(_pipe, ref callbackMsg) && !_callbackBwg.CancellationPending)
                {
                    switch (callbackMsg.m_iCallback)
                    {
                    case PurchaseResponse_t.k_iCallback:
                        onPurchaseResponse((PurchaseResponse_t)Marshal.PtrToStructure(callbackMsg.m_pubParam, typeof(PurchaseResponse_t)));
                        break;
                    }

                    Steamworks.FreeLastCallback(_pipe);
                }

                Thread.Sleep(100);
            }
        }
Esempio n. 7
0
        /// <summary>
        /// Calls RunFrame and processes events from this Steam Pipe
        /// </summary>
        internal static void Frame(HSteamPipe pipe)
        {
            if (runningFrame)
            {
                return;
            }

            try
            {
                runningFrame = true;

                SteamAPI_ManualDispatch_RunFrame(pipe);
                SteamNetworkingUtils.OutputDebugMessages();

                CallbackMsg_t msg = default;

                while (SteamAPI_ManualDispatch_GetNextCallback(pipe, ref msg))
                {
                    try
                    {
                        ProcessCallback(msg, pipe == ServerPipe);
                    }
                    finally
                    {
                        SteamAPI_ManualDispatch_FreeLastCallback(pipe);
                    }
                }
            }
            catch (System.Exception e)
            {
                OnException?.Invoke(e);
            }
            finally
            {
                runningFrame = false;
            }
        }
Esempio n. 8
0
        public static int Main()
        {
            //Environment.SetEnvironmentVariable("SteamAppId", "730");

            Console.Write("Loading Steam2 and Steam3... ");

            if (Steamworks.Load(true))
            {
                Console.WriteLine("Ok");
            }
            else
            {
                Console.WriteLine("Failed");
                return(-1);
            }

            Console.WriteLine("\nSteam2 tests:");

            ISteam006 steam006 = Steamworks.CreateSteamInterface <ISteam006>();

            if (steam006 == null)
            {
                Console.WriteLine("steam006 is null !");
                return(-1);
            }


            TSteamError steamError = new TSteamError();


            Console.Write("GetVersion: ");
            StringBuilder version = new StringBuilder();

            if (steam006.GetVersion(version) != 0)
            {
                Console.WriteLine("Ok (" + version.ToString() + ")");
            }
            else
            {
                Console.WriteLine("Failed");
                return(-1);
            }

            steam006.ClearError(ref steamError);

            Console.Write("Startup: ");
            if (steam006.Startup(0, ref steamError) != 0)
            {
                Console.WriteLine("Ok");
            }
            else
            {
                Console.WriteLine("Failed (" + steamError.szDesc + ")");
                return(-1);
            }

            Console.Write("OpenTmpFile: ");
            uint hFile = 0;

            if ((hFile = steam006.OpenTmpFile(ref steamError)) != 0)
            {
                Console.WriteLine("Ok");
            }
            else
            {
                Console.WriteLine("Failed (" + steamError.szDesc + ")");
                return(-1);
            }

            Console.Write("WriteFile: ");
            byte[] fileContent = System.Text.UTF8Encoding.UTF8.GetBytes("test");
            if (steam006.WriteFile(fileContent, (uint)fileContent.Length, hFile, ref steamError) == fileContent.Length)
            {
                Console.WriteLine("Ok");
            }
            else
            {
                Console.WriteLine("Failed (" + steamError.szDesc + ")");
                return(-1);
            }

            Console.Write("CloseFile: ");
            if (steam006.CloseFile(hFile, ref steamError) == 0)
            {
                Console.WriteLine("Ok");
            }
            else
            {
                Console.WriteLine("Failed (" + steamError.szDesc + ")");
                return(-1);
            }

            Console.WriteLine("\nSteam3 tests:");

            ISteamClient012 steamclient  = Steamworks.CreateInterface <ISteamClient012>();
            ISteamClient009 steamclient9 = Steamworks.CreateInterface <ISteamClient009>();

            if (steamclient == null)
            {
                Console.WriteLine("steamclient is null !");
                return(-1);
            }

            IClientEngine clientengine = Steamworks.CreateInterface <IClientEngine>();

            if (clientengine == null)
            {
                Console.WriteLine("clientengine is null !");
                return(-1);
            }

            Console.ReadKey();

            int pipe = steamclient.CreateSteamPipe();

            if (pipe == 0)
            {
                Console.WriteLine("Failed to create a pipe");
                return(-1);
            }

            int user = steamclient.ConnectToGlobalUser(pipe);

            if (user == 0 || user == -1)
            {
                Console.WriteLine("Failed to connect to global user");
                return(-1);
            }

            ISteamUser016 steamuser = steamclient.GetISteamUser <ISteamUser016>(user, pipe);

            if (steamuser == null)
            {
                Console.WriteLine("steamuser is null !");
                return(-1);
            }
            ISteamUtils005 steamutils = steamclient.GetISteamUtils <ISteamUtils005>(pipe);

            if (steamutils == null)
            {
                Console.WriteLine("steamutils is null !");
                return(-1);
            }
            ISteamUserStats002 userstats002 = steamclient.GetISteamUserStats <ISteamUserStats002>(user, pipe);

            if (userstats002 == null)
            {
                Console.WriteLine("userstats002 is null !");
                return(-1);
            }
            ISteamUserStats010 userstats010 = steamclient.GetISteamUserStats <ISteamUserStats010>(user, pipe);

            if (userstats010 == null)
            {
                Console.WriteLine("userstats010 is null !");
                return(-1);
            }
            IClientUser clientuser = clientengine.GetIClientUser <IClientUser>(user, pipe);

            if (clientuser == null)
            {
                Console.WriteLine("clientuser is null !");
                return(-1);
            }
            IClientFriends clientfriends = clientengine.GetIClientFriends <IClientFriends>(user, pipe);

            if (clientfriends == null)
            {
                Console.WriteLine("clientfriends is null !");
                return(-1);
            }

            //Console.Write("RequestCurrentStats: ");
            //if (userstats002.RequestCurrentStats(steamutils.GetAppID()))
            //{
            //    Console.WriteLine("Ok");
            //}
            //else
            //{
            //    Console.WriteLine("Failed");
            //    return -1;
            //}

            uint a = steam006.RequestAccountsByEmailAddressEmail("*****@*****.**", ref steamError);

            //Console.WriteLine(steamError.nDetailedErrorCode);
            //Console.ReadLine();

            Console.Write("Waiting for stats... ");

            CallbackMsg_t callbackMsg   = new CallbackMsg_t();
            bool          statsReceived = false;

            while (!statsReceived)
            {
                while (Steamworks.GetCallback(pipe, ref callbackMsg) && !statsReceived)
                {
                    Console.WriteLine(callbackMsg.m_iCallback);
                    if (callbackMsg.m_iCallback == UserStatsReceived_t.k_iCallback)
                    {
                        UserStatsReceived_t userStatsReceived = (UserStatsReceived_t)Marshal.PtrToStructure(callbackMsg.m_pubParam, typeof(UserStatsReceived_t));
                        if (userStatsReceived.m_steamIDUser == steamuser.GetSteamID() && userStatsReceived.m_nGameID == steamutils.GetAppID())
                        {
                            if (userStatsReceived.m_eResult == EResult.k_EResultOK)
                            {
                                Console.WriteLine("Ok");
                                statsReceived = true;
                            }
                            else
                            {
                                Console.WriteLine("Failed (" + userStatsReceived.m_eResult + ")");
                                return(-1);
                            }
                        }
                    }
                    Steamworks.FreeLastCallback(pipe);
                }
                System.Threading.Thread.Sleep(100);
            }

            Console.WriteLine("Stats for the current game :");
            uint numStats = userstats002.GetNumStats(steamutils.GetAppID());

            for (uint i = 0; i < numStats; i++)
            {
                string             statName = userstats002.GetStatName(steamutils.GetAppID(), i);
                ESteamUserStatType statType = userstats002.GetStatType(steamutils.GetAppID(), statName);
                switch (statType)
                {
                case ESteamUserStatType.k_ESteamUserStatTypeINT:
                {
                    int value = 0;
                    Console.Write("\t" + statName + " ");
                    if (userstats002.GetStat(steamutils.GetAppID(), statName, ref value))
                    {
                        Console.WriteLine(value);
                    }
                    else
                    {
                        Console.WriteLine("Failed");
                        return(-1);
                    }

                    break;
                }

                case ESteamUserStatType.k_ESteamUserStatTypeFLOAT:
                {
                    float value = 0;
                    Console.Write("\t" + statName + " ");
                    if (userstats002.GetStat(steamutils.GetAppID(), statName, ref value))
                    {
                        Console.WriteLine(value);
                    }
                    else
                    {
                        Console.WriteLine("Failed");
                        return(-1);
                    }
                    break;
                }
                }
            }

            Console.Write("GetNumberOfCurrentPlayers: ");
            ulong getNumberOfCurrentPlayersCall = userstats010.GetNumberOfCurrentPlayers();
            bool  failed = false;

            while (!steamutils.IsAPICallCompleted(getNumberOfCurrentPlayersCall, ref failed) && !failed)
            {
                System.Threading.Thread.Sleep(100);
            }

            if (failed)
            {
                Console.WriteLine("Failed (IsAPICallCompleted failure)");
                return(-1);
            }

            IntPtr pData = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(NumberOfCurrentPlayers_t)));

            if (!Steamworks.GetAPICallResult(pipe, getNumberOfCurrentPlayersCall, pData, Marshal.SizeOf(typeof(NumberOfCurrentPlayers_t)), NumberOfCurrentPlayers_t.k_iCallback, ref failed))
            {
                Console.WriteLine("Failed (GetAPICallResult failure: " + steamutils.GetAPICallFailureReason(getNumberOfCurrentPlayersCall) + ")");
                return(-1);
            }

            NumberOfCurrentPlayers_t numberOfCurrentPlayers = (NumberOfCurrentPlayers_t)Marshal.PtrToStructure(pData, typeof(NumberOfCurrentPlayers_t));

            if (!System.Convert.ToBoolean(numberOfCurrentPlayers.m_bSuccess))
            {
                Console.WriteLine("Failed (numberOfCurrentPlayers.m_bSuccess is false)");
                return(-1);
            }
            Console.WriteLine("Ok (" + numberOfCurrentPlayers.m_cPlayers + ")");

            Marshal.FreeHGlobal(pData);


            //Console.Write("Games running: ");
            //for(int i = 0; i < clientuser.NumGamesRunning(); i++)
            //{
            //    CGameID gameID = clientuser.GetRunningGameID(i);
            //    Console.Write(gameID);
            //    if(i + 1 < clientuser.NumGamesRunning())
            //        Console.Write(", ");
            //    else
            //        Console.Write("\n");
            //}

            Console.WriteLine("Current user SteamID: " + steamuser.GetSteamID());

            FriendSessionStateInfo_t sessionStateInfo = clientfriends.GetFriendSessionStateInfo(clientuser.GetSteamID());

            clientfriends.SetPersonaState(EPersonaState.k_EPersonaStateAway);

            Console.WriteLine("m_uiOnlineSessionInstances: " + sessionStateInfo.m_uiOnlineSessionInstances);
            Console.WriteLine("m_uiPublishedToFriendsSessionInstance: " + sessionStateInfo.m_uiPublishedToFriendsSessionInstance);

            Console.Write("RequestFriendProfileInfo: ");
            ulong requestFriendProfileInfoCall = clientfriends.RequestFriendProfileInfo(steamuser.GetSteamID());

            while (!steamutils.IsAPICallCompleted(requestFriendProfileInfoCall, ref failed) && !failed)
            {
                System.Threading.Thread.Sleep(100);
            }

            if (failed)
            {
                Console.WriteLine("Failed (IsAPICallCompleted failure)");
                return(-1);
            }

            pData = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(FriendProfileInfoResponse_t)));

            if (!Steamworks.GetAPICallResult(pipe, requestFriendProfileInfoCall, pData, Marshal.SizeOf(typeof(FriendProfileInfoResponse_t)), FriendProfileInfoResponse_t.k_iCallback, ref failed))
            {
                Console.WriteLine("Failed (GetAPICallResult failure: " + steamutils.GetAPICallFailureReason(requestFriendProfileInfoCall) + ")");
                return(-1);
            }

            FriendProfileInfoResponse_t friendProfileInfoResponse = (FriendProfileInfoResponse_t)Marshal.PtrToStructure(pData, typeof(FriendProfileInfoResponse_t));

            if (friendProfileInfoResponse.m_eResult != EResult.k_EResultOK)
            {
                Console.WriteLine("Failed (friendProfileInfoResponse.m_eResult = " + friendProfileInfoResponse.m_eResult + ")");
                return(-1);
            }
            if (friendProfileInfoResponse.m_steamIDFriend == clientuser.GetSteamID())
            {
                Console.WriteLine("Ok");
            }
            else
            {
                Console.WriteLine("Failed (SteamIDs doesn't match)");
            }

            Marshal.FreeHGlobal(pData);

            return(0);
        }
        private static void StartAndWaitForSteam()
        {
            if (Process.GetProcessesByName("Steam").Length == 0 && Directory.Exists(steamDir))
            {
                Environment.SetEnvironmentVariable("SteamAppId", "000");
                Stopwatch stopwatch = null;
                if (!Steamworks.Load(true))
                {
                    Println("Steamworks could not be loaded, falling back to older method...", "warning");
                    LegacyStartAndWaitForSteam();
                    return;
                }

                if (!firstRun)
                {
                    steamclient = Steamworks.CreateInterface <ISteamClient017>();
                }

                if (steamclient == null)
                {
                    Println("Steamworks could not be loaded, falling back to older method...", "warning");
                    LegacyStartAndWaitForSteam();
                    return;
                }

                int pipe = steamclient.CreateSteamPipe();
                if (pipe == 0)
                {
                    Println("Starting Steam...");
                    Process.Start(steamDir + "\\Steam.exe", steamargs);
                    Println("Waiting for friends list to connect...");
                    stopwatch = Stopwatch.StartNew();
                    while (pipe == 0 && stopwatch.Elapsed.Seconds < Timeout)
                    {
                        pipe = steamclient.CreateSteamPipe();
                        Thread.Sleep(100);
                    }

                    stopwatch.Stop();
                    if (stopwatch.Elapsed.Seconds >= Timeout && pipe == 0)
                    {
                        Println("Steamworks could not be loaded, falling back to older method...", "warning");
                        steamclient.BShutdownIfAllPipesClosed();
                        LegacyStartAndWaitForSteam();
                        return;
                    }
                }

                int user = steamclient.ConnectToGlobalUser(pipe);
                if (user == 0 || user == -1)
                {
                    Println("Steamworks could not be loaded, falling back to older method...", "warning");
                    steamclient.BReleaseSteamPipe(pipe);
                    steamclient.BShutdownIfAllPipesClosed();
                    LegacyStartAndWaitForSteam();
                    return;
                }

                if (!firstRun)
                {
                    steamfriends = steamclient.GetISteamFriends <ISteamFriends015>(user, pipe);
                    firstRun     = true;
                }

                if (steamfriends == null)
                {
                    Println("Steamworks could not be loaded, falling back to older method...", "warning");
                    steamclient.BReleaseSteamPipe(pipe);
                    steamclient.BShutdownIfAllPipesClosed();
                    LegacyStartAndWaitForSteam();
                    return;
                }

                CallbackMsg_t callbackMsg         = default(CallbackMsg_t);
                bool          stateChangeDetected = false;
                stopwatch = Stopwatch.StartNew();
                while (!stateChangeDetected && stopwatch.Elapsed.Seconds < Timeout)
                {
                    while (Steamworks.GetCallback(pipe, ref callbackMsg) && !stateChangeDetected && stopwatch.Elapsed.Seconds < Timeout)
                    {
                        if (callbackMsg.m_iCallback == PersonaStateChange_t.k_iCallback)
                        {
                            PersonaStateChange_t onPersonaStateChange = (PersonaStateChange_t)Marshal.PtrToStructure(callbackMsg.m_pubParam, typeof(PersonaStateChange_t));
                            if (onPersonaStateChange.m_nChangeFlags.HasFlag(EPersonaChange.k_EPersonaChangeComeOnline))
                            {
                                stateChangeDetected = true;
                                Println("Friends list connected!", "success");
                                break;
                            }
                        }

                        Steamworks.FreeLastCallback(pipe);
                    }

                    Thread.Sleep(100);
                }

                stopwatch.Stop();
                Steamworks.FreeLastCallback(pipe);
                steamclient.ReleaseUser(pipe, user);
                steamclient.BReleaseSteamPipe(pipe);
                steamclient.BShutdownIfAllPipesClosed();
                if (stopwatch.Elapsed.Seconds >= Timeout)
                {
                    Println("Steamworks could not be loaded, falling back to older method...", "warning");
                    LegacyStartAndWaitForSteam();
                    return;
                }
            }
        }
Esempio n. 10
0
        private void HandleCallback()
        {
            // cache for callback
            CallbackMsg_t callbackMsg = new CallbackMsg_t();

            while (true)
            {
                // get callback if available
                bool callbackAvailable = Steamworks.GetCallback(m_Pipe, ref callbackMsg);

                if (callbackAvailable)
                {
                    // process callback
                    switch (callbackMsg.m_iCallback)
                    {
                    case 805:
                        // convert to chat message callback
                        FriendChatMsg_t chatMsg = (FriendChatMsg_t)Marshal.PtrToStructure(callbackMsg.m_pubParam, typeof(FriendChatMsg_t));

                        // setup buffers
                        byte[]         bMsg           = new byte[1024];
                        EChatEntryType eChatEntryType = (EChatEntryType)0;

                        // get chat message
                        int len = m_SteamFriends002.GetChatMessage((CSteamID)chatMsg.m_ulSender, (int)chatMsg.m_iChatID, bMsg, ref eChatEntryType);

                        // get sender
                        CSteamID sender = (CSteamID)chatMsg.m_ulSender;

                        if (len > 0 && eChatEntryType == EChatEntryType.k_EChatEntryTypeChatMsg)
                        {
                            // decode message (excluding null terminator)
                            string msg = Encoding.UTF8.GetString(bMsg, 0, len - 1);

                            if (msg == "PGPSTEAM_REQUEST_KEY")
                            {
                                // send public key
                                SendKey(sender);
                                break;
                            }
                            else if (msg.StartsWith("-----BEGIN PGP PUBLIC KEY BLOCK-----"))
                            {
                                // cache public key
                                File.WriteAllText("key_cache/" + sender.AccountID.ToString() + ".key", msg);
                                break;
                            }

                            if (m_ChatWindows.ContainsKey(sender))
                            {
                                // decode
                                msg = m_PGP.Decrypt(msg);

                                // inject chat message
                                m_ChatWindows[sender].Message(msg);
                            }
                            else
                            {
                                // check has key
                                if (!HasPublicKey(sender))
                                {
                                    break;
                                }

                                // open chat window
                                Chat(sender);

                                // inject chat message
                                if (m_ChatWindows.ContainsKey(sender))
                                {
                                    // decode
                                    msg = m_PGP.Decrypt(msg);

                                    // inject chat message
                                    m_ChatWindows[sender].Message(msg);
                                }
                            }
                        }
                        break;
                    }

                    // free callback
                    Steamworks.FreeLastCallback(m_Pipe);
                }
            }
        }
Esempio n. 11
0
 internal static extern bool SteamAPI_ManualDispatch_GetNextCallback(HSteamPipe pipe, [In, Out] ref CallbackMsg_t msg);