Exemple #1
0
        public static void LogSingleEntry(LoggerModel loggerModel, JustPressPlayDBEntities _dbContext, bool autoSave = false)
        {
            log newLogEntry = new log()
            {
                action     = loggerModel.Action,
                ip_address = loggerModel.IPAddress,
                id_type_1  = loggerModel.IDType1 == null ? null : loggerModel.IDType1,
                id_type_2  = loggerModel.IDType2 == null ? null : loggerModel.IDType2,
                id_1       = loggerModel.ID1 == null ? null : loggerModel.ID1,
                id_2       = loggerModel.ID2 == null ? null : loggerModel.ID2,
                timestamp  = loggerModel.TimeStamp,
                user_id    = loggerModel.UserID,
                value_1    = loggerModel.Value1 == null? null : loggerModel.Value1,
                value_2    = loggerModel.Value2 == null? null : loggerModel.Value2,
            };

            _dbContext.log.Add(newLogEntry);

            if (autoSave)
            {
                _dbContext.SaveChanges();
            }
        }
        private void RevokeQuest(quest_instance questInstance, int achievementID, bool autoSave)
        {
            #region Log Quest Revoke
            LoggerModel logQuestRevoke = new LoggerModel()
            {
                Action = Logger.QuestInstanceLogType.QuestRevoked.ToString(),
                UserID = questInstance.user_id,
                IPAddress = HttpContext.Current.Request.UserHostAddress,
                TimeStamp = DateTime.Now,
                ID1 = questInstance.quest_id,
                IDType1 = Logger.LogIDType.QuestTemplate.ToString(),
                Value1 = "Achievement:" + achievementID + " was revoked.",
            };
            Logger.LogSingleEntry(logQuestRevoke, _dbContext, false);
            #endregion

            _dbContext.quest_instance.Remove(questInstance);

            if(autoSave)
                Save();
        }
        private void CompleteQuest(int questID, user userToCheck, int? achievementID, bool autoSave)
        {
            if (userToCheck.status != (int)JPPConstants.UserStatus.Active || !userToCheck.is_player)
                return;

            //Check if the quest exists and is active, and if an instance already exists
            quest_template questTemplate = _dbContext.quest_template.Find(questID);
            if (questTemplate.state == (int)JPPConstants.AchievementQuestStates.Retired || _dbContext.quest_instance.Any(qi => qi.quest_id == questTemplate.id && qi.user_id == userToCheck.id))
                return;

            quest_instance newInstance = new quest_instance()
            {
                quest_id = questID,
                user_id = userToCheck.id,
                completed_date = DateTime.Now,
                comments_disabled = true
            };

            _dbContext.quest_instance.Add(newInstance);
            _unitOfWork.SystemRepository.AddNotification(
                userToCheck.id,
                userToCheck.id,
                "You completed the quest [" + questTemplate.title + "]",
                questTemplate.icon,
                new UrlHelper(HttpContext.Current.Request.RequestContext).Action(
                    "IndividualQuest",
                    "Quests",
                    new { id = questTemplate.id }
                ) + "#" + newInstance.id + "-1",
                false);

            LoggerModel logQuestUnlock = new LoggerModel()
            {
                Action = Logger.QuestInstanceLogType.QuestUnlocked.ToString(),
                UserID = userToCheck.id,
                IPAddress = HttpContext.Current.Request.UserHostAddress,
                TimeStamp = DateTime.Now,
                ID1 = questID,
                IDType1 = Logger.LogIDType.QuestTemplate.ToString(),
                ID2 = achievementID,
                IDType2 = Logger.LogIDType.AchievementTemplate.ToString(),
                Value1 = "ID2 represents the ID of the achievement that triggered the quest unlock"
            };

            Logger.LogSingleEntry(logQuestUnlock, _dbContext);

            if (autoSave)
                Save();
        }
        public void DenyUserQuest(int questID, string reason)
        {
            quest_template userQuest = _dbContext.quest_template.Find(questID);
            if (userQuest == null)
                return;
            //TODO: Change Message, Verify Action Name for URL
            _unitOfWork.SystemRepository.AddNotification(
               userQuest.creator_id,
               WebSecurity.CurrentUserId,
               "Quest Denied",
               userQuest.icon,
               new UrlHelper(HttpContext.Current.Request.RequestContext).Action(
                   "SubmitQuestIdea",
                   "Quests",
                   new { id = userQuest.id }
               ),
               false);

            LoggerModel logQuestDeny = new LoggerModel()
            {
                Action = Logger.ManageSubmissionsLogType.DeniedUserQuest.ToString(),
                UserID = WebSecurity.CurrentUserId,
                IPAddress = HttpContext.Current.Request.UserHostAddress,
                TimeStamp = DateTime.Now,
                ID1 = userQuest.creator_id,
                IDType1 = Logger.LogIDType.User.ToString(),
                Value1 = reason
            };

            Logger.LogSingleEntry(logQuestDeny, _dbContext);

            _dbContext.quest_template.Remove(userQuest);
            Save();
        }
Exemple #5
0
        public static void LogSingleEntry(LoggerModel loggerModel, JustPressPlayDBEntities _dbContext, bool autoSave = false)
        {
            log newLogEntry = new log()
            {
                action = loggerModel.Action,
                ip_address = loggerModel.IPAddress,
                id_type_1 = loggerModel.IDType1 == null ? null : loggerModel.IDType1,
                id_type_2 = loggerModel.IDType2 == null ? null : loggerModel.IDType2,
                id_1 = loggerModel.ID1 == null ? null : loggerModel.ID1,
                id_2 = loggerModel.ID2 == null ? null : loggerModel.ID2,
                timestamp = loggerModel.TimeStamp,
                user_id = loggerModel.UserID,
                value_1 = loggerModel.Value1 == null? null : loggerModel.Value1,
                value_2 = loggerModel.Value2 == null? null : loggerModel.Value2,
            };

            _dbContext.log.Add(newLogEntry);

            if (autoSave)
                _dbContext.SaveChanges();
        }
        public void AwardCard(achievement_instance instance)
        {
            if (!instance.card_given)
            {
                LoggerModel logCard = new LoggerModel()
                {
                    Action = Logger.AchievementInstanceLogType.CardGiven.ToString(),
                    UserID = WebSecurity.CurrentUserId,
                    IPAddress = HttpContext.Current.Request.UserHostAddress,
                    TimeStamp = DateTime.Now,
                    IDType1 = Logger.LogIDType.User.ToString(),
                    ID1 = instance.user_id,
                    IDType2 = Logger.LogIDType.AchievementTemplate.ToString(),
                    ID2 = instance.achievement_template.id
                };
                instance.card_given_date = DateTime.Now;
                instance.card_given = true;
            }

            Save();
        }
        //TODO: OPTIMIZE THE WAY ACHIEVEMENTS ARE ASSIGNED TO REDUCE DATABASE QUERIES AND SPEED UP THE OVERALL PROCESS
        /// <summary>
        /// Assigns an achievement
        /// TODO: Put in lots more error checking!
        /// </summary>
        /// <param name="userID">The id of the user getting the achievement</param>
        /// <param name="achievementID">The id of the achievement template</param>
        /// <param name="assignedByID">The id of the user assigning the achievement</param>
        /// <param name="cardGiven">Was the card given to the user?</param>
        public JPPConstants.AssignAchievementResult AssignAchievement(int userID, int achievementID, int? assignedByID = null, bool autoSave = true, DateTime? dateAssigned = null, bool cardGiven = false, bool isGlobal = false)
        {
            //Int value to keep track of whether a repeatable achievement can be awarded or not.
            AchievementInstanceResult instanceResult = AchievementInstanceResult.First;
            // Get the achievement template
            achievement_template template = _dbContext.achievement_template.Find(achievementID);
            // Get the user
            user user = _dbContext.user.Find(userID);

            //Get the assigner
            user assigner = _dbContext.user.Find(assignedByID);

            //Make sure the achievement can be assigned
            #region Validate Parameters
            //Make sure the achievement and user exist
            if (template == null)
                return JPPConstants.AssignAchievementResult.FailureInvalidAchievement;
            if (user == null)
                return JPPConstants.AssignAchievementResult.FailureInvalidPlayer;
            if (assigner == null && assignedByID != null)
                return JPPConstants.AssignAchievementResult.FailureInvalidAssigner;
            //Check to make sure the user is a player, and that they are not suspended,deactivate,deleted
            if (user.status != (int)JPPConstants.UserStatus.Active || !user.is_player)
                return JPPConstants.AssignAchievementResult.FailureUnauthorizedPlayer;
            // Check For Instances
            if (_dbContext.achievement_instance.Any(ai => ai.achievement_id == achievementID && ai.user_id == userID) && !template.is_repeatable)
                return JPPConstants.AssignAchievementResult.FailureAlreadyAchieved;
            //Check to see if the achievement is repeatable, and if so, has the user waited long enough since the last time they received it
            if (template.is_repeatable)
                instanceResult = CanAwardRepeatableAchievement(template, userID);
            if (instanceResult.Equals(AchievementInstanceResult.TooSoon))
                return JPPConstants.AssignAchievementResult.FailureRepetitionDelay;
            #endregion

            // Create the new instance
            achievement_instance newInstance = new achievement_instance()
            {
                achieved_date = dateAssigned == null ? DateTime.Now : (DateTime)dateAssigned,
                achievement_id = achievementID,
                assigned_by_id = assignedByID.HasValue ? assignedByID.Value : userID,
                card_given = cardGiven,
                card_given_date = cardGiven ? (Nullable<DateTime>)DateTime.Now : null,
                comments_disabled = false,
                has_user_content = false,
                has_user_story = false,
                points_create = instanceResult.Equals(AchievementInstanceResult.Repeat) ? 0 : template.points_create,
                points_explore = instanceResult.Equals(AchievementInstanceResult.Repeat) ? 0 : template.points_explore,
                points_learn = instanceResult.Equals(AchievementInstanceResult.Repeat) ? 0 : template.points_learn,
                points_socialize = instanceResult.Equals(AchievementInstanceResult.Repeat) ? 0 : template.points_socialize,
                user_content_id = null,
                user_id = userID,
                user_story_id = null,
                globally_assigned = isGlobal,
            };
            // Add the instance to the database
            _dbContext.achievement_instance.Add(newInstance);
            _unitOfWork.SystemRepository.AddNotification(
                userID,
                newInstance.assigned_by_id,
                "You earned the achievement [" + template.title + "]",
                template.icon,
                new UrlHelper(HttpContext.Current.Request.RequestContext).Action(
                    "IndividualAchievement",
                    "Achievements",
                    new { id = template.id }
                ) + "#" + newInstance.id,
                false);

            #region Facebook Sharing
            bool facebookEnabledOnSite = bool.Parse(JPPConstants.SiteSettings.GetValue(JPPConstants.SiteSettings.FacebookIntegrationEnabled));
            if (facebookEnabledOnSite)
            {
                facebook_connection fbConnectionData = _unitOfWork.UserRepository.GetUserFacebookSettingsById(userID);
                if (fbConnectionData != null)
                {
                    string appNamespace = JPPConstants.SiteSettings.GetValue(JPPConstants.SiteSettings.FacebookAppNamespace);
                    UrlHelper urlHelper = new UrlHelper(HttpContext.Current.Request.RequestContext);
                    string achievementUri = JppUriInfo.GetAbsoluteUri(new HttpRequestWrapper(HttpContext.Current.Request),
                        urlHelper.RouteUrl("AchievementsPlayersRoute", new { id = achievementID })
                        );
                    string relativeEarnedAchievementUri = urlHelper.RouteUrl("AchievementsPlayersRoute", new { id = achievementID, playerID = userID });

                    try
                    {
                        FacebookClient fbClient = new FacebookClient();

                        // Cannot send notifications unless we're a canvas app. Code implemented,
                        // but will return an OAuth error
                        /*
                        if (fbConnectionData.notifications_enabled)
                        {
                            string appAccessToken = JppFacebookHelper.GetAppAccessToken(fbClient);

                            fbClient.Post("/" + fbConnectionData.facebook_user_id + "/notifications", new
                            {
                                access_token = appAccessToken,
                                template = JPPConstants.GetFacebookNotificationMessage(template.title),
                                href = VirtualPathUtility.ToAbsolute(relativeEarnedAchievementUri),
                            });
                        }//*/

                        if (fbConnectionData.automatic_sharing_enabled)
                        {
                            fbClient.Post("/me/" + appNamespace + ":earn", new
                            {
                                access_token = fbConnectionData.access_token,
                                achievement = achievementUri
                            });
                        }
                    }
                    catch (FacebookOAuthException e)
                    {
                        // TODO: log FB error
                    }
                }
            }
            #endregion

            JPPConstants.AssignAchievementResult result = JPPConstants.AssignAchievementResult.Success;

            if (Convert.ToBoolean(JPPConstants.SiteSettings.GetValue(JPPConstants.SiteSettings.CardDistributionEnabled)))
            {
                if (cardGiven)
                {
                    result = JPPConstants.AssignAchievementResult.SuccessYesCard;
                    LoggerModel logCard = new LoggerModel()
                    {
                        Action = Logger.AchievementInstanceLogType.CardGiven.ToString(),
                        IPAddress = HttpContext.Current.Request.UserHostAddress,
                        UserID = newInstance.assigned_by_id,
                        TimeStamp = (DateTime)newInstance.card_given_date,
                        ID1 = newInstance.achievement_id,
                        IDType1 = Logger.LogIDType.AchievementTemplate.ToString(),
                    };
                    Logger.LogSingleEntry(logCard, _dbContext);
                }
                else
                    result = JPPConstants.AssignAchievementResult.SuccessNoCard;
            }

            if (template.is_repeatable)
            {
                result = JPPConstants.AssignAchievementResult.SuccessRepetition;

                if (CheckForThresholdUnlock(achievementID, userID))
                    result = JPPConstants.AssignAchievementResult.SuccessThresholdTriggered;
            }

            if (!isGlobal)
            {
                List<achievement_instance> userAchievements = _dbContext.achievement_instance.Where(ai => ai.user_id == userID).ToList().Union(_dbContext.achievement_instance.Local.Where(ai => ai.user_id == userID).ToList()).ToList();
                _unitOfWork.QuestRepository.CheckAssociatedQuestCompletion(achievementID, user, userAchievements, autoSave);
                CheckRingSystemAchievements(userID, userAchievements);
                CheckOneKAndTenKSystemAchievements(userID);
            }

            if (autoSave)
                Save();

            return result;
        }
        /// <summary>
        /// Ignores a friend request between the specified
        /// id (the source) and the logged in user (the destination)
        /// </summary>
        /// <param name="id">The id of the source of the friend request</param>
        /// <returns>True if successful, false otherwise</returns>
        public Boolean IgnoreFriendRequest(int id)
        {
            // Find the pending request
            friend_pending pending = (from f in _dbContext.friend_pending
                                      where f.source_id == id && f.destination_id == WebSecurity.CurrentUserId
                                      select f).FirstOrDefault();
            if (pending == null)
                return false;

            // Ignore pending request
            pending.ignored = true;

            LoggerModel logFriendRequest = new LoggerModel()
            {
                Action = Logger.PlayerFriendLogType.IgnoreRequest.ToString(),
                UserID = WebSecurity.CurrentUserId,
                IPAddress = HttpContext.Current.Request.UserHostAddress,
                TimeStamp = DateTime.Now,
                ID1 = id,
                IDType1 = Logger.LogIDType.User.ToString()
            };
            Logger.LogSingleEntry(logFriendRequest, _dbContext);

            _dbContext.SaveChanges();
            return true;
        }
        public Boolean UserAddAchievementStoryText(int instanceID, String text)
        {
            //Get the achievement instance, if it doesn't exist, don't continue
            achievement_instance instance = _dbContext.achievement_instance.Find(instanceID);
            if (instance == null)
                return false;

            //Set up the user story
            achievement_user_story userStory = null;
            //If the instance has a story already, get it and set userStory equal to it
            if (instance.has_user_story)
                userStory = _dbContext.achievement_user_story.Find(instance.user_story_id);
            //Make sure the userStory isn't null and then set the text equal to the new text
            if (userStory != null)
                userStory.text = text;
            else
            {
                //userStory was null create one and add it to the database
                userStory = new achievement_user_story()
                {
                    date_submitted = DateTime.Now,
                    text = text
                };

                _dbContext.achievement_user_story.Add(userStory);
                //Update the instance to include the user story
                instance.has_user_story = true;
                instance.user_story_id = userStory.id;
            }
            LoggerModel logUserStoryText = new LoggerModel()
            {
                Action = Logger.UserStoryLogType.AddStoryText.ToString(),
                UserID = instance.user_id,
                IPAddress = HttpContext.Current.Request.UserHostAddress,
                TimeStamp = DateTime.Now,
                ID1 = userStory.id,
                IDType1 = Logger.LogIDType.UserStory.ToString(),
                Value1 = text
            };
            Logger.LogSingleEntry(logUserStoryText, _dbContext);

            Save();
            return true;
        }
        private void DenyContentSubmission(achievement_user_content_pending pendingContent, string reason)
        {
            _unitOfWork.SystemRepository.AddNotification(
                pendingContent.submitted_by_id,
                WebSecurity.CurrentUserId,
                "Your submission for the achievement [" + pendingContent.achievement_template.title + "] was denied for the following reason: " + reason,
                pendingContent.achievement_template.icon, new UrlHelper(HttpContext.Current.Request.RequestContext).Action(
                    "IndividualAchievement",
                    "Achievements",
                    new { id = pendingContent.achievement_id }
                ),
                false);

            LoggerModel logSubmissionDeny = new LoggerModel()
            {
                Action = Logger.ManageSubmissionsLogType.DeniedContentSubmission.ToString(),
                UserID = WebSecurity.CurrentUserId,
                IPAddress = HttpContext.Current.Request.UserHostAddress,
                TimeStamp = DateTime.Now,
                ID1 = pendingContent.submitted_by_id,
                IDType1 = Logger.LogIDType.User.ToString(),
                ID2 = pendingContent.achievement_id,
                IDType2 = Logger.LogIDType.AchievementTemplate.ToString(),
                Value1 = reason
            };

            Logger.LogSingleEntry(logSubmissionDeny, _dbContext);

            _dbContext.achievement_user_content_pending.Remove(pendingContent);

            Save();
        }
        //TODO: MAKE THIS PRETTY AND NOT SUPER SLOW
        public void RevokeAchievement(int instanceID, string reason, bool autoSave = true, int? adminID = null)
        {
            //Get the instance
            achievement_instance instanceToRevoke = _dbContext.achievement_instance.Find(instanceID);

            if (instanceToRevoke == null)
                return;

            //Get the user
            user user = instanceToRevoke.user;
            //Get all the user's instances, minus the one being removed
            List<achievement_instance> userAchievements = _dbContext.achievement_instance.Where(ai => ai.user_id == instanceToRevoke.user_id).ToList();
            userAchievements.Remove(instanceToRevoke);

            //Get Content, Story, and Comments for the instance
            achievement_user_content userContent = instanceToRevoke.user_content;
            achievement_user_story userStory = instanceToRevoke.user_story;
            List<comment> comments = _dbContext.comment.Where(c => c.location_type == (int)JPPConstants.CommentLocation.Achievement && c.location_id == instanceID).ToList();

            #region Check Threshold Achievements
            //Get rid of threshold achievements if they no longer qualify
            if (instanceToRevoke.achievement_template.is_repeatable)
            {
                bool revokingFirstInstance = true;
                if (instanceToRevoke.points_create == 0 && instanceToRevoke.points_explore == 0 && instanceToRevoke.points_learn == 0 && instanceToRevoke.points_socialize == 0)
                    revokingFirstInstance = false;

                //If the achievement being revoked was the first one earned in a set of repeatables, set the next instance's points equal to the revoked achievement's
                List<achievement_instance> instancesOfAchievement = userAchievements.Where(ua => ua.achievement_id == instanceToRevoke.achievement_id).ToList();
                if (instancesOfAchievement != null && revokingFirstInstance)
                {
                    instancesOfAchievement[0].points_create = instanceToRevoke.points_create;
                    instancesOfAchievement[0].points_explore = instanceToRevoke.points_explore;
                    instancesOfAchievement[0].points_learn = instanceToRevoke.points_learn;
                    instancesOfAchievement[0].points_socialize = instanceToRevoke.points_socialize;
                }

                //Get all the threshold achievements.
                List<achievement_template> thresholdAchievements = _dbContext.achievement_template.Where(at => at.parent_id == instanceToRevoke.achievement_id).ToList();
                achievement_instance thresholdInstance = null;
                if (thresholdAchievements != null)
                {
                    foreach (achievement_template thresholdTemplate in thresholdAchievements)
                    {
                        //Get the instance if it exists
                        thresholdInstance = _dbContext.achievement_instance.SingleOrDefault(ai => ai.achievement_id == thresholdTemplate.id && ai.user_id == instanceToRevoke.user_id);
                        //Check the instance count vs the threshold for it
                        if (thresholdInstance != null && thresholdTemplate.threshold > instancesOfAchievement.Count)
                        {
                            RevokeAchievement(thresholdInstance.id, "Achievement:" + instanceToRevoke.achievement_id.ToString() + " was revoked.", false);
                        }
                    }
                }
            }
            #endregion

            #region Log the Achievement Revoke
            LoggerModel logAchievementRevoke = new LoggerModel()
            {
                Action = Logger.AchievementInstanceLogType.AchievementRevoked.ToString(),
                UserID = user.id,
                IPAddress = HttpContext.Current.Request.UserHostAddress,
                TimeStamp = DateTime.Now,
                ID1 = instanceToRevoke.achievement_id,
                IDType1 = Logger.LogIDType.AchievementTemplate.ToString(),
                ID2 = adminID == null ? null : adminID,
                IDType2 = adminID == null ? null : Logger.LogIDType.Admin.ToString(),
                Value1 = reason
            };
            Logger.LogSingleEntry(logAchievementRevoke, _dbContext);
            #endregion

            _unitOfWork.SystemRepository.AddNotification(
                user.id,
                WebSecurity.CurrentUserId,
                "Your achievement [" + instanceToRevoke.achievement_template.title + "] was revoked for the following reason: " + reason,
                instanceToRevoke.achievement_template.icon, new UrlHelper(HttpContext.Current.Request.RequestContext).Action(
                    "IndividualAchievement",
                    "Achievements",
                    new { id = instanceToRevoke.achievement_id }
                ),
                false);

            #region Deletion and Removal
            //Delete Associated Images
            if (userContent != null && userContent.image != null && System.IO.File.Exists(userContent.image))
            {
                System.IO.File.Delete(userContent.image);
                userContent.image = null;
            }
            if (userStory != null && userStory.image != null && System.IO.File.Exists(userStory.image))
            {
                System.IO.File.Delete(userStory.image);
                userStory.image = null;
            }

            //Remove the achievement instance from the database along with the content, story, and comments
            _dbContext.achievement_instance.Remove(instanceToRevoke);
            if (userContent != null)
                _dbContext.achievement_user_content.Remove(userContent);
            if (userStory != null)
                _dbContext.achievement_user_story.Remove(userStory);
            if (comments != null)
            {
                foreach (comment comment in comments)
                {
                    _dbContext.comment.Remove(comment);
                }
            }
            #endregion

            //Check for quest revokes
            _unitOfWork.QuestRepository.CheckAssociatedQuestCompletion(instanceToRevoke.achievement_id, user, userAchievements, false, true);

            if (autoSave)
                Save();
        }
        /// <summary>
        /// Accepts a friend request between the specified
        /// id (the source) and the logged in user (the destination)
        /// </summary>
        /// <param name="id">The id of the source of the friend request</param>
        /// <returns>True if successful, false otherwise</returns>
        public Boolean AcceptFriendRequest(int id)
        {
            // Ssame user?
            if (id == WebSecurity.CurrentUserId)
                return false;

            // Find the pending request
            friend_pending pending = (from f in _dbContext.friend_pending
                                      where f.source_id == id && f.destination_id == WebSecurity.CurrentUserId
                                      select f).FirstOrDefault();
            if (pending == null)
                return false;

            // Remove pending, then add friendships in both directions
            _dbContext.friend_pending.Remove(pending);

            friend f1 = new friend()
            {
                source_id = id,
                destination_id = WebSecurity.CurrentUserId,
                request_date = pending.request_date,
                friended_date = DateTime.Now
            };

            friend f2 = new friend()
            {
                source_id = WebSecurity.CurrentUserId,
                destination_id = id,
                request_date = pending.request_date,
                friended_date = f1.friended_date
            };

            _dbContext.friend.Add(f1);
            _dbContext.friend.Add(f2);

            _unitOfWork.AchievementRepository.CheckFriendSystemAchievements(WebSecurity.CurrentUserId);
            _unitOfWork.AchievementRepository.CheckFriendSystemAchievements(f1.source_id);
            LoggerModel logFriendRequest = new LoggerModel()
            {
                Action = Logger.PlayerFriendLogType.AcceptRequest.ToString(),
                UserID = WebSecurity.CurrentUserId,
                IPAddress = HttpContext.Current.Request.UserHostAddress,
                TimeStamp = DateTime.Now,
                ID1 = id,
                IDType1 = Logger.LogIDType.User.ToString()
            };
            Logger.LogSingleEntry(logFriendRequest, _dbContext);
            _dbContext.SaveChanges();
            return true;
        }
        /// <summary>
        /// Removes a friendship between the specified
        /// id and the logged in user
        /// </summary>
        /// <param name="id">The id of the friend to remove</param>
        /// <returns>True if successful, false otherwise</returns>
        public Boolean RemoveFriend(int id)
        {
            // Find the friendships
            friend f1 = (from f in _dbContext.friend
                         where f.source_id == id && f.destination_id == WebSecurity.CurrentUserId
                         select f).FirstOrDefault();
            friend f2 = (from f in _dbContext.friend
                         where f.source_id == WebSecurity.CurrentUserId && f.destination_id == id
                         select f).FirstOrDefault();

            // If neither exists, can't remove
            if (f1 == null && f2 == null)
                return false;

            LoggerModel logFriendRequest = new LoggerModel()
            {
                Action = Logger.PlayerFriendLogType.RemoveFriend.ToString(),
                UserID = WebSecurity.CurrentUserId,
                IPAddress = HttpContext.Current.Request.UserHostAddress,
                TimeStamp = DateTime.Now,
                ID1 = id,
                IDType1 = Logger.LogIDType.User.ToString()
            };
            Logger.LogSingleEntry(logFriendRequest, _dbContext);
            // Remove both - It should be either both or neither, but
            // during testing we may end up with just one way, so better
            // to remove the stragglers
            if (f1 != null) _dbContext.friend.Remove(f1);
            if (f2 != null) _dbContext.friend.Remove(f2);
            _dbContext.SaveChanges();
            return true;
        }
        public ActionResult Delete(int commentID)
        {
            UnitOfWork work = new UnitOfWork();

            // Grab the comment and check for edit capabilities
            comment c = work.EntityContext.comment.Find(commentID);

            // Is the current user the instance owner?
            bool instanceOwner = false;
            if (c.location_type == (int)JPPConstants.CommentLocation.Achievement)
            {
                instanceOwner = (from e in work.EntityContext.achievement_instance
                                 where e.id == c.location_id && e.user_id == WebSecurity.CurrentUserId
                                 select e).Any();
            }
            else if(c.location_type == (int)JPPConstants.CommentLocation.Quest)
            {
                instanceOwner = (from e in work.EntityContext.quest_instance
                                 where e.id == c.location_id && e.user_id == WebSecurity.CurrentUserId
                                 select e).Any();
            }

            // Instance owner, comment owner or admin?
            if (!instanceOwner && c.user_id != WebSecurity.CurrentUserId && !Roles.IsUserInRole(JPPConstants.Roles.FullAdmin))
                return new HttpStatusCodeResult(406, "Invalid credentials"); // Invalid text

            LoggerModel logCommentDelete = new LoggerModel()
            {
                Action = Logger.CommentBehaviorLogType.CommentDelete.ToString(),
                UserID = WebSecurity.CurrentUserId,
                IPAddress = Request.UserHostAddress,
                TimeStamp = DateTime.Now,
                ID1 = c.id,
                IDType1 = Logger.LogIDType.Comment.ToString(),
                Value1 = c.text
            };

            Logger.LogSingleEntry(logCommentDelete, work.EntityContext);

            // Mark as deleted
            c.deleted = true;
            c.last_modified_by_id = WebSecurity.CurrentUserId;
            c.last_modified_date = DateTime.Now;
            work.SaveChanges();

            // Get the current user's display name
            user u = work.EntityContext.user.Find(WebSecurity.CurrentUserId);

            EarningComment response = new EarningComment()
            {
                Deleted = true,
                ID = c.id,
                Text = JPPConstants.SiteSettings.DeletedCommentText + u.display_name,
                PlayerID = c.last_modified_by_id,
                DisplayName = null,
                PlayerImage = null,
                CurrentUserCanEdit = false,
                CurrentUserCanDelete = false
            };

            return Json(response); // Success
        }
        //TODO : OPTIMIZE THIS
        /// <summary>
        /// Assigns the specified achievement to all users in the system.
        /// </summary>
        /// <param name="achievementID">The ID of the achievement to assign</param>
        /// <param name="assignedByID">The ID of the User who assigned the achievement</param>
        public void AssignGlobalAchievement(int achievementID, DateTime startRange, DateTime endRange, int assignedByID)
        {
            _unitOfWork.EntityContext.Configuration.AutoDetectChangesEnabled = false;
            // Get the achievement template
            achievement_template template = _dbContext.achievement_template.Find(achievementID);
            if (template == null)
                throw new ArgumentException("Invalid achievement ID");

            bool partOfQuest = _dbContext.quest_achievement_step.Any(qas => qas.achievement_id == template.id);

            List<user> qualifiedUsers = _dbContext.user.Where(u => u.status == (int)JPPConstants.UserStatus.Active && u.is_player == true && EntityFunctions.TruncateTime(u.created_date) >= EntityFunctions.TruncateTime(startRange) && EntityFunctions.TruncateTime(u.created_date) <= EntityFunctions.TruncateTime(endRange)).ToList();

            // Loop through the user list and assign the achievement to each user.
            foreach (user user in qualifiedUsers)
            {
                AssignAchievement(user.id, achievementID, assignedByID, false, null, false, true);
            }

            List<achievement_instance> localAndDatabaseInstances = _dbContext.achievement_instance.Local.ToList().Union(_dbContext.achievement_instance.ToList()).ToList();

            //List that will hold a specific user's achievements
            List<achievement_instance> userAchievements = new List<achievement_instance>();
            //Check for quest unlocks and Ring system achievement unlocks
            foreach (user user in qualifiedUsers)
            {
                //Get only the current users achievements
                userAchievements = localAndDatabaseInstances.Where(ai => ai.user_id == user.id).ToList();
                if (partOfQuest)
                    _unitOfWork.QuestRepository.CheckAssociatedQuestCompletion(achievementID, user, userAchievements, false);
                CheckRingSystemAchievements(user.id, userAchievements);
                localAndDatabaseInstances = localAndDatabaseInstances.Except(userAchievements).ToList();
                userAchievements.Clear();
            }

            #region//Log that this was assigned
            LoggerModel logGlobal = new LoggerModel()
            {
                Action = Logger.AchievementInstanceLogType.GlobalAssigned.ToString(),
                UserID = assignedByID,
                IPAddress = HttpContext.Current.Request.UserHostAddress,
                TimeStamp = DateTime.Now,
                ID1 = achievementID,
                IDType1 = Logger.LogIDType.AchievementTemplate.ToString(),
                Value1 = "Assigned to " + qualifiedUsers.Count + " players",
            };
            Logger.LogSingleEntry(logGlobal, _dbContext);
            #endregion
            _unitOfWork.EntityContext.Configuration.AutoDetectChangesEnabled = true;
            Save();

            CheckOneKAndTenKSystemAchievements(assignedByID);
        }
        public ActionResult Edit(int commentID, String text)
        {
            // Need text for a comment
            if (String.IsNullOrWhiteSpace(text))
                return new HttpStatusCodeResult(406, "Invalid comment text"); // Invalid text

            UnitOfWork work = new UnitOfWork();

            // Grab the comment and check for edit capabilities
             			comment c = work.EntityContext.comment.Find(commentID);
            if (c.deleted)
                return new HttpStatusCodeResult(406, "Cannot edit: Comment has been deleted"); // Deleted comment
            if (c.user_id != WebSecurity.CurrentUserId && !Roles.IsUserInRole(JPPConstants.Roles.FullAdmin))
                return new HttpStatusCodeResult(406, "Cannot edit: User has insufficient privileges"); // Not admin or original commenter

            // Edit the comment
            LoggerModel logCommentEdit = new LoggerModel()
            {
                Action = Logger.CommentBehaviorLogType.CommentEdit.ToString(),
                UserID = WebSecurity.CurrentUserId,
                IPAddress = Request.UserHostAddress,
                TimeStamp = DateTime.Now,
                ID1 = c.id,
                IDType1 = Logger.LogIDType.Comment.ToString(),
                Value1 = c.text,
                Value2 = text
            };

            Logger.LogSingleEntry(logCommentEdit, work.EntityContext);

            c.text = text;
            c.last_modified_by_id = WebSecurity.CurrentUserId;
            c.last_modified_date = DateTime.Now;
            work.SaveChanges();

            EditCommentResponseModel response = new EditCommentResponseModel()
            {
                Text = text
            };

            return Json(response);
        }
        /// <summary>
        /// Attempts to add a friend (sends a request)
        /// </summary>
        /// <param name="id">The id of the user to add as a friend</param>
        /// <returns>True if successful, false otherwise</returns>
        public Boolean AddFriend(int id)
        {
            // Can't be us!
            if (id == WebSecurity.CurrentUserId)
                return false;

            // Get the user and make sure they're playing
            user u = GetUser(id);
            if (u == null || !u.is_player || u.status != (int)JPPConstants.UserStatus.Active)
                return false;

            // Are we already friends?
            bool alreadyFriends = (from f in _dbContext.friend
                                   where ((f.source_id == id && f.destination_id == WebSecurity.CurrentUserId) ||
                                           (f.source_id == WebSecurity.CurrentUserId && f.destination_id == id))
                                   select f).Any();
            if (alreadyFriends)
                return false;

            // Pending friend invite?
            bool alreadyPending = (from f in _dbContext.friend_pending
                                   where ((f.source_id == id && f.destination_id == WebSecurity.CurrentUserId) ||
                                           (f.source_id == WebSecurity.CurrentUserId && f.destination_id == id))
                                   select f).Any();
            if (alreadyPending)
                return false;

            // Create the new pending request
            friend_pending friend = new friend_pending()
            {
                source_id = WebSecurity.CurrentUserId,
                destination_id = u.id,
                ignored = false,
                request_date = DateTime.Now
            };
            _dbContext.friend_pending.Add(friend);
            LoggerModel logFriendRequest = new LoggerModel()
            {
                Action = Logger.PlayerFriendLogType.AddFriend.ToString(),
                UserID = WebSecurity.CurrentUserId,
                IPAddress = HttpContext.Current.Request.UserHostAddress,
                TimeStamp = DateTime.Now,
                ID1 = id,
                IDType1 = Logger.LogIDType.User.ToString()
            };
            Logger.LogSingleEntry(logFriendRequest, _dbContext);

            Save();
            return true;
        }