/// <summary> /// Cancels a trade with the given ID. /// </summary> /// <param name="tradeId">Trade ID</param> /// <exception cref="ArgumentException">Trade ID cannot be null or empty</exception> public void CancelTrade(string tradeId) { if (string.IsNullOrEmpty(tradeId)) { throw new ArgumentException("Trade ID cannot be null or empty.", nameof(tradeId)); } lock (activeTradesLock) { // Make sure the trade exists if (!activeTrades.ContainsKey(tradeId)) { return; } } // Do nothing if not online if (!(netClient.Connected || authenticator.Authenticated || userManager.LoggedIn)) { return; } // Create and pack a CompleteTradePacket UpdateTradeStatusPacket packet = new UpdateTradeStatusPacket { SessionId = authenticator.SessionId, Uuid = userManager.Uuid, TradeId = tradeId, Cancelled = true }; Any packedPacket = ProtobufPacketHelper.Pack(packet); // Send it on its way netClient.Send(MODULE_NAME, packedPacket.ToByteArray()); }
/// <summary> /// Handles incoming packets. /// </summary> /// <param name="module">Destination module</param> /// <param name="connectionId">Original connection ID</param> /// <param name="data">Data payload</param> private void packetHandler(string module, string connectionId, byte[] data) { // Validate the incoming packet and discard it if validation fails if (!ProtobufPacketHelper.ValidatePacket(typeof(ServerUserManager).Namespace, MODULE_NAME, module, data, out Any message, out TypeUrl typeUrl)) { return; } // Determine what to do with this packet type switch (typeUrl.Type) { case "LoginPacket": RaiseLogEntry(new LogEventArgs(string.Format("Got a LoginPacket from {0}", connectionId.Highlight(HighlightType.ConnectionID)))); handleLoginPacket(connectionId, message.Unpack <LoginPacket>()); break; case "UserUpdatePacket": RaiseLogEntry(new LogEventArgs(string.Format("Got a UserUpdatePacket from {0}", connectionId.Highlight(HighlightType.ConnectionID)))); handleUserUpdatePacket(connectionId, message.Unpack <UserUpdatePacket>()); break; default: RaiseLogEntry(new LogEventArgs("Got an unknown packet type (" + typeUrl.Type + "), discarding...", LogLevel.DEBUG)); break; } }
private void loginHandler(object sender, ServerLoginEventArgs args) { lock (messageHistoryLock) { // Create a chat history packet ChatHistoryPacket packet = new ChatHistoryPacket(); // Convert each chat message to their packet counterparts foreach (ChatMessage chatMessage in messageHistory) { // Create a chat message packet and add it to the history packet packet.ChatMessages.Add( new ChatMessagePacket { Uuid = chatMessage.SenderUuid, MessageId = chatMessage.MessageId, Message = chatMessage.Message, Timestamp = chatMessage.Timestamp.ToTimestamp() } ); } // Pack the history packet Any packedPacket = ProtobufPacketHelper.Pack(packet); // Send it on its way if (!netServer.TrySend(args.ConnectionId, MODULE_NAME, packedPacket.ToByteArray())) { RaiseLogEntry(new LogEventArgs("Failed to send ChatHistoryPacket to connection " + args.ConnectionId.Highlight(HighlightType.ConnectionID), LogLevel.ERROR)); } } }
/// <summary> /// Broadcasts a <see cref="ChatMessagePacket"/> to all currently logged-in users. /// </summary> /// <param name="senderUuid">Sender's UUID</param> /// <param name="messageId">Message ID</param> /// <param name="message">Message content</param> /// <param name="timestamp">Timestamp</param> /// <param name="excludedConnectionIds">Array of connection IDs to be excluded from the broadcast</param> private void broadcastChatMessage(string senderUuid, string messageId, string message, DateTime timestamp, string[] excludedConnectionIds = null) { // Create and pack a ChatMessagePacket ChatMessagePacket packet = new ChatMessagePacket { Uuid = senderUuid, MessageId = messageId, Message = message, Timestamp = timestamp.ToTimestamp() }; Any packedPacket = ProtobufPacketHelper.Pack(packet); // Get an array of connection IDs for each logged in user string[] connectionIds = userManager.GetConnections(); // Remove the connection IDs to be excluded from the broadcast (if any) if (excludedConnectionIds != null) { connectionIds = connectionIds.Except(excludedConnectionIds).ToArray(); } // Send it to each of the remaining connection IDs foreach (string connectionId in connectionIds) { // Try send the chat message if (!netServer.TrySend(connectionId, MODULE_NAME, packedPacket.ToByteArray())) { RaiseLogEntry(new LogEventArgs("Failed to send ChatMessagePacket to connection " + connectionId.Highlight(HighlightType.ConnectionID), LogLevel.ERROR)); } } }
/// <summary> /// Handles incoming packets. /// </summary> /// <param name="module">Target module</param> /// <param name="connectionId">Original connection ID</param> /// <param name="data">Data payload</param> private void packetHandler(string module, string connectionId, byte[] data) { // Discard packet if it fails validation if (!ProtobufPacketHelper.ValidatePacket(typeof(ClientChat).Namespace, MODULE_NAME, module, data, out Any message, out TypeUrl typeUrl)) { return; } // Determine what to do with the packet switch (typeUrl.Type) { case "ChatMessagePacket": RaiseLogEntry(new LogEventArgs("Got a ChatMessagePacket", LogLevel.DEBUG)); chatMessagePacketHandler(connectionId, message.Unpack <ChatMessagePacket>()); break; case "ChatMessageResponsePacket": RaiseLogEntry(new LogEventArgs("Got a ChatMessageResponsePacket", LogLevel.DEBUG)); chatMessageResponsePacketHandler(connectionId, message.Unpack <ChatMessageResponsePacket>()); break; case "ChatHistoryPacket": RaiseLogEntry(new LogEventArgs("Got a ChatHistoryPacket", LogLevel.DEBUG)); chatHistoryPacketHandler(connectionId, message.Unpack <ChatHistoryPacket>()); break; default: RaiseLogEntry(new LogEventArgs("Got an unknown packet type (" + typeUrl.Type + "), discarding...", LogLevel.DEBUG)); break; } }
/// <summary> /// Attempts to create a trade with another party. /// </summary> /// <param name="otherPartyUuid">Other party's UUID</param> /// <exception cref="ArgumentException">UUID cannot be null or empty</exception> public void CreateTrade(string otherPartyUuid) { if (string.IsNullOrEmpty(otherPartyUuid)) { throw new ArgumentException("UUID cannot be null or empty.", nameof(otherPartyUuid)); } // Do nothing if not online if (!(netClient.Connected || authenticator.Authenticated || userManager.LoggedIn)) { return; } // Create and pack a CreateTradePacket CreateTradePacket packet = new CreateTradePacket { SessionId = authenticator.SessionId, Uuid = userManager.Uuid, OtherPartyUuid = otherPartyUuid }; Any packedPacket = ProtobufPacketHelper.Pack(packet); // Send it on its way netClient.Send(MODULE_NAME, packedPacket.ToByteArray()); }
/// <summary> /// Sends a <see cref="UserSyncPacket"/> containing all users to the given connection. /// Usernames are stripped from users for security. /// </summary> /// <param name="connectionId">Destination connection ID</param> private void sendSyncPacket(string connectionId) { // Create a blank sync packet UserSyncPacket packet = new UserSyncPacket(); lock (userStoreLock) { // Add users to the sync packet foreach (User userRef in userStore.Users.Values) { // Get a non-reference copy of the user so we can blank out the username without affecting the original User user = userRef.Clone(); user.Username = ""; packet.Users.Add(user); } } // Pack it Any packedPacket = ProtobufPacketHelper.Pack(packet); // Send it on its way if (!netServer.TrySend(connectionId, MODULE_NAME, packedPacket.ToByteArray())) { RaiseLogEntry(new LogEventArgs("Failed to send UserSyncPacket to connection " + connectionId, LogLevel.ERROR)); } }
/// <inheritdoc /> protected override void packetHandler(string module, string connectionId, byte[] data) { // Validate the incoming packet and discard it if validation fails if (!ProtobufPacketHelper.ValidatePacket(typeof(ServerAuthenticator).Namespace, MODULE_NAME, module, data, out Any message, out TypeUrl typeUrl)) { return; } // Determine what to do with this packet type switch (typeUrl.Type) { case "AuthenticatePacket": RaiseLogEntry(new LogEventArgs(string.Format("Got an AuthenticatePacket for session {0}", message.Unpack <AuthenticatePacket>().SessionId.Highlight(HighlightType.SessionID)), LogLevel.DEBUG)); authenticatePacketHandler(connectionId, message.Unpack <AuthenticatePacket>()); break; case "ExtendSessionPacket": RaiseLogEntry(new LogEventArgs(string.Format("Got an ExtendSessionPacket for session {0}", message.Unpack <ExtendSessionPacket>().SessionId.Highlight(HighlightType.SessionID)), LogLevel.DEBUG)); extendSessionPacketHandler(connectionId, message.Unpack <ExtendSessionPacket>()); break; default: RaiseLogEntry(new LogEventArgs("Got an unknown packet type (" + typeUrl.Type + "), discarding...", LogLevel.DEBUG)); break; } }
/// <summary> /// Handles incoming packets from <see cref="NetCommon"/>. /// </summary> /// <param name="module">Target module</param> /// <param name="connectionId">Original connection ID</param> /// <param name="data">Data payload</param> private void packetHandler(string module, string connectionId, byte[] data) { // Validate the incoming packet and discard it if validation fails if (!ProtobufPacketHelper.ValidatePacket(typeof(ServerTrading).Namespace, MODULE_NAME, module, data, out Any message, out TypeUrl typeUrl)) { return; } // Determine what to do with this packet type switch (typeUrl.Type) { case "CreateTradePacket": RaiseLogEntry(new LogEventArgs(string.Format("Got a CreateTradePacket from {0}", connectionId), LogLevel.DEBUG)); createTradePacketHandler(connectionId, message.Unpack <CreateTradePacket>()); break; case "UpdateTradeItemsPacket": RaiseLogEntry(new LogEventArgs(string.Format("Got an UpdateTradeItemsPacket from {0}", connectionId), LogLevel.DEBUG)); updateTradeItemsPacketHandler(connectionId, message.Unpack <UpdateTradeItemsPacket>()); break; case "UpdateTradeStatusPacket": RaiseLogEntry(new LogEventArgs(string.Format("Got an UpdateTradeStatusPacket from {0}", connectionId), LogLevel.DEBUG)); updateTradeStatusPacketHandler(connectionId, message.Unpack <UpdateTradeStatusPacket>()); break; default: RaiseLogEntry(new LogEventArgs("Got an unknown packet type (" + typeUrl.Type + "), discarding...", LogLevel.DEBUG)); break; } }
/// <summary> /// Handles incoming packets. /// </summary> /// <param name="module">Destination module</param> /// <param name="connectionId">Original connection ID</param> /// <param name="data">Data payload</param> private void packetHandler(string module, string connectionId, byte[] data) { // Validate the packet and discard it if it fails if (!ProtobufPacketHelper.ValidatePacket(typeof(ClientUserManager).Namespace, MODULE_NAME, module, data, out Any message, out TypeUrl typeUrl)) { return; } // Determine what to do with this packet type switch (typeUrl.Type) { case "UserUpdatePacket": RaiseLogEntry(new LogEventArgs("Got a UserUpdatePacket", LogLevel.DEBUG)); userUpdatePacketHandler(connectionId, message.Unpack <UserUpdatePacket>()); break; case "UserSyncPacket": RaiseLogEntry(new LogEventArgs("Got a UserSyncPacket", LogLevel.DEBUG)); userSyncPacketHandler(connectionId, message.Unpack <UserSyncPacket>()); break; case "LoginResponsePacket": RaiseLogEntry(new LogEventArgs("Got a LoginResponsePacket", LogLevel.DEBUG)); loginResponsePacketHandler(connectionId, message.Unpack <LoginResponsePacket>()); break; default: RaiseLogEntry(new LogEventArgs("Got an unknown packet type (" + typeUrl.Type + "), discarding...", LogLevel.DEBUG)); break; } }
/// <summary> /// Updates the currently-logged in user locally and on the server. /// Returns whether the update was successful locally and was sent to server. /// </summary> /// <param name="displayName">New display name</param> /// <param name="acceptingTrades">Whether to accept trades from other users</param> /// <returns>User update was successful and sent to server</returns> public bool UpdateSelf(string displayName = null, bool?acceptingTrades = null) { // Don't do anything unless we are logged in if (!LoggedIn) { return(false); } // Don't do anything if the parameters are all null if (displayName == null && acceptingTrades == null) { return(false); } lock (userStoreLock) { // Make sure we are in the user store if (!userStore.Users.ContainsKey(Uuid)) { return(false); // This should never return as the server ensures you exist on login } // Clone the user to avoid editing properties by reference User user = userStore.Users[Uuid].Clone(); // Set the user's display name if it is present if (displayName != null) { user.DisplayName = displayName; } // Set the user's trade acceptance if it is present if (acceptingTrades.HasValue) { user.AcceptingTrades = acceptingTrades.Value; } // Create and pack a user update packet UserUpdatePacket packet = new UserUpdatePacket { SessionId = authenticator.SessionId, Uuid = Uuid, User = user }; Any packedPacket = ProtobufPacketHelper.Pack(packet); // Send it on its way netClient.Send(MODULE_NAME, packedPacket.ToByteArray()); } return(true); }
/// <summary> /// Sends an <see cref="ExtendSessionPacket"/> to the server to extend the current session. /// </summary> /// <param name="sessionId">Session ID</param> private void sendExtendSessionPacket(string sessionId) { RaiseLogEntry(new LogEventArgs("Sending ExtendSessionPacket", LogLevel.DEBUG)); // Create and pack a session extension packet ExtendSessionPacket packet = new ExtendSessionPacket { SessionId = sessionId }; Any packedPacket = ProtobufPacketHelper.Pack(packet); // Send it on its way netClient.Send(MODULE_NAME, packedPacket.ToByteArray()); }
/// <summary> /// Sends a message to the chat. /// </summary> /// <param name="message">Message</param> /// <exception cref="ArgumentException">Message cannot be null or empty</exception> public void Send(string message) { if (string.IsNullOrEmpty(message)) { throw new ArgumentException("Message cannot be null or empty", nameof(message)); } // Check if we aren't authenticated if (!authenticator.Authenticated) { RaiseLogEntry(new LogEventArgs("Cannot send chat message: Not authenticated")); return; } // Check if we aren't logged in if (!userManager.LoggedIn) { RaiseLogEntry(new LogEventArgs("Cannot send chat message: Not logged in")); return; } // Create a random message ID string messageId = Guid.NewGuid().ToString(); // Create and store a chat message locally ClientChatMessage localMessage = new ClientChatMessage(messageId, userManager.Uuid, message); lock (messageHistoryLock) { messageHistory.Add(localMessage); } // Create and pack the chat message packet ChatMessagePacket packet = new ChatMessagePacket { SessionId = authenticator.SessionId, Uuid = userManager.Uuid, MessageId = messageId, Message = message }; Any packedPacket = ProtobufPacketHelper.Pack(packet); // Send it on its way netClient.Send(MODULE_NAME, packedPacket.ToByteArray()); }
/// <summary> /// Sends a failed <see cref="ExtendSessionResponsePacket"/> to a connection. /// </summary> /// <param name="connectionId">Recipient's connection ID</param> private void sendFailedExtendSessionResponsePacket(string connectionId) { RaiseLogEntry(new LogEventArgs(string.Format("Sending failed ExtendSessionResponsePacket to connection {0}", connectionId.Highlight(HighlightType.ConnectionID)), LogLevel.DEBUG)); // Create and pack a response ExtendSessionResponsePacket packet = new ExtendSessionResponsePacket { Success = false }; Any packedPacket = ProtobufPacketHelper.Pack(packet); // Send it on its way if (!netServer.TrySend(connectionId, MODULE_NAME, packedPacket.ToByteArray())) { RaiseLogEntry(new LogEventArgs("Failed to send ExtendSessionResponsePacket to connection " + connectionId.Highlight(HighlightType.ConnectionID), LogLevel.ERROR)); } }
/// <summary> /// Creates and sends a <see cref="ChatMessageResponsePacket"/> to the given connection ID. /// </summary> /// <param name="connectionId">Destination connection ID</param> /// <param name="success">Whether the chat message was processed successfully</param> /// <param name="originalMessageId">Original message ID</param> /// <param name="newMessageId">Newly-generated message ID</param> /// <param name="message">Message content</param> private void sendChatMessageResponse(string connectionId, bool success, string originalMessageId, string newMessageId, string message) { // Prepare and pack a ChatMessageResponsePacket ChatMessageResponsePacket packet = new ChatMessageResponsePacket { Success = success, OriginalMessageId = originalMessageId, NewMessageId = newMessageId, Message = message }; Any packedPacket = ProtobufPacketHelper.Pack(packet); // Send it on its way if (!netServer.TrySend(connectionId, MODULE_NAME, packedPacket.ToByteArray())) { RaiseLogEntry(new LogEventArgs("Failed to send ChatMessageResponsePacket to connection " + connectionId.Highlight(HighlightType.ConnectionID), LogLevel.ERROR)); } }
/// <summary> /// Sends a <see cref="ChatMessagePacket"/> to the user. /// </summary> /// <param name="connectionId">Destination connection ID</param> /// <param name="senderUuid">Sender's UUID</param> /// <param name="messageId">Message ID</param> /// <param name="message">Message content</param> /// <param name="timestamp">Timestamp</param> private void sendChatMessage(string connectionId, string senderUuid, string messageId, string message, DateTime timestamp) { // Create and pack our chat message packet ChatMessagePacket packet = new ChatMessagePacket { MessageId = messageId, Uuid = senderUuid, Message = message, Timestamp = timestamp.ToTimestamp() }; Any packedPacket = ProtobufPacketHelper.Pack(packet); // Send it on its way if (!netServer.TrySend(connectionId, MODULE_NAME, packedPacket.ToByteArray())) { RaiseLogEntry(new LogEventArgs("Failed to send ChatMessagePacket to connection " + connectionId.Highlight(HighlightType.ConnectionID), LogLevel.ERROR)); } }
/// <summary> /// Sends a successful <see cref="ExtendSessionResponsePacket"/> to a connection with the given expiry. /// </summary> /// <param name="connectionId">Recipient's connection ID</param> /// <param name="expiry">New session expiry</param> private void sendSuccessfulExtendSessionResponsePacket(string connectionId, DateTime expiry) { RaiseLogEntry(new LogEventArgs(string.Format("Sending successful ExtendSessionResponsePacket to connection {0}", connectionId.Highlight(HighlightType.ConnectionID)), LogLevel.DEBUG)); // Create and pack a response ExtendSessionResponsePacket packet = new ExtendSessionResponsePacket { Success = true, ExpiresIn = (int)(expiry - DateTime.UtcNow).TotalMilliseconds }; Any packedPacket = ProtobufPacketHelper.Pack(packet); // Send it on its way if (!netServer.TrySend(connectionId, MODULE_NAME, packedPacket.ToByteArray())) { RaiseLogEntry(new LogEventArgs("Failed to send ExtendSessionResponsePacket to connection " + connectionId.Highlight(HighlightType.ConnectionID), LogLevel.ERROR)); } }
private void ConnectionEstablishedHandler(object sender, ConnectionEventArgs e) { RaiseLogEntry(new LogEventArgs("Sending HelloPacket to incoming connection " + e.ConnectionId.Highlight(HighlightType.ConnectionID), LogLevel.DEBUG)); // Create a new session for this connection Session session = new Session { SessionId = Guid.NewGuid().ToString(), ConnectionId = e.ConnectionId, Expiry = DateTime.UtcNow + TimeSpan.FromMinutes(5), Authenticated = false }; lock (sessionsLock) { // Remove any existing sessions for this connection if (sessions.ContainsKey(e.ConnectionId)) { sessions.Remove(e.ConnectionId); } // Add it to the session dictionary sessions.Add(e.ConnectionId, session); } // Construct a HelloPacket HelloPacket hello = new HelloPacket { AuthType = authType, ServerName = serverName, ServerDescription = serverDescription, SessionId = session.SessionId }; // Pack it into an Any message Any packedHello = ProtobufPacketHelper.Pack(hello); // Try send it if (!netServer.TrySend(e.ConnectionId, MODULE_NAME, packedHello.ToByteArray())) { RaiseLogEntry(new LogEventArgs("Failed to send HelloPacket to connection " + e.ConnectionId.Highlight(HighlightType.ConnectionID), LogLevel.ERROR)); } }
/// <summary> /// Creates and sends an <see cref="AuthenticatePacket"/>. /// </summary> /// <param name="sessionId">Session ID</param> /// <param name="credential">Credentials</param> private void sendAuthenticatePacket(string sessionId, Credential credential) { RaiseLogEntry(new LogEventArgs("Sending AuthenticatePacket", LogLevel.DEBUG)); // Create and populate an authentication packet AuthenticatePacket authPacket = new AuthenticatePacket { AuthType = credential.AuthType, SessionId = sessionId, Username = credential.Username, Password = credential.Password }; // Pack it into an Any for transmission Any packedAuthPacket = ProtobufPacketHelper.Pack(authPacket); // Send it on its way netClient.Send(MODULE_NAME, packedAuthPacket.ToByteArray()); }
/// <summary> /// Sends a failed <see cref="LoginResponsePacket"/> with the given reason and message. /// </summary> /// <param name="connectionId">Connection ID</param> /// <param name="failureReason">Failure reason</param> /// <param name="failureMessage">Failure message</param> private void sendFailedLoginResponsePacket(string connectionId, LoginFailureReason failureReason, string failureMessage) { RaiseLogEntry(new LogEventArgs(string.Format("Sending failed LoginResponsePacket to connection {0}", connectionId), LogLevel.DEBUG)); // Create and pack a response LoginResponsePacket response = new LoginResponsePacket { Success = false, FailureReason = failureReason, FailureMessage = failureMessage }; Any packedResponse = ProtobufPacketHelper.Pack(response); // Send it on its way if (!netServer.TrySend(connectionId, MODULE_NAME, packedResponse.ToByteArray())) { RaiseLogEntry(new LogEventArgs("Failed to send LoginResponsePacket to connection " + connectionId, LogLevel.ERROR)); } }
/// <summary> /// Sends a successful <see cref="LoginResponsePacket"/> with the given UUID and display name. /// </summary> /// <param name="connectionId">Connection ID</param> /// <param name="uuid">User's UUID</param> /// <param name="displayName">User's display name</param> private void sendSuccessfulLoginResponsePacket(string connectionId, string uuid, string displayName) { RaiseLogEntry(new LogEventArgs(string.Format("Sending successful LoginResponsePacket to connection {0}", connectionId), LogLevel.DEBUG)); // Create and pack a response LoginResponsePacket response = new LoginResponsePacket { Success = true, Uuid = uuid, DisplayName = displayName }; Any packedResponse = ProtobufPacketHelper.Pack(response); // Send it on its way if (!netServer.TrySend(connectionId, MODULE_NAME, packedResponse.ToByteArray())) { RaiseLogEntry(new LogEventArgs("Failed to send LoginResponsePacket to connection " + connectionId, LogLevel.ERROR)); } }
/// <summary> /// Packs and sends the given user to all currently-logged in users. /// Used when a user's state changes. /// </summary> /// <param name="user">User to broadcast</param> private void broadcastUserUpdate(User user) { // Create and pack the user update packet UserUpdatePacket packet = new UserUpdatePacket { User = user }; Any packedPacket = ProtobufPacketHelper.Pack(packet); lock (connectedUsersLock) { // Send the update to each connection ID foreach (string connectionId in connectedUsers.Keys) { if (!netServer.TrySend(connectionId, MODULE_NAME, packedPacket.ToByteArray())) { RaiseLogEntry(new LogEventArgs("Failed to send UserUpdatePacket to connection " + connectionId, LogLevel.ERROR)); } } } }
/// <summary> /// Sends a successful <see cref="AuthResponsePacket"/> to a connection. /// </summary> /// <param name="connectionId">Recipient's connection ID</param> /// <param name="sessionId">New session ID</param> /// <param name="expiresIn">Milliseconds until session expiry</param> private void sendSuccessfulAuthResponsePacket(string connectionId, string sessionId, int expiresIn) { RaiseLogEntry(new LogEventArgs(string.Format("Sending successful AuthResponsePacket to connection {0}", connectionId.Highlight(HighlightType.ConnectionID)), LogLevel.DEBUG)); // Construct an AuthResponsePacket in success configuration AuthResponsePacket response = new AuthResponsePacket { Success = true, SessionId = sessionId, ExpiresIn = expiresIn }; // Pack it into an Any for transmission Any packedResponse = ProtobufPacketHelper.Pack(response); // Send it if (!netServer.TrySend(connectionId, MODULE_NAME, packedResponse.ToByteArray())) { RaiseLogEntry(new LogEventArgs("Failed to send AuthResponsePacket to connection " + connectionId.Highlight(HighlightType.ConnectionID), LogLevel.ERROR)); } }
/// <summary> /// Sends a failed <see cref="AuthResponsePacket"/> to a connection. /// </summary> /// <param name="connectionId">Recipient's connection ID</param> /// <param name="failureReason">Failure reason enum</param> /// <param name="failureMessage">Failure reason message</param> private void sendFailedAuthResponsePacket(string connectionId, AuthFailureReason failureReason, string failureMessage) { RaiseLogEntry(new LogEventArgs(string.Format("Sending failed AuthResponsePacket to connection {0}", connectionId.Highlight(HighlightType.ConnectionID)), LogLevel.DEBUG)); // Construct an AuthResponsePacket in failure configuration AuthResponsePacket response = new AuthResponsePacket { Success = false, FailureReason = failureReason, FailureMessage = failureMessage }; // Pack it into an Any for transmission Any packedResponse = ProtobufPacketHelper.Pack(response); // Send it if (!netServer.TrySend(connectionId, MODULE_NAME, packedResponse.ToByteArray())) { RaiseLogEntry(new LogEventArgs("Failed to send AuthResponsePacket to connection " + connectionId.Highlight(HighlightType.ConnectionID), LogLevel.ERROR)); } }
/// <summary> /// Sends an item update for the given trade with the given items to the server. /// </summary> /// <param name="tradeId">Trade ID</param> /// <param name="items">Items on offer</param> /// <param name="token">Unique request token</param> public void UpdateItems(string tradeId, IEnumerable <ProtoThing> items, string token = "") { // Do nothing if not online if (!(netClient.Connected && authenticator.Authenticated && userManager.LoggedIn)) { return; } // Create and pack an UpdateTradeItems packet UpdateTradeItemsPacket packet = new UpdateTradeItemsPacket { SessionId = authenticator.SessionId, Uuid = userManager.Uuid, TradeId = tradeId, Items = { items }, Token = token }; Any packedPacket = ProtobufPacketHelper.Pack(packet); // Send it on its way netClient.Send(MODULE_NAME, packedPacket.ToByteArray()); }
/// <summary> /// Attempts to log in to the server. /// Must be authenticated. /// </summary> /// <param name="displayName">Display name to log in with</param> /// <param name="useServerDisplayName">Use the server's copy of the user's display name if it has one</param> /// <param name="acceptingTrades">Whether to accept trades from other users</param> public void SendLogin(string displayName, bool useServerDisplayName = false, bool acceptingTrades = true) { if (!authenticator.Authenticated) { return; } // Create and pack a new LoginPacket LoginPacket packet = new LoginPacket { SessionId = authenticator.SessionId, DisplayName = displayName, UseServerDisplayName = useServerDisplayName, AcceptingTrades = acceptingTrades }; Any packedPacket = ProtobufPacketHelper.Pack(packet); RaiseLogEntry(new LogEventArgs("Sending LoginPacket", LogLevel.DEBUG)); // Send it on its way netClient.Send(MODULE_NAME, packedPacket.ToByteArray()); }
/// <summary> /// Sends a status update for the given trade to the server. /// </summary> /// <param name="tradeId">Trade ID</param> /// <param name="accepted">Accepted state</param> /// <param name="cancelled">Cancel the trade</param> public void UpdateStatus(string tradeId, bool?accepted = null, bool?cancelled = null) { // Do nothing if not online if (!(netClient.Connected && authenticator.Authenticated && userManager.LoggedIn)) { return; } // Create and pack an UpdateTradeStatus packet UpdateTradeStatusPacket packet = new UpdateTradeStatusPacket { SessionId = authenticator.SessionId, Uuid = userManager.Uuid, TradeId = tradeId, Accepted = accepted.HasValue ? accepted.Value : false, Cancelled = cancelled.HasValue ? cancelled.Value : false }; Any packedPacket = ProtobufPacketHelper.Pack(packet); // Send it on its way netClient.Send(MODULE_NAME, packedPacket.ToByteArray()); }