public void GuardAgainstNullMessageModel()
        {
            Action action = () => _sut.Execute(null);

            action.Should()
            .Throw <ArgumentNullException>()
            .WithMessage("Value cannot be null. (Parameter 'messageModel')");
        }
예제 #2
0
        public async Task SendPrivateMessageFromSubverse()
        {
            var id        = Guid.NewGuid().ToString();
            var sender    = "unit";
            var recipient = "User100CCP";

            TestHelper.SetPrincipal("unit");

            var message = new Domain.Models.SendMessage()
            {
                Sender    = $"v/{sender}",
                Recipient = recipient,
                Subject   = id,
                Message   = id
            };
            var cmd      = new SendMessageCommand(message);
            var response = await cmd.Execute();

            Assert.IsNotNull(response, "Response is null");
            Assert.IsTrue(response.Success, response.Status.ToString());

            using (var db = new voatEntities())
            {
                var record = (from x in db.Messages
                              where
                              x.Sender == sender &&
                              x.SenderType == (int)Domain.Models.IdentityType.Subverse &&
                              x.Recipient == recipient &&
                              x.RecipientType == (int)Domain.Models.IdentityType.User &&
                              x.Title == id &&
                              x.Content == id
                              select x).FirstOrDefault();
                Assert.IsNotNull(record, "Can not find message in database");
            }
        }
        public async Task <ActionResult> Compose(NewMessageViewModel message)
        {
            //ViewBag.PmView = "compose";
            //ViewBag.Title = "Compose";

            //set this incase invalid submittal
            var userData = UserData;

            message.RequireCaptcha = userData.Information.CommentPoints.Sum < VoatSettings.Instance.MinimumCommentPointsForCaptchaMessaging && VoatSettings.Instance.CaptchaEnabled;

            if (!ModelState.IsValid)
            {
                return(View(message));
            }

            if (message.Recipient == null || message.Subject == null || message.Body == null)
            {
                return(RedirectToAction("Sent", "Messages"));
            }

            if (message.RequireCaptcha)
            {
                bool isCaptchaValid = await ReCaptchaUtility.Validate(Request);

                if (!isCaptchaValid)
                {
                    ModelState.AddModelError(string.Empty, "Incorrect recaptcha answer.");
                    return(View(message));
                }
            }
            var sendMessage = new SendMessage()
            {
                Recipient = message.Recipient,
                Message   = message.Body,
                Subject   = message.Subject,
                Sender    = message.Sender
            };
            var cmd      = new SendMessageCommand(sendMessage, false, true).SetUserContext(User);
            var response = await cmd.Execute();



            if (response.Success)
            {
                var m = response.Response;
                if (m.SenderType == IdentityType.Subverse)
                {
                    return(RedirectToAction("SubverseIndex", "Messages", new { subverse = m.Sender, type = MessageTypeFlag.Sent, state = MessageState.All }));
                }
                else
                {
                    return(RedirectToAction("Sent", "Messages"));
                }
            }
            else
            {
                ModelState.AddModelError(string.Empty, response.Message);
                return(View(message));
            }
        }
        public async Task SendPrivateMessageFromSubverse()
        {
            var id        = Guid.NewGuid().ToString();
            var sender    = "unit";
            var recipient = USERNAMES.User100CCP;

            var user = TestHelper.SetPrincipal(sender);

            var message = new Domain.Models.SendMessage()
            {
                Sender    = $"v/{sender}",
                Recipient = recipient,
                Subject   = id,
                Message   = id
            };
            var cmd = new SendMessageCommand(message).SetUserContext(user);
            var r   = await cmd.Execute();

            VoatAssert.IsValid(r);

            using (var db = new VoatDataContext())
            {
                var record = (from x in db.Message
                              where
                              x.Sender == sender &&
                              x.SenderType == (int)Domain.Models.IdentityType.Subverse &&
                              x.Recipient == recipient &&
                              x.RecipientType == (int)Domain.Models.IdentityType.User &&
                              x.Title == id &&
                              x.Content == id
                              select x).FirstOrDefault();
                Assert.IsNotNull(record, "Can not find message in database");
            }
        }
예제 #5
0
 private void Send_Click(object sender, EventArgs e)
 {
     if (SendMessageCommand != null)
     {
         SendMessageCommand.Execute(null);
     }
 }
        public async Task SendBadRecipientInfo_CheckExists()
        {
            var id     = Guid.NewGuid().ToString();
            var sender = USERNAMES.User100CCP;

            var user = TestHelper.SetPrincipal(sender);
            var cmd  = new SendMessageCommand(new Domain.Models.SendMessage()
            {
                Recipient = "Do you like chocolate", Message = id, Subject = "All That Matters"
            }, false, true).SetUserContext(user);
            var response = await cmd.Execute();

            VoatAssert.IsValid(response, Status.Error);

            Assert.AreNotEqual("Comment points too low to send messages. Need at least 10 CCP.", response.Message);

            using (var db = new VoatDataContext())
            {
                var count = (from x in db.Message
                             where
                             x.Content == id
                             select x).Count();
                Assert.AreEqual(0, count, "Expecting no messages to make it through");
            }
        }
예제 #7
0
        public async Task SendPrivateMessage()
        {
            var id        = Guid.NewGuid().ToString();
            var sender    = "User100CCP";
            var recipient = "anon";

            TestHelper.SetPrincipal(sender);

            var message = new Domain.Models.SendMessage()
            {
                //Sender = User.Identity.Name,
                Recipient = recipient,
                Subject   = id,
                Message   = id
            };
            var cmd      = new SendMessageCommand(message);
            var response = await cmd.Execute();

            Assert.IsNotNull(response, "Response is null");
            Assert.IsTrue(response.Success, response.Status.ToString());

            using (var db = new voatEntities())
            {
                var record = (from x in db.Messages
                              where
                              x.Recipient == recipient &&
                              x.Sender == sender &&
                              x.Title == id &&
                              x.Content == id &&
                              x.Subverse == null &&
                              x.CommentID == null &&
                              x.SubmissionID == null &&
                              x.Type == (int)Domain.Models.MessageType.Sent
                              //&& x.Direction == (int)Domain.Models.MessageDirection.OutBound
                              select x).FirstOrDefault();
                Assert.IsNotNull(record, "Can not find outbound in database");

                record = (from x in db.Messages
                          where
                          x.Recipient == recipient &&
                          x.Sender == sender &&
                          x.Title == id &&
                          x.Content == id &&
                          x.Subverse == null &&
                          x.CommentID == null &&
                          x.SubmissionID == null &&
                          x.Type == (int)Domain.Models.MessageType.Private
                          //&& x.Direction == (int)Domain.Models.MessageDirection.InBound
                          select x).FirstOrDefault();
                Assert.IsNotNull(record, "Can not find inbound in database");
            }
        }
        public async Task SendPrivateMessage()
        {
            var id        = Guid.NewGuid().ToString();
            var sender    = USERNAMES.User100CCP;
            var recipient = USERNAMES.Anon;

            var user = TestHelper.SetPrincipal(sender);

            var message = new Domain.Models.SendMessage()
            {
                //Sender = User.Identity.Name,
                Recipient = recipient,
                Subject   = id,
                Message   = id
            };
            var cmd      = new SendMessageCommand(message).SetUserContext(user);
            var response = await cmd.Execute();

            VoatAssert.IsValid(response);

            using (var db = new VoatDataContext())
            {
                var record = (from x in db.Message
                              where
                              x.Recipient == recipient &&
                              x.Sender == sender &&
                              x.Title == id &&
                              x.Content == id &&
                              x.Subverse == null &&
                              x.CommentID == null &&
                              x.SubmissionID == null &&
                              x.Type == (int)Domain.Models.MessageType.Sent
                              //&& x.Direction == (int)Domain.Models.MessageDirection.OutBound
                              select x).FirstOrDefault();
                Assert.IsNotNull(record, "Can not find outbound in database");

                record = (from x in db.Message
                          where
                          x.Recipient == recipient &&
                          x.Sender == sender &&
                          x.Title == id &&
                          x.Content == id &&
                          x.Subverse == null &&
                          x.CommentID == null &&
                          x.SubmissionID == null &&
                          x.Type == (int)Domain.Models.MessageType.Private
                          //&& x.Direction == (int)Domain.Models.MessageDirection.InBound
                          select x).FirstOrDefault();
                Assert.IsNotNull(record, "Can not find inbound in database");
            }
        }
예제 #9
0
        public void TestInitialize()
        {
            //create user inbox
            Message message = null;

            TestHelper.SetPrincipal(userName);
            var msg = "1";
            var cmd = new SendMessageCommand(new Domain.Models.SendMessage()
            {
                Subject = "Chain", Recipient = "TestUser1", Message = msg
            });
            var response = cmd.Execute().Result;

            Assert.IsTrue(response.Success, "Expecting true on send");
            Assert.IsNotNull(response.Response, "Expecting non-null response");
            message = response.Response;
            messages.Add(message);

            TestHelper.SetPrincipal("TestUser1");
            msg = "1.1";
            var cmdReply      = new SendMessageReplyCommand(message.ID, msg);
            var responseReply = cmdReply.Execute().Result;

            Assert.IsTrue(responseReply.Success, "Expecting true on send");
            Assert.IsNotNull(responseReply.Response, "Expecting non-null response");
            message = responseReply.Response;
            messages.Add(message);


            TestHelper.SetPrincipal(userName);
            msg           = "1.1.1";
            cmdReply      = new SendMessageReplyCommand(message.ID, msg);
            responseReply = cmdReply.Execute().Result;
            Assert.IsTrue(responseReply.Success, "Expecting true on send");
            Assert.IsNotNull(responseReply.Response, "Expecting non-null response");
            message = responseReply.Response;
            messages.Add(message);

            TestHelper.SetPrincipal("TestUser1");
            msg           = "1.1.1.1";
            cmdReply      = new SendMessageReplyCommand(message.ID, msg);
            responseReply = cmdReply.Execute().Result;
            Assert.IsTrue(responseReply.Success, "Expecting true on send");
            Assert.IsNotNull(responseReply.Response, "Expecting non-null response");
            message = responseReply.Response;
            messages.Add(message);
        }
예제 #10
0
 private void PreviewKeyDown(KeyEventArgs e)
 {
     if (e.Key == Key.Enter &&
         SendMessageCommand.CanExecute(null))
     {
         SendMessageCommand.Execute(null);
         LocalChatState = ChatStateEvent.Paused;
     }
     else if (e.Key == Key.Delete || e.Key == Key.Back)
     {
         LocalChatState = ChatStateEvent.Deleting;
     }
     else
     {
         LocalChatState = ChatStateEvent.Composing;
     }
 }
예제 #11
0
        public async Task SendPrivateMessageDeniedCCP()
        {
            var id        = Guid.NewGuid().ToString();
            var sender    = "unit";
            var recipient = "anon";

            TestHelper.SetPrincipal(sender);

            var message = new Domain.Models.SendMessage()
            {
                //Sender = User.Identity.Name,
                Recipient = recipient,
                Subject   = id,
                Message   = id
            };
            var cmd      = new SendMessageCommand(message);
            var response = await cmd.Execute();

            Assert.IsNotNull(response, "Response is null");
            Assert.IsFalse(response.Success, "Expecting not success response");
        }
예제 #12
0
        public async Task SendPrivateMessageDeniedCCP()
        {
            var id        = Guid.NewGuid().ToString();
            var sender    = USERNAMES.Unit;
            var recipient = USERNAMES.Anon;

            var user = TestHelper.SetPrincipal(sender);

            var message = new Domain.Models.SendMessage()
            {
                //Sender = User.Identity.Name,
                Recipient = recipient,
                Subject   = id,
                Message   = id
            };
            var cmd      = new SendMessageCommand(message).SetUserContext(user);
            var response = await cmd.Execute();

            VoatAssert.IsValid(response, Status.Ignored);
            Assert.IsNotNull(response, "Response is null");
            Assert.IsFalse(response.Success, "Expecting not success response");
        }
예제 #13
0
        public async Task SendBadRecipientInfo()
        {
            var id     = Guid.NewGuid().ToString();
            var sender = "User100CCP";

            TestHelper.SetPrincipal(sender);
            var cmd = new SendMessageCommand(new Domain.Models.SendMessage()
            {
                Recipient = "Do you like chocolate", Message = id, Subject = "All That Matters"
            }, false, false);
            var response = await cmd.Execute();

            Assert.IsTrue(response.Success, "Expecting success");
            Assert.AreEqual(null, response.Response, "Expecting null return payload");
            using (var db = new voatEntities())
            {
                var count = (from x in db.Messages
                             where
                             x.Content == id
                             select x).Count();
                Assert.AreEqual(0, count, "Expecting no messages to make it through");
            }
        }
예제 #14
0
        public async Task SendBadRecipientInfo_CheckExists()
        {
            var id     = Guid.NewGuid().ToString();
            var sender = "User100CCP";

            TestHelper.SetPrincipal(sender);
            var cmd = new SendMessageCommand(new Domain.Models.SendMessage()
            {
                Recipient = "Do you like chocolate", Message = id, Subject = "All That Matters"
            }, false, true);
            var response = await cmd.Execute();

            Assert.IsFalse(response.Success, "Expecting failure");
            Assert.AreNotEqual("Comment points too low to send messages. Need at least 10 CCP.", response.Message);

            using (var db = new voatEntities())
            {
                var count = (from x in db.Messages
                             where
                             x.Content == id
                             select x).Count();
                Assert.AreEqual(0, count, "Expecting no messages to make it through");
            }
        }
        public async Task <ActionResult> AcceptModeratorInvitation(int invitationId)
        {
            int maximumOwnedSubs = VoatSettings.Instance.MaximumOwnedSubs;

            //TODO: These errors are not friendly - please update to redirect or something
            // check if there is an invitation for this user with this id
            var userInvitation = _db.ModeratorInvitation.Find(invitationId);

            if (userInvitation == null)
            {
                return(ErrorView(new ErrorViewModel()
                {
                    Title = "Moderator Invite Not Found", Description = "The moderator invite is no longer valid", Footer = "Where did it go?"
                }));
                //return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }

            // check if logged in user is actually the invited user
            if (!User.Identity.Name.IsEqual(userInvitation.Recipient))
            {
                return(ErrorView(ErrorViewModel.GetErrorViewModel(HttpStatusCode.Unauthorized)));
                //return new HttpStatusCodeResult(HttpStatusCode.Unauthorized);
            }

            // check if user is over modding limits
            var amountOfSubsUserModerates = _db.SubverseModerator.Where(s => s.UserName.ToLower() == User.Identity.Name.ToLower());

            if (amountOfSubsUserModerates.Any())
            {
                if (amountOfSubsUserModerates.Count() >= maximumOwnedSubs)
                {
                    return(ErrorView(new ErrorViewModel()
                    {
                        Title = "Maximum Moderation Level Exceeded", Description = $"Sorry, you can not own or moderate more than {maximumOwnedSubs} subverses.", Footer = "That's too bad"
                    }));
                }
            }

            // check if subverse exists
            var subverse = _db.Subverse.FirstOrDefault(s => s.Name.ToLower() == userInvitation.Subverse.ToLower());

            if (subverse == null)
            {
                return(ErrorView(ErrorViewModel.GetErrorViewModel(ErrorType.SubverseNotFound)));
                //return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }

            // check if user is already a moderator of this sub
            var userModerating = _db.SubverseModerator.Where(s => s.Subverse.ToLower() == userInvitation.Subverse.ToLower() && s.UserName.ToLower() == User.Identity.Name.ToLower());

            if (userModerating.Any())
            {
                _db.ModeratorInvitation.Remove(userInvitation);
                _db.SaveChanges();
                return(ErrorView(new ErrorViewModel()
                {
                    Title = "You = Moderator * 2?", Description = "You are currently already a moderator of this subverse", Footer = "How much power do you want?"
                }));
                //return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }

            // add user as moderator as specified in invitation
            var subAdm = new SubverseModerator
            {
                Subverse     = subverse.Name,
                UserName     = UserHelper.OriginalUsername(userInvitation.Recipient),
                Power        = userInvitation.Power,
                CreatedBy    = UserHelper.OriginalUsername(userInvitation.CreatedBy),
                CreationDate = Repository.CurrentDate
            };

            _db.SubverseModerator.Add(subAdm);

            // notify sender that user has accepted the invitation
            var message = new Domain.Models.SendMessage()
            {
                Sender    = $"v/{subverse.Name}",
                Subject   = $"Moderator invitation for v/{subverse.Name} accepted",
                Recipient = userInvitation.CreatedBy,
                Message   = $"User {User.Identity.Name} has accepted your invitation to moderate subverse v/{subverse.Name}."
            };
            var cmd = new SendMessageCommand(message).SetUserContext(User);
            await cmd.Execute();

            //clear mod cache
            CacheHandler.Instance.Remove(CachingKey.SubverseModerators(subverse.Name));

            // delete the invitation from database
            _db.ModeratorInvitation.Remove(userInvitation);
            _db.SaveChanges();

            return(RedirectToAction("Update", "SubverseModeration", new { subverse = subverse.Name }));
            //return Update(subverse.Name);
        }
예제 #16
0
        public override void ClassInitialize()
        {
            var user2 = "TestUser01";
            //create user inbox
            Message message = null;

            var user = TestHelper.SetPrincipal(userName);
            var msg  = "1";
            var cmd  = new SendMessageCommand(new Domain.Models.SendMessage()
            {
                Subject = "Chain", Recipient = "TestUser01", Message = msg
            }).SetUserContext(user);
            var response = cmd.Execute().Result;

            VoatAssert.IsValid(response);

            message = response.Response;
            messages.Add(message);

            user = TestHelper.SetPrincipal(user2);
            //Find message
            var query = new QueryMessages(user, MessageTypeFlag.Private, MessageState.Unread, false).SetUserContext(user);
            var inbox = query.Execute();

            VoatAssert.IsValid(inbox);
            message = inbox.FirstOrDefault(x => x.Sender == USERNAMES.User50CCP && x.Content == msg);
            Assert.IsNotNull(message, "Can not find message in recipient inbox 1");

            msg = "1.1";
            var cmdReply      = new SendMessageReplyCommand(message.ID, msg).SetUserContext(user);
            var responseReply = cmdReply.Execute().Result;

            VoatAssert.IsValid(responseReply);
            messages.Add(message);


            user = TestHelper.SetPrincipal(userName);
            //Find message
            query = new QueryMessages(user, MessageTypeFlag.Private, MessageState.Unread, false).SetUserContext(user);
            inbox = query.Execute();
            VoatAssert.IsValid(inbox);
            message = inbox.FirstOrDefault(x => x.Sender == user2 && x.Content == msg);
            Assert.IsNotNull(message, "Can not find message in recipient inbox 2");

            msg           = "1.1.1";
            cmdReply      = new SendMessageReplyCommand(message.ID, msg).SetUserContext(user);
            responseReply = cmdReply.Execute().Result;
            VoatAssert.IsValid(responseReply);

            message = responseReply.Response;
            messages.Add(message);

            user = TestHelper.SetPrincipal(user2);
            //Find message
            query = new QueryMessages(user, MessageTypeFlag.Private, MessageState.Unread, false).SetUserContext(user);
            inbox = query.Execute();
            VoatAssert.IsValid(inbox);
            message = inbox.FirstOrDefault(x => x.Sender == USERNAMES.User50CCP && x.Content == msg);
            Assert.IsNotNull(message, "Can not find message in recipient inbox 3");

            msg           = "1.1.1.1";
            cmdReply      = new SendMessageReplyCommand(message.ID, msg).SetUserContext(user);
            responseReply = cmdReply.Execute().Result;
            VoatAssert.IsValid(responseReply);

            message = responseReply.Response;
            messages.Add(message);
        }
예제 #17
0
        public async Task <ActionResult> ReportSubmission(int id)
        {
            var s = _db.Submissions.Find(id);

            if (s != null)
            {
                // prepare report headers
                var subverse = s.Subverse;

                //don't allow banned users to send reports
                if (!UserHelper.IsUserBannedFromSubverse(User.Identity.Name, subverse) && !UserHelper.IsUserGloballyBanned(User.Identity.Name))
                {
                    var reportTimeStamp = Repository.CurrentDate.ToString(CultureInfo.InvariantCulture);
                    try
                    {
                        string cacheKeyReport = CachingKey.ReportKey(ContentType.Submission, id);

                        //see if comment has been reported before
                        if (CacheHandler.Instance.Retrieve <object>(cacheKeyReport) == null)
                        {
                            //mark comment in cache as having been reported
                            CacheHandler.Instance.Register(cacheKeyReport, new Func <object>(() => { return(new object()); }), contentReportTimeOut, -1);


                            string userName = User.Identity.Name;
                            string cacheKeyUserReportCount = CachingKey.ReportCountUserKey(ContentType.Submission, userName);
                            int    reportsPerUserThreshold = 5;

                            var reportCountViaUser = CacheHandler.Instance.Retrieve <int?>(cacheKeyUserReportCount);
                            //ensure user is below reporting threshold
                            if (reportCountViaUser == null || reportCountViaUser.Value <= reportsPerUserThreshold)
                            {
                                //add or update cache with current user reports
                                if (reportCountViaUser.HasValue)
                                {
                                    CacheHandler.Instance.Replace <int?>(cacheKeyUserReportCount, new Func <int?, int?>((x) => { return((int?)(x.Value + 1)); }), contentUserCountTimeOut);
                                }
                                else
                                {
                                    CacheHandler.Instance.Register <int?>(cacheKeyUserReportCount, new Func <int?>(() => { return((int?)1); }), contentUserCountTimeOut, -1);
                                }

                                string body = String.Format("This submission has been reported:\r\n\r\nhttps://voat.co/v/{0}/{1}\r\n\r\n\r\nReport Spammers to v/ReportSpammers.", s.Subverse, s.ID);

                                var message = new Domain.Models.SendMessage()
                                {
                                    Sender    = s.IsAnonymized ? "Anon" : userName,
                                    Recipient = $"v/{subverse}",
                                    Subject   = "Submission Spam Report",
                                    Message   = body
                                };
                                var cmd = new SendMessageCommand(message, true);
                                await cmd.Execute();

                                //MesssagingUtility.SendPrivateMessage(commentToReport.IsAnonymized ? "Anon" : userName, String.Format("v/{0}", commentSubverse), "Comment Spam Report", body);
                            }
                        }
                    }
                    catch (Exception)
                    {
                        return(new HttpStatusCodeResult(HttpStatusCode.ServiceUnavailable, "Service Unavailable"));
                    }
                }
            }
            else
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest, "Bad Request"));
            }

            return(new HttpStatusCodeResult(HttpStatusCode.OK, "OK"));
        }
예제 #18
0
        public async Task SendPrivateMessageToSubverse()
        {
            var id       = Guid.NewGuid().ToString();
            var sender   = "User100CCP";
            var subverse = "unit";

            //ensure v/Unit has moderators
            using (var db = new voatEntities())
            {
                var record = (from x in db.SubverseModerators
                              where
                              x.Subverse == subverse
                              select x).ToList();
                var mod = "anon";
                if (!record.Any(x => x.UserName == mod))
                {
                    db.SubverseModerators.Add(new SubverseModerator()
                    {
                        UserName = mod, Subverse = subverse, CreatedBy = "UnitTesting", CreationDate = DateTime.UtcNow, Power = 1
                    });
                }
                mod = "unit";
                if (!record.Any(x => x.UserName == mod))
                {
                    db.SubverseModerators.Add(new SubverseModerator()
                    {
                        UserName = mod, Subverse = subverse, CreatedBy = "UnitTesting", CreationDate = DateTime.UtcNow, Power = 1
                    });
                }
                db.SaveChanges();
            }

            TestHelper.SetPrincipal(sender);

            var message = new Domain.Models.SendMessage()
            {
                //Sender = User.Identity.Name,
                Recipient = $"v/{subverse}",
                Subject   = id,
                Message   = id
            };
            var cmd      = new SendMessageCommand(message);
            var response = await cmd.Execute();

            Assert.IsNotNull(response, "Response is null");
            Assert.IsTrue(response.Success, response.Status.ToString());

            using (var db = new voatEntities())
            {
                var record = (from x in db.Messages
                              where
                              x.Sender == sender &&
                              x.SenderType == (int)Domain.Models.IdentityType.User &&
                              x.Recipient == subverse &&
                              x.RecipientType == (int)Domain.Models.IdentityType.Subverse &&
                              x.Title == id &&
                              x.Content == id
                              select x).ToList();
                Assert.IsNotNull(record, "Can not find message in database");
                Assert.AreEqual(2, record.Count, "Expecting 2 PMs");
            }
        }
        public async Task <ActionResult> AddModerator([Bind("ID,Subverse,UserName,Power")] SubverseModerator subverseAdmin)
        {
            if (!ModelState.IsValid)
            {
                return(View(subverseAdmin));
            }

            // check if caller can add mods, if not, deny posting
            if (!ModeratorPermission.HasPermission(User, subverseAdmin.Subverse, Domain.Models.ModeratorAction.InviteMods))
            {
                return(RedirectToAction("Index", "Home"));
            }

            subverseAdmin.UserName = subverseAdmin.UserName.TrimSafe();
            Subverse subverseModel = null;

            //lots of premature retuns so wrap the common code
            var sendFailureResult = new Func <string, ActionResult>(errorMessage =>
            {
                ViewBag.SubverseModel    = subverseModel;
                ViewBag.SubverseName     = subverseAdmin.Subverse;
                ViewBag.SelectedSubverse = string.Empty;
                ModelState.AddModelError(string.Empty, errorMessage);
                SetNavigationViewModel(subverseAdmin.Subverse);

                return(View("~/Views/Subverses/Admin/AddModerator.cshtml",
                            new SubverseModeratorViewModel
                {
                    UserName = subverseAdmin.UserName,
                    Power = subverseAdmin.Power
                }
                            ));
            });

            // prevent invites to the current moderator
            if (User.Identity.Name.IsEqual(subverseAdmin.UserName))
            {
                return(sendFailureResult("Can not add yourself as a moderator"));
            }

            string originalRecipientUserName = UserHelper.OriginalUsername(subverseAdmin.UserName);

            // prevent invites to the current moderator
            if (String.IsNullOrEmpty(originalRecipientUserName))
            {
                return(sendFailureResult("User can not be found"));
            }

            // get model for selected subverse
            subverseModel = DataCache.Subverse.Retrieve(subverseAdmin.Subverse);
            if (subverseModel == null)
            {
                return(ErrorView(ErrorViewModel.GetErrorViewModel(ErrorType.SubverseNotFound)));
            }

            if ((subverseAdmin.Power < 1 || subverseAdmin.Power > 4) && subverseAdmin.Power != 99)
            {
                return(sendFailureResult("Only powers levels 1 - 4 and 99 are supported currently"));
            }

            //check current mod level and invite level and ensure they are a lower level
            var currentModLevel = ModeratorPermission.Level(User, subverseModel.Name);

            if (subverseAdmin.Power <= (int)currentModLevel && currentModLevel != Domain.Models.ModeratorLevel.Owner)
            {
                return(sendFailureResult("Sorry, but you can only add moderators that are a lower level than yourself"));
            }

            int maximumOwnedSubs = VoatSettings.Instance.MaximumOwnedSubs;

            // check if the user being added is not already a moderator of 10 subverses
            var currentlyModerating = _db.SubverseModerator.Where(a => a.UserName == originalRecipientUserName).ToList();

            SubverseModeratorViewModel tmpModel;

            if (currentlyModerating.Count <= maximumOwnedSubs)
            {
                // check that user is not already moderating given subverse
                var isAlreadyModerator = _db.SubverseModerator.FirstOrDefault(a => a.UserName == originalRecipientUserName && a.Subverse == subverseAdmin.Subverse);

                if (isAlreadyModerator == null)
                {
                    // check if this user is already invited
                    var userModeratorInvitations = _db.ModeratorInvitation.Where(i => i.Recipient.ToLower() == originalRecipientUserName.ToLower() && i.Subverse.ToLower() == subverseModel.Name.ToLower());
                    if (userModeratorInvitations.Any())
                    {
                        return(sendFailureResult("Sorry, the user is already invited to moderate this subverse"));
                    }

                    // send a new moderator invitation
                    ModeratorInvitation modInv = new ModeratorInvitation
                    {
                        CreatedBy    = User.Identity.Name,
                        CreationDate = Repository.CurrentDate,
                        Recipient    = originalRecipientUserName,
                        Subverse     = subverseAdmin.Subverse,
                        Power        = subverseAdmin.Power
                    };

                    _db.ModeratorInvitation.Add(modInv);
                    _db.SaveChanges();
                    int invitationId   = modInv.ID;
                    var invitationBody = new StringBuilder();

                    //v/{subverse}/about/moderatorinvitations/accept/{invitationId}

                    string acceptInviteUrl = VoatUrlFormatter.BuildUrlPath(this.HttpContext, new PathOptions(true, true), $"/v/{subverseModel.Name}/about/moderatorinvitations/accept/{invitationId}");

                    invitationBody.Append("Hello,");
                    invitationBody.Append(Environment.NewLine);
                    invitationBody.Append($"@{User.Identity.Name} invited you to moderate v/" + subverseAdmin.Subverse + ".");
                    invitationBody.Append(Environment.NewLine);
                    invitationBody.Append(Environment.NewLine);
                    invitationBody.Append($"Please visit the following link if you want to accept this invitation: {acceptInviteUrl}");
                    invitationBody.Append(Environment.NewLine);
                    invitationBody.Append(Environment.NewLine);
                    invitationBody.Append("Thank you.");

                    var cmd = new SendMessageCommand(new Domain.Models.SendMessage()
                    {
                        Sender    = $"v/{subverseAdmin.Subverse}",
                        Recipient = originalRecipientUserName,
                        Subject   = $"v/{subverseAdmin.Subverse} moderator invitation",
                        Message   = invitationBody.ToString()
                    }, true).SetUserContext(User);
                    await cmd.Execute();

                    return(RedirectToAction("SubverseModerators"));
                }
                else
                {
                    return(sendFailureResult("Sorry, the user is already moderating this subverse"));
                }
            }
            else
            {
                return(sendFailureResult("Sorry, the user is already moderating a maximum of " + maximumOwnedSubs + " subverses"));
            }
        }
예제 #20
0
 private void ElapsedTimerTick(object sender, ElapsedEventArgs e)
 {
     SendMessageCommand?.Execute(null);
 }
예제 #21
0
        public async Task SendPrivateMessageReply()
        {
            var id        = Guid.NewGuid().ToString();
            var sender    = USERNAMES.User100CCP;
            var recipient = "anon";

            var user = TestHelper.SetPrincipal(sender);

            var message = new Domain.Models.SendMessage()
            {
                //Sender = User.Identity.Name,
                Recipient = recipient,
                Subject   = id,
                Message   = id
            };
            var cmd      = new SendMessageCommand(message).SetUserContext(user);
            var response = await cmd.Execute();

            VoatAssert.IsValid(response);

            var firstMessage  = response.Response;
            var idToRespondTo = 0;

            //Ensure first msg is in db
            using (var db = new VoatDataContext())
            {
                var record = (from x in db.Message
                              where
                              x.Recipient == recipient &&
                              x.Sender == sender &&
                              x.Title == id &&
                              x.Content == id &&
                              x.Subverse == null &&
                              x.CommentID == null &&
                              x.SubmissionID == null &&
                              x.Type == (int)Domain.Models.MessageType.Sent
                              //&& x.Direction == (int)Domain.Models.MessageDirection.OutBound
                              select x).FirstOrDefault();
                Assert.IsNotNull(record, "Can not find sent in database");

                record = (from x in db.Message
                          where
                          x.Recipient == recipient &&
                          x.Sender == sender &&
                          x.Title == id &&
                          x.Content == id &&
                          x.Subverse == null &&
                          x.CommentID == null &&
                          x.SubmissionID == null &&
                          x.Type == (int)Domain.Models.MessageType.Private
                          //&& x.Direction == (int)Domain.Models.MessageDirection.InBound
                          select x).FirstOrDefault();
                Assert.IsNotNull(record, "Can not find message in database");

                idToRespondTo = record.ID;
            }

            //reply
            user = TestHelper.SetPrincipal(recipient);
            var replyCmd      = new SendMessageReplyCommand(idToRespondTo, $"Reply to {idToRespondTo.ToString()}").SetUserContext(user);
            var replyResponse = await replyCmd.Execute();

            VoatAssert.IsValid(replyResponse);

            var replyMessage = replyResponse.Response;

            Assert.AreEqual(idToRespondTo, replyMessage.ParentID);
        }