Example #1
0
        public ActionResult EditCharacter(long id, AddEditCharacterViewModel vModel)
        {
            string          userId     = User.Identity.GetUserId();
            ApplicationUser authedUser = UserManager.FindById(userId);
            IPlayerTemplate obj        = PlayerDataCache.Get(new PlayerDataCacheKey(typeof(IPlayerTemplate), authedUser.GlobalIdentityHandle, id));

            obj.Name                = vModel.DataObject.Name;
            obj.SurName             = vModel.DataObject.SurName;
            obj.Gender              = vModel.DataObject.Gender;
            obj.SuperSenses         = vModel.DataObject.SuperSenses;
            obj.GamePermissionsRank = vModel.DataObject.GamePermissionsRank;
            obj.Race                = vModel.DataObject.Race;
            string message;

            if (obj == null)
            {
                message = "That character does not exist";
            }
            else
            {
                if (obj.Save(authedUser.GameAccount, authedUser.GetStaffRank(User)))
                {
                    LoggingUtility.Log("*WEB* - EditCharacter[" + authedUser.GameAccount.GlobalIdentityHandle + "]", LogChannels.AccountActivity);
                    message = "Edit Successful.";
                }
                else
                {
                    message = "Error; edit failed.";
                }
            }

            return(RedirectToAction("ManageCharacters", new { Message = message }));
        }
Example #2
0
        public ActionResult RemoveCharacter(long removeId, string authorizeRemove)
        {
            string message = string.Empty;

            if (string.IsNullOrWhiteSpace(authorizeRemove) || !removeId.ToString().Equals(authorizeRemove))
            {
                message = "You must check the proper authorize radio button first.";
            }
            else
            {
                string userId = User.Identity.GetUserId();
                ManageCharactersViewModel model = new ManageCharactersViewModel
                {
                    AuthedUser = UserManager.FindById(userId)
                };

                IPlayerTemplate character = model.AuthedUser.GameAccount.Characters.FirstOrDefault(ch => ch.Id.Equals(removeId));

                if (character == null)
                {
                    message = "That character does not exist";
                }
                else if (character.Remove(model.AuthedUser.GameAccount, model.AuthedUser.GetStaffRank(User)))
                {
                    message = "Character successfully deleted.";
                }
                else
                {
                    message = "Error. Character not removed.";
                }
            }

            return(RedirectToAction("ManageCharacters", new { Message = message }));
        }
Example #3
0
        /// <summary>
        /// Dumps everything of a single type into the cache from the filesystem for BackingData
        /// </summary>
        /// <typeparam name="T">the type to get and store</typeparam>
        /// <returns>full or partial success</returns>
        public bool LoadAllCharactersForAccountToCache(string accountHandle)
        {
            string currentBackupDirectory = BaseDirectory + accountHandle + "/" + CurrentDirectoryName;

            //No current directory? WTF
            if (!VerifyDirectory(currentBackupDirectory, false))
            {
                return(false);
            }

            DirectoryInfo charDirectory = new DirectoryInfo(currentBackupDirectory);

            foreach (FileInfo file in charDirectory.EnumerateFiles("*.playertemplate", SearchOption.AllDirectories))
            {
                try
                {
                    byte[] fileData = ReadFile(file);
                    System.Runtime.Remoting.ObjectHandle blankEntity = Activator.CreateInstance("NetMud.Data", "NetMud.Data.Players.PlayerTemplate");

                    IPlayerTemplate objRef = blankEntity.Unwrap() as IPlayerTemplate;

                    IPlayerTemplate newChar = objRef.FromBytes(fileData) as IPlayerTemplate;

                    PlayerDataCache.Add(newChar);
                }
                catch (Exception ex)
                {
                    LoggingUtility.LogError(ex);
                    //Let it keep going
                }
            }

            return(true);
        }
Example #4
0
        /// <summary>
        /// Write one character to its player current data
        /// </summary>
        /// <param name="entity">the char to write</param>
        public void WriteCharacter(IPlayerTemplate entity)
        {
            string dirName = BaseDirectory + entity.AccountHandle + "/" + CurrentDirectoryName + entity.Id + "/";

            if (!VerifyDirectory(dirName))
            {
                throw new Exception("Unable to locate or create base player directory.");
            }

            string entityFileName = GetCharacterFilename(entity);

            if (string.IsNullOrWhiteSpace(entityFileName))
            {
                return;
            }

            string fullFileName = dirName + entityFileName;

            try
            {
                ArchiveCharacter(entity);
                WriteToFile(fullFileName, entity.ToBytes());
            }
            catch (Exception ex)
            {
                LoggingUtility.LogError(ex, false);
            }
        }
Example #5
0
        /// <summary>
        /// Writes one player out to disk
        /// </summary>
        /// <param name="player">the player to write</param>
        /// <param name="checkDirectories">skip checking directories or not</param>
        /// <returns></returns>
        public bool WriteOnePlayer(IPlayer entity)
        {
            string playersDir = BaseDirectory;

            if (!VerifyDirectory(playersDir))
            {
                throw new Exception("Players directory unable to be verified or created during full backup.");
            }

            LoggingUtility.Log("Backing up player character " + entity.TemplateId + ".", LogChannels.Backup, true);

            try
            {
                IPlayerTemplate charData = entity.Template <IPlayerTemplate>();

                string currentDirName = playersDir + charData.AccountHandle + "/" + CurrentDirectoryName + charData.Id + "/";
                string archiveDirName = playersDir + charData.AccountHandle + "/" + ArchiveDirectoryName + charData.Id + "/";

                //Wipe out the existing one so we can create all new files
                if (VerifyDirectory(currentDirName, false))
                {
                    DirectoryInfo currentRoot = new DirectoryInfo(currentDirName);

                    if (!VerifyDirectory(archiveDirName))
                    {
                        return(false);
                    }

                    //Already exists?
                    if (VerifyDirectory(archiveDirName + DatedBackupDirectory, false))
                    {
                        return(false);
                    }

                    //move is literal move, no need to delete afterwards
                    currentRoot.MoveTo(archiveDirName + DatedBackupDirectory);
                }

                DirectoryInfo entityDirectory = Directory.CreateDirectory(currentDirName);

                WritePlayer(entityDirectory, entity);
                WriteCharacter(charData);
            }
            catch (Exception ex)
            {
                LoggingUtility.LogError(ex);
                return(false);
            }

            return(true);
        }
Example #6
0
        public ActionResult AddPlaylist()
        {
            string          message    = string.Empty;
            ApplicationUser authedUser = UserManager.FindById(User.Identity.GetUserId());

            IPlayerTemplate currentCharacter = authedUser.GameAccount.Characters.FirstOrDefault(chr => chr.Id == authedUser.GameAccount.CurrentlySelectedCharacter);

            AddEditPlaylistViewModel vModel = new AddEditPlaylistViewModel
            {
                AuthedUser = authedUser,
                ValidSongs = ContentUtility.GetMusicTracksForZone(currentCharacter?.CurrentLocation?.CurrentZone)
            };

            return(View(vModel));
        }
Example #7
0
        /// <summary>
        /// Archive a character
        /// </summary>
        /// <param name="entity">the thing to archive</param>
        public void ArchiveCharacter(IPlayerTemplate entity)
        {
            string dirName = BaseDirectory + entity.AccountHandle + "/" + CurrentDirectoryName + entity.Id + "/";

            if (!VerifyDirectory(dirName))
            {
                throw new Exception("Unable to locate or create current player directory.");
            }

            string entityFileName = GetCharacterFilename(entity);

            if (string.IsNullOrWhiteSpace(entityFileName))
            {
                return;
            }

            string fullFileName = dirName + entityFileName;

            if (!File.Exists(fullFileName))
            {
                return;
            }

            string archiveFileDirectory = BaseDirectory + entity.AccountHandle + "/" + ArchiveDirectoryName + entity.Id + "/" + DatedBackupDirectory;

            if (!VerifyDirectory(archiveFileDirectory))
            {
                throw new Exception("Unable to locate or create archive player directory.");
            }

            CullDirectoryCount(BaseDirectory + entity.AccountHandle + "/" + ArchiveDirectoryName + entity.Id + "/");

            try
            {
                string archiveFile = archiveFileDirectory + entityFileName;

                if (File.Exists(archiveFile))
                {
                    File.Delete(archiveFile);
                }

                File.Move(fullFileName, archiveFile);
            }
            catch (Exception ex)
            {
                LoggingUtility.LogError(ex);
            }
        }
Example #8
0
        public ActionResult EditCharacter(long id)
        {
            string          userId = User.Identity.GetUserId();
            ApplicationUser user   = UserManager.FindById(userId);

            IPlayerTemplate           obj   = PlayerDataCache.Get(new PlayerDataCacheKey(typeof(IPlayerTemplate), user.GlobalIdentityHandle, id));
            AddEditCharacterViewModel model = new AddEditCharacterViewModel
            {
                AuthedUser   = user,
                DataObject   = obj,
                ValidRaces   = TemplateCache.GetAll <IRace>(),
                ValidGenders = TemplateCache.GetAll <IGender>()
            };

            return(View(model));
        }
Example #9
0
        /// <summary>
        /// Add a character to this account
        /// </summary>
        /// <param name="newChar">the character data to add</param>
        /// <returns>errors or Empty if successful</returns>
        public string AddCharacter(IPlayerTemplate newChar)
        {
            HashSet <IPlayerTemplate> systemChars = new HashSet <IPlayerTemplate>(PlayerDataCache.GetAll());

            if (systemChars.Any(ch => ch.Name.Equals(newChar.Name, StringComparison.InvariantCultureIgnoreCase) && newChar.SurName.Equals(newChar.SurName, StringComparison.InvariantCultureIgnoreCase)))
            {
                return("A character with that name already exists, please choose another.");
            }

            newChar.AccountHandle = GlobalIdentityHandle;
            newChar.Create(this, StaffRank.Player); //characters dont need approval yet but your rank is ALWAYS player here
            systemChars.Add(newChar);

            Characters = systemChars;

            return(string.Empty);
        }
Example #10
0
        public ActionResult EditPlaylist(string name)
        {
            string              message           = string.Empty;
            ApplicationUser     authedUser        = UserManager.FindById(User.Identity.GetUserId());
            HashSet <IPlaylist> existingPlaylists = authedUser.GameAccount.Config.Playlists;
            IPlaylist           obj = existingPlaylists.FirstOrDefault(list => list.Name.Equals(name));

            if (obj == null)
            {
                return(RedirectToAction("Playlists", new { Message = "That playlist does not exist." }));
            }

            IPlayerTemplate          currentCharacter = authedUser.GameAccount.Characters.FirstOrDefault(chr => chr.Id == authedUser.GameAccount.CurrentlySelectedCharacter);
            AddEditPlaylistViewModel vModel           = new AddEditPlaylistViewModel
            {
                AuthedUser = UserManager.FindById(User.Identity.GetUserId()),
                Name       = obj.Name,
                DataObject = obj,
                ValidSongs = ContentUtility.GetMusicTracksForZone(currentCharacter?.CurrentLocation?.CurrentZone)
            };

            return(View(vModel));
        }
Example #11
0
        public ActionResult AddViewNotification(AddViewNotificationViewModel vModel)
        {
            string          message    = string.Empty;
            string          userId     = User.Identity.GetUserId();
            ApplicationUser authedUser = UserManager.FindById(userId);

            try
            {
                if (string.IsNullOrWhiteSpace(vModel.Body) || string.IsNullOrWhiteSpace(vModel.Subject))
                {
                    message = "You must include a valid body and subject.";
                }
                else
                {
                    if (string.IsNullOrWhiteSpace(vModel.RecipientAccount))
                    {
                        message = "You must include a valid recipient.";
                    }
                    else
                    {
                        IAccount recipient = Account.GetByHandle(vModel.RecipientAccount);

                        if (recipient == null || recipient.Config.Acquaintences.Any(acq => acq.IsFriend == false && acq.PersonHandle.Equals(authedUser.GameAccount.GlobalIdentityHandle)))
                        {
                            message = "You must include a valid recipient.";
                        }
                        else
                        {
                            PlayerMessage newMessage = new PlayerMessage
                            {
                                Body             = vModel.Body,
                                Subject          = vModel.Subject,
                                Sender           = authedUser.GameAccount,
                                RecipientAccount = recipient
                            };

                            IPlayerTemplate recipientCharacter = TemplateCache.GetByName <IPlayerTemplate>(vModel.Recipient);

                            if (recipientCharacter != null)
                            {
                                newMessage.Recipient = recipientCharacter;
                            }

                            //messages come from players always here
                            if (newMessage.Save(authedUser.GameAccount, StaffRank.Player))
                            {
                                message = "Successfully sent.";
                            }
                            else
                            {
                                LoggingUtility.Log("Message unsuccessful.", LogChannels.SystemWarnings);
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                LoggingUtility.LogError(ex, LogChannels.SystemWarnings);
            }

            return(RedirectToAction("Notifications", new { Message = message }));
        }
Example #12
0
 /// <summary>
 /// Gets the statically formatted filename for a player
 /// </summary>
 /// <param name="entity">The player in question</param>
 /// <returns>the filename</returns>
 private string GetCharacterFilename(IPlayerTemplate entity)
 {
     return(string.Format("{0}.playertemplate", entity.Id));
 }
Example #13
0
        /// <summary>
        /// Restores one character from their Current backup
        /// </summary>
        /// <param name="accountHandle">Global Account Handle for the account</param>
        /// <param name="charID">Which character to load</param>
        /// <returns></returns>
        public IPlayer RestorePlayer(string accountHandle, IPlayerTemplate chr)
        {
            IPlayer newPlayerToLoad = null;

            try
            {
                string currentBackupDirectory = BaseDirectory + accountHandle + "/" + CurrentDirectoryName + chr.Id.ToString() + "/";

                //No backup directory? No live data.
                if (!VerifyDirectory(currentBackupDirectory, false))
                {
                    return(null);
                }

                DirectoryInfo playerDirectory = new DirectoryInfo(currentBackupDirectory);

                byte[] fileData = new byte[0];
                using (FileStream stream = File.Open(currentBackupDirectory + GetPlayerFilename(chr.Id), FileMode.Open))
                {
                    fileData = new byte[stream.Length];
                    stream.Read(fileData, 0, (int)stream.Length);
                }

                //no player file to load, derp
                if (fileData.Length == 0)
                {
                    return(null);
                }

                IPlayer blankEntity = Activator.CreateInstance(chr.EntityClass) as IPlayer;
                newPlayerToLoad = (IPlayer)blankEntity.FromBytes(fileData);

                //bad load, dump it
                if (newPlayerToLoad == null)
                {
                    return(null);
                }

                //We have the player in live cache now so make it move to the right place
                newPlayerToLoad.GetFromWorldOrSpawn();
                newPlayerToLoad.UpsertToLiveWorldCache(true);

                //We'll need one of these per container on players
                if (Directory.Exists(playerDirectory + "Inventory/"))
                {
                    DirectoryInfo inventoryDirectory = new DirectoryInfo(playerDirectory + "Inventory/");

                    foreach (FileInfo file in inventoryDirectory.EnumerateFiles())
                    {
                        IInanimate blankObject = Activator.CreateInstance("NetMud.Data", "NetMud.Data.Game.Inanimate") as IInanimate;

                        IInanimate newObj = (IInanimate)blankObject.FromBytes(ReadFile(file));
                        newObj.UpsertToLiveWorldCache(true);
                        newObj.TryMoveTo(newPlayerToLoad.GetContainerAsLocation());
                    }
                }
            }
            catch (Exception ex)
            {
                LoggingUtility.LogError(ex);
            }

            return(newPlayerToLoad);
        }
Example #14
0
        /// <summary>
        /// Validates the game account from the aspnet cookie
        /// </summary>
        /// <param name="handshake">the headers from the http request</param>
        private void ValidateUser(Cookie cookie)
        {
            //Grab the user
            GetUserIDFromCookie(cookie.Value);

            ApplicationUser authedUser = UserManager.FindById(_userId);

            IPlayerTemplate currentCharacter = authedUser.GameAccount.Characters.FirstOrDefault(ch => ch.Id.Equals(authedUser.GameAccount.CurrentlySelectedCharacter));

            if (currentCharacter == null)
            {
                Send("<p>No character selected</p>");
                return;
            }

            //Try to see if they are already live
            _currentPlayer = LiveCache.GetAll <IPlayer>().FirstOrDefault(player => player.Descriptor != null && player.Descriptor._userId == _userId);

            //Check the backup
            if (_currentPlayer == null)
            {
                PlayerData playerDataWrapper = new PlayerData();
                _currentPlayer = playerDataWrapper.RestorePlayer(currentCharacter.AccountHandle, currentCharacter);
            }

            //else new them up
            if (_currentPlayer == null)
            {
                _currentPlayer = new Player(currentCharacter);
            }

            _currentPlayer.Descriptor = this;

            //We need to barf out to the connected client the welcome message. The client will only indicate connection has been established.
            List <string> welcomeMessage = new List <string>
            {
                string.Format("Welcome to alpha phase Under the Eclipse, {0}", currentCharacter.FullName()),
                "Please feel free to LOOK around."
            };

            _currentPlayer.WriteTo(welcomeMessage);

            //Send the look command in
            Interpret.Render("look", _currentPlayer);

            try
            {
                IEnumerable <IPlayer> validPlayers = LiveCache.GetAll <IPlayer>().Where(player => player.Descriptor != null &&
                                                                                        player.Template <IPlayerTemplate>().Account.Config.WantsNotification(_currentPlayer.AccountHandle, false, AcquaintenceNotifications.EnterGame));

                foreach (IPlayer player in validPlayers)
                {
                    player.WriteTo(new string[] { string.Format("{0} has entered the game.", _currentPlayer.AccountHandle) });
                }

                if (authedUser.GameAccount.Config.GossipSubscriber)
                {
                    GossipClient gossipClient = LiveCache.Get <GossipClient>("GossipWebClient");

                    if (gossipClient != null)
                    {
                        gossipClient.SendNotification(authedUser.GlobalIdentityHandle, Notifications.EnterGame);
                    }
                }
            }
            catch (Exception ex)
            {
                LoggingUtility.LogError(ex, LogChannels.SocketCommunication);
            }
        }
Example #15
0
        /// <summary>
        /// Adds a single entity into the cache
        /// </summary>
        /// <param name="objectToCache">the entity to cache</param>
        public static void Add(IPlayerTemplate objectToCache)
        {
            PlayerDataCacheKey cacheKey = new PlayerDataCacheKey(objectToCache);

            BackingCache.Add(objectToCache, cacheKey);
        }
Example #16
0
 /// <summary>
 /// Make a new cache key using the object
 /// </summary>
 /// <param name="character">the character object</param>
 public PlayerDataCacheKey(IPlayerTemplate character)
 {
     ObjectType    = character.GetType();
     AccountHandle = character.AccountHandle;
     CharacterId   = character.Id;
 }