public object GetActionData(ListenTo.Shared.DO.Action action)
        {
            CommentOnNewsItemActionData commentOnNewsItemActionData = new CommentOnNewsItemActionData();
            Comment comment = CommentManager.GetByID(action.ContentID);

            if (comment != null)
            {
                NewsItem newsItem = NewsItemManager.GetByID(comment.TargetId);

                if (newsItem != null)
                {
                    commentOnNewsItemActionData.NewsItem = newsItem;
                }
                else
                {
                    throw new Exception("NewsItem does not exist or is deleted");
                }
            }
            else
            {
                throw new Exception("Comment doesnt exist!");
            }

            return commentOnNewsItemActionData;
        }
        public IList<ListenTo.Shared.DO.UserProfile> ResolveUsersToInformAboutAction(ListenTo.Shared.DO.Action action)
        {
            IList<UserProfile> userProfiles = new List<UserProfile>();
            UserProfile newsItemOwnerUserProfile = null;
            Comment comment = CommentManager.GetByID(action.ContentID);

            if (comment != null)
            {
                NewsItem newsItem = NewsItemManager.GetByID(comment.TargetId);

                //Ensure that the news exists and isnt deleted
                if (newsItem != null && newsItem.IsDeleted==false)
                {
                    Guid ownerId = newsItem.OwnerID;
                    newsItemOwnerUserProfile = UserProfileManager.GetByID(ownerId);
                }
                else
                {
                    throw new Exception("NewsItem does not exist or is deleted");
                }

                userProfiles.Add(newsItemOwnerUserProfile);
            }
            else
            {
                throw new Exception("Comment does not exist");
            }

            return userProfiles;
        }
Пример #3
0
        public ListenTo.Shared.DO.NewsItem Save(ListenTo.Shared.Interfaces.DO.IDO dO, ListenTo.Shared.DO.UserCredentials userCredentials)
        {
            NewsItem newsItem = (NewsItem)dO;

            this.CheckOwnership(newsItem, userCredentials);

            bool isValid = ValidationRunner.Validate(newsItem, userCredentials);

            bool isNew = this.CheckIsNew(newsItem, userCredentials);

            newsItem =  this.Repository.SaveNewsItem(newsItem);

            if (isNew)
            {
                ListenTo.Shared.DO.Action action = new ListenTo.Shared.DO.Action();
                action.ActionType = ActionType.ADDED_A_NEWS_ITEM;
                action.ContentType = ContentType.NEWSITEM;
                action.ContentID = newsItem.ID;

                foreach (Site site in newsItem.TargetSites)
                {
                    action.TargetSites.Add(site.ID);
                }

                action.OwnerID = newsItem.OwnerID;
                ActionsManager.AddAction(action, userCredentials);
            }

            return newsItem;
        }
Пример #4
0
        public ListenTo.Shared.DO.Comment Save(ListenTo.Shared.Interfaces.DO.IDO dO, ListenTo.Shared.DO.UserCredentials userCredentials)
        {
            ListenTo.Shared.DO.Comment comment = (ListenTo.Shared.DO.Comment)dO;

            this.CheckOwnership(comment, userCredentials);

            //Construct an action
            //The actual action type is dependent upon the content type of the comment
            //should check is new here
            comment = this.Repository.SaveComment(comment);

            //Using the factory try to grab an IActionForCommentBuilder instance
            //We will use this to build the action.
            IActionForCommentBuilder actionForCommentBuilder = ActionForCommentBuilderFactory.GetBuilder(comment);

            ListenTo.Shared.DO.Action action = null;

            if (actionForCommentBuilder != null)
            {
                //we can build an action!
                action = actionForCommentBuilder.BuildAction(comment);
            }

            if (action != null)
            {
                //We have an action, so save it
                ActionsManager.AddAction(action, userCredentials);
            }

            return comment;
        }
Пример #5
0
        public ValidationStateDictionary Validate(ListenTo.Shared.DO.BaseDO domainObject, ListenTo.Shared.DO.UserCredentials userCredentials)
        {
            ValidationStateDictionary validationStateDictionary = new ValidationStateDictionary();

            Gig gig = (Gig)domainObject;

            if (gig.Name == string.Empty)
            {
                validationStateDictionary.AddValidationError("Name", ValidationStateKeys.GIG_NEEDS_A_NAME);
            }
            else if (gig.Name.Length > 100)
            {
                validationStateDictionary.AddValidationError("Name", ValidationStateKeys.GIG_NAME_IS_TOO_LONG);
            }

            if (gig.Description.Length > 6000)
            {
                validationStateDictionary.AddValidationError("Name", ValidationStateKeys.GIG_DESCRIPTION_IS_TOO_LONG);
            }

            if (gig.Venue== null)
            {
                validationStateDictionary.AddValidationError("Venue", ValidationStateKeys.GIG_NEEDS_A_VENUE);
            }

            if (gig.Acts == null || (gig.Acts!=null && gig.Acts.Count==0))
            {
                validationStateDictionary.AddValidationError("Acts", ValidationStateKeys.GIG_NEEDS_AT_LEAST_ONE_ACT);
            }

            return validationStateDictionary;
        }
        public IList<ListenTo.Shared.DO.UserProfile> ResolveUsersToInformAboutAction(ListenTo.Shared.DO.Action action)
        {
            IList<UserProfile> userProfiles = new List<UserProfile>();
            Comment comment = CommentManager.GetByID(action.ContentID);

            if (comment != null)
            {
                UserProfile userProfile = UserProfileManager.GetByID(comment.TargetId);

                if (userProfile != null)
                {
                    userProfiles.Add(userProfile);
                }
                else
                {
                    throw new Exception("UserProfile  does not exist");
                }
            }
            else
            {
                throw new Exception("Comment does not exist");
            }

            return userProfiles;
        }
        public ValidationStateDictionary Validate(ListenTo.Shared.DO.BaseDO domainObject, ListenTo.Shared.DO.UserCredentials userCredentials)
        {
            ValidationStateDictionary validationStateDictionary = new ValidationStateDictionary();

            Track track = (Track)domainObject;

            if (track.Style == null)
            {
                validationStateDictionary.AddValidationError("Style", ValidationStateKeys.TRACK_NEEDS_A_STYLE);
            }

            if (track.Artist == null)
            {
                validationStateDictionary.AddValidationError("Artist", ValidationStateKeys.TRACK_NEEDS_AN_ARTIST);
            }

            if (track.Name.Trim() == string.Empty)
            {
                validationStateDictionary.AddValidationError("Name", ValidationStateKeys.TRACK_NEEDS_A_NAME);
            }

            if (track.Data == null)
            {
                validationStateDictionary.AddValidationError("Data", ValidationStateKeys.TRACK_NEEDS_AN_MP3);
            }
            else if( !ListenTo.Shared.Helpers.TrackHelpers.TrackContainsMP3Data(track))
            {
                validationStateDictionary.AddValidationError("Data", ValidationStateKeys.TRACK_NEEDS_A_VALID_MP3);
            }

            return validationStateDictionary;
        }
        public object GetActionData(ListenTo.Shared.DO.Action action)
        {
            CommentOnUserProfileActionData commentOnUserProfileActionData = new CommentOnUserProfileActionData();
            Comment comment = CommentManager.GetByID(action.ContentID);

            if (comment != null)
            {
                UserProfile userProfile = UserProfileManager.GetByID(comment.TargetId);

                if (userProfile != null)
                {
                    commentOnUserProfileActionData.UserProfile = userProfile;
                }
                else
                {
                    throw new Exception("UserProfile does not exist or is deleted");
                }
            }
            else
            {
                throw new Exception("Comment doesnt exist!");
            }

            return commentOnUserProfileActionData;
        }
Пример #9
0
 public ImageMetaData Adapt(ListenTo.Shared.DO.Image image)
 {
     ImageMetaData imageMetaData = new ImageMetaData();
     imageMetaData.ID = image.ID;
     imageMetaData.Height = image.Height;
     imageMetaData.Width = image.Width;
     imageMetaData.Thumbnail = image.Thumbnail;
     return imageMetaData;
 }
        public void PublishAction(ListenTo.Shared.DO.Action action)
        {
            IList<IActionPublisher> publishers = ActionPublisherFactory.GetPublishers(action);

            foreach (IActionPublisher publisher in publishers)
            {
                WaitCallbackData data = new WaitCallbackData(publisher, action);
                ThreadPool.QueueUserWorkItem(new WaitCallback(Publish), data);
            }
        }
Пример #11
0
        public static bool TrackContainsMP3Data(ListenTo.Shared.DO.Track track)
        {
            bool containsMP3Data = false;

            if (track!=null && track.Data!=null)
            {
                containsMP3Data = ContainsMP3Data(track.Data);
            }
            return containsMP3Data;
        }
Пример #12
0
        public ListenTo.Shared.DO.UserProfile Save(ListenTo.Shared.Interfaces.DO.IDO dO, UserCredentials userCredentials)
        {
            UserProfile userProfile = (UserProfile)dO;

               //This will throw an exception if the data model is invalid.
               bool isValid = ValidationRunner.Validate(userProfile, userCredentials);

               this.Repository.SaveUserProfile(userProfile);
               return userProfile;
        }
Пример #13
0
        public bool DoesRelationshipExist(ListenTo.Shared.DO.Relationship relationship)
        {
            var qry = from r in DBContext.Relationships
                      where r.SourceID == relationship.SourceId &&
                      r.TargetID == relationship.TargetId
                      select r.ID;
            int count = qry.Count();

            return count > 0;
        }
Пример #14
0
        public bool CheckOwnership(ListenTo.Shared.DO.BaseDO baseDO, UserCredentials userCredentials)
        {
            IOwnershipHelper helper = OwnershipHelperFactory.CreateHelper(baseDO);
            bool isOwner = helper.IsOwner(baseDO, userCredentials);

            if (isOwner == false)
            {
                throw new Exception("The user does not own this object");
            }

            return isOwner;
        }
Пример #15
0
        public bool CheckIsNew(ListenTo.Shared.DO.BaseDO baseDO, UserCredentials userCredentials)
        {
            IIsNewHelper helper = IsNewHelperFactory.CreateHelper(baseDO);

            if (helper == null)
            {
                throw new Exception("There isnt a IsNewHelper defined for this");
            }

            bool isNew = helper.IsNew(baseDO, userCredentials);

            return isNew;
        }
        public ValidationStateDictionary Validate(ListenTo.Shared.DO.BaseDO domainObject, ListenTo.Shared.DO.UserCredentials userCredentials)
        {
            ValidationStateDictionary validationStateDictionary = new ValidationStateDictionary();

            Comment commentDO = (Comment)domainObject;

            if (commentDO.Body == string.Empty)
            {
                validationStateDictionary.AddValidationError(ValidationStateKeys.COMMENT_BODY_INVALID);
            }

            return validationStateDictionary;
        }
        public IActionDataHelper CreateHelper(ListenTo.Shared.DO.Action action)
        {
            IActionDataHelper foundHelper = null;

            string actionName = Enum.GetName(typeof(ActionType), action.ActionType);

            if (this.ActionDataHelpers.ContainsKey(actionName))
            {
                foundHelper = this.ActionDataHelpers[actionName];
            }

            return foundHelper;
        }
Пример #18
0
        public ValidationStateDictionary Validate(ListenTo.Shared.DO.BaseDO domainObject, ListenTo.Shared.DO.UserCredentials userCredentials)
        {
            ValidationStateDictionary validationStateDictionary = new ValidationStateDictionary();

            Image image = (Image)domainObject;

            if (image.Data == null || image.Data.Length==0)
            {
                validationStateDictionary.AddValidationError("Data", ValidationStateKeys.FILE_NEEDS_DATA);
            }
            else if(!ListenTo.Shared.Helpers.ImageHelpers.IsFileImage(image.Data))
            {
                validationStateDictionary.AddValidationError("Data", ValidationStateKeys.FILE_IS_NOT_AN_IMAGE);
            }
            return validationStateDictionary;
        }
Пример #19
0
        public static string ActionOwnerLink(this HtmlHelper helper, ListenTo.Shared.DO.Action action, string defaultLinkText, object htmlAttributes)
        {
            string friendlyUsername = defaultLinkText;
            string username = action.OwnerUsername;
            string url = helper.ViewWhoIsUrl(username);
            if (!helper.IsOwner(action))
            {
                friendlyUsername = username;
            }

            var builder = new TagBuilder("a");
            builder.SetInnerText(friendlyUsername);
            builder.Attributes.Add("href", url);
            builder.MergeAttributes(new RouteValueDictionary(htmlAttributes));
            return builder.ToString();
        }
        public ValidationStateDictionary Validate(ListenTo.Shared.DO.BaseDO domainObject, ListenTo.Shared.DO.UserCredentials userCredentials)
        {
            ValidationStateDictionary validationStateDictionary = new ValidationStateDictionary();

            Artist artist = (Artist)domainObject;

            if (artist.Town == null)
            {
                validationStateDictionary.AddValidationError("Town", ValidationStateKeys.ARTIST_NEEDS_A_TOWN);
            }

            if (artist.Style == null)
            {
                validationStateDictionary.AddValidationError("Style", ValidationStateKeys.ARTIST_NEEDS_A_STYLE);
            }

            if (artist.ProfileAddress == string.Empty)
            {
                validationStateDictionary.AddValidationError("ProfileAddress", ValidationStateKeys.ARTIST_NEEDS_A_PROFILE_ADDRESS);
            }
            else
            {
                if (!FormatHelpers.IsAlphaNumeric(artist.ProfileAddress))
                {
                    validationStateDictionary.AddValidationError("ProfileAddress", ValidationStateKeys.ARTIST_PROFILE_ADDRESS_MUST_BE_ALPHA_NUMERIC);
                }

                Artist artistWithProfileAddress = ArtistManager.GetByProfileAddress(artist.ProfileAddress);
                if (artistWithProfileAddress != null && artistWithProfileAddress.ID != artist.ID)
                {
                    validationStateDictionary.AddValidationError("ProfileAddress", ValidationStateKeys.ARTIST_PROFILE_ADDRESS_MUST_BE_UNIQUE);
                }
            }

            if (artist.Name == string.Empty)
            {
                validationStateDictionary.AddValidationError("Name", ValidationStateKeys.ARTIST_NEEDS_A_NAME);
            }

            if (artist.Email != string.Empty && !FormatHelpers.IsEmail(artist.Email))
            {
                validationStateDictionary.AddValidationError("Email", ValidationStateKeys.ARTIST_EMAIL_ADDRESS_INVALID);
            }

            return validationStateDictionary;
        }
Пример #21
0
        /// <summary>
        /// 
        /// </summary>
        /// <param name="baseDO"></param>
        /// <param name="userCredentials">The credentials of the user who wants to access the object</param>
        /// <returns></returns>
        public bool IsOwner(ListenTo.Shared.DO.BaseDO baseDO, UserCredentials userCredentials)
        {
            IOwnershipHelper helper = OwnershipHelperFactory.CreateHelper(baseDO);

            if (helper == null)
            {
                throw new Exception("There isnt a IOwnershipHelper defined for this");
            }

            bool isOwner = helper.IsOwner(baseDO, userCredentials);

            if (isOwner == false)
            {
                throw new Exception("The user does not own this object");
            }

            return isOwner;
        }
Пример #22
0
        public ValidationStateDictionary Validate(ListenTo.Shared.DO.BaseDO domainObject, ListenTo.Shared.DO.UserCredentials userCredentials)
        {
            ValidationStateDictionary validationStateDictionary = new ValidationStateDictionary();

            Venue venueDO = (Venue)domainObject;

            if (venueDO.Name == string.Empty)
            {
                validationStateDictionary.AddValidationError(ValidationStateKeys.VENUE_NEEDS_NAME);
            }

            if (venueDO.Name.Length > 50)
            {
                validationStateDictionary.AddValidationError(ValidationStateKeys.VENUE_NAME_IS_TOO_LONG);
            }

            return validationStateDictionary;
        }
Пример #23
0
        public void Publish(ListenTo.Shared.DO.Action action)
        {
            object data = ActionDataHelper.GetActionData(action);
            action.ActionData = data;

            IList<UserProfile> usersToEmail = UsersToInformAboutActionResolver.ResolveUsersToInformAboutAction(action);

            Hashtable templateParameters = null;
            string bodyTemplate;
            string subjectTemplate;

            foreach(UserProfile profile in usersToEmail){

                //Check that we have an email address and ensure we dont email the owner of the content!
                if(profile.Email!=string.Empty && profile.ID!=action.OwnerID){

                    try
                    {

                        templateParameters = new Hashtable();
                        templateParameters.Add("Action", action);
                        templateParameters.Add("UsersToEmail", usersToEmail);

                        //This shouldnt be static!
                        bodyTemplate = TemplateHelpers.GetTemplateFromFilename(BodyTemplateFilename);

                        //This shouldnt be static!
                        subjectTemplate = TemplateHelpers.GetTemplateFromFilename(SubjectTemplateFilename);

                        subjectTemplate = TempateEngine.Process(subjectTemplate, templateParameters);

                        bodyTemplate = TempateEngine.Process(bodyTemplate, templateParameters);

                        EmailSender.Send(MailHelpers.GetSourceEmailAddressForOutboundMail(), profile.Email, subjectTemplate, bodyTemplate);
                    }
                    catch (Exception e)
                    {
                        //swallow this and log it
                        //just because one of the emails failed doesnt men we dont want the others sent..

                    }
                }
            }
        }
        public ValidationStateDictionary Validate(ListenTo.Shared.DO.BaseDO domainObject, ListenTo.Shared.DO.UserCredentials userCredentials)
        {
            ValidationStateDictionary validationStateDictionary = new ValidationStateDictionary();

            NewsItem newsItem = (NewsItem)domainObject;

            if (newsItem.Name.Trim() == string.Empty)
            {
                validationStateDictionary.AddValidationError("Name", ValidationStateKeys.NEWSITEM_NEEDS_A_NAME);
            }
            else if(newsItem.Name.Length> 50)
            {
                validationStateDictionary.AddValidationError("Name", ValidationStateKeys.NEWSITEM_NAME_IS_TOO_LONG);
            }

            if (newsItem.Description.Trim() == string.Empty)
            {
                validationStateDictionary.AddValidationError("Description", ValidationStateKeys.NEWSITEM_NEEDS_A_DESCRIPTION);
            }
            else if (newsItem.Description.Length > 200)
            {
                validationStateDictionary.AddValidationError("Description", ValidationStateKeys.NEWSITEM_DESCRIPTION_IS_TOO_LONG);
            }

            if (newsItem.Body.Trim() == string.Empty)
            {
                validationStateDictionary.AddValidationError("Body", ValidationStateKeys.NEWSITEM_NEEDS_A_BODY);
            }
            //else if (newsItem.Body.Length > 6000)
            //{
            //    validationStateDictionary.AddValidationError("Body", ValidationStateKeys.NEWSITEM_BODY_IS_TOO_LONG);
            //}

            if (newsItem.TargetSites == null || newsItem.TargetSites.Count == 0) {
                validationStateDictionary.AddValidationError("TargetSites", ValidationStateKeys.NEWSITEM_SHOULD_BE_PUBLISHED_TO_AT_LEAST_ONE_SITE);
            }

            return validationStateDictionary;
        }
Пример #25
0
        public void Publish(ListenTo.Shared.DO.Action action)
        {
            LOG.Info("Publish an action to twitter");

            try
            {
                //This executes in a seperate thread
                //which doesnt have access to the request scopes linqtosql repository
                //until ive solved this we cant use the ActionDataHelper

                object data = ActionDataHelper.GetActionData(action);
                action.ActionData = data;
                string url = ActionUrlHelper.GetUrl(action);

                url = UrlShortener.ShortenUrl(url);

                Hashtable templateParameters = new Hashtable();
                templateParameters.Add("Action", action);
                templateParameters.Add("Url", url);
                string templatePath = TemplateFilename;

                templatePath = TemplateHelpers.GetTemplateFromFilename(TemplateFilename);

                string content = TempateEngine.Process(templatePath, templateParameters);

                //var twitter = FluentTwitter.CreateRequest()
                //    .AuthenticateAs(TWITTER_USERNAME, TWITTER_PASSWORD)
                //    .Statuses().Update(content)
                //    .AsJson();

                //var response = twitter.Request();
            }
            catch (Exception e)
            {
                LOG.Error("Error Tweeting", e);
                //log here
                throw;
            }
        }
Пример #26
0
        public ValidationStateDictionary Validate(ListenTo.Shared.DO.BaseDO domainObject, ListenTo.Shared.DO.UserCredentials userCredentials)
        {
            ValidationStateDictionary validationStateDictionary = new ValidationStateDictionary();

            UserProfile userProfileDO = (UserProfile)domainObject;

            if (userProfileDO.Forename != null && userProfileDO.Forename.Length > 50)
            {
                validationStateDictionary.AddValidationError("Forename", ValidationStateKeys.USERPROFILE_FORENAME_IS_TOO_LONG);
            }

            if (userProfileDO.Surname!=null && userProfileDO.Surname.Length > 50)
            {
                validationStateDictionary.AddValidationError("Surname", ValidationStateKeys.USERPROFILE_SURNAME_IS_TOO_LONG);
            }

            if (userProfileDO.Profile!=null && userProfileDO.Profile.Length > 1000)
            {
                validationStateDictionary.AddValidationError("Profile", ValidationStateKeys.USERPROFILE_PROFILE_IS_TOO_LONG);
            }

            return validationStateDictionary;
        }
        /// <summary>
        /// Constructs an action for a comment associated with a news item
        /// </summary>
        /// <param name="comment"></param>
        /// <returns></returns>
        public ListenTo.Shared.DO.Action BuildAction(ListenTo.Shared.DO.Comment comment)
        {
            //Load the content so we can determine the site its associated with
            NewsItem newsItem = NewsItemManager.GetByID(comment.TargetId);

            if (newsItem == null)
            {
                throw new Exception("Cannot create Action for NewsItem Comment. NewsItem does not exist");
            }

            ListenTo.Shared.DO.Action action = new ListenTo.Shared.DO.Action();
            action.ContentID = comment.ID;
            action.ContentType = ContentType.COMMENT;
            action.ActionType = ActionType.COMMENTED_ON_A_NEWSITEM;
            action.Created = DateTime.Now;
            action.TargetSites = new List<Guid>();
            action.OwnerID = comment.OwnerID;
            foreach(Site site in newsItem.TargetSites){
                action.TargetSites.Add(site.ID);
            }

            return action;
        }
        public ListenTo.Shared.DO.Action BuildAction(ListenTo.Shared.DO.Comment comment)
        {
            //Load the content so we can determine the site its associated with
            UserProfile userProfile = UserProfileManager.GetByID(comment.TargetId);

            if (userProfile == null)
            {
                throw new Exception("Cannot create Action for UserProfile Comment. UserProfile does not exist");
            }

            ListenTo.Shared.DO.Action action = new ListenTo.Shared.DO.Action();
            action.ContentID = comment.ID;
            action.ContentType = ContentType.COMMENT;
            action.ActionType = ActionType.COMMENTED_ON_A_USERPROFILE;
            action.Created = DateTime.Now;
            action.TargetSites = new List<Guid>();
            action.OwnerID = comment.OwnerID;

            foreach(Site site in userProfile.Town.Sites){
                action.TargetSites.Add(site.ID);
            }

            return action;
        }
 public WaitCallbackData(IActionPublisher actionPublisher, ListenTo.Shared.DO.Action action)
 {
     ActionPublisher = actionPublisher;
     Action = action;
 }
Пример #30
0
 /// <summary>
 /// CHNAGE THIS SO WE PASS IN THE BYTE ARRAY - currently this will read the stream which is forward only!
 /// WE WILL NOT BE ABLE TO REACCESS THE DATA!!!
 /// </summary>
 /// <param name="postedFile"></param>
 /// <returns></returns>
 //public static bool IsFileMp3(HttpPostedFileBase postedFile)
 //{
 //    bool isFileAudio = false;
 //    if(IsFileAudio(postedFile)) {
 //        ListenTo.Core.Audio.MP3Info mp3Info = new ListenTo.Core.Audio.MP3Info();
 //        isFileAudio = mp3Info.ReadMP3Information(postedFile.InputStream);
 //    }
 //    return isFileAudio;
 //}
 public static ListenTo.Shared.DO.Image UpdateImageFromRequest(ListenTo.Shared.DO.Image image, HttpRequestBase request, string key)
 {
     ListenTo.Shared.DO.Image tempImage = GetImageFromRequest(request, key);
     if (tempImage != null)
     {
         image.Width = tempImage.Width;
         image.Height = tempImage.Height;
         image.Data = tempImage.Data;
     }
     return image;
 }
Пример #31
0
        public static OperationResult Pregame(Abyxa abyxa, bool serverBrowser, CustomGame cg, Map[] maps, int minimumPlayers, CancellationToken cs)
        {
            int       prevPlayerCount = 0;
            Stopwatch pregame         = new Stopwatch();
            Stopwatch skirmish        = new Stopwatch();

            skirmish.Start();

            // Create the PlayerTracker
            PlayerTracker playerTracker = new PlayerTracker();
            // Add the $SWAPME command
            ListenTo swapMeCommand = new ListenTo(command: "$SWAPME", listen: true, getNameAndProfile: true, checkIfFriend: false, callback: (commandData) => OnSwapMe(commandData, cg, playerTracker));

            cg.Commands.ListenTo.Add(swapMeCommand);

            if (abyxa != null)
            {
                abyxa.ZombieServer.Mode = Abyxa.Pregame;
                UpdateMap(abyxa, cg);
                abyxa.Update();
            }

            cg.Chat.SwapChannel(Channel.Match);

            // Make game publc if there is less than 7 players.
            if (serverBrowser)
            {
                if (cg.AllCount < 7)
                {
                    cg.Settings.JoinSetting = Join.Everyone;
                }
                else
                {
                    cg.Settings.JoinSetting = Join.InviteOnly;
                }
            }

            try
            {
                while (true)
                {
                    if (cs.IsCancellationRequested)
                    {
                        return(OperationResult.Canceled);
                    }

                    if (cg.IsDisconnected())
                    {
                        return(OperationResult.Disconnected);
                    }

                    if (abyxa != null)
                    {
                        abyxa.Update();
                    }

                    cg.TrackPlayers(playerTracker, SlotFlags.BlueAndRed | SlotFlags.IngameOnly);

                    if (skirmish.ElapsedMilliseconds >= 300 * 1000)
                    {
                        cg.RestartGame();
                        prevPlayerCount = 0;
                        skirmish.Restart();
                        cg.Chat.SwapChannel(Channel.Match);

                        string currentMap = UpdateMap(abyxa, cg) ?? "Unknown";
                        Log("Restarting the game. New map: " + currentMap);
                    }

                    InviteQueueToGame(abyxa, cg, minimumPlayers);

                    var invitedSlots = cg.GetInvitedSlots();
                    int playerCount  = PlayingCount - invitedSlots.Count;

                    // update server
                    if (abyxa != null)
                    {
                        abyxa.ZombieServer.PlayerCount  = playerCount;
                        abyxa.ZombieServer.InvitedCount = invitedSlots.Count;
                        abyxa.Update();
                    }

                    // Send a message when someone joins
                    if (playerCount > prevPlayerCount)
                    {
                        int wait = minimumPlayers - playerCount;
                        if (wait > 1)
                        {
                            cg.Chat.SendChatMessage("Welcome to Zombies! Waiting for " + wait + " more players. I am a bot, source is at the github repository ItsDeltin/Overwatch-Custom-Game-Automation");
                        }
                        if (wait == 1)
                        {
                            cg.Chat.SendChatMessage("Welcome to Zombies! Waiting for " + wait + " more player. I am a bot, source is at the github repository ItsDeltin/Overwatch-Custom-Game-Automation");
                        }
                        if (wait < 0)
                        {
                            cg.Chat.SendChatMessage("Welcome to Zombies! Game will be starting soon. I am a bot, source is at the github repository ItsDeltin/Overwatch-Custom-Game-Automation");
                        }
                    }
                    prevPlayerCount = playerCount;

                    if (!pregame.IsRunning && playerCount >= minimumPlayers)
                    {
                        cg.Chat.SendChatMessage("Enough players have joined, starting game in 15 seconds.");
                        pregame.Start();
                    }

                    // if too many players leave, cancel the countdown.
                    if (pregame.IsRunning == true && playerCount < minimumPlayers)
                    {
                        cg.Chat.SendChatMessage("Players left, waiting for " + (minimumPlayers - playerCount) + " more players, please wait.");
                        pregame.Reset();
                    }

                    if (serverBrowser && cg.Settings.JoinSetting == Join.Everyone && PlayingCount >= 7)
                    {
                        cg.Settings.JoinSetting = Join.InviteOnly;
                    }
                    else if (serverBrowser && cg.Settings.JoinSetting == Join.InviteOnly && PlayingCount < 7)
                    {
                        cg.Settings.JoinSetting = Join.Everyone;
                    }

                    // if the amount of players equals 7 or the queue list is empty and there is enough players,
                    // and the pregame timer elapsed 15 seconds,
                    // and there is no one invited and loading,
                    // start the game.
                    if (pregame.ElapsedMilliseconds >= 15 * 1000)
                    {
                        SetupGame(abyxa, serverBrowser, cg, maps);
                        return(OperationResult.Success);
                    }
                }
            }
            finally
            {
                playerTracker.Dispose();
                cg.Commands.ListenTo.Remove(swapMeCommand);
            }
        } // Pregame
    public static Map VoteForMap(CustomGame cg, Map[] maps, Gamemode enabledGamemodes, OWEvent currentEvent, bool logResults)
    {
        if (maps.Length < 3)
        {
            throw new ArgumentException($"{nameof(maps)} must have at least 3 maps.", nameof(maps));
        }

        Map[] voteForMaps = Get3RandomMaps(maps);

        List <Vote> voteResults = new List <Vote>();
        ListenTo    voteCommand = new ListenTo("$VOTE", true, false, false, (cd) => OnVote(cd, voteResults, voteForMaps, logResults));

        cg.Commands.Listen = true;

        // Send the maps to vote for to the chat.
        cg.Chat.SwapChannel(Channel.Match); // Join the match channel
        cg.Chat.SendChatMessage(FormatMessage(
                                    "Vote for map! (15 seconds)",
                                    voteForMaps[0].ShortName + " - $VOTE 1",
                                    voteForMaps[1].ShortName + " - $VOTE 2",
                                    voteForMaps[2].ShortName + " - $VOTE 3"));

        // Listen to the "$VOTE" command for 15 seconds.
        cg.Commands.ListenTo.Add(voteCommand);
        Thread.Sleep(15000);
        cg.Commands.ListenTo.Remove(voteCommand);
        // Get results
        int[] results = new int[3]
        {
            voteResults.Count(vr => vr.VotingFor == 1),
            voteResults.Count(vr => vr.VotingFor == 2),
            voteResults.Count(vr => vr.VotingFor == 3)
        };

        Map winningmap = voteForMaps[Array.IndexOf(results, results.Max())];

        // Dispose all chat identities.
        foreach (Vote voteResult in voteResults)
        {
            voteResult.ChatIdentity.Dispose();
        }
        voteResults = new List <Vote>();

        // Print the results to the chat
        string mapResults = String.Format("{0}: {1} votes, {2}: {3} votes, {4}: {5} votes",
                                          voteForMaps[0].ShortName, results[0],
                                          voteForMaps[1].ShortName, results[1],
                                          voteForMaps[2].ShortName, results[2]);

        cg.Chat.SendChatMessage(mapResults);

        if (logResults)
        {
            Console.WriteLine(mapResults);
            Console.WriteLine("Next map: " + winningmap.ShortName);
        }
        cg.Chat.SendChatMessage("Next map: " + winningmap.ShortName);
        cg.ToggleMap(enabledGamemodes, currentEvent, ToggleAction.DisableAll, winningmap);

        return(winningmap);
    }