public static TestableChat GetTestableChat(string connectionId, StateChangeTracker clientState, ChatUser user, IDictionary<string, Cookie> cookies) { // setup things needed for chat var repository = new InMemoryRepository(); var resourceProcessor = new Mock<IResourceProcessor>(); var chatService = new Mock<IChatService>(); var connection = new Mock<IConnection>(); var settings = new Mock<IApplicationSettings>(); var mockPipeline = new Mock<IHubPipelineInvoker>(); // add user to repository repository.Add(user); // create testable chat var chat = new TestableChat(settings, resourceProcessor, chatService, repository, connection); var mockedConnectionObject = chat.MockedConnection.Object; chat.Clients = new HubConnectionContext(mockPipeline.Object, mockedConnectionObject, "Chat", connectionId, clientState); var prinicipal = new Mock<IPrincipal>(); var request = new Mock<IRequest>(); request.Setup(m => m.Cookies).Returns(cookies); request.Setup(m => m.User).Returns(prinicipal.Object); // setup context chat.Context = new HubCallerContext(request.Object, connectionId); return chat; }
public void CanDeserializeClientState() { var clientState = new TrackingDictionary(); string clientId = "1"; var user = new ChatUser { Id = "1234", Name = "John" }; var cookies = new NameValueCollection(); cookies["jabbr.state"] = JsonConvert.SerializeObject(new ClientState { UserId = user.Id }); TestableChat chat = GetTestableChat(clientId, clientState, user, cookies); bool result = chat.Join(); Assert.Equal("1234", clientState["id"]); Assert.Equal("John", clientState["name"]); Assert.True(result); chat.MockedConnection.Verify(m => m.Broadcast("Chat." + clientId, It.IsAny<object>()), Times.Once()); chat.MockedChatService.Verify(c => c.AddClient(user, clientId), Times.Once()); chat.MockedChatService.Verify(c => c.UpdateActivity(user), Times.Once()); }
public static TestableChat GetTestableChat(string clientId, TrackingDictionary clientState, ChatUser user, NameValueCollection cookies) { // setup things needed for chat var repository = new InMemoryRepository(); var resourceProcessor = new Mock<IResourceProcessor>(); var chatService = new Mock<IChatService>(); var connection = new Mock<IConnection>(); // add user to repository repository.Add(user); // create testable chat var chat = new TestableChat(resourceProcessor, chatService, repository, connection); var mockedConnectionObject = chat.MockedConnection.Object; // setup client agent chat.Agent = new ClientAgent(mockedConnectionObject, "Chat"); var request = new Mock<IRequest>(); request.Setup(m => m.Cookies).Returns(cookies); // setup signal agent var prinicipal = new Mock<IPrincipal>(); chat.Caller = new SignalAgent(mockedConnectionObject, clientId, "Chat", clientState); // setup context chat.Context = new HubContext(new HostContext(request.Object, null, prinicipal.Object), clientId); return chat; }
public override void Execute(CommandContext context, CallerContext callerContext, ChatUser callingUser, string[] args) { if (args.Length == 0) { throw new InvalidOperationException("Join which room?"); } // Extract arguments string roomName = args[0]; string inviteCode = null; if (args.Length > 1) { inviteCode = args[1]; } // Locate the room, does NOT have to be open ChatRoom room = context.Repository.VerifyRoom(roomName, mustBeOpen: false); if (!context.Repository.IsUserInRoom(context.Cache, callingUser, room)) { // Join the room context.Service.JoinRoom(callingUser, room, inviteCode); context.Repository.CommitChanges(); } context.NotificationService.JoinRoom(callingUser, room); }
private async void NotifyMyAndroid(ChatUser user, ChatMessage message) { var preferences = user.Preferences.PushNotifications.NMA; // Check preferences validity if (preferences == null || !preferences.Enabled || preferences.APIKey == null) return; var apikey = preferences.APIKey.Replace(" ", ""); if (apikey.Length != 48) return; // Create event and description content values and add ellipsis if over limits var descriptionContent = message.Content; if (descriptionContent.Length > 10000) descriptionContent = descriptionContent.Substring(0, 10000 - 3) + "..."; var request = new Dictionary<string, string> { {"apikey", apikey}, {"application", "vox"}, {"event", GetTitle(message, 100)}, {"description", descriptionContent} }; var result = await _httpClient.PostAsync("https://www.notifymyandroid.com/publicapi/notify", new FormUrlEncodedContent(request)); _logger.Log("Send NotifyMyAndroid: {0}", result.StatusCode); }
public override void Execute(CommandContext context, CallerContext callerContext, ChatUser callingUser, string[] args) { if (context.Repository.Users.Count() == 1) { throw new InvalidOperationException("You're the only person in here..."); } if (args.Length == 0 || String.IsNullOrWhiteSpace(args[0])) { throw new InvalidOperationException("Who are you trying send a private message to?"); } var toUserName = HttpUtility.HtmlDecode(args[0]); ChatUser toUser = context.Repository.VerifyUser(toUserName); if (toUser == callingUser) { throw new InvalidOperationException("You can't private message yourself!"); } string messageText = String.Join(" ", args.Skip(1)).Trim(); if (String.IsNullOrEmpty(messageText)) { throw new InvalidOperationException(String.Format("What did you want to say to '{0}'?", toUser.Name)); } HashSet<string> urls; var transform = new TextTransform(context.Repository); messageText = transform.Parse(messageText); messageText = TextTransform.TransformAndExtractUrls(messageText, out urls); context.NotificationService.SendPrivateMessage(callingUser, toUser, messageText); }
public static void SetUserInRoom(this ICache cache, ChatUser user, ChatRoom room, bool value) { string key = CacheKeys.GetUserInRoom(user, room); // Cache this forever since people don't leave rooms often cache.Set(key, value, TimeSpan.FromDays(365)); }
public ChatUser AddUser(string userName, string identity, string email) { if (!IsValidUserName(userName)) { throw new InvalidOperationException(String.Format("'{0}' is not a valid user name.", userName)); } // This method is used in the auth workflow. If the username is taken it will add a number // to the user name. if (UserExists(userName)) { var usersWithNameLikeMine = _repository.Users.Count(u => u.Name.StartsWith(userName)); userName += usersWithNameLikeMine; } var user = new ChatUser { Name = userName, Status = (int)UserStatus.Active, Email = email, Hash = email.ToMD5(), Identity = identity, Id = Guid.NewGuid().ToString("d"), LastActivity = DateTime.UtcNow }; _repository.Add(user); _repository.CommitChanges(); return user; }
public static TestableChat GetTestableChat(string connectionId, TrackingDictionary clientState, ChatUser user, NameValueCollection cookies) { // setup things needed for chat var repository = new InMemoryRepository(); var resourceProcessor = new Mock<IResourceProcessor>(); var chatService = new Mock<IChatService>(); var connection = new Mock<IConnection>(); var settings = new Mock<IApplicationSettings>(); settings.Setup(m => m.AuthApiKey).Returns("key"); // add user to repository repository.Add(user); // create testable chat var chat = new TestableChat(settings, resourceProcessor, chatService, repository, connection); var mockedConnectionObject = chat.MockedConnection.Object; // setup client agent chat.Clients = new ClientProxy(mockedConnectionObject, "Chat"); // setup signal agent var prinicipal = new Mock<IPrincipal>(); var request = new Mock<IRequest>(); request.Setup(m => m.Cookies).Returns(new Cookies(cookies)); request.Setup(m => m.User).Returns(prinicipal.Object); chat.Caller = new StatefulSignalProxy(mockedConnectionObject, connectionId, "Chat", clientState); // setup context chat.Context = new HubCallerContext(request.Object, connectionId); return chat; }
public static ChatRoom VerifyUserRoom(this IJabbrRepository repository, ICache cache, ChatUser user, string roomName) { if (String.IsNullOrEmpty(roomName)) { throw new InvalidOperationException("Use '/join room' to join a room."); } roomName = ChatService.NormalizeRoomName(roomName); ChatRoom room = repository.GetRoomByName(roomName); if (room == null) { throw new InvalidOperationException(String.Format("You're in '{0}' but it doesn't exist.", roomName)); } bool? cached = cache.IsUserInRoom(user, room); if (cached == null) { cached = repository.IsUserInRoom(user, room); cache.SetUserInRoom(user, room, cached.Value); } if (!cached.Value) { throw new InvalidOperationException(String.Format("You're not in '{0}'. Use '/join {0}' to join it.", roomName)); } return room; }
public override void Execute(CommandContext context, CallerContext callerContext, ChatUser callingUser, string[] args) { if (String.IsNullOrEmpty(callerContext.RoomName)) { throw new InvalidOperationException("This command cannot be invoked from the Lobby."); } string targetRoomName = args.Length > 0 ? args[0] : callerContext.RoomName; if (String.IsNullOrEmpty(targetRoomName)) { throw new InvalidOperationException("Which room?"); } ChatRoom targetRoom = context.Repository.VerifyRoom(targetRoomName, mustBeOpen: false); // ensure the user could join the room if they wanted to callingUser.EnsureAllowed(targetRoom); if (String.IsNullOrEmpty(targetRoom.InviteCode)) { context.Service.SetInviteCode(callingUser, targetRoom, RandomUtils.NextInviteCode()); } ChatRoom callingRoom = context.Repository.GetRoomByName(callerContext.RoomName); context.NotificationService.PostNotification(callingRoom, callingUser, String.Format("Invite Code for {0}: {1}", targetRoomName, targetRoom.InviteCode)); }
public void UpdateUnreadMentions(ChatUser mentionedUser, int unread) { foreach (var client in mentionedUser.ConnectedClients) { HubContext.Clients.Client(client.Id).updateUnreadNotifications(unread); } }
public override void Execute(CommandContext context, CallerContext callerContext, ChatUser callingUser, string[] args) { if (args.Length == 0) { throw new InvalidOperationException("Who are you trying to kick?"); } string targetUserName = args[0]; ChatUser targetUser = context.Repository.VerifyUser(targetUserName); string targetRoomName = args.Length > 1 ? args[1] : callerContext.RoomName; if (String.IsNullOrEmpty(targetRoomName)) { throw new InvalidOperationException("Which room?"); } ChatRoom room = context.Repository.VerifyRoom(targetRoomName); context.Service.KickUser(callingUser, targetUser, room); context.NotificationService.KickUser(targetUser, room); context.Repository.CommitChanges(); }
public override void Execute(CommandContext context, CallerContext callerContext, ChatUser callingUser, string[] args) { if (String.IsNullOrEmpty(callerContext.RoomName)) { throw new HubException(LanguageResources.InvokeFromRoomRequired); } string targetRoomName = args.Length > 0 ? args[0] : callerContext.RoomName; if (String.IsNullOrEmpty(targetRoomName)) { throw new HubException(LanguageResources.InviteCode_RoomRequired); } ChatRoom targetRoom = context.Repository.VerifyRoom(targetRoomName, mustBeOpen: false); // ensure the user could join the room if they wanted to callingUser.EnsureAllowed(targetRoom); if (String.IsNullOrEmpty(targetRoom.InviteCode)) { context.Service.SetInviteCode(callingUser, targetRoom, RandomUtils.NextInviteCode()); } ChatRoom callingRoom = context.Repository.GetRoomByName(callerContext.RoomName); context.NotificationService.PostNotification(callingRoom, callingUser, String.Format(LanguageResources.InviteCode_Success, targetRoomName, targetRoom.InviteCode)); }
public void MessageReadStateChanged(ChatUser mentionedUser, ChatMessage message, Notification notification) { foreach (var client in mentionedUser.ConnectedClients) { HubContext.Clients.Client(client.Id).messageReadStateChanged(message.Id, notification.Read); } }
public override void Execute(CommandContext context, CallerContext callerContext, ChatUser callingUser, string[] args) { if (args.Length == 0) { throw new InvalidOperationException("Which room do you want to open?"); } string roomName = args[0]; ChatRoom room = context.Repository.VerifyRoom(roomName, mustBeOpen: false); context.Service.OpenRoom(callingUser, room); // join the room, unless already in the room if (!room.Users.Contains(callingUser)) { context.Service.JoinRoom(callingUser, room, inviteCode: null); context.Repository.CommitChanges(); context.NotificationService.JoinRoom(callingUser, room); } var users = room.Users.ToList(); context.NotificationService.UnCloseRoom(users, room); }
public ChatRoom AddRoom(ChatUser user, string name) { if (name.Equals("Lobby", StringComparison.OrdinalIgnoreCase)) { throw new InvalidOperationException("Lobby is not a valid chat room."); } if (!IsValidRoomName(name)) { throw new InvalidOperationException(String.Format("'{0}' is not a valid room name.", name)); } var room = new ChatRoom { Name = name, Creator = user }; room.Owners.Add(user); _repository.Add(room); user.OwnedRooms.Add(room); return room; }
public override void Execute(CommandContext context, CallerContext callerContext, ChatUser callingUser, string[] args) { if (args.Length == 0) { throw new HubException(LanguageResources.Allow_UserRequired); } string targetUserName = args[0]; ChatUser targetUser = context.Repository.VerifyUser(targetUserName); string roomName = args.Length > 1 ? args[1] : callerContext.RoomName; if (String.IsNullOrEmpty(roomName)) { throw new HubException(LanguageResources.Allow_RoomRequired); } ChatRoom targetRoom = context.Repository.VerifyRoom(roomName, mustBeOpen: false); context.Service.AllowUser(callingUser, targetUser, targetRoom); context.NotificationService.AllowUser(targetUser, targetRoom); context.Repository.CommitChanges(); }
public override void Execute(CommandContext context, CallerContext callerContext, ChatUser callingUser, string[] args) { if (args.Length == 0) { throw new InvalidOperationException("Which owner do you want to remove?"); } string targetUserName = HttpUtility.HtmlDecode(args[0]); ChatUser targetUser = context.Repository.VerifyUser(targetUserName); if (args.Length == 1) { throw new InvalidOperationException("Which room?"); } string roomName = HttpUtility.HtmlDecode(args[1]); ChatRoom targetRoom = context.Repository.VerifyRoom(roomName); context.Service.RemoveOwner(callingUser, targetUser, targetRoom); context.NotificationService.RemoveOwner(targetUser, targetRoom); context.Repository.CommitChanges(); }
public ChatUser AddUser(string userName, string email, string password) { if (!IsValidUserName(userName)) { throw new InvalidOperationException(String.Format("'{0}' is not a valid user name.", userName)); } if (String.IsNullOrEmpty(password)) { ThrowPasswordIsRequired(); } EnsureUserNameIsAvailable(userName); var user = new ChatUser { Name = userName, Email = email, Status = (int)UserStatus.Active, Id = Guid.NewGuid().ToString("d"), Salt = _crypto.CreateSalt(), LastActivity = DateTime.UtcNow, IsAdmin = IsFirstUser() }; ValidatePassword(password); user.HashedPassword = password.ToSha256(user.Salt); _repository.Add(user); return user; }
public override void Execute(CommandContext context, CallerContext callerContext, ChatUser callingUser, string[] args) { if (args.Length == 0) { throw new InvalidOperationException("Which owner do you want to remove?"); } string targetUserName = args[0]; ChatUser targetUser = context.Repository.VerifyUser(targetUserName); string roomName = args.Length > 1 ? args[1] : callerContext.RoomName; if (String.IsNullOrEmpty(roomName)) { throw new InvalidOperationException("Which room do you want to remove the owner from?"); } ChatRoom targetRoom = context.Repository.VerifyRoom(roomName); context.Service.RemoveOwner(callingUser, targetUser, targetRoom); context.NotificationService.RemoveOwner(targetUser, targetRoom); context.Repository.CommitChanges(); }
private static void NudgeUser(CommandContext context, ChatUser callingUser, string[] args) { if (context.Repository.Users.Count() == 1) { throw new InvalidOperationException("You're the only person in here..."); } var toUserName = args[0]; ChatUser toUser = context.Repository.VerifyUser(toUserName); if (toUser == callingUser) { throw new InvalidOperationException("You can't nudge yourself!"); } string messageText = String.Format("{0} nudged you", callingUser); var betweenNudges = TimeSpan.FromSeconds(60); if (toUser.LastNudged.HasValue && toUser.LastNudged > DateTime.Now.Subtract(betweenNudges)) { throw new InvalidOperationException(String.Format("User can only be nudged once every {0} seconds.", betweenNudges.TotalSeconds)); } toUser.LastNudged = DateTime.Now; context.Repository.CommitChanges(); context.NotificationService.NugeUser(callingUser, toUser); }
private void HandleAddOwner(ChatUser user, string[] parts) { if (parts.Length == 1) { throw new InvalidOperationException("Who do you want to make an owner?"); } string targetUserName = parts[1]; ChatUser targetUser = _repository.VerifyUser(targetUserName); if (parts.Length == 2) { throw new InvalidOperationException("Which room?"); } string roomName = parts[2]; ChatRoom targetRoom = _repository.VerifyRoom(roomName); _chatService.AddOwner(user, targetUser, targetRoom); _notificationService.OnOwnerAdded(targetUser, targetRoom); _repository.CommitChanges(); }
public override void Execute(CommandContext context, CallerContext callerContext, ChatUser callingUser, string[] args) { if (args.Length == 0) { throw new HubException(LanguageResources.Kick_UserRequired); } string targetUserName = args[0]; ChatUser targetUser = context.Repository.VerifyUser(targetUserName); string targetRoomName = args.Length > 1 ? args[1] : callerContext.RoomName; if (String.IsNullOrEmpty(targetRoomName)) { throw new HubException(LanguageResources.Kick_RoomRequired); } ChatRoom room = context.Repository.VerifyRoom(targetRoomName); context.Service.KickUser(callingUser, targetUser, room); // try to extract the reason string reason = null; if (args.Length > 2) { reason = String.Join(" ", args.Skip(2)).Trim(); } context.NotificationService.KickUser(targetUser, room, callingUser, reason); context.Repository.CommitChanges(); }
public override void Execute(CommandContext context, CallerContext callerContext, ChatUser callingUser, string[] args) { if (context.Repository.Users.Count() == 1) { throw new InvalidOperationException("You're the only person in here..."); } if (args.Length == 0 || String.IsNullOrWhiteSpace(args[0])) { throw new InvalidOperationException("Who do you want to send a private message to?"); } var toUserName = args[0]; ChatUser toUser = context.Repository.VerifyUser(toUserName); if (toUser == callingUser) { throw new InvalidOperationException("You can't private message yourself!"); } string messageText = String.Join(" ", args.Skip(1)).Trim(); if (String.IsNullOrEmpty(messageText)) { throw new InvalidOperationException(String.Format("What do you want to say to '{0}'?", toUser.Name)); } context.NotificationService.SendPrivateMessage(callingUser, toUser, messageText); }
public void AddOwner(ChatUser ownerOrCreator, ChatUser targetUser, ChatRoom targetRoom) { // Ensure the user is owner of the target room EnsureOwner(ownerOrCreator, targetRoom); if (targetRoom.Owners.Contains(targetUser)) { // If the target user is already an owner, then throw throw new InvalidOperationException(String.Format("'{0}' is already and owner of '{1}'.", targetUser.Name, targetRoom.Name)); } // Make the user an owner targetRoom.Owners.Add(targetUser); targetUser.OwnedRooms.Add(targetRoom); if (targetRoom.Private) { if (!targetRoom.AllowedUsers.Contains(targetUser)) { // If the room is private make this user allowed targetRoom.AllowedUsers.Add(targetUser); targetUser.AllowedRooms.Add(targetRoom); } } }
public void MakesOwnerAllowedIfRoomLocked() { var repository = new InMemoryRepository(); var user = new ChatUser { Name = "foo" }; var user2 = new ChatUser { Name = "foo2" }; repository.Add(user); repository.Add(user2); var room = new ChatRoom { Name = "Room", Creator = user, Private = true }; room.Owners.Add(user); user.OwnedRooms.Add(room); user.Rooms.Add(room); room.Users.Add(user); var service = new ChatService(repository, new Mock<ICryptoService>().Object); service.AddOwner(user, user2, room); Assert.True(user2.AllowedRooms.Contains(room)); Assert.True(room.AllowedUsers.Contains(user2)); Assert.True(room.Owners.Contains(user2)); Assert.True(user2.OwnedRooms.Contains(room)); }
public void MakesUserOwner() { var repository = new InMemoryRepository(); var user = new ChatUser { Name = "foo" }; var user2 = new ChatUser { Name = "foo2" }; repository.Add(user); repository.Add(user2); var room = new ChatRoom { Name = "Room", Creator = user }; room.Owners.Add(user); user.OwnedRooms.Add(room); user.Rooms.Add(room); room.Users.Add(user); var service = new ChatService(repository); service.AddOwner(user, user2, room); Assert.True(room.Owners.Contains(user2)); Assert.True(user2.OwnedRooms.Contains(room)); }
public override void Execute(CommandContext context, CallerContext callerContext, ChatUser callingUser, string[] args) { if (args.Length == 0) { throw new InvalidOperationException("Who do you want to invite?"); } string targetUserName = HttpUtility.HtmlDecode(args[0]); ChatUser targetUser = context.Repository.VerifyUser(targetUserName); if (targetUser == callingUser) { throw new InvalidOperationException("You can't invite yourself!"); } if (args.Length == 1) { throw new InvalidOperationException("Invite them to which room?"); } string roomName = HttpUtility.HtmlDecode(args[1]); ChatRoom targetRoom = context.Repository.VerifyRoom(roomName); context.NotificationService.Invite(callingUser, targetUser, targetRoom); }
public override void Execute(CommandContext context, CallerContext callerContext, ChatUser callingUser, string[] args) { if (args.Length == 0) { throw new InvalidOperationException("Who do you want to invite?"); } string targetUserName = args[0]; ChatUser targetUser = context.Repository.VerifyUser(targetUserName); if (targetUser == callingUser) { throw new InvalidOperationException("You can't invite yourself!"); } string roomName = args.Length > 1 ? args[1] : callerContext.RoomName; if (String.IsNullOrEmpty(roomName)) { throw new InvalidOperationException("Which room do you want to invite them to?"); } ChatRoom targetRoom = context.Repository.VerifyRoom(roomName, mustBeOpen: false); context.NotificationService.Invite(callingUser, targetUser, targetRoom); }
public void Add(ChatUser user) { _db.Users.Add(user); _db.SaveChanges(); }
public void Serialize(ChatUser chatUser) { chatUser.RawPreferences = JsonConvert.SerializeObject(this); }
public void Remove(ChatUser user) { _users.Remove(user); }
public void Add(ChatUser user) { _users.Add(user); }
public void AddUserRoom(ChatUser user, ChatRoom room) { RunNonLazy(() => room.Users.Add(user)); }
public void Remove(ChatUser user) { _db.Users.Remove(user); _db.SaveChanges(); }