public static void Main()
        {
            var chatRoom = new ChatRoom();

            Participant george = new Beetle("George"); // new Beetle("George", chatRoom);
            chatRoom.Register(george);

            Participant paul = new Beetle("Paul");
            chatRoom.Register(paul);

            Participant ringo = new Beetle("Ringo");
            chatRoom.Register(ringo);

            Participant john = new Beetle("John");
            chatRoom.Register(john);

            Participant yoko = new NonBeetle("Yoko");
            chatRoom.Register(yoko);

            yoko.Send("John", "Hi John!");
            paul.Send("Ringo", "All you need is love");
            ringo.Send("George", "My sweet Lord");
            paul.Send("John", "Can't buy me love");
            john.Send("Yoko", "My sweet love");

            yoko.SendToAll("Hi, all!");
        }
 public InviteToChatDialog(Network network, ChatRoom room)
     : this(network, null, room)
 {
     if (room == null) {
         throw new ArgumentNullException ("room");
     }
 }
Example #3
0
        public void GivenAConnectedUserWithOneConnection_WhenTheUserConnectWithANewConnection_ThenNothingHappens()
        {
            var chat = new ChatRoom();
            chat.Connect("username", DummyDateTime, DummyConnectionId());

            ChatEvent chatEvent = chat.Connect("username", Now, "newConnection");

            chatEvent.Should().Be(ChatEvent.NothingHappens(Now));
        }
Example #4
0
        public void GivenAConnectedUserWithManyConnections_WhenTheUserDisconnectFromOneConnection_ThenNothingHappens()
        {
            var chat = new ChatRoom();
            chat.Connect("username", DummyDateTime, "connection1");
            chat.Connect("username", DummyDateTime, "connection2");

            ChatEvent chatEvent = chat.Disconnect("connection1", Now);

            chatEvent.Should().Be(ChatEvent.NothingHappens(Now));
        }
Example #5
0
        private void AddChat(ChatRoom room)
        {
            var chatView = new ChatRoomControl(room, _session);
            chatView.Dock = DockStyle.Fill;

            var tabPage = new TabPage(room.FriendlyName);
            tabPage.Controls.Add(chatView);
            tabPage.Tag = room;
            tcChats.TabPages.Add(tabPage);
            tcChats.Invalidate();
        }
Example #6
0
        public void GivenAConnectedUserWithManyConnections_ThenTheJoinedAtDatetimeShouldBeTheTimestampOfTheFirstConnection()
        {
            var chat = new ChatRoom();
            chat.Connect("username", Now.AddMinutes(-2), DummyConnectionId());
            chat.Connect("username", Now.AddMinutes(-1), DummyConnectionId());

            chat.Connect("username", Now, DummyConnectionId());

            chat.ConnectedUserByUsername("username").Value
                .JoinedAt.Should().Be(Now.AddMinutes(-2));
        }
Example #7
0
        public void GivenAConnectedUserWithManyConnections_WhenTheUserDisconnectFromAllConnections_ThenTheUserShouldLeaveChat()
        {
            var chat = new ChatRoom();
            chat.Connect("username", DummyDateTime, "connection1");
            chat.Connect("username", DummyDateTime, "connection2");

            chat.Disconnect("connection1", DummyDateTime);
            ChatEvent chatEvent = chat.Disconnect("connection2", Now);

            chatEvent.Should().Be(ChatEvent.UserLeavesChat("username", Now));
        }
Example #8
0
        public void CanGetConnectedUsers()
        {
            var chat = new ChatRoom();
            chat.Connect("username1", Now.AddMinutes(-1), "connection1");
            chat.Connect("username2", Now, "connection2");

            chat.ConnectedUsers.ShouldAllBeEquivalentTo(
                new[]
                {
                    new ConnectedUser("username1", new UserConnection("connection1", Now.AddMinutes(-1))),
                    new ConnectedUser("username2", new UserConnection("connection2", Now))
                });
        }
Example #9
0
File: Rooms.cs Project: ringe/JoMAR
        /// <summary>
        /// Find a private room for two users.
        /// </summary>
        /// <param name="user1">First user's Profile</param>
        /// <param name="user2">Second user's Profile</param>
        /// <param name="db">JodADataContext</param>
        /// <returns></returns>
        public static ChatRoom Private(Profile user1, Profile user2, JodADataContext db)
        {
            // Possible names of private rooms between these users.
            String A = user1.CellPhone + user2.CellPhone;
            String B = user2.CellPhone + user1.CellPhone;

            // No rooms with oneself
            if (A == B) return null;

            // Select rooms where name is A or B and the room is private, not public and with only two users
            List<ChatRoom> rooms = (from r in db.ChatRooms
                                     where (r.Name == A || r.Name == B && r.isPrivate && !r.isPublic && r.UserRooms.Count == 2)
                                     select r).ToList();

            ChatRoom newRoom;
            // Return private room, create if necessary
            if (rooms.Count == 0)
            {
                // Prepare new private room
                newRoom = new ChatRoom();
                newRoom.UserID = user1.UserId;
                newRoom.RoomID = Guid.NewGuid();
                newRoom.isPrivate = true;
                newRoom.Name = A;

                // Insert new room
                db.ChatRooms.InsertOnSubmit(newRoom);

                // Join user 1 to room
                UserRoom nr = new UserRoom();
                nr.UserID = user1.UserId;
                nr.RoomID = newRoom.RoomID;

                // Join user 2 to room
                UserRoom nr2 = new UserRoom();
                nr2.UserID = user2.UserId;
                nr2.RoomID = newRoom.RoomID;

                // Insert user_room relationsships
                db.UserRooms.InsertOnSubmit(nr);
                db.UserRooms.InsertOnSubmit(nr2);

                // Submit changes to DB
                db.SubmitChanges();

                return newRoom;
            }
            else return rooms.First();
        }
Example #10
0
        public InviteForm(CoreUI ui, ChatService chat, ulong user, ChatRoom room)
        {
            InitializeComponent();

            UI = ui;
            Core = ui.Core;
            Chat = chat;
            Room = room;

            IntroLabel.Text = IntroLabel.Text.Replace("<name>", Core.GetName(user));

            NameLabel.Text = room.Title;

            TypeLabel.Text = room.Kind.ToString();
        }
Example #11
0
        public ChatModel(ChatRoom room, JodADataContext db)
        {
            MessageBoard = room.ChatMessages.ToArray();

            Users = (from user in db.aspnet_Users
                           join m2m in db.UserRooms on user.UserId equals m2m.UserID
                           where m2m.RoomID == room.RoomID
                           select user).ToList();

            if (!Users.Contains(room.aspnet_User))
                Users.Add(room.aspnet_User);

            Name = room.Name;
            RoomID = room.RoomID;
            Private = room.isPrivate;
        }
Example #12
0
 public ChatRoomControl(ChatRoom chatRoom, Session session)
 {
     _chatRoom = chatRoom;
     _session = session;
     _encryptedChat = _chatRoom.EncryptedChat;
     _encryptedChat.InviteReceived += EncryptedChatOnInviteReceived;
     _encryptedChat.MessageReceived += EncryptedChatOnMessageReceived;
     _encryptedChat.UserKeyReceived += EncryptedChatOnUserKeyReceived;
     _encryptedChat.UserWantsToJoin += EncryptedChatOnUserWantsToJoin;
     _encryptedChat.StateChanged += EncryptedChatOnStateChanged;
     _encryptedChat.InternalMessageReceived += EncryptedChatOnInternalMessageReceived;
     _encryptedChat.UserListChanged += EncryptedChatOnUserListChanged;
     _encryptedChat.UserJoined += EncryptedChatOnUserJoined;
     _encryptedChat.UserLeft += EncryptedChatOnUserLeft;
     InitializeComponent();
 }
Example #13
0
        public ActionResult create(ChatRoom model, string returnUrl)
        {
            JodADataContext db = new JodADataContext();

            if (ModelState.IsValid)
            {
                model.UserID = (from p in db.aspnet_Users
                                where p.UserName == User.Identity.Name
                                select p).First().UserId;
                db.ChatRooms.InsertOnSubmit(model);
                model.RoomID = Guid.NewGuid();

                db.SubmitChanges();

                return Redirect(Url.Action(model.Name, "Chat"));
            }
            return View(model);
        }
Example #14
0
	public Game(){
		login = new Login ();
		wealth = new List<Wealth> ();
		for (int i = 0; i < 3; i++) {
			wealth.Add (new Wealth ());
		}

		friend = new List<Friend> ();
		chatRoom = new ChatRoom ();
		general = new List<General> ();
		counselor = new List<Counselor> ();
		trainings = new List<Trainings> ();
		buildings = new List<Buildings> ();
		warfare = new List<Warfare> ();
		messages = new List<Message> ();
		privateMessages = new List<PrivateMessage> ();
		storage = new List<Storage> ();
		//_additionalData = new Dictionary<string, Newtonsoft.Json.Linq.JToken>();
	}
Example #15
0
        public static void Main()
        {
            var chatRoom = new ChatRoom();

            Participant george = new Beetle("George"); // new Beetle("George", chatRoom);
            chatRoom.Register(george);

            Participant paul = new Beetle("Paul");
            chatRoom.Register(paul);

            Participant ringo = new Beetle("Ringo");
            chatRoom.Register(ringo);

            Participant john = new Beetle("John");
            chatRoom.Register(john);

            Participant yoko = new NonBeetle("Yoko");
            chatRoom.Register(yoko);

            yoko.Send("John", "Hi John!");
            paul.Send("Ringo", "All you need is love");
            ringo.Send("George", "My sweet Lord");
            paul.Send("John", "Can't buy me love");
            john.Send("Yoko", "My sweet love");

            yoko.SendToAll("Hi, all!");

            /*
             * Alternative:
             * Meet Paul with George and vice-versa
             * Meet Ringo with Paul and vice-versa
             * Meet Ringo with George and vice-versa
             * Meet John with Paul and vice-versa
             * Meet John with George and vice-versa
             * Meet John with Ringo and vice-versa
             * Meet Yoko with Paul and vice-versa
             * Meet Yoko with George and vice-versa
             * Meet Yoko with Ringo and vice-versa
             * Meet Yoko with John and vice-versa
             */
        }
Example #16
0
        internal static void Main()
        {
            var chatRoom = new ChatRoom();

            // There are lots of Users, Which do not know for each other. The connection between them is through Chat Room
            Participant george = new Beetle("George");
            Participant paul = new Beetle("Paul");
            Participant ringo = new Beetle("Ringo");
            Participant john = new Beetle("John");
            Participant yoko = new NonBeetle("Yoko");

            chatRoom.Register(george);
            chatRoom.Register(paul);
            chatRoom.Register(ringo);
            chatRoom.Register(john);
            chatRoom.Register(yoko);

            yoko.Send(john.Name, "Hi John!");
            paul.Send(ringo.Name, "All you need is love");
            ringo.Send(george.Name, "My sweet Lord");
            paul.Send(john.Name, "Can't buy me love");
            john.Send(yoko.Name, "My sweet love");
        }
Example #17
0
        private bool TryHandleCommand(string message)
        {
            string room = Caller.room;
            string name = Caller.name;

            message = message.Trim();
            if (message.StartsWith("/"))
            {
                string[] parts       = message.Substring(1).Split(' ');
                string   commandName = parts[0];

                if (commandName.Equals("nick", StringComparison.OrdinalIgnoreCase))
                {
                    string newUserName = String.Join(" ", parts.Skip(1));

                    if (String.IsNullOrEmpty(newUserName))
                    {
                        throw new InvalidOperationException("No username specified!");
                    }

                    if (newUserName.Equals(name, StringComparison.OrdinalIgnoreCase))
                    {
                        throw new InvalidOperationException("That's already your username...");
                    }

                    if (!_users.ContainsKey(newUserName))
                    {
                        if (String.IsNullOrEmpty(name) || !_users.ContainsKey(name))
                        {
                            var user = AddUser(newUserName);
                        }
                        else
                        {
                            var oldUser = _users[name];
                            var newUser = new ChatUser
                            {
                                Name         = newUserName,
                                Hash         = GetMD5Hash(newUserName),
                                Id           = oldUser.Id,
                                ConnectionId = oldUser.ConnectionId
                            };

                            _users[newUserName]     = newUser;
                            _userRooms[newUserName] = new HashSet <string>(_userRooms[name]);

                            if (_userRooms[name].Any())
                            {
                                foreach (var r in _userRooms[name])
                                {
                                    _rooms[r].Users.Remove(name);
                                    _rooms[r].Users.Add(newUserName);
                                    Clients[r].changeUserName(oldUser, newUser);
                                }
                            }

                            _userRooms.Remove(name);
                            _users.Remove(name);

                            Caller.hash = newUser.Hash;
                            Caller.name = newUser.Name;

                            Caller.changeUserName(oldUser, newUser);
                        }
                    }
                    else
                    {
                        throw new InvalidOperationException(String.Format("Username '{0}' is already taken!", newUserName));
                    }

                    return(true);
                }
                else
                {
                    EnsureUser();
                    if (commandName.Equals("rooms", StringComparison.OrdinalIgnoreCase))
                    {
                        var rooms = _rooms.Select(r => new
                        {
                            Name  = r.Key,
                            Count = r.Value.Users.Count
                        });

                        Caller.showRooms(rooms);

                        return(true);
                    }
                    else if (commandName.Equals("join", StringComparison.OrdinalIgnoreCase))
                    {
                        if (parts.Length == 1)
                        {
                            throw new InvalidOperationException("Join which room?");
                        }

                        // Only support one room at a time for now

                        string   newRoom = parts[1];
                        ChatRoom chatRoom;
                        // Create the room if it doesn't exist
                        if (!_rooms.TryGetValue(newRoom, out chatRoom))
                        {
                            chatRoom = new ChatRoom();
                            _rooms.Add(newRoom, chatRoom);
                        }

                        // Remove the old room
                        if (!String.IsNullOrEmpty(room))
                        {
                            _userRooms[name].Remove(room);
                            _rooms[room].Users.Remove(name);

                            Clients[room].leave(_users[name]);
                            RemoveFromGroup(room);
                        }

                        _userRooms[name].Add(newRoom);
                        if (!chatRoom.Users.Add(name))
                        {
                            throw new InvalidOperationException("You're already in that room!");
                        }

                        Clients[newRoom].addUser(_users[name]);

                        // Set the room on the caller
                        Caller.room = newRoom;

                        AddToGroup(newRoom);

                        Caller.refreshRoom(newRoom);

                        return(true);
                    }
                    else if (commandName.Equals("msg", StringComparison.OrdinalIgnoreCase))
                    {
                        if (_users.Count == 1)
                        {
                            throw new InvalidOperationException("You're the only person in here...");
                        }

                        if (parts.Length < 2)
                        {
                            throw new InvalidOperationException("Who are you trying send a private message to?");
                        }

                        string to = parts[1];
                        if (to.Equals(name, StringComparison.OrdinalIgnoreCase))
                        {
                            throw new InvalidOperationException("You can't private message yourself!");
                        }

                        if (!_users.ContainsKey(to))
                        {
                            throw new InvalidOperationException(String.Format("Couldn't find any user named '{0}'.", to));
                        }

                        string messageText = String.Join(" ", parts.Skip(2)).Trim();

                        if (String.IsNullOrEmpty(messageText))
                        {
                            throw new InvalidOperationException(String.Format("What did you want to say to '{0}'.", to));
                        }

                        string recipientId = _users[to].ConnectionId;
                        // Send a message to the sender and the sendee
                        Clients[recipientId].sendPrivateMessage(name, to, messageText);
                        Caller.sendPrivateMessage(name, to, messageText);

                        return(true);
                    }
                    else
                    {
                        EnsureUserAndRoom();
                        if (commandName.Equals("me", StringComparison.OrdinalIgnoreCase))
                        {
                            if (parts.Length == 1)
                            {
                                throw new InvalidProgramException("You what?");
                            }
                            var content = String.Join(" ", parts.Skip(1));

                            Clients[room].sendMeMessage(name, content);
                            return(true);
                        }
                        else if (commandName.Equals("leave", StringComparison.OrdinalIgnoreCase))
                        {
                            ChatRoom chatRoom;
                            if (_rooms.TryGetValue(room, out chatRoom))
                            {
                                chatRoom.Users.Remove(name);
                                _userRooms[name].Remove(room);

                                Clients[room].leave(_users[name]);
                            }

                            RemoveFromGroup(room);

                            Caller.room = null;

                            return(true);
                        }

                        throw new InvalidOperationException(String.Format("'{0}' is not a valid command.", parts[0]));
                    }
                }
            }
            return(false);
        }
Example #18
0
        public void Execute(GameClients.GameClient Session, Rooms.Room Room, string[] Params)
        {
            Dictionary <object, object> AllChats = new Dictionary <object, object>();

            foreach (WebSocketChatRoom ChatRoom in WebSocketChatManager.RunningChatRooms.Values)
            {
                AllChats.Add(ChatRoom.ChatName, JsonConvert.SerializeObject(new Dictionary <object, object>()
                {
                    { "chatName", ChatRoom.ChatName }, { "chatVisitors", ChatRoom.ChatUsers.Count }, { "chatType", (ChatRoom.GetChatType()) }
                }));
            }

            PlusEnvironment.GetGame().GetWebEventManager().SendDataDirect(Session, JsonConvert.SerializeObject(new Dictionary <object, object>()
            {
                { "event", "chatManager" },
                { "chatname", "getchats" },
                { "action", "getchatrooms" },
                { "returnedChats", JsonConvert.SerializeObject(AllChats) },
            }));
        }
Example #19
0
            public MucService()
            {
                this.ServiceType = ServiceType.GroupChat;

                this.roomList = new Dictionary<string, ChatRoom>();

                ChatRoom chatroom = new ChatRoom();

                chatroom.Name = "Conference";
                chatroom.Subject = "Site View Logistics Chat Room";
                chatroom.Category = ServiceType.GroupChat.ToString();
                chatroom.Type = "text";

                chatroom.JID = new agsXMPP.Jid("*****@*****.**");

                User owner = new User();
                owner.Nick = "Administrator";
                owner.Role = agsXMPP.protocol.x.muc.Role.none;
                owner.Affiliation = agsXMPP.protocol.x.muc.Affiliation.owner;
                owner.JID = new agsXMPP.Jid("admin@" + ConfigManager.Server);

                chatroom.Owner = owner;

                //<feature var='http://jabber.org/protocol/muc'/>
                //<feature var='muc_passwordprotected'/>
                //<feature var='muc_hidden'/>
                //<feature var='muc_temporary'/>
                //<feature var='muc_open'/>
                //<feature var='muc_unmoderated'/>
                //<feature var='muc_nonanonymous'/>

                chatroom.AddFeature(agsXMPP.Uri.MUC);

                this.roomList.Add(chatroom.Name, chatroom);

            }
Example #20
0
        public ChatRoom GetChatRoom(int chatRoomId)
        {
            if (!Config.Misc.EnableAjaxChat && !Config.Groups.EnableAjaxChat)
                return null;

            if (Config.Misc.EnableAjaxChat && chatRoomId == -1)
            {
                lock (ChatRooms)
                {
                    if (ChatRooms.ContainsKey(-1))
                    {
                        return ChatRooms[-1];
                    }
                    else
                    {
                        ChatRoom room = new ChatRoom(Estream.AjaxChat.Classes.Lang.Trans("Main Chat"));
                        room.Id = chatRoomId;
                        room.Topic = Estream.AjaxChat.Classes.Lang.Trans("Welcome to main chat");
                        ChatRooms.Add(-1, room);
                        return room;
                    }
                }
            }

            if (Config.Groups.EnableAjaxChat)
            {
                Group group = Group.Fetch(chatRoomId);
                if (group == null) return null;

                lock (ChatRooms)
                {
                    if (ChatRooms.ContainsKey(group.ID))
                    {
                        return ChatRooms[group.ID];
                    }
                    else
                    {
                        ChatRoom room = new ChatRoom(group.Name);
                        room.Id = chatRoomId;
                        room.Topic = Estream.AjaxChat.Classes.Lang.Trans(String.Format("Welcome to group {0}", group.Name));

                        return room;
                    }
                }
            }

            return null;
        }
Example #21
0
        //отправить списку клиентов
        private async Task NotifyClients(string message, ClientObject fromClient, List <ClientObject> toClients, ChatRoom room)
        {
            if (!message.StartsWith("/"))
            {
                string fromClientName = fromClient == null ? "" : fromClient.UserLogin;
                message = String.Format("{0}{1}{2}{1}{3}", fromClientName, ChatSyntax.MessageDiv, message, room.Name);
            }

            string encryptedMessage = await Crypto.Encrypt(message);

            byte[] buffer = await base.GetMessageBytes(encryptedMessage);

            try
            {
                foreach (ClientObject client in toClients)
                {
                    if (client == null || string.IsNullOrEmpty(client.UserLogin))
                    {
                        continue;
                    }
                    await base.SendMessageToClient(client.Socket, buffer);
                }
            }
            catch (Exception ex) { onServerInform?.Invoke("Невозможно оповестить клиента: " + ex.Message); }
        }
Example #22
0
        public void GivenUsersLimitReached_WhenANewUserConnect_ThenShouldThrowException()
        {
            var chat = new ChatRoom(2);
            chat.Connect("username1", DummyDateTime, DummyConnectionId());
            chat.Connect("username2", DummyDateTime, DummyConnectionId());

            Action act = () =>
                chat.Connect("username3", DummyDateTime, DummyConnectionId());

            act.ShouldThrow<InvalidOperationException>();
        }
Example #23
0
 public ServerInternalSubscriber(RouterSocket socket, string port, Publisher pub) : base(pub, null)
 {
     userSession = UserSession.GetServerUser();
     chatRoom    = new ChatRoom(userSession);
     broker      = new ServerMessageBroker(chatRoom, socket, port);
 }
Example #24
0
        public HttpResponseMessage GetAllMessages(string room, string range)
        {
            if (String.IsNullOrWhiteSpace(range))
            {
                range = "last-hour";
            }

            var      end = DateTime.Now;
            DateTime start;

            switch (range)
            {
            case "last-hour":
                start = end.AddHours(-1);
                break;

            case "last-day":
                start = end.AddDays(-1);
                break;

            case "last-week":
                start = end.AddDays(-7);
                break;

            case "last-month":
                start = end.AddDays(-30);
                break;

            case "all":
                start = DateTime.MinValue;
                break;

            default:
                return(Request.CreateJabbrErrorMessage(HttpStatusCode.BadRequest, "range value not recognized"));
            }

            var filenamePrefix = room + ".";

            if (start != DateTime.MinValue)
            {
                filenamePrefix += start.ToString(FilenameDateFormat, CultureInfo.InvariantCulture) + ".";
            }

            filenamePrefix += end.ToString(FilenameDateFormat, CultureInfo.InvariantCulture);


            ChatRoom chatRoom = null;

            try
            {
                chatRoom = _repository.VerifyRoom(room, mustBeOpen: false);
            }
            catch (Exception ex)
            {
                return(Request.CreateJabbrErrorMessage(HttpStatusCode.NotFound, ex.Message, filenamePrefix));
            }

            if (chatRoom.Private)
            {
                // TODO: Allow viewing messages using auth token
                return(Request.CreateJabbrErrorMessage(HttpStatusCode.NotFound, String.Format(LanguageResources.RoomNotFound, chatRoom.Name), filenamePrefix));
            }

            var messages = _repository.GetMessagesByRoom(chatRoom)
                           .Where(msg => msg.When <= end && msg.When >= start)
                           .OrderBy(msg => msg.When)
                           .Select(msg => new MessageApiModel
            {
                Content     = msg.Content,
                Username    = msg.User.Name,
                When        = msg.When,
                HtmlEncoded = msg.HtmlEncoded,
            });


            return(Request.CreateJabbrSuccessMessage(HttpStatusCode.OK, messages, filenamePrefix));
        }
Example #25
0
        public static bool?IsUserInRoom(this ICache cache, ChatUser user, ChatRoom room)
        {
            string key = CacheKeys.GetUserInRoom(user, room);

            return((bool?)cache.Get(key));
        }
Example #26
0
        /// <summary>
        /// Notifies the BOS server that the client is ready to go online -- SNAC(01,02)
        /// </summary>
        /// <param name="dp">A <see cref="DataPacket"/> object</param>
        /// <remarks>
        /// The client sends this SNAC to notify the server that it is ready to receive messages
        /// and online notifications.
        /// <para>
        /// This SNAC must be sent within 30 seconds of connection, or the connection
        /// will drop. This should not ever be a problem, barring a lost connection well below
        /// the level of this library.
        /// </para>
        /// </remarks>
        public static void SendReadyNotification(DataPacket dp)
        {
            // Build SNAC(01,02)
            SNACHeader sh = new SNACHeader();

            sh.FamilyServiceID = (ushort)SNACFamily.BasicOscarService;
            sh.FamilySubtypeID = (ushort)GenericServiceControls.ClientOnline;
            sh.Flags           = 0x0000;
            sh.RequestID       = Session.GetNextRequestID();

            ConnectionManager cm = dp.ParentSession.Connections;

            ushort[]      families = cm.GetFamilies(dp.ParentConnection);
            FamilyManager fm       = dp.ParentSession.Families;

            Array.Sort(families);
            Array.Reverse(families);

            bool isChatRoomConnection = false;
            bool isChatNavService     = false;

            ByteStream stream = new ByteStream();

            DataPacket[][] delayedframes = new DataPacket[families.Length][];

            for (int i = 0; i < families.Length; i++)
            {
                ushort family = families[i];
                delayedframes[i] = dp.ParentSession.Connections.GetDelayedPackets(family);

                stream.WriteUshort(family);
                stream.WriteUshort(fm.GetFamilyVersion(family));
                stream.WriteUshort(fm.GetFamilyToolID(family));
                stream.WriteUshort(fm.GetFamilyToolVersion(family));

                if (family == 0x000D)
                {
                    isChatNavService = true;
                }
                else if (family == 0x000E)
                {
                    isChatRoomConnection = true;
                }
            }

            /*
             * The initial service connection has to send SNAC(01,1E) before it actually
             * sends SNAC(01,02), thus the check for the initial connection here
             * and after it gets sent.
             */
            Session sess = dp.ParentSession;

            if (!sess.LoggedIn)
            {
                SetExtendedStatus(sess, sess.AvailableMessage, ICQFlags.Normal, ICQStatus.Online);
                SetExtendedStatus(sess, null, ICQFlags.Normal, ICQStatus.Online);
            }

            // The connection is done, so start sending keepalives
            dp.ParentConnection.Connecting   = false;
            dp.ParentConnection.ReadyForData = true;

            // Build and send a new DataPacket instead of re-using the originator;
            // SNAC(01,02) was getting sent twice on child connections with the reuse
            DataPacket dp2 = Marshal.BuildDataPacket(dp.ParentSession, sh, stream);

            dp2.ParentConnection = dp.ParentConnection;
            SNACFunctions.BuildFLAP(dp2);

            /*
             * If this is a new service connection, there is probably at least one
             * delayed packet. Process those packets. Additionally, if the new connection is
             * a chatroom connection, query the Rendezvous manager to see if it is the result
             * of an explict room creation (or implict, as in accepting a chat invitation).
             * If it was explict, notify the user that it's done
             */
            if (sess.LoggedIn)
            {
                foreach (DataPacket[] list in delayedframes)
                {
                    if (list == null)
                    {
                        continue;
                    }
                    foreach (DataPacket dp_delay in list)
                    {
                        dp_delay.ParentConnection = dp.ParentConnection;
                        SNACFunctions.DispatchToRateClass(dp_delay);
                    }
                }

                if (isChatNavService)
                {
                    sess.ChatRooms.OnChatNavServiceAvailable();
                }
                else if (isChatRoomConnection)
                {
                    ChatRoom chatRoom = sess.Connections.GetChatByConnection((ChatConnection)dp.ParentConnection);
                    sess.ChatRooms.OnChatRoomConnectionAvailable(chatRoom);
                }
            }
        }
Example #27
0
 internal void Init()
 {
     chatRoom = new ChatRoom();
 }
Example #28
0
 public User(ChatRoom ChatRoom)
 {
     this.ChatRoom = ChatRoom;
 }
Example #29
0
File: Chat.cs Project: loqu8/JabbR
 void INotificationService.LeaveRoom(ChatUser user, ChatRoom room)
 {
     LeaveRoom(user, room);
 }
Example #30
0
File: Chat.cs Project: loqu8/JabbR
 void INotificationService.NudgeRoom(ChatRoom room, ChatUser user)
 {
     Clients.Group(room.Name).nudge(user.Name);
 }
Example #31
0
        public void GivenAnEmptyChatRoom_WhenANewUserConnect_ThenTheUserShouldJoinChat()
        {
            var chat = new ChatRoom();

            ChatEvent chatEvent = chat.Connect("username", Now, DummyConnectionId());

            chatEvent.Should().Be(
                ChatEvent.UserJoinsChat("username", Now));
        }
Example #32
0
 public static void RemoveUserInRoom(this ICache cache, ChatUser user, ChatRoom room)
 {
     cache.Remove(CacheKeys.GetUserInRoom(user, room));
 }
Example #33
0
        public void GivenSomeConnectedUsers_WhenANewUserConnect_ThenTheUserShouldJoinChat()
        {
            var chat = new ChatRoom();
            chat.Connect("dummyUser1", DummyDateTime, DummyConnectionId());
            chat.Connect("dummyUser2", DummyDateTime, DummyConnectionId());

            ChatEvent chatEvent = chat.Connect("username", Now, DummyConnectionId());

            chatEvent.Should().Be(
                ChatEvent.UserJoinsChat("username", Now));
        }
Example #34
0
 public static string GetUserInRoom(ChatUser user, ChatRoom room)
 {
     return("UserInRoom" + user.Key + "_" + room.Key);
 }
Example #35
0
        public ActionResult Chat(string fromMemID)
        {
            string session = Session["memid"].ToString();
            //找出聊天室房號
            var findRecord = db.Chat_Records.Where(m => (m.ToMemId == session && m.FromMemId == fromMemID) || m.FromMemId == session && m.ToMemId == fromMemID).FirstOrDefault();
            int roomID;

            //判斷是否已有聊天記錄
            if (findRecord == null)
            {
                //判斷是否有空房可用
                //select* from chatroom as a left join Chat_Records as b on a.chatroom = b.chatroom where b.chatroom is null
                var EmptyRoom = (from a in db.ChatRoom
                                 join b in db.Chat_Records
                                 on a.ChatRoom1 equals b.ChatRoom
                                 into groupjoin
                                 from c in groupjoin.DefaultIfEmpty()
                                 where c.chatSerial == null
                                 select a).ToList();


                if (EmptyRoom.Count() > 0)
                {
                    //取得尚未取用的房號,(RoomUsed為false)
                    var emp = EmptyRoom.Take(1).FirstOrDefault();
                    //將之前已取用房號但仍未有聊天記錄的房間重新釋放
                    emp.RoomUsed = false;
                    roomID       = emp.ChatRoom1;
                    //儲存房號
                    TempData["roomID"] = roomID;
                    //若房號已被取用,修改RoomUsed、取用日期欄位
                    db.ChatRoom.Find(roomID).RoomUsed   = true;
                    db.ChatRoom.Find(roomID).CreateTime = DateTime.Now;

                    db.SaveChanges();
                }
                else
                {
                    //新建房間
                    DateTime now = DateTime.Now;
                    ChatRoom R   = new ChatRoom()
                    {
                        CreateTime = now,
                        RoomUsed   = false
                    };
                    db.ChatRoom.Add(R);
                    db.SaveChanges();
                }
            }
            else
            {
                //取得原房號
                roomID = (int)(findRecord.ChatRoom);
                //已讀所有對方寄送過來的未讀訊息
                string UpdateString = "Update Chat_Records set ReadYet=1 where chatroom=@chatroom and ToMemId=@ToMemId";
                db.Database.ExecuteSqlCommand(UpdateString, new SqlParameter("@chatroom", roomID), new SqlParameter("@ToMemId", session));
                //取得所有歷史記錄
                ViewBag.chat = db.Chat_Records.Where(m => m.ChatRoom == roomID).OrderByDescending(m => m.Time).ToList().OrderBy(m => m.Time);
                //儲存房號
                TempData["roomID"] = roomID;
            }

            //取得對方暱稱
            ViewBag.Nick = db.Member.Find(fromMemID).memNick;

            return(View());
        }
Example #36
0
 private bool IsUserAllowed(ChatRoom room, ChatUser user)
 {
     return(room.AllowedUsers.Contains(user) || user.IsAdmin);
 }
Example #37
0
File: Chat.cs Project: loqu8/JabbR
 void INotificationService.ListUsers(ChatRoom room, IEnumerable <string> names)
 {
     Clients.Caller.showUsersInRoom(room.Name, names);
 }
Example #38
0
 public void ChangeTopic(ChatUser user, ChatRoom room, string newTopic)
 {
     EnsureOwnerOrAdmin(user, room);
     room.Topic = newTopic;
     _repository.CommitChanges();
 }
        protected void btnSave_Click(object sender, EventArgs e)
        {
            if (null == Session["strSiteName"] || null == Session["strSiteCode"] || null == Session["strLoginName"])
            {
                Response.Write("<script language=JavaScript>;parent.location.href='../Index.aspx';</script>");
                Response.End();
            }
            if (RoomName.Text.Trim() != null && RoomName.Text.Trim() != "")
            {
                ChatRoomDAL dal        = new ChatRoomDAL();
                int         roommaxnum = Convert.ToInt32(dal.GetMaxRoomNum());
                roommaxnum = roommaxnum + 1;
                string strSiteCode = Session["strSiteCode"].ToString();
                if (dal.ExistChatRoom(strSiteCode, RoomName.Text))
                {
                    MessageBox.Show(this, "该房间已经存在!");
                }
                else if (dal.ExistChatRoomNum(strSiteCode, roommaxnum))
                {
                    MessageBox.Show(this, "该房间已经存在!");
                }
                else
                {
                    //上传图像
                    string strIconFileName     = string.Empty; //图像路径
                    string strIconSaveFileName = string.Empty; //网址路径
                    try
                    {
                        if (this.file0.PostedFile.FileName == "")
                        {
                            strIconSaveFileName = "";
                        }
                        else
                        {
                            if (!System.IO.Directory.Exists(Server.MapPath("~") + @"/Images"))
                            {
                                System.IO.Directory.CreateDirectory(Server.MapPath("~") + @"/Images");
                            }
                            if (!System.IO.Directory.Exists(String.Format(@"{0}/WXWall/images/{1}", Server.MapPath("~"), Session["strSiteCode"].ToString())))
                            {
                                System.IO.Directory.CreateDirectory(String.Format(@"{0}/WXWall/images/{1}", Server.MapPath("~"), Session["strSiteCode"].ToString()));
                            }
                            string orignalName = this.file0.PostedFile.FileName;                      //获取客户机上传文件的文件名
                            string extendName  = orignalName.Substring(orignalName.LastIndexOf(".")); //获取扩展名

                            if (extendName != ".gif" && extendName != ".jpg" && extendName != ".jpeg" && extendName != ".png")
                            {
                                MessageBox.Show(this, "文件格式有误!");
                                return;
                            }//检查文件格式
                            string newName = String.Format("{0}_{1}{2}", DateTime.Now.Millisecond, file0.PostedFile.ContentLength, extendName);//对文件进行重命名
                            strIconFileName     = String.Format(@"{0}WXWall/images/{1}/{2}", Server.MapPath("~"), Session["strSiteCode"].ToString(), newName);
                            strIconSaveFileName = String.Format(@"images/{0}/{1}", Session["strSiteCode"].ToString(), newName);
                            file0.PostedFile.SaveAs(strIconFileName);
                        }
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(this, "上传发生错误!原因是:" + ex.ToString());
                    }

                    //上传二维码图像
                    string strcodeIconFileName     = string.Empty; //图像路径
                    string strcodeIconSaveFileName = string.Empty; //网址路径
                    try
                    {
                        if (this.file1.PostedFile.FileName == "")
                        {
                            strcodeIconSaveFileName = "";
                        }
                        else
                        {
                            if (!System.IO.Directory.Exists(Server.MapPath("~") + @"/Images"))
                            {
                                System.IO.Directory.CreateDirectory(Server.MapPath("~") + @"/Images");
                            }
                            if (!System.IO.Directory.Exists(String.Format(@"{0}/WXWall/images/{1}", Server.MapPath("~"), Session["strSiteCode"].ToString())))
                            {
                                System.IO.Directory.CreateDirectory(String.Format(@"{0}/WXWall/images/{1}", Server.MapPath("~"), Session["strSiteCode"].ToString()));
                            }
                            string orignalName = this.file1.PostedFile.FileName;                      //获取客户机上传文件的文件名
                            string extendName  = orignalName.Substring(orignalName.LastIndexOf(".")); //获取扩展名

                            if (extendName != ".gif" && extendName != ".jpg" && extendName != ".jpeg" && extendName != ".png")
                            {
                                MessageBox.Show(this, "文件格式有误!");
                                return;
                            }//检查文件格式
                            string newName = String.Format("{0}_{1}{2}", DateTime.Now.Millisecond, file1.PostedFile.ContentLength, extendName);//对文件进行重命名
                            strcodeIconFileName     = String.Format(@"{0}WXWall/images/{1}/{2}", Server.MapPath("~"), Session["strSiteCode"].ToString(), newName);
                            strcodeIconSaveFileName = String.Format(@"images/{0}/{1}", Session["strSiteCode"].ToString(), newName);
                            file1.PostedFile.SaveAs(strcodeIconFileName);
                        }
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(this, "上传发生错误!原因是:" + ex.ToString());
                    }

                    ChatRoom model = new ChatRoom();
                    model.RoomName   = RoomName.Text;
                    model.RoomDesc   = hd_content.Value;
                    model.RoomImg    = strIconSaveFileName;
                    model.WebCodeImg = strcodeIconSaveFileName;
                    if (phonenum.Text.Trim() != null && phonenum.Text.Trim() != "")
                    {
                        model.PhoneNum = Convert.ToInt32(phonenum.Text);
                    }
                    if (appid.Text.Trim() != null && appid.Text.Trim() != "")
                    {
                        model.AppID = appid.Text;
                    }
                    model.SiteCode = Session["strSiteCode"].ToString();
                    model.IsDel    = 0;
                    model.ID       = roommaxnum;
                    if (dal.AddChatRoom(model))
                    {
                        MessageBox.Show(this, "操作成功!");
                    }
                    else
                    {
                        MessageBox.Show(this, "操作失败!");
                    }
                }
            }
            else
            {
                MessageBox.Show(this, "请输入相应标题名称!");
            }
        }
Example #40
0
File: Chat.cs Project: loqu8/JabbR
        private void OnUpdateActivity(ChatUser user, ChatRoom room)
        {
            var userViewModel = new UserViewModel(user);

            Clients.Group(room.Name).updateActivity(userViewModel, room.Name);
        }
Example #41
0
 public ChatRoomUser(ChatRoom room, IClient client)
 {
     Room   = room;
     Client = client;
 }
Example #42
0
File: Chat.cs Project: loqu8/JabbR
        private void UpdateActivity(ChatUser user, ChatRoom room)
        {
            UpdateActivity(user);

            OnUpdateActivity(user, room);
        }
Example #43
0
 private void LoadChatRooms()
 {
     ChatRoom chroomObj = new ChatRoom();
     chatRoomList.DataSource = chroomObj.GetAllChatRoom();
     chatRoomList.DataBind();
 }
Example #44
0
        public ICollection <User> GetUsers(ChatRoom chatRoom)
        {
            var entity = this.chatRoomRepository.Get(chatRoom.Id).Users;

            return(entity);
        }
Example #45
0
 public RoomUserMsg()
 {
     user    = new User();
     room    = new ChatRoom();
     message = "";
 }
Example #46
0
 private void MessageReceived(ChatRoom room, ChatMessage message)
 {
     GetMessagesAndDisplayConversationsList();
 }
Example #47
0
        private bool TryHandleCommand(string message)
        {
            string room = Caller.room;
            string name = Caller.name;

            message = message.Trim();
            if (message.StartsWith("/"))
            {
                string[] parts = message.Substring(1).Split(' ');
                string commandName = parts[0];

                if (commandName.Equals("nick", StringComparison.OrdinalIgnoreCase))
                {
                    string newUserName = String.Join(" ", parts.Skip(1));

                    if (String.IsNullOrEmpty(newUserName))
                    {
                        throw new InvalidOperationException("No username specified!");
                    }

                    if (newUserName.Equals(name, StringComparison.OrdinalIgnoreCase))
                    {
                        throw new InvalidOperationException("That's already your username...");
                    }

                    if (!_users.ContainsKey(newUserName))
                    {
                        if (String.IsNullOrEmpty(name) || !_users.ContainsKey(name))
                        {
                            var user = AddUser(newUserName);
                        }
                        else
                        {
                            var oldUser = _users[name];
                            var newUser = new ChatUser
                            {
                                Name = newUserName,
                                Hash = GetMD5Hash(newUserName),
                                Id = oldUser.Id,
                                ConnectionId = oldUser.ConnectionId
                            };

                            _users[newUserName] = newUser;
                            _userRooms[newUserName] = new HashSet<string>(_userRooms[name]);

                            if (_userRooms[name].Any())
                            {
                                foreach (var r in _userRooms[name])
                                {
                                    _rooms[r].Users.Remove(name);
                                    _rooms[r].Users.Add(newUserName);
                                    Clients[r].changeUserName(oldUser, newUser);
                                }
                            }

                            _userRooms.Remove(name);
                            _users.Remove(name);

                            Caller.hash = newUser.Hash;
                            Caller.name = newUser.Name;

                            Caller.changeUserName(oldUser, newUser);
                        }
                    }
                    else
                    {
                        throw new InvalidOperationException(String.Format("Username '{0}' is already taken!", newUserName));
                    }

                    return true;
                }
                else
                {
                    EnsureUser();
                    if (commandName.Equals("rooms", StringComparison.OrdinalIgnoreCase))
                    {
                        var rooms = _rooms.Select(r => new
                        {
                            Name = r.Key,
                            Count = r.Value.Users.Count
                        });

                        Caller.showRooms(rooms);

                        return true;
                    }
                    else if (commandName.Equals("join", StringComparison.OrdinalIgnoreCase))
                    {
                        if (parts.Length == 1)
                        {
                            throw new InvalidOperationException("Join which room?");
                        }

                        // Only support one room at a time for now

                        string newRoom = parts[1];
                        ChatRoom chatRoom;
                        // Create the room if it doesn't exist
                        if (!_rooms.TryGetValue(newRoom, out chatRoom))
                        {
                            chatRoom = new ChatRoom();
                            _rooms.Add(newRoom, chatRoom);
                        }

                        // Remove the old room
                        if (!String.IsNullOrEmpty(room))
                        {
                            _userRooms[name].Remove(room);
                            _rooms[room].Users.Remove(name);

                            Clients[room].leave(_users[name]);
                            RemoveFromGroup(room);
                        }

                        _userRooms[name].Add(newRoom);
                        if (!chatRoom.Users.Add(name))
                        {
                            throw new InvalidOperationException("You're already in that room!");
                        }

                        Clients[newRoom].addUser(_users[name]);

                        // Set the room on the caller
                        Caller.room = newRoom;

                        AddToGroup(newRoom);

                        Caller.refreshRoom(newRoom);

                        return true;
                    }
                    else if (commandName.Equals("msg", StringComparison.OrdinalIgnoreCase))
                    {
                        if (_users.Count == 1)
                        {
                            throw new InvalidOperationException("You're the only person in here...");
                        }

                        if (parts.Length < 2)
                        {
                            throw new InvalidOperationException("Who are you trying send a private message to?");
                        }

                        string to = parts[1];
                        if (to.Equals(name, StringComparison.OrdinalIgnoreCase))
                        {
                            throw new InvalidOperationException("You can't private message yourself!");
                        }

                        if (!_users.ContainsKey(to))
                        {
                            throw new InvalidOperationException(String.Format("Couldn't find any user named '{0}'.", to));
                        }

                        string messageText = String.Join(" ", parts.Skip(2)).Trim();

                        if (String.IsNullOrEmpty(messageText))
                        {
                            throw new InvalidOperationException(String.Format("What did you want to say to '{0}'.", to));
                        }

                        string recipientId = _users[to].ConnectionId;
                        // Send a message to the sender and the sendee
                        Clients[recipientId].sendPrivateMessage(name, to, messageText);
                        Caller.sendPrivateMessage(name, to, messageText);

                        return true;
                    }
                    else
                    {
                        EnsureUserAndRoom();
                        if (commandName.Equals("me", StringComparison.OrdinalIgnoreCase))
                        {
                            if (parts.Length == 1)
                            {
                                throw new InvalidProgramException("You what?");
                            }
                            var content = String.Join(" ", parts.Skip(1));

                            Clients[room].sendMeMessage(name, content);
                            return true;
                        }
                        else if (commandName.Equals("leave", StringComparison.OrdinalIgnoreCase))
                        {
                            ChatRoom chatRoom;
                            if (_rooms.TryGetValue(room, out chatRoom))
                            {
                                chatRoom.Users.Remove(name);
                                _userRooms[name].Remove(room);

                                Clients[room].leave(_users[name]);
                            }

                            RemoveFromGroup(room);

                            Caller.room = null;

                            return true;
                        }

                        throw new InvalidOperationException(String.Format("'{0}' is not a valid command.", parts[0]));
                    }
                }
            }
            return false;
        }
Example #48
0
        public Task <IRoom> BuildRoom(string roomName, CancellationToken token = default)
        {
            var chatRoom = new ChatRoom(roomName, roomName);

            return(BuildRoom(chatRoom, token));
        }
Example #49
0
        public void GivenAnEmptyChatRoom_WhenANewUserDisconnect_ThenNothingHappens()
        {
            var chat = new ChatRoom();

            ChatEvent chatEvent = chat.Disconnect("dummyConnection", Now);

            chatEvent.Should().Be(
                ChatEvent.NothingHappens(Now));
        }
Example #50
0
 public ChatRoomPasswordDialog(Window parent, ChatRoom room)
     : base(parent, "ChatRoomPasswordDialog")
 {
     this.room        = room;
     infoLabel.Markup = "<b>" + String.Format(infoLabel.Text, room.Name) + "</b>";
 }
Example #51
0
        public void GivenSomeConnectedUsers_WhenANotConnectedUserDisconnect_ThenNothingHappens()
        {
            var chat = new ChatRoom();
            chat.Connect("dummyUser1", DummyDateTime, DummyConnectionId());
            chat.Connect("dummyUser2", DummyDateTime, DummyConnectionId());

            ChatEvent chatEvent = chat.Disconnect("newConnection", Now);

            chatEvent.Should().Be(
               ChatEvent.NothingHappens(Now));
        }
Example #52
0
 public void AddDelayedChatPacket(ChatRoom roominfo, DataPacket dp)
 {
 }
Example #53
0
        public void GivenUsersLimitReached_WhenAnExistingUserMakeANewConnection_ThenShouldNotThrow()
        {
            var chat = new ChatRoom(2);
            chat.Connect("username", DummyDateTime, "connection1");
            chat.Connect("other", DummyDateTime, DummyConnectionId());

            Action act = () =>
                chat.Connect("username", DummyDateTime, "connection2");

            act.ShouldNotThrow<InvalidOperationException>();
        }
Example #54
0
 /// <summary>
 /// Creates a new chat room connection
 /// </summary>
 /// <param name="roominfo">The name of the chat room</param>
 /// <returns>The newly created chat connection</returns>
 public ChatConnection CreateNewChatConnection(ChatRoom roominfo)
 {
     ChatConnection retval = new ChatConnection(_parent, _id++, roominfo);
     roominfo.Connection = retval;
     _chatconnections.Add(roominfo);
     return retval;
 }
Example #55
0
    protected void Page_Load(object sender, EventArgs e)
    {
        if (WebUtil.PrepareEnvironment(this,
                                       ref app,
                                       ref sessioninfo) == false)
        {
            return;
        }

        // SSO登录
        PrepareSsoLogin();


        string strError = "";
        int    nRet     = 0;

#if NO
        // 是否登录?
        if (sessioninfo.UserID == "")
        {
            if (this.Page.Request["forcelogin"] == "on")
            {
                sessioninfo.LoginCallStack.Push(Request.RawUrl);
                Response.Redirect("login.aspx", true);
                return;
            }
            if (this.Page.Request["forcelogin"] == "userid")
            {
                sessioninfo.LoginCallStack.Push(Request.RawUrl);
                Response.Redirect("login.aspx?loginstyle=librarian", true);
                return;
            }
            sessioninfo.LoginCallStack.Push(Request.RawUrl);
            Response.Redirect("login.aspx", true);
            return;
        }
#endif

        /*
         * Decoder decoder = (Decoder)this.Session["decoder"];
         * if (decoder == null)
         * {
         *  decoder = Encoding.UTF8.GetDecoder();
         *  this.Session["decoder"] = decoder;
         * }
         * */


        LoginState loginstate = GlobalUtil.GetLoginState(this.Page);

        bool bIsManager = false;

        if (loginstate == LoginState.Librarian &&
            StringUtil.IsInList("managechatroom", sessioninfo.RightsOrigin) == true)
        {
            bIsManager = true;
        }

        string strAction = this.Request["action"];

        if (strAction == "getimage")
        {
            DoGetImage();
            return;
        }

        if (strAction == "sendimage")
        {
            DoSendImage();
            return;
        }

        if (strAction == "send")
        {
            DoSendText(loginstate);
            return;
        }

        if (strAction == "delete")
        {
            DoDeleteItem(-1, bIsManager);
            return;
        }

        if (strAction == "getinfo")
        {
            DoGetInfo(bIsManager);
            return;
        }

        if (strAction == "optionchanged")
        {
            DoOptionChanged();
            return;
        }

        // 以下为出现页面
        if (this.IsPostBack == false)
        {
            List <string> name_list = app.ChatRooms.GetRoomNames(
                MergeRights(sessioninfo.RightsOrigin, sessioninfo.SsoRights));
            foreach (string name in name_list)
            {
                this.DropDownList_roomName.Items.Add(name);
            }

            if (loginstate == LoginState.Public ||
                loginstate == LoginState.NotLogin)
            {
                this.TextBox_userName.Enabled = true;
            }
            else
            {
                this.TextBox_userName.Enabled = false;

                this.TextBox_userName.Text = sessioninfo.UserID;
                if (loginstate == LoginState.Reader &&
                    sessioninfo.ReaderInfo != null &&
                    string.IsNullOrEmpty(sessioninfo.ReaderInfo.DisplayName) == false)
                {
                    this.TextBox_userName.Text = "[" + sessioninfo.ReaderInfo.DisplayName + "]";
                }
            }

            // 通过URL直接选定栏目
            string strRoom = this.Request["room"];
            if (string.IsNullOrEmpty(strRoom) == false)
            {
                DecodeUri(ref strRoom);

                string strTemp = "";
                // return:
                //      -2  权限不够
                //      -1  出错
                //      0   栏目不存在
                //      1   栏目找到
                nRet = app.GetRoomName(
                    MergeRights(sessioninfo.RightsOrigin, sessioninfo.SsoRights),
                    strRoom,
                    out strTemp);
                if (nRet == 1)
                {
                    strRoom = strTemp;
                    this.DropDownList_roomName.Text = strRoom;
                }
                else if (nRet == -2)
                {
                    /*
                     * sessioninfo.LoginCallStack.Push(Request.RawUrl);
                     * Response.Redirect("login.aspx", true);
                     * */
                    Response.Redirect(this.TitleBarControl1.GetLoginUrl(), true);
                    return;
                }
                else
                {
                    strError = "栏目 '" + strRoom + "' 不存在";
                    goto ERROR1;
                }
            }

            // 首次设置displayOperation(缺省为false) 根据Cookie
            HttpCookie cookie = this.Request.Cookies["dp2opac-chat"];
            if (cookie != null)
            {
                Hashtable table = StringUtil.ParseParameters(cookie.Value, ',', '=', "url");

                this.CheckBox_displayOperation.Checked = StringUtil.GetBooleanValue((string)table["displayOperation"], false);
            }
            else
            {
                this.CheckBox_displayOperation.Checked = false;
            }

            if (string.IsNullOrEmpty(sessioninfo.UserID) == true)
            {
                this.Label_userNameComment.Text = "(您现在是访客身份)";
            }
        }

        this.TextBox_currentDate.Text = DateTimeUtil.DateTimeToString8(this.Calendar1.SelectedDate);
        if (this.TextBox_currentDate.Text == "00010101")
        {
            this.TextBox_currentDate.Text = DateTimeUtil.DateTimeToString8(DateTime.Now);
            this.Calendar1.SelectedDate   = DateTime.Now;
        }

        if (bIsManager == true)
        {
            // 创建和删除栏目的界面要素
            this.PlaceHolder_createDialog.Visible   = true;
            this.PlaceHolder_managemenPanel.Visible = true;
        }
        else
        {
            this.PlaceHolder_createDialog.Visible   = false;
            this.PlaceHolder_managemenPanel.Visible = false;
        }

        {
            // -1 0 1
            int nIsEditor = app.IsEditor(this.DropDownList_roomName.Text,
                                         sessioninfo.UserID,
                                         out strError);

            if (nIsEditor == 1 || bIsManager == true)
            {
                // 指示javascript代码,显示每个消息的删除按钮
                this.HiddenField_isManager.Value = "yes";
            }
            else
            {
                this.HiddenField_isManager.Value = "no";
            }
        }

        this.HiddenField_today.Value = DateTimeUtil.DateTimeToString8(DateTime.Now);

        ChatRoom room = app.GetChatRoom(
            MergeRights(sessioninfo.RightsOrigin, sessioninfo.SsoRights),
            this.DropDownList_roomName.Text);
        this.HiddenField_editors.Value = room != null?StringUtil.MakePathList(room.EditorList) : "";

        return;

ERROR1:
        this.Response.Write(strError);
        this.Response.End();
    }
Example #56
0
        //
        // GET: /Chat/Start
        public ActionResult Start(string id)
        {
            var toId = WebSecurity.GetUserId(id);
            var myId = WebSecurity.GetUserId(User.Identity.Name);

            var inboxes = db.ChatInboxes.Where(i => i.UserId == toId || i.UserId == myId).ToList();

            ChatRoom room = new ChatRoom()
            {
                ConnectionId = string.Format("{0};{1}", User.Identity.Name, id),
                User1 = User.Identity.Name,
                User2 = id
            };

            db.ChatRooms.Add(room);
            //db.SaveChanges();

            foreach (var inbox in inboxes)
                inbox.ChatRooms.Add(room);

            db.SaveChanges();

            return RedirectToAction("~/Home/Index");
        }
Example #57
0
 public void ChangeWelcome(ChatUser user, ChatRoom room, string newWelcome)
 {
     EnsureOwnerOrAdmin(user, room);
     room.Welcome = newWelcome;
     _repository.CommitChanges();
 }
Example #58
0
File: Chat.cs Project: loqu8/JabbR
 void INotificationService.OnSelfMessage(ChatRoom room, ChatUser user, string content)
 {
     Clients.Group(room.Name).sendMeMessage(user.Name, content, room.Name);
 }
Example #59
0
        public void GivenAConnectedUser_WhenTheUserDisconnect_ThenTheUserShouldLeaveChat()
        {
            var chat = new ChatRoom();
            chat.Connect("username", DummyDateTime, "connection");

            ChatEvent chatEvent = chat.Disconnect("connection", Now);

            chatEvent.Should().Be(
                ChatEvent.UserLeavesChat("username", Now));
        }
Example #60
0
        public ICollection <Post> GetPosts(ChatRoom chatRoom)
        {
            var entity = this.chatRoomRepository.Get(chatRoom.Id).Posts;

            return(entity);
        }