Ejemplo n.º 1
0
        private void CheckMessage(EventPacket packet, PluginContext context)
        {
            if (!enabled) return;

            bool isToBot = MessageHelper.IsMessageToUser(packet.Message, context.BotSettings.UserName, MsgUsernameParse.Strict);

            // if it's not to us or the message is from us, then don't do anything
            if (!isToBot || packet.From.Equals(context.BotSettings.UserName, StringComparison.OrdinalIgnoreCase))
                return;

            string message = packet.Message.Replace(context.BotSettings.UserName + ":", string.Empty);
            var session = GetSession(packet.From);

            try
            {
                string response = session.Think(message);
                context.ThisRoom.Respond(response);
            }
            catch (Exception ex)
            {
                // log error and try to restart the conversation
                context.Console.WriteLine("Error getting AI response. See bot log for details.", Core.Framework.Shell.Style.Error);
                context.Logger.ErrorFormat(ex, "Error getting AI response. See bot log for details.");
                context.ThisRoom.Respond("Sorry, I missed that. Could you say that again?");
            }
        }
Ejemplo n.º 2
0
        private void AdminRemove(EventPacket eventPacket, PluginContext context)
        {
            string chatroom = eventPacket.ChatRoom;
            var room = context.ChatRooms[chatroom];

            if (room == null)
            {
                context.Logger.ErrorFormat("Error: priv remove for a chatroom which doesn't exist.");
                return;
            }

            Packet subPacket = eventPacket.Packet.GetSubPacket();
            string by = subPacket.args["by"];
            string privClass = subPacket.args["name"];
            room.RemovePrivClass(privClass);

            // get all users who have this priv class
            List<Member> members = (from m in room.Members
                                    where m.PrivClass == privClass
                                    select m).ToList();

            // update their priv class
            foreach (Member m in members)
                m.PrivClass = string.Empty;

            context.Console.WriteLine(string.Format("The privclass '{0}' was removed by {1}.", privClass, by));
            room.Logger.Log(eventPacket.Packet);
        }
Ejemplo n.º 3
0
        private void ChatroomPrivClasses(EventPacket eventPacket, PluginContext context)
        {
            string chatroom = eventPacket.ChatRoom;
            var room = context.ChatRooms[chatroom];

            if (room == null)
            {
                context.Logger.ErrorFormat("Error: member add to a chatroom which doesn't exist.");
                return;
            }

            // iterate through each priv class
            string[] privClasses = eventPacket.Packet.body.TrimEnd('\n').Split('\n');
            foreach (string privClass in privClasses)
            {
                // get priv class details
                string[] tokens = privClass.Split(':');
                string privClassName = tokens[1];
                int privClassLevel = Convert.ToInt32(tokens[0]);

                // add to room
                if (room.HasPrivClass(privClassName))
                    room.GetPrivClass(privClassName).Order = privClassLevel;
                else
                    room.AddPrivClass(new PrivClass(privClassName, privClassLevel));
            }
        }
Ejemplo n.º 4
0
        private void Part(EventPacket eventPacket, PluginContext context)
        {
            var packet = eventPacket.Packet;
            string chatroom = eventPacket.ChatRoom;

            if (packet.args["e"] == "not joined" ||
                packet.args["e"] == "bad namespace")
                return; // bail here because we wouldn't have this chatroom registered in these cases

            // get part reason
            string reason = string.Empty;
            if (packet.args.ContainsKey("r"))
                reason = packet.args["r"];
            reason = string.IsNullOrEmpty(reason) ? reason : " Reason: " + reason;

            // tell the bot to leave the chatroom
            context.ChatRooms[chatroom].Logger.Log(packet);
            context.ChatRooms.Remove(chatroom);
            context.Console.WriteLine(string.Format("** Bot has left the chatroom {0}.{1}", chatroom, reason), Style.Out);

            // if it's an autojoin channel, try to sign back in
            if (context.BotSettings.AutoJoins.Contains(chatroom.Trim('#')))
            {
                context.Client.Join(chatroom);
                context.Console.WriteLine("*** Bot rejoined " + chatroom + " *", Style.Out);
            }
            else if (context.ChatRooms.Count == 0)
            {
                context.Console.WriteLine("No longer joined to any rooms! Exiting...", Style.Warning);
                context.Listener.Stop();
            }
        }
Ejemplo n.º 5
0
        private void ChatroomPrivChange(EventPacket eventPacket, PluginContext context)
        {
            string chatroom = eventPacket.ChatRoom;
            var room = context.ChatRooms[chatroom];

            if (room == null)
            {
                context.Logger.ErrorFormat("Error: priv change for a chatroom which doesn't exist.");
                return;
            }

            // get info from packet
            Packet subPacket = eventPacket.Packet.GetSubPacket();
            string username = subPacket.param;
            string privClass = subPacket.args["pc"];
            string by = subPacket.args["by"];

            // update priv class if user is signed on
            Member member = room.GetMember(username);
            if (member != null)
            {
                member.PrivClass = privClass;
            }

            context.Console.WriteLine(string.Format("** {0} has been made a member of {1} by {2} *", username, privClass, by), Style.Warning);
            room.Logger.Log(eventPacket.Packet);
        }
Ejemplo n.º 6
0
        private void Join(EventPacket eventPacket, PluginContext context)
        {
            var packet = eventPacket.Packet;
            string chatroom = eventPacket.ChatRoom;

            if (packet.args["e"] != "ok")
            {
                context.ChatRooms.Remove(chatroom);
                context.Console.WriteLine(string.Format("Unable to join chatroom {0}. Reason: {1}", chatroom, packet.args["e"]), Style.Warning);

                if (context.ChatRooms.Count == 0)
                {
                    context.Console.WriteLine("No longer joined to any rooms! Exiting...", Style.Warning);
                    context.Listener.Stop();
                    return;
                }
                else
                {
                    return;
                }
            }
            context.Console.WriteLine(string.Format("*** Bot has joined {0} *", chatroom), Style.Out);
            if (!context.ChatRooms.HasChatRoom(chatroom))
                context.ChatRooms.Add(chatroom);
        }
Ejemplo n.º 7
0
        private void AdminRename(EventPacket eventPacket, PluginContext context)
        {
            string chatroom = eventPacket.ChatRoom;
            var room = context.ChatRooms[chatroom];

            if (room == null)
            {
                context.Logger.ErrorFormat("Error: priv rename for a chatroom which doesn't exist.");
                return;
            }

            Packet subPacket = eventPacket.Packet.GetSubPacket();
            string privClass = subPacket.args["prev"];
            string newPrivClass = subPacket.args["name"];
            string by = subPacket.args["by"];
            if (room.HasPrivClass(privClass))
            {
                int privClassLevel = room.GetPrivClass(privClass).Order;
                // remove the old and add the new
                room.RemovePrivClass(privClass);
                room.AddPrivClass(new PrivClass(newPrivClass, privClassLevel));

                // update users who have this priv class
                List<Member> members = (from m in room.Members
                                        where m.PrivClass == privClass
                                        select m).ToList();
                // update their priv class to the new one
                foreach (Member m in members)
                    m.PrivClass = newPrivClass;

                context.Console.WriteLine(string.Format("The privclass '{0}' was renamed to '{!}' by {2}.", privClass, newPrivClass, by));
                room.Logger.Log(eventPacket.Packet);
            }
        }
Ejemplo n.º 8
0
        private void AdminMove(EventPacket eventPacket, PluginContext context)
        {
            string chatroom = eventPacket.ChatRoom;
            var room = context.ChatRooms[chatroom];

            if (room == null)
            {
                context.Logger.ErrorFormat("Error: priv move for a chatroom which doesn't exist.");
                return;
            }

            Packet subPacket = eventPacket.Packet.GetSubPacket();
            string privClass = subPacket.args["prev"];
            string newPrivClass = subPacket.args["name"];
            string by = subPacket.args["by"];

            // get all users who have this priv class
            List<Member> members = (from m in room.Members
                                    where m.PrivClass == privClass
                                    select m).ToList();

            // update their priv class to the new one
            foreach (Member m in members)
                m.PrivClass = newPrivClass;

            context.Console.WriteLine(string.Format("{0} users moved from privclass '{1}' to '{2}' by {3}.", members.Count, privClass, newPrivClass, by));
            room.Logger.Log(eventPacket.Packet);
        }
Ejemplo n.º 9
0
        private void Kicked(EventPacket eventPacket, PluginContext context)
        {
            string chatroom = eventPacket.ChatRoom;
            var room = context.ChatRooms[chatroom];
            var packet = eventPacket.Packet;

            if (room == null)
            {
                context.Logger.ErrorFormat("Error: kick event for a chatroom which doesn't exist.");
                return;
            }

            // log kick
            string reason = string.IsNullOrEmpty(packet.body) ? string.Empty : " Reason: " + packet.body;
            string message = string.Format("Bot was kicked from {0}.{1}", chatroom, reason);
            room.Logger.Log(packet);
            context.Console.WriteLine(message, Style.Warning);

            // remove chatroom
            context.ChatRooms.Remove(chatroom);

            // if it's an autojoin channel, try to sign back in
            if (context.BotSettings.AutoJoins.Contains(chatroom.Trim('#')))
            {
                context.Client.Join(chatroom);
                context.Console.WriteLine("Bot rejoined " + chatroom);
            }
        }
Ejemplo n.º 10
0
        private void Part(EventPacket packet, PluginContext context)
        {
            if (!context.ChatRooms.HasChatRoom(packet.ChatRoom))
                return; // we don't have a reference for some wierd reason

            var chatroom = context.ChatRooms[packet.ChatRoom];
            MainWindowInvoke(window => window.PartChatroom(chatroom));
        }
Ejemplo n.º 11
0
 private void CheckMessage(EventPacket packet, PluginContext context)
 {
     // make sure the message is to us but not from us - if so flash the window
     if (MessageHelper.IsMessageToUser(packet.Message, context.BotSettings.UserName, MsgUsernameParse.Lazy) &&
         packet.From.ToLower() != context.BotSettings.UserName.ToLower() &&
         packet.ChatRoom.ToLower().Trim('#') != "datashare")
     {
         FlashConsoleWindow(Process.GetCurrentProcess().MainWindowHandle);
     }
 }
Ejemplo n.º 12
0
        private void AutoJoinDatashare(EventPacket packet, PluginContext context)
        {
            var p = packet.Packet;
            if (p.args.ContainsKey("e") && p.args["e"] == "ok")
            {
                // we've successfully logged in, register all BDS handlers
                bdsHandlers.Add("BOTCHECK", BdsBotcheck);
                bdsHandlers.Add("BOTDEF", BdsBotdef);

                // join the room
                context.Client.Join(DatashareNS);
            }
        }
Ejemplo n.º 13
0
 private void Action(EventPacket eventPacket, PluginContext context)
 {
     var room = context.ChatRooms[eventPacket.ChatRoom];
     if (room != null && room.Logger.Enabled)
     {
         var subPacket = eventPacket.Packet.GetSubPacket();
         context.Console.WriteLine(string.Format("[{0}] * {1} {2}",
             eventPacket.ChatRoom,
             subPacket.args["from"],
             subPacket.body));
         room.Logger.Log(eventPacket.Packet);
     }
 }
Ejemplo n.º 14
0
        private void ChatroomMemberList(EventPacket eventPacket, PluginContext context)
        {
            string chatroom = eventPacket.ChatRoom;
            var room = context.ChatRooms[chatroom];

            if (room == null)
            {
                context.Logger.ErrorFormat("Error: member list for a chatroom which doesn't exist.");
                return;
            }

            // iterate through each user
            string[] subPackets = eventPacket.Packet.body.Split(new string[] { "\n\n" }, StringSplitOptions.None);
            foreach (string subPacket in subPackets)
            {
                if (subPacket == "")
                    continue;

                // get subpacket
                Packet p = new Packet(subPacket);
                Member member = room.GetMember(p.param);
                if (member == null)
                {
                    // get the bot user if they exist
                    var user = context.Authorizer.GetUser(p.param);

                    room.AddMember(new Member
                    {
                        UserName = p.param,
                        RealName = p.args.ContainsKey("realname") ? p.args["realname"] : string.Empty,
                        Description = p.args.ContainsKey("typename") ? p.args["typename"] : string.Empty,
                        PrivClass = p.args.ContainsKey("pc") ? p.args["pc"] : string.Empty,
                        //ServerPrivClass = p.args["gpc"],
                        Symbol = p.args.ContainsKey("symbol") ? p.args["symbol"] : string.Empty,
                        Role = user == null ? context.Authorizer.DefaultRole : user.Role
                    });
                }
                else
                {
                    member.UserName = p.param;
                    member.RealName = p.args.ContainsKey("realname") ? p.args["realname"] : string.Empty;
                    member.Description = p.args.ContainsKey("typename") ? p.args["typename"] : string.Empty;
                    member.PrivClass = p.args.ContainsKey("pc") ? p.args["pc"] : string.Empty;
                    //user.ServerPrivClass = p.args["gpc"];
                    member.Symbol = p.args.ContainsKey("symbol") ? p.args["symbol"] : string.Empty;
                    member.Count++;
                }
            }
        }
Ejemplo n.º 15
0
        private void ChatroomJoin(EventPacket eventPacket, PluginContext context)
        {
            var packet = eventPacket.Packet;
            string chatroom = eventPacket.ChatRoom;
            var room = context.ChatRooms.Get(chatroom);

            if (room == null)
            {
                context.Logger.ErrorFormat("Error: user add for chatroom '{0}' which doesn't exist.", chatroom);
                return;
            }

            Packet subPacket = packet.GetSubPacket();
            string username = subPacket.param;
            // user may exist already (bot and user can sign on at same time)
            var member = room.GetMember(username);
            if (member == null)
            {
                // get user details from  arg list from the packet
                Packet.Args a = Packet.Args.getArgsNData(subPacket.body);

                // get the bot user if they exist
                var user = context.Authorizer.GetUser(username);

                // create new user
                Member m = new Member
                {
                    UserName = username,
                    PrivClass = a.args["pc"],
                    Symbol = a.args["symbol"],
                    RealName = a.args["realname"],
                    Description = a.args["typename"],
                    ServerPrivClass = a.args["gpc"],
                    Role = user == null ? context.Authorizer.DefaultRole : user.Role
                };
                room.AddMember(m);
            }
            else
            {
                member.Count++;
            }

            if (room.Logger.Enabled)
            {
                context.Console.WriteLine(string.Format("[{0}] {1} joined.", chatroom, username));
                room.Logger.Log(eventPacket.Packet);
            }
        }
Ejemplo n.º 16
0
        private void ChatroomTopic(EventPacket eventPacket, PluginContext context)
        {
            string chatroom = eventPacket.ChatRoom;
            var room = context.ChatRooms[chatroom];

            if (room == null)
            {
                context.Logger.ErrorFormat("Error: topic change for chatroom '{0}' which doesn't exist.", chatroom);
                return;
            }

            string topic = eventPacket.Packet.body;
            room.Topic = topic;
            //context.Console.WriteLine("Room topic is: " + topic.Left(150) + (topic.Length >= 150 ? "..." : ""));
            room.Logger.Log(eventPacket.Packet);
        }
Ejemplo n.º 17
0
        private void ChatroomTitle(EventPacket eventPacket, PluginContext context)
        {
            string chatroom = eventPacket.ChatRoom;
            var room = context.ChatRooms[chatroom];

            if (room == null)
            {
                context.Logger.ErrorFormat("Error: title change for chatroom '{0}' which doesn't exist.", chatroom);
                return;
            }

            string title = eventPacket.Packet.body;
            room.Title = title;
            //context.Console.WriteLine("Room title is: " +  title);
            room.Logger.Log(eventPacket.Packet);
        }
Ejemplo n.º 18
0
 /// <summary>
 /// Initializes a new instance of the <see cref="PluginContext"/> class.
 /// Is marked as internal so external clients cannot instantiate.
 /// </summary>
 /// <param name="client">The client.</param>
 /// <param name="console">The console.</param>
 /// <param name="authorizer">The authorizer.</param>
 /// <param name="chatrooms">The chatrooms.</param>
 /// <param name="listener">The listener.</param>
 /// <param name="botSettings">The bot settings.</param>
 /// <param name="pluginHandler">The plugin handler.</param>
 /// <param name="dispatcher">The system dispatcher.</param>
 /// <param name="packet">The current packet to be processed.</param>
 /// <param name="chatHelper">The chat helper.</param>
 public PluginContext(Client client, IConsole console,
     IAuthorization authorizer, IChatRoomContainer chatrooms,
     IListener listener, IBotSettings botSettings, 
     IPluginHandler pluginHandler, IDispatcher dispatcher, 
     EventPacket packet, IChatHelper chatHelper)
 {
     this.Client = client;
     this.Console = console;
     this.Authorizer = authorizer;
     this.ChatRooms = chatrooms;
     this.Listener = listener;
     this.BotSettings = botSettings;
     this.Plugins = pluginHandler;
     this.Dispatcher = dispatcher;
     this.ThisRoom = chatHelper;
 }
Ejemplo n.º 19
0
        private void AdminError(EventPacket eventPacket, PluginContext context)
        {
            string chatroom = eventPacket.ChatRoom;
            var room = context.ChatRooms[chatroom];

            if (room == null)
            {
                context.Logger.ErrorFormat("Error: admin show command for a chatroom which doesn't exist.");
                return;
            }

            Packet subPacket = eventPacket.Packet.GetSubPacket();
            string command = subPacket.body;
            string error = subPacket.args["e"];
            context.Console.WriteLine(string.Format("Admin error. The command '{0}' returned: {1}", command, error));
            room.Logger.Log(eventPacket.Packet);
        }
Ejemplo n.º 20
0
        private void AdminUpdate(EventPacket eventPacket, PluginContext context)
        {
            string chatroom = eventPacket.ChatRoom;
            var room = context.ChatRooms[chatroom];

            if (room == null)
            {
                context.Logger.ErrorFormat("Error: priv update for a chatroom which doesn't exist.");
                return;
            }

            Packet subPacket = eventPacket.Packet.GetSubPacket();
            string privClass = subPacket.args["name"];
            string by = subPacket.args["by"];
            string privs = subPacket.args["privs"];

            context.Console.WriteLine(string.Format("** privilege class {0} has been updated  by {1} with {2}", privClass, by, privs));
            room.Logger.Log(eventPacket.Packet);
        }
Ejemplo n.º 21
0
        private void AdminCreate(EventPacket eventPacket, PluginContext context)
        {
            string chatroom = eventPacket.ChatRoom;
            var room = context.ChatRooms[chatroom];

            if (room == null)
            {
                context.Logger.ErrorFormat("Error: priv add for a chatroom which doesn't exist.");
                return;
            }

            Packet subPacket = eventPacket.Packet.GetSubPacket();
            string privClass = subPacket.args["name"];
            string by = subPacket.args["by"];
            room.AddPrivClass(new PrivClass(privClass, 1)); // TODO - figure out what really happens here

            context.Console.WriteLine(string.Format("Privclass '{0}' was created by {1}.", privClass, by));
            room.Logger.Log(eventPacket.Packet);
        }
Ejemplo n.º 22
0
        private void _mainWorker_OnPageLoaded(string url, int status)
        {
            // log.Info("Navigated to:"+url);

            GenericEvent msg = new GenericEvent()
            {
                StringContent = url,
                GenericType   = BrowserEventType.Generic,
                Type          = GenericEventType.PageLoaded
            };

            EventPacket ep = new EventPacket
            {
                Event = msg,
                Type  = BrowserEventType.Generic
            };

            if (!_outCommServer.TrySend(ep, 100))
            {
                log.Info("message send failed");
            }
        }
Ejemplo n.º 23
0
        public void SendNavigateEvent(string url, bool back, bool forward)
        {
            if (Initialized)
            {
                if (!(url.StartsWith("http://") || url.StartsWith("https://")))
                {
                    url = "https://www.google.com/search?q=" + url;
                }

                GenericEvent ge = new GenericEvent()
                {
                    Type        = GenericEventType.Navigate,
                    GenericType = MessageLibrary.BrowserEventType.Generic,
                    NavigateUrl = url
                };

                if (back)
                {
                    ge.Type = GenericEventType.GoBack;
                }
                else if (forward)
                {
                    ge.Type = GenericEventType.GoForward;
                }

                EventPacket ep = new EventPacket()
                {
                    Event = ge,
                    Type  = MessageLibrary.BrowserEventType.Generic
                };

                /*MemoryStream mstr = new MemoryStream();
                 * BinaryFormatter bf = new BinaryFormatter();
                 * bf.Serialize(mstr, ep);
                 * byte[] b = mstr.GetBuffer();
                 * _outCommServer.WriteBytes(b);*/
                _outCommServer.WriteMessage(ep);
            }
        }
Ejemplo n.º 24
0
        public EventPacket GetMessage()
        {
            if (_isWrite)
            {
                return(null);
            }

            byte[] arr = ReadBytes();
            //  EventPacket ret = null;

            if (arr != null)
            {
                try
                {
                    MemoryStream    mstr = new MemoryStream(arr);
                    BinaryFormatter bf   = new BinaryFormatter();
                    EventPacket     ep   = bf.Deserialize(mstr) as EventPacket;

                    if (ep != null && ep.Type != BrowserEventType.StopPacket)
                    {
                        //_lastPacket = ep;
                        //log.Info("_____RETURNING PACKET:" + ep.Type.ToString());
                        WriteStop();
                        return(ep);
                    }
                    else
                    {
                        return(null);
                    }
                }
                catch (Exception ex)
                {
                    log.Error("Serialization exception,length=" + arr.Length + ":" + ex.Message);
                    return(null);
                }
            }
            return(null);
        }
Ejemplo n.º 25
0
        private void ChatroomPart(EventPacket eventPacket, PluginContext context)
        {
            var packet = eventPacket.Packet;
            string chatroom = eventPacket.ChatRoom;
            var room = context.ChatRooms.Get(chatroom);

            if (room == null)
            {
                context.Logger.ErrorFormat("Error: user part for chatroom '{0}' which doesn't exist.", chatroom);
                return;
            }

            Packet subPacket = packet.GetSubPacket();
            string username = subPacket.param;
            string reason = "reason unknown";
            if (subPacket.args.ContainsKey("r"))
                reason = subPacket.args["r"];
            // if more than one user is signed in with same user name, only unregister
            // them if it is the last one
            Member member = room.GetMember(username);
            if (member != null)
            {
                if (member.Count == 1)
                {
                    room.RemoveMember(username);
                }
                else
                {
                    member.Count--;
                }
            }

            if (room.Logger.Enabled)
            {
                context.Console.WriteLine(string.Format("[{0}] ** {1} has left. [{2}]", chatroom, username, reason));
                room.Logger.Log(eventPacket.Packet);
            }
        }
Ejemplo n.º 26
0
        public void SendCharEvent(int character, KeyboardEventType type)
        {
            log.Info("____________CHAR EVENT:" + character);
            KeyboardEvent keyboardEvent = new KeyboardEvent()
            {
                Type = type,
                Key  = character
            };
            EventPacket ep = new EventPacket()
            {
                Event = keyboardEvent,
                Type  = BrowserEventType.Keyboard
            };

            MemoryStream    mstr = new MemoryStream();
            BinaryFormatter bf   = new BinaryFormatter();

            bf.Serialize(mstr, ep);
            byte[] b = mstr.GetBuffer();
            //
            _outCommServer.WriteBytes(b);
            //  MessageBox.Show(_sendEvents.Count.ToString());
        }
Ejemplo n.º 27
0
        public void SendCharEvent(int character, KeyboardEventType type)
        {
            KeyboardEvent keyboardEvent = new KeyboardEvent()
            {
                Type = type,
                Key  = character
            };
            EventPacket ep = new EventPacket()
            {
                Event = keyboardEvent,
                Type  = BrowserEventType.Keyboard
            };

            MemoryStream    mstr = new MemoryStream();
            BinaryFormatter bf   = new BinaryFormatter();

            bf.Serialize(mstr, ep);
            byte[] b = mstr.GetBuffer();
            lock (_clientSocket.GetStream())
            {
                _clientSocket.GetStream().Write(b, 0, b.Length);
            }
        }
Ejemplo n.º 28
0
        public void SendQueryResponse(string response)
        {
            GenericEvent ge = new GenericEvent()
            {
                Type          = GenericEventType.JSQueryResponse,
                GenericType   = BrowserEventType.Generic,
                StringContent = response
            };

            EventPacket ep = new EventPacket()
            {
                Event = ge,
                Type  = BrowserEventType.Generic
            };

            MemoryStream    mstr = new MemoryStream();
            BinaryFormatter bf   = new BinaryFormatter();

            bf.Serialize(mstr, ep);
            byte[] b = mstr.GetBuffer();
            //
            _outCommServer.WriteBytes(b);
        }
Ejemplo n.º 29
0
        private void _mainWorker_OnJSDialog(string message, string prompt, DialogEventType type)
        {
            DialogEvent msg = new DialogEvent()
            {
                DefaultPrompt = prompt,
                Message       = message,
                Type          = type,
                GenericType   = BrowserEventType.Dialog
            };

            EventPacket ep = new EventPacket
            {
                Event = msg,
                Type  = BrowserEventType.Dialog
            };

            MemoryStream    mstr = new MemoryStream();
            BinaryFormatter bf   = new BinaryFormatter();

            bf.Serialize(mstr, ep);

            _outCommServer.WriteBytes(mstr.GetBuffer());
        }
Ejemplo n.º 30
0
        public void SendShutdownEvent()
        {
            GenericEvent ge = new GenericEvent()
            {
                Type        = GenericEventType.Shutdown,
                GenericType = BrowserEventType.Generic
            };

            EventPacket ep = new EventPacket()
            {
                Event = ge,
                Type  = BrowserEventType.Generic
            };

            MemoryStream    mstr = new MemoryStream();
            BinaryFormatter bf   = new BinaryFormatter();

            bf.Serialize(mstr, ep);
            byte[] b = mstr.GetBuffer();
            //
            _outCommServer.WriteBytes(b);
            //  MessageBox.Show(_sendEvents.Count.ToString());
        }
Ejemplo n.º 31
0
        public void SendShutdownEvent()
        {
            GenericEvent ge = new GenericEvent()
            {
                Type        = GenericEventType.Shutdown,
                GenericType = BrowserEventType.Generic
            };

            EventPacket ep = new EventPacket()
            {
                Event = ge,
                Type  = BrowserEventType.Generic
            };

            MemoryStream    mstr = new MemoryStream();
            BinaryFormatter bf   = new BinaryFormatter();

            bf.Serialize(mstr, ep);
            byte[] b = mstr.GetBuffer();
            lock (_clientSocket.GetStream())
            {
                _clientSocket.GetStream().Write(b, 0, b.Length);
            }
        }
Ejemplo n.º 32
0
        public void SendMouseEvent(MouseMessage msg)
        {
            // if (_MouseDone)
            //_controlMem.Write(ref msg,0);
            // _MouseDone = false;

            if (!_inModalDialog)
            {
                EventPacket ep = new EventPacket
                {
                    Event = msg,
                    Type  = BrowserEventType.Mouse
                };

                MemoryStream    mstr = new MemoryStream();
                BinaryFormatter bf   = new BinaryFormatter();
                bf.Serialize(mstr, ep);
                byte[] b = mstr.GetBuffer();

                //
                _outCommServer.WriteBytes(b);
            }
            //  MessageBox.Show(_sendEvents.Count.ToString());
        }
Ejemplo n.º 33
0
        public void SendDialogResponse(bool ok)
        {
            DialogEvent de = new DialogEvent()
            {
                GenericType = BrowserEventType.Dialog,
                success     = ok,
                input       = ""
            };

            EventPacket ep = new EventPacket
            {
                Event = de,
                Type  = BrowserEventType.Dialog
            };

            MemoryStream    mstr = new MemoryStream();
            BinaryFormatter bf   = new BinaryFormatter();

            bf.Serialize(mstr, ep);
            byte[] b = mstr.GetBuffer();

            //
            _outCommServer.WriteBytes(b);
        }
Ejemplo n.º 34
0
        /// <summary>
        /// Gets the data usage or AFLT hits for the period.
        /// </summary>
        /// <param name="type">The type of count to get.</param>
        /// <param name="dataFactory">The data to use for testing.</param>
        /// <returns>The devices meeting the specified criteria.</returns>
        public DataTable GetData(Enumerators.StatisticsType type, DataFactory dataFactory)
        {
            DataTable result = null;

            DataFactory df = new DataFactory();

            if (dataFactory != null)
            {
                df = dataFactory;
            }

            DataTable temp = null;

            try
            {
                if (type == Enumerators.StatisticsType.DataUsage)
                {
                    this.eventPacket = df.GetNewEventPacket();
                    temp             = this.eventPacket.GetPacketsByDateRange(this.startDate, this.endDate);
                }
                else
                {
                    this.gpsData = df.GetNewGpsData();
                    temp         = this.gpsData.GetHitsByDateRange(this.startDate, this.endDate);
                }

                if (temp != null)
                {
                    result = new DataTable();

                    result.Columns.Add("SerialId", typeof(int));
                    result.Columns.Add("ReceivedDate", typeof(DateTime));
                    result.Columns.Add("Count", typeof(int));

                    DataRow[] rows = new DataRow[temp.Rows.Count];

                    temp.Rows.CopyTo(rows, 0);

                    int            max    = 0;
                    List <DataRow> filter = new List <DataRow>();

                    if (type == Enumerators.StatisticsType.DataUsage)
                    {
                        max = (from r in rows
                               select r.Field <int>("PacketSize")).Max();

                        filter = (from r in rows
                                  where r.Field <int>("PacketSize") == max
                                  select r).ToList();
                    }
                    else
                    {
                        max = (from r in rows
                               select r.Field <int>("Hits")).Max();

                        filter = (from r in rows
                                  where r.Field <int>("Hits") == max
                                  select r).ToList();
                    }

                    foreach (DataRow row in filter)
                    {
                        result.NewRow();

                        if (type == Enumerators.StatisticsType.DataUsage)
                        {
                            result.Rows.Add(row["SerialId"], row["ReceivedDate"], row["PacketSize"]);
                        }
                        else
                        {
                            result.Rows.Add(row["lSerial_ID"], row["Received"], row["Hits"]);
                        }
                    }
                }
            }
            finally
            {
                temp.Dispose();
            }

            return(result);
        }
Ejemplo n.º 35
0
 /// <summary>
 /// Initializes a new instance of the <see cref="ChatHelper"/> class.
 /// </summary>
 /// <param name="client">The client.</param>
 /// <param name="packet">The packet.</param>
 public ChatHelper(Client client, EventPacket packet)
 {
     this.client = client;
     this.packet = packet;
 }
Ejemplo n.º 36
0
 internal async Task SendEventPacket(EventPacket eventPacket)
 => await WebSocket.SendMessage(eventPacket.ToServerResponseString());
Ejemplo n.º 37
0
 private void Shutdown(EventPacket packet, PluginContext context)
 {
     MainWindowInvoke(window => window.ResetChatrooms());
 }
Ejemplo n.º 38
0
        /// <summary>
        /// Main message handler
        /// </summary>
        /// <param name="msg">Message from client app</param>
        public void HandleMessage(EventPacket msg)
        {
            //reset timer
            _exitTimer.Stop();
            _exitTimer.Start();



            switch (msg.Type)
            {
            case BrowserEventType.Ping:
            {
                break;
            }

            case BrowserEventType.Generic:
            {
                GenericEvent genericEvent = msg.Event as GenericEvent;
                if (genericEvent != null)
                {
                    switch (genericEvent.Type)
                    {
                    case GenericEventType.Shutdown:
                    {
                        try
                        {
                            log.Info("==============SHUTTING DOWN==========");

                            _mainWorker.Shutdown();

                            _memServer.Dispose();


                            _outCommServer.Dispose();
                            _inCommServer.Dispose();

                            IsRunning = false;
                        }
                        catch (Exception e)
                        {
                            log.Info("Exception on shutdown:" + e.StackTrace);
                        }

                        break;
                    }

                    case GenericEventType.Navigate:

                        _mainWorker.Navigate(genericEvent.NavigateUrl);
                        break;

                    case GenericEventType.GoBack:
                        _mainWorker.GoBack();
                        break;

                    case GenericEventType.GoForward:
                        _mainWorker.GoForward();
                        break;

                    case GenericEventType.ExecuteJS:
                        _mainWorker.ExecuteJavaScript(genericEvent.JsCode);
                        break;

                    case GenericEventType.JSQueryResponse:
                    {
                        _mainWorker.AnswerQuery(genericEvent.JsQueryResponse);
                        break;
                    }
                    }
                }
                break;
            }

            case BrowserEventType.Dialog:
            {
                DialogEvent de = msg.Event as DialogEvent;
                if (de != null)
                {
                    _mainWorker.ContinueDialog(de.success, de.input);
                }
                break;
            }

            case BrowserEventType.Keyboard:
            {
                KeyboardEvent keyboardEvent = msg.Event as KeyboardEvent;



                if (keyboardEvent != null)
                {
                    if (keyboardEvent.Type != KeyboardEventType.Focus)
                    {
                        _mainWorker.KeyboardEvent(keyboardEvent.Key, keyboardEvent.Type);
                    }
                    else
                    {
                        _mainWorker.FocusEvent(keyboardEvent.Key);
                    }
                }
                break;
            }

            case BrowserEventType.Mouse:
            {
                MouseMessage mouseMessage = msg.Event as MouseMessage;
                if (mouseMessage != null)
                {
                    switch (mouseMessage.Type)
                    {
                    case MouseEventType.ButtonDown:
                        _mainWorker.MouseEvent(mouseMessage.X, mouseMessage.Y, false, mouseMessage.Button);
                        break;

                    case MouseEventType.ButtonUp:
                        _mainWorker.MouseEvent(mouseMessage.X, mouseMessage.Y, true, mouseMessage.Button);
                        break;

                    case MouseEventType.Move:
                        _mainWorker.MouseMoveEvent(mouseMessage.X, mouseMessage.Y, mouseMessage.Button);
                        break;

                    case MouseEventType.Leave:
                        _mainWorker.MouseLeaveEvent();
                        break;

                    case MouseEventType.Wheel:
                        _mainWorker.MouseWheelEvent(mouseMessage.X, mouseMessage.Y, mouseMessage.Delta);
                        break;
                    }
                }

                break;
            }
            }
        }
Ejemplo n.º 39
0
 private void Ping(EventPacket packet, PluginContext context)
 {
     context.Client.Send(new Packet { cmd = "pong" });
 }
Ejemplo n.º 40
0
 private void RespondToDude(EventPacket packet, PluginContext context)
 {
     if (packet.Message.StartsWith("dude"))
         context.ThisRoom.Respond("No surfer talk in here!!");
 }
 protected void SendSpecificEvent <T>(EventPacket eventPacket, EventHandler <T> eventHandler)
 {
     this.SendSpecificPacket(JsonConvert.DeserializeObject <T>(eventPacket.data.ToString()), eventHandler);
 }
Ejemplo n.º 42
0
 private void ConstellationClient_OnEventOccurred(object sender, EventPacket e)
 {
     this.eventPackets.Add(e);
 }
Ejemplo n.º 43
0
 /// <summary>
 /// Generates a plugin context which is aware of the current 
 /// packet and the plugin executing it.
 /// </summary>
 private PluginContext GenerateContext(EventPacket packet, PluginHandle pluginHandle)
 {
     return contextFactory.Create(packet, pluginHandle);
 }
Ejemplo n.º 44
0
        private void CheckMessage()
        {
            //push
            _outCommServer.PushMessages();

            try
            {
                EventPacket ep = _inCommServer.GetMessage();
                if (ep != null)
                {
                    // if (ep.Type == BrowserEventType.Ping)
                    //    SendPing();
                    //  //  MessageBox.Show("PINGBACK");

                    if (ep.Type == BrowserEventType.Dialog)
                    {
                        DialogEvent dev = ep.Event as DialogEvent;
                        switch (dev.Type)
                        {
                        case DialogEventType.Alert:
                        {
                            _inModalDialog = true;
                            MessageBox.Show(dev.Message, "InApp");
                            SendDialogResponse(true);

                            _inModalDialog = false;
                            break;
                        }

                        case DialogEventType.Confirm:
                        {
                            _inModalDialog = true;
                            if (MessageBox.Show(dev.Message, "InApp", MessageBoxButtons.OKCancel) == DialogResult.OK)
                            {
                                SendDialogResponse(true);
                            }
                            else
                            {
                                SendDialogResponse(false);
                            }
                            _inModalDialog = false;
                            break;
                        }
                        }
                    }

                    if (ep.Type == BrowserEventType.Generic)
                    {
                        GenericEvent ge = ep.Event as GenericEvent;

                        if (ge.Type == GenericEventType.JSQuery)
                        {
                            if (MessageBox.Show("JS QUERY:" + ge.StringContent, "Query", MessageBoxButtons.OKCancel) == DialogResult.OK)
                            {
                                SendQueryResponse("Query ok");
                            }
                            else
                            {
                                SendQueryResponse("Query cancel");
                            }
                        }

                        if (ge.Type == GenericEventType.PageLoaded)
                        {
                            MessageBox.Show("Navigated to:" + ge.StringContent);
                        }
                    }
                }
            }
            catch (Exception e)
            {
            }
        }
Ejemplo n.º 45
0
 public virtual EventPacket GetNewEventPacket()
 {
     return(EventPacket.NewEventPacket(Configuration.CoreConnectionString, Configuration.ConnectionTimeout));
 }
Ejemplo n.º 46
0
 private void CheckMessage(EventPacket packet, PluginContext context)
 {
     if (packet.From.ToLower().Trim() == context.BotSettings.UserName.ToLower())
         return;
     ProcessMessage(packet.Message, packet.ChatRoom, context);
 }
Ejemplo n.º 47
0
        private void OnReceiveEvent(EventPacket packet, NetPeer peer)
        {
            if (!Servers.TryGetValue(peer, out NPServer server))
            {
                return;
            }

            NetDataReader data = new NetDataReader(packet.Data);

            switch ((EventType)packet.Type)
            {
            case EventType.PlayerJoined:
            {
                string userId    = data.GetString();
                string nickname  = data.GetString();
                var    newPlayer = new NPPlayer(server, userId, nickname);

                if (server.PlayersDictionary.ContainsKey(userId))
                {
                    break;
                }

                server.PlayersDictionary.Add(userId, newPlayer);

                foreach (var handler in DedicatedAddonHandlers.Values)
                {
                    handler.InvokePlayerJoined(new PlayerJoinedEvent(newPlayer), server);
                }

                NetDataWriter writer = new NetDataWriter();
                writer.Put(userId);
                PacketProcessor.Send <EventPacket>(peer, new EventPacket()
                    {
                        Type = (byte)EventType.PlayerJoined,
                        Data = writer.Data
                    }, DeliveryMethod.ReliableOrdered);
            }
            break;

            case EventType.PlayerLeft:
            {
                string userId = data.GetString();

                if (!server.PlayersDictionary.TryGetValue(userId, out NPPlayer plr))
                {
                    break;
                }

                foreach (var handler in DedicatedAddonHandlers.Values)
                {
                    handler.InvokePlayerLeft(new PlayerLeftEvent(plr), server);
                }

                server.PlayersDictionary.Remove(userId);
            }
            break;

            case EventType.PlayerLocalReport:
            {
                string userId       = data.GetString();
                string targetUserId = data.GetString();
                string reason       = data.GetString();

                if (!server.PlayersDictionary.TryGetValue(userId, out NPPlayer plr))
                {
                    break;
                }

                if (!server.PlayersDictionary.TryGetValue(targetUserId, out NPPlayer target))
                {
                    break;
                }

                foreach (var handler in DedicatedAddonHandlers.Values)
                {
                    handler.InvokePlayerLocalReport(new PlayerLocalReportEvent(plr, target, reason), server);
                }
            }
            break;

            case EventType.PreAuth:
            {
                string userid  = data.GetString();
                string ip      = data.GetString();
                string country = data.GetString();
                byte   flags   = data.GetByte();
                foreach (var handler in DedicatedAddonHandlers.Values)
                {
                    handler.InvokePlayerPreAuth(new PlayerPreAuthEvent(server, userid, ip, country, flags), server);
                }
            }
            break;

            case EventType.WaitingForPlayers:
            {
                foreach (var handler in DedicatedAddonHandlers.Values)
                {
                    handler.InvokeWaitingForPlayers(new WaitingForPlayersEvent(server), server);
                }
            }
            break;

            case EventType.RoundEnded:
            {
                foreach (var handler in DedicatedAddonHandlers.Values)
                {
                    handler.InvokeRoundEnded(new RoundEndedEvent(server), server);
                }
            }
            break;
            }
        }
Ejemplo n.º 48
0
 protected void WebSocketClient_OnEventOccurred(object sender, EventPacket e)
 {
     Logger.Log(string.Format(Environment.NewLine + "WebSocket Event: {0} - {1} - {2} - {3}" + Environment.NewLine, e.id, e.type, e.eventName, e.data));
 }
Ejemplo n.º 49
0
        //Receiver
        public void CheckMessage()
        {
            if (Initialized)
            {
                try
                {
                    // Ensure that no other threads try to use the stream at the same time.
                    EventPacket ep = _inCommServer.TryRecive(0);


                    if (ep != null)
                    {
                        //main handlers
                        switch (ep.Type)
                        {
                        case BrowserEventType.Dialog:
                            DialogEvent dev = ep.Event as DialogEvent;
                            if (dev != null)
                            {
                                if (OnJavaScriptDialog != null)
                                {
                                    OnJavaScriptDialog(dev.Message, dev.DefaultPrompt, dev.Type);
                                }
                            }

                            break;

                        case BrowserEventType.Generic:
                            var ge = ep.Event as GenericEvent;
                            if (ge != null)
                            {
                                switch (ge.Type)
                                {
                                case GenericEventType.JSQuery:
                                    if (OnJavaScriptQuery != null)
                                    {
                                        OnJavaScriptQuery(ge.StringContent);
                                    }
                                    break;

                                case GenericEventType.PageLoaded:
                                    if (OnPageLoaded != null)
                                    {
                                        OnPageLoaded(ge.StringContent);
                                    }
                                    break;

                                case GenericEventType.DynamicDataRequest:
                                    string result = null;
                                    if (dynamicRequestHandler != null)
                                    {
                                        result = dynamicRequestHandler.Request(ge.StringContent,
                                                                               ge.AdditionalStringContent);
                                    }
                                    SendDynamicResponse(ge.StringContent, result);
                                    break;
                                }
                            }
                            break;
                        }
                    }
                }
                catch (Exception e)
                {
                    Debug.Log("Error reading from socket,waiting for plugin server to start...");
                }
            }
        }
Ejemplo n.º 50
0
 private void ChatClient_OnEventOccurred(object sender, EventPacket e)
 {
     this.eventPackets.Add(e);
 }
Ejemplo n.º 51
0
        /// <summary>
        /// Invokes a command.
        /// </summary>
        /// <param name="command">The command.</param>
        private void InvokeCommand(string command)
        {
            var botSettings = Module.UIContext.BotSettings;

            // get the settings
            var botTrigger = botSettings.Trigger;
            var username = botSettings.UserName;
            var owner = botSettings.Owner;

            // create the command packet as if it from from the server
            string data = string.Format("recv chat:{0}\n\nmsg main\nfrom={1}\n\n{2}", chatroom.Name, owner, command);
            ServerPacket serverPacket = new ServerPacket(data);
            EventPacket eventPacket = new EventPacket(serverPacket);
            CommandPacket commandPacket = new CommandPacket(botTrigger, username, serverPacket);

            // create a plugin context
            PluginContext context = Module.UIContext.PluginContextFactory.Create(eventPacket, null);

            // send the command!
            Oberon.Core.Plugins.System.ValidateAndInvokeCommand(commandPacket, context);
        }
Ejemplo n.º 52
0
 /// <summary>
 /// Creates a new plugin context based on the current packet and plugin.
 /// </summary>
 /// <param name="packet">The packet.</param>
 /// <param name="pluginHandle">The plugin handle.</param>
 /// <returns>Context.</returns>
 public PluginContext Create(EventPacket packet, PluginHandle pluginHandle)
 {
     // create a new context with a buttload of dependendies
     return generator(packet);
 }
Ejemplo n.º 53
0
        //Receiver
        private void StreamReceiver(IAsyncResult ar)
        {
            int BytesRead;

            try
            {
                // Ensure that no other threads try to use the stream at the same time.
                lock (_clientSocket.GetStream())
                {
                    // Finish asynchronous read into readBuffer and get number of bytes read.
                    BytesRead = _clientSocket.GetStream().EndRead(ar);
                }
                MemoryStream    mstr = new MemoryStream(readBuffer);
                BinaryFormatter bf   = new BinaryFormatter();
                EventPacket     ep   = bf.Deserialize(mstr) as EventPacket;
                if (ep != null)
                {
                    //main handlers
                    if (ep.Type == BrowserEventType.Dialog)
                    {
                        DialogEvent dev = ep.Event as DialogEvent;
                        if (dev != null)
                        {
                            if (OnJavaScriptDialog != null)
                            {
                                OnJavaScriptDialog(dev.Message, dev.DefaultPrompt, dev.Type);
                            }
                        }
                    }
                    if (ep.Type == BrowserEventType.Generic)
                    {
                        GenericEvent ge = ep.Event as GenericEvent;
                        if (ge != null)
                        {
                            if (ge.Type == GenericEventType.JSQuery)
                            {
                                if (OnJavaScriptQuery != null)
                                {
                                    OnJavaScriptQuery(ge.JsQuery);
                                }
                            }
                        }

                        if (ge.Type == GenericEventType.PageLoaded)
                        {
                            if (OnPageLoaded != null)
                            {
                                OnPageLoaded(ge.NavigateUrl);
                            }
                        }
                    }
                }
                lock (_clientSocket.GetStream())
                {
                    // Start a new asynchronous read into readBuffer.
                    _clientSocket.GetStream()
                    .BeginRead(readBuffer, 0, READ_BUFFER_SIZE, new AsyncCallback(StreamReceiver), null);
                }
            }
            catch (Exception e)
            {
                //Debug.Log("Error reading from socket,waiting for plugin server to start...");
            }
        }