/// <summary> /// Updates the tiles /// </summary> public void Update() { //blocks wrong execution if (!Network.isServer || AmApplication.CurrentMatchState != MatchState.MATCH) return; Color currentTileColor = gameObject.GetComponent<Renderer>().material.color; // increment the current color to white (tile color decay) // if touched (by a player or spawner) if (Touched) { if (currentTileColor != AmApplication.DEFAULT_COLOR) { currentTileColor.r += AmApplication.TILE_COLOR_DECAY; currentTileColor.g += AmApplication.TILE_COLOR_DECAY; currentTileColor.b += AmApplication.TILE_COLOR_DECAY; currentTileColor.a = 0.5f; gameObject.GetComponent<Renderer>().material.color = currentTileColor; // color has been reset: reset touch variables too } else { gameObject.GetComponent<Renderer>().material = defaultTileMaterial; Touched = false; _touchedBy = null; } } }
/// <summary> /// Collision detection /// </summary> public void OnCollisionEnter(Collision collision) { // hey, you touched me! Touched = true; _touchedBy = collision.gameObject.GetComponent<ConnectedPlayer> (); //update the color Color tileColor = gameObject.GetComponent<Renderer>().material.color; if (tileColor != Color.red) gameObject.GetComponent<Renderer>().material.color = collision.gameObject.GetComponent<Renderer>().material.color; }
//Check if tokens match and if the player is an admin or is banned private async Task <bool> CheckUserState( string unverifiedUserid, string unverifiedToken, ConnectedPlayer unverifiedConnPlayer, string unverifiedClientId) { if (GameData.Instance.OfflineMode) { Logger.Log($"{unverifiedConnPlayer.Username} logged in successfully in offline mode. " + $"userid: {unverifiedUserid}", Category.Admin); return(true); } //allow empty token for local offline testing if (string.IsNullOrEmpty(unverifiedToken) || string.IsNullOrEmpty(unverifiedUserid)) { StartCoroutine(KickPlayer(unverifiedConnPlayer, $"Server Error: Account has invalid cookie.")); Logger.Log($"A user tried to connect with null userid or token value" + $"Details: Username: {unverifiedConnPlayer.Username}, ClientID: {unverifiedClientId}, IP: {unverifiedConnPlayer.Connection.address}", Category.Admin); return(false); } //check if they are already logged in, skip this check if offline mode is enable or if not a release build. if (BuildPreferences.isForRelease) { var otherUser = GetByUserID(unverifiedUserid); if (otherUser != null) { if (otherUser.Connection != null && otherUser.GameObject != null) { if (unverifiedConnPlayer.UserId == unverifiedUserid && unverifiedConnPlayer.Connection != otherUser.Connection) { StartCoroutine( KickPlayer(unverifiedConnPlayer, $"Server Error: You are already logged into this server!")); Logger.Log($"A user tried to connect with another client while already logged in \r\n" + $"Details: Username: {unverifiedConnPlayer.Username}, ClientID: {unverifiedClientId}, IP: {unverifiedConnPlayer.Connection.address}", Category.Admin); return(false); } } } otherUser = GetByConnection(unverifiedConnPlayer.Connection); if (otherUser != null) { StartCoroutine( KickPlayer(unverifiedConnPlayer, $"Server Error: You already have an existing connection with the server!")); Logger.LogWarning($"Warning 2 simultaneous connections from same IP detected\r\n" + $"Details: Unverified Username: {unverifiedConnPlayer.Username}, Unverified ClientID: {unverifiedClientId}, IP: {unverifiedConnPlayer.Connection.address}", Category.Admin); } } var refresh = new RefreshToken { userID = unverifiedUserid, refreshToken = unverifiedToken }; //Assuming this validates it for now var response = await ServerData.ValidateToken(refresh, true); //fail, unless doing local offline testing if (!GameData.Instance.OfflineMode) { if (response == null) { StartCoroutine(KickPlayer(unverifiedConnPlayer, $"Server Error: Server request error")); Logger.Log($"Server request error for " + $"Details: Username: {unverifiedConnPlayer.Username}, ClientID: {unverifiedClientId}, IP: {unverifiedConnPlayer.Connection.address}", Category.Admin); return(false); } } else { if (response == null) { return(false); } } //allow error response for local offline testing if (response.errorCode == 1) { StartCoroutine(KickPlayer(unverifiedConnPlayer, $"Server Error: Account has invalid cookie.")); Logger.Log($"A spoof attempt was recorded. " + $"Details: Username: {unverifiedConnPlayer.Username}, ClientID: {unverifiedClientId}, IP: {unverifiedConnPlayer.Connection.address}", Category.Admin); return(false); } var Userid = unverifiedUserid; var Token = unverifiedToken; //whitelist checking: var lines = File.ReadAllLines(whiteListPath); //Adds server to admin list if not already in it. if (Userid == ServerData.UserID && !adminUsers.Contains(Userid)) { File.AppendAllLines(adminsPath, new string[] { "\r\n" + Userid }); adminUsers.Add(Userid); var user = GetByUserID(Userid); if (user == null) { return(false); } var newToken = System.Guid.NewGuid().ToString(); if (!loggedInAdmins.ContainsKey(Userid)) { loggedInAdmins.Add(Userid, newToken); AdminEnableMessage.Send(user.Connection, newToken); } } //Checks whether the userid is in either the Admins or whitelist AND that the whitelist file has something in it. //Whitelist only activates if whitelist is populated. if (lines.Length > 0 && !adminUsers.Contains(Userid) && !whiteListUsers.Contains(Userid)) { StartCoroutine(KickPlayer(unverifiedConnPlayer, $"Server Error: This account is not whitelisted.")); Logger.Log($"{unverifiedConnPlayer.Username} tried to log in but the account is not whitelisted. " + $"IP: {unverifiedConnPlayer.Connection.address}", Category.Admin); return(false); } //banlist checking: var banEntry = banList?.CheckForEntry(Userid, unverifiedConnPlayer.Connection.address, unverifiedClientId); if (banEntry != null) { var entryTime = DateTime.ParseExact(banEntry.dateTimeOfBan, "O", CultureInfo.InvariantCulture); var totalMins = Mathf.Abs((float)(entryTime - DateTime.Now).TotalMinutes); if (totalMins > (float)banEntry.minutes) { //Old ban, remove it banList.banEntries.Remove(banEntry); SaveBanList(); Logger.Log($"{unverifiedConnPlayer.Username} ban has expired and the user has logged back in.", Category.Admin); } else { //User is still banned: StartCoroutine(KickPlayer(unverifiedConnPlayer, $"Server Error: This account is banned. " + $"You were banned for {banEntry.reason}. This ban has {banEntry.minutes - totalMins} minutes remaining.")); Logger.Log($"{unverifiedConnPlayer.Username} tried to log back in but the account is banned. " + $"IP: {unverifiedConnPlayer.Connection.address}", Category.Admin); return(false); } } Logger.Log($"{unverifiedConnPlayer.Username} logged in successfully. " + $"userid: {Userid}", Category.Admin); return(true); }
public override void ExecuteServer(ConnectedPlayer subject) { ServerMethod.Invoke(Value); }
public CommandResponse?OnCall(Game g, ConnectedPlayer p, string msg) { g.StartGame(); return(null); }
public void Analyze(ConnectedPlayer player) { chemMasterTab.Analyze(Reagent, player); }
private void ProcessFurther(ConnectedPlayer player, GameObject tabProvider, NetMessage msg) { if (player == null) { Logger.LogWarning("[TabInteractMessage.ProcessFurther] - player is null", Category.NetUI); return; } else if (tabProvider == null) { Logger.LogWarning("[TabInteractMessage.ProcessFurther] - tabProvider is null", Category.NetUI); return; } var playerScript = player.Script; //First Validations is for objects in the world (computers, etc), second check is for items in active hand (null rod, PADs). bool validate; if (playerScript.PlayerState == PlayerScript.PlayerStates.Ai) { validate = Validations.CanApply(new AiActivate(player.GameObject, null, tabProvider, Intent.Help, AiActivate.ClickTypes.NormalClick), NetworkSide.Server); } else { validate = Validations.CanApply(player.Script, tabProvider, NetworkSide.Server) || playerScript.DynamicItemStorage.GetActiveHandSlot().ItemObject == tabProvider; } if (!validate) { FailValidation(player, tabProvider, msg, "Can't interact/reach"); return; } var tabInfo = NetworkTabManager.Instance.Get(tabProvider, msg.NetTabType); if (!tabInfo /* == NetworkTabInfo.Invalid*/) { //No such tab exists on server! FailValidation(player, tabProvider, msg, $"No such tab: {tabProvider}/{msg.NetTabType}"); return; } var updatedElement = tabInfo[msg.ElementId]; if (updatedElement == null) { //No such element exists on server! FailValidation(player, tabProvider, msg, $"No such element: {tabInfo}[{msg.ElementId}]"); return; } if (updatedElement.InteractionMode == ElementMode.ServerWrite) { //Don't change labels and other non-interactable elements. If this is triggered, someone's tampering with client FailValidation(player, tabProvider, msg, $"Non-interactable {updatedElement}"); return; } var valueBeforeUpdate = updatedElement.ValueObject; updatedElement.BinaryValue = msg.ElementValue; updatedElement.ExecuteServer(player); if (updatedElement.InteractionMode == ElementMode.ClientWrite) { //Don't rememeber value provided by client and restore to the initial one updatedElement.ValueObject = valueBeforeUpdate; } //Notify all peeping players of the change List <ConnectedPlayer> list = NetworkTabManager.Instance.GetPeepers(tabProvider, msg.NetTabType); for (var i = 0; i < list.Count; i++) { var connectedPlayer = list[i]; //Not sending that update to the same player if (connectedPlayer.GameObject != player.GameObject) { TabUpdateMessage.Send(connectedPlayer.GameObject, tabProvider, msg.NetTabType, TabAction.Update, player.GameObject, new[] { new ElementValue { Id = msg.ElementId, Value = updatedElement.BinaryValue } }); } } }
private ItemSlot GetBestSlot(GameObject item, ConnectedPlayer subject) { if (subject == null) { return(default);
public override void AfterSpawn(ConnectedPlayer player) { UpdateChatMessage.Send(player.GameObject, ChatChannel.System, ChatModifier.None, "<color=red>Something has awoken in you. You feel the urgent need to rebel " + "alongside all your brothers in your department against this station.</color>"); }
public Player(ConnectedPlayer p) { playerInfo = p; }
public override bool CastSpellServer(ConnectedPlayer caster) { StartCoroutine(SpawnPortals(caster.Script.WorldPos)); return(SpawnGunInHand(caster)); }
public abstract void onPlayerLeft(ConnectedPlayer newPlayer);
public virtual ConnectedPlayer onPlayerJoined(ConnectedPlayer newPlayer) { addNewPlayerAndClient(newPlayer); newPlayer.color = assignPlayerColor(newPlayer.username, colorOrder); return(newPlayer); }
public void Reply(string message, params object[] args) => ConnectedPlayer.Reply(message, args);
public void CallActionServer(ConnectedPlayer SentByPlayer) { ServerChangeState(SentByPlayer); }
/// <summary> /// Update this Monobehaviour instance /// </summary> void Update() { // pause menu toggle if (Input.GetKeyUp (KeyCode.Escape) || Input.GetKey (KeyCode.Menu)) { Debug.Log("EscKey"); _escPressed = !_escPressed; } // reference to the current ConnectedPlayer if (Network.isClient) _player = GameObject.Find (AmApplication.GAMEOBJECT_MAP_GENERATOR_NAME).GetComponent<C_PlayerManager> ().Player; }
public void ServerChangeState(ConnectedPlayer newPlayer) { this.player = newPlayer; isOn = !isOn; }
/// <summary> /// Try spawn vending item and reduce items count in stock /// </summary> public void TryVendItem(VendorItem vendorItem, ConnectedPlayer player = null) { if (vendorItem == null) { return; } if (!CanSell(vendorItem, player)) { return; } // Spawn item on top of the vending machine Vector3 spawnPos = gameObject.RegisterTile().WorldPositionServer; var spawnedItem = Spawn.ServerPrefab(vendorItem.Item, spawnPos, transform.parent, scatterRadius: DispenseScatterRadius).GameObject; //something went wrong trying to spawn the item if (spawnedItem == null) { return; } vendorItem.Stock--; // State sucsess message to chat Chat.AddLocalMsgToChat($"The {spawnedItem.ExpensiveName()} was dispensed from the vending machine", gameObject); // Play vending sound AudioSourceParameters audioSourceParameters = new AudioSourceParameters(pitch: Random.Range(.75f, 1.1f)); SoundManager.PlayNetworkedAtPos(VendingSound, gameObject.WorldPosServer(), audioSourceParameters, sourceObj: gameObject); //Ejecting in direction if (EjectObjects && EjectDirection != EjectDirection.None && spawnedItem.TryGetComponent <CustomNetTransform>(out var cnt)) { Vector3 offset = Vector3.zero; switch (EjectDirection) { case EjectDirection.Up: offset = transform.rotation * Vector3.up / Random.Range(4, 12); break; case EjectDirection.Down: offset = transform.rotation * Vector3.down / Random.Range(4, 12); break; case EjectDirection.Random: offset = new Vector3(Random.Range(-0.15f, 0.15f), Random.Range(-0.15f, 0.15f), 0); break; } cnt.Throw(new ThrowInfo { ThrownBy = spawnedItem, Aim = BodyPartType.Chest, OriginWorldPos = spawnPos, WorldTrajectory = offset, SpinMode = (EjectDirection == EjectDirection.Random) ? SpinMode.Clockwise : SpinMode.None }); } OnItemVended.Invoke(vendorItem); }
private void SavePlayerData(ConnectedPlayer obj) { obj.positionalData.instanceID = room.instanceID; obj.positionalData.templateID = room.roomTemplate.templateID; obj.positionalData.position = position; }
private TabUpdateMessage FailValidation(ConnectedPlayer player, GameObject tabProvider, NetMessage msg, string reason = "") { Logger.LogWarning($"{player.Name}: Tab interaction w/{tabProvider} denied: {reason}", Category.NetUI); return(TabUpdateMessage.Send(player.GameObject, tabProvider, msg.NetTabType, TabAction.Close)); }
public override void onPlayerLeft(ConnectedPlayer newPlayer) { print("Player left"); base.shutdownGameServer(); logic.gameOver(); }
public void ClaimLaborPoints(ConnectedPlayer connectedPlayer) { oreRedemptionMachine.ClaimLaborPoints(connectedPlayer.GameObject); }
public void AddPrevious(ConnectedPlayer oldPlayer) { oldValues.Add(ConnectedPlayer.ArchivedPlayer(oldPlayer)); }
public abstract void Punish(ConnectedPlayer player);
public static bool IsConnWhitelisted(ConnectedPlayer player) { return(player.Connection == null || player.Connection == ConnectedPlayer.Invalid.Connection || !player.Connection.isConnected); }
protected virtual void HandlePlayer(ConnectedPlayer player) { GiveGunToPlayer(player); }
public void Add(ConnectedPlayer player) => TryAdd(player);
public async Task <bool> ValidatePlayer(string unverifiedClientId, string unverifiedUsername, string unverifiedUserid, int unverifiedClientVersion, ConnectedPlayer unverifiedConnPlayer, string unverifiedToken) { var validAccount = await CheckUserState(unverifiedUserid, unverifiedToken, unverifiedConnPlayer, unverifiedClientId); if (!validAccount) { return(false); } if (unverifiedClientVersion != GameData.BuildNumber) { StartCoroutine(KickPlayer(unverifiedConnPlayer, $"Invalid Client Version! You need version {GameData.BuildNumber}." + " This can be acquired through the station hub.")); return(false); } return(true); }
protected override string FormatInvocationMessage(ConnectedPlayer caster, string modPrefix) { return(string.Format(SpellData.InvocationMessage, caster.Name, caster.CharacterSettings.ThemPronoun())); }
IEnumerator KickPlayer(ConnectedPlayer connPlayer, string reason, bool ban = false, int banLengthInMinutes = 0) { Logger.Log("Processing KickPlayer/ban for " + "\n" + "UserId " + connPlayer?.UserId + "\n" + "Username " + connPlayer?.Username + "\n" + "address " + connPlayer?.Connection?.address + "\n" + "clientId " + connPlayer?.ClientId + "\n" ); string message = ""; if (ban) { message = $"You have been banned for {banLengthInMinutes}" + $" minutes. Reason: {reason}"; var index = banList.banEntries.FindIndex(x => x.userId == connPlayer.UserId); if (index != -1) { Logger.Log("removing pre-existing ban entry for userId of" + connPlayer.UserId); banList.banEntries.RemoveAt(index); } banList.banEntries.Add(new BanEntry { userId = connPlayer?.UserId, userName = connPlayer?.Username, minutes = banLengthInMinutes, reason = reason, dateTimeOfBan = DateTime.Now.ToString("O"), ipAddress = connPlayer?.Connection?.address, clientId = connPlayer?.ClientId }); SaveBanList(); if (banList.banEntries.Count != 0) { Logger.Log(banList.banEntries[banList.banEntries.Count - 1].ToString()); } } else { message = $"You have been kicked. Reason: {reason}"; } SendClientLogMessage.SendLogToClient(connPlayer.GameObject, message, Category.Admin, true); yield return(WaitFor.Seconds(0.1f)); if (connPlayer.Connection == null) { Logger.Log($"Not kicking, already disconnected: {connPlayer.Name}"); yield break; } Logger.Log($"Kicking client {connPlayer.Username} : {message}"); InfoWindowMessage.Send(connPlayer.GameObject, message, "Disconnected"); yield return(WaitFor.Seconds(1f)); connPlayer.Connection.Disconnect(); connPlayer.Connection.Dispose(); while (!loggedOff.Contains(connPlayer)) { yield return(WaitFor.EndOfFrame); } loggedOff.Remove(connPlayer); }
public bool IsAdmin(ConnectedPlayer player) { return(IsAdmin(player.UserId)); }
public override void ExecuteServer(ConnectedPlayer subject) { }
/// <summary> /// Called on client join to server, to update their info. /// </summary> /// <param name="connPlayer"></param> /// <returns></returns> private List <JobBanEntry> ClientAskingAboutJobBans(ConnectedPlayer connPlayer) { if (connPlayer.Equals(ConnectedPlayer.Invalid)) { Logger.LogError($"Attempted to check job-ban for invalid player.", Category.Jobs); return(default);
internal void Add(ConnectedPlayer connectedPlayer) { items[count++] = connectedPlayer; }
/// <summary> /// Initializes the PlayerManager /// </summary> void Start() { //Blocks wrong execution if (!Network.isClient) return; GameObject _playerCube = (GameObject)GameObject.Instantiate (playerPrefab); _playerCube.GetComponent<BoxCollider> ().enabled = false; _playerCube.GetComponent<Rigidbody> ().useGravity = false; _playerCube.AddComponent<rotate> (); Color color = new Color (UnityEngine.Random.value, UnityEngine.Random.value, UnityEngine.Random.value); _playerCube.GetComponent<Renderer>().material.color = color; GetComponent<NetworkView>().RPC ("AddPlayerName", RPCMode.Server, Network.player.guid, PlayerSettings.PlayerName); GetComponent<NetworkView>().RPC ("AddPlayerColor", RPCMode.Server, Network.player.guid, color.r, color.g, color.b); Player = _playerCube.GetComponent<ConnectedPlayer> (); Camera.main.transform.position = new Vector3 (0, 5, -5); Debug.Log ("Start Client Player Manager"); }