Esempio n. 1
0
        //array("sec" => 2, "usec" => 0);
        public WhatsApp(string phoneNum, string imei, string nick, bool debug = false)
        {
            this.messageQueue = new List<ProtocolTreeNode>();
            //this.sysEncoding = Encoding.GetEncoding("ISO-8859-1");
            //this.challengeArray = new Dictionary<string, string>();

            this.phoneNumber = phoneNum;
            this.imei = imei;
            this.name = nick;
            WhatsApp.DEBUG = debug;
            string[] dict = DecodeHelper.getDictionary();
            this.writer = new BinTreeNodeWriter(dict);
            this.reader = new BinTreeNodeReader(dict);

            //this.loginStatus = disconnectedStatus;
            this.loginStatus = CONNECTION_STATUS.DISCONNECTED;

            //this.whatsNetwork = new WhatsNetwork(WhatsConstants.WhatsAppHost, WhatsConstants.WhatsPort, this.sysEncoding, this.timeout);
            //this.WhatsParser = new WhatsParser(this.whatsNetwork);
            this.whatsNetwork = new WhatsNetwork(WhatsConstants.WhatsAppHost, WhatsConstants.WhatsPort, this.timeout);
            this.WhatsParser = new WhatsParser(this.whatsNetwork, this.writer);
            this.WhatsSendHandler = this.WhatsParser.WhatsSendHandler;

            _incompleteBytes = new List<IncompleteMessageException>();
        }
Esempio n. 2
0
 public void Disconnect(Exception ex = null)
 {
     this.whatsNetwork.Disconenct();
     this.loginStatus = CONNECTION_STATUS.DISCONNECTED;
     ClearUploadResponses();
     this.fireOnDisconnect(ex);
 }
Esempio n. 3
0
 public SocketClientTest(string username, string password)
 {
     _username        = username;
     _password        = password;
     port             = 5150;
     recvTimeout      = 1000;
     this.loginStatus = CONNECTION_STATUS.CONNECTED;
     //success
     this.fireOnConnectSuccess();
 }
Esempio n. 4
0
 public void Disconnect(Exception ex = null)
 {
     if (this.socket != null)
     {
         this.SendData(Encoding.ASCII.GetBytes("exit"));
         this.socket.Close();
     }
     this.loginStatus = CONNECTION_STATUS.DISCONNECTED;
     this.fireOnDisconnect(ex);
 }
 void OnConnected(Cube cube, CONNECTION_STATUS status)
 {
     if (status.IsNewConnected)
     {
         Debug.Log("new-connected!!");
     }
     else if (status.IsReConnected)
     {
         Debug.Log("re-connected!!");
     }
 }
Esempio n. 6
0
 protected void _constructBase(string phoneNum, string imei, string nick, bool debug, bool hidden)
 {
     this.messageQueue = new List <ProtocolTreeNode>();
     this.phoneNumber  = phoneNum;
     this.password     = imei;
     this.name         = nick;
     this.hidden       = hidden;
     WhatsApp.DEBUG    = debug;
     this.reader       = new BinTreeNodeReader();
     this.loginStatus  = CONNECTION_STATUS.DISCONNECTED;
     this.BinWriter    = new BinTreeNodeWriter();
     this.whatsNetwork = new WhatsNetwork(WhatsConstants.WhatsAppHost, WhatsConstants.WhatsPort, this.timeout);
 }
Esempio n. 7
0
 protected void _constructBase(string phoneNum, string imei, string nick, bool debug, bool hidden)
 {
     this.messageQueue = new List<ProtocolTreeNode>();
     this.phoneNumber = phoneNum;
     this.password = imei;
     this.name = nick;
     this.hidden = hidden;
     WhatsApp.DEBUG = debug;
     this.reader = new BinTreeNodeReader();
     this.loginStatus = CONNECTION_STATUS.DISCONNECTED;
     this.BinWriter = new BinTreeNodeWriter();
     this.whatsNetwork = new WhatsNetwork(WhatsConstants.WhatsAppHost, WhatsConstants.WhatsPort, this.timeout);
 }
 protected void processInboundData(byte[] data)
 {
     try
     {
         var node = this.reader.nextTree(data);
         while (node != null)
         {
             this.WhatsParser.ParseProtocolNode(node);
             if (ProtocolTreeNode.TagEquals(node, "challenge"))
             {
                 this.processChallenge(node);
             }
             else if (ProtocolTreeNode.TagEquals(node, "success"))
             {
                 this.loginStatus = CONNECTION_STATUS.CONNECTED;
                 this.accountinfo = new AccountInfo(node.GetAttribute("status"),
                                                    node.GetAttribute("kind"),
                                                    node.GetAttribute("creation"),
                                                    node.GetAttribute("expiration"));
             }
             else if (ProtocolTreeNode.TagEquals(node, "failure"))
             {
                 this.loginStatus = CONNECTION_STATUS.DISCONNECTED;
             }
             if (ProtocolTreeNode.TagEquals(node, "message"))
             {
                 this.AddMessage(node);
                 this.sendMessageReceived(node);
             }
             if (ProtocolTreeNode.TagEquals(node, "stream:error"))
             {
                 Console.Write(node.NodeString());
             }
             if (ProtocolTreeNode.TagEquals(node, "iq") &&
                 node.GetAttribute("type").Equals("get", StringComparison.OrdinalIgnoreCase) &&
                 ProtocolTreeNode.TagEquals(node.children.First(), "ping"))
             {
                 this.Pong(node.GetAttribute("id"));
             }
             if (ProtocolTreeNode.TagEquals(node, "Replaced by new connection"))
             {
                 this.Connect();
                 this.Login();
             }
             node = this.reader.nextTree();
         }
     }
     catch (IncompleteMessageException e)
     {
     }
 }
Esempio n. 9
0
 public void Connect()
 {
     try
     {
         this.whatsNetwork.Connect();
         this.loginStatus = CONNECTION_STATUS.CONNECTED;
         //success
         this.fireOnConnectSuccess();
     }
     catch (Exception e)
     {
         this.fireOnConnectFailed(e);
     }
 }
Esempio n. 10
0
 public void Connect()
 {
     try
     {
         this.whatsNetwork.Connect();
         this.loginStatus = CONNECTION_STATUS.CONNECTED;
         //success
         this.fireOnConnectSuccess();
     }
     catch (Exception e)
     {
         this.fireOnConnectFailed(e);
     }
 }
 private void OnPrepareClose(ushort code, string msg)
 {
     if (isConnect)
     {
         if (PrepareCloseOccurred != null)
         {
             PrepareCloseOccurred(code, msg);
         }
         ReceivePacketAction = delegate
         {
         };
         isConnect = false;
         CurrentConnectionStatus = CONNECTION_STATUS.CLOSED;
     }
 }
    public WhatsAppProtocol(WhatsappAccount _Acc)
    {
        this.messageQueue = new List<ProtocolTreeNode>();
        WhatsAppProtocol.DEBUG = false;
        string[] dict = DecodeHelper.getDictionary();
        this.writer = new BinTreeNodeWriter(dict);
        this.reader = new BinTreeNodeReader(dict);
        this.loginStatus = CONNECTION_STATUS.DISCONNECTED;
        this.whatsNetwork = new WhatsNetwork(WhatsConstants.WhatsAppHost, WhatsConstants.WhatsPort, this.timeout);
        this.WhatsParser = new WhatsParser(this.whatsNetwork, this.writer);
        this.WhatsSendHandler = this.WhatsParser.WhatsSendHandler;

        _incompleteBytes = new List<IncompleteMessageException>();

        Acc = _Acc;
    }
Esempio n. 13
0
        public bool pollMessage()
        {
            if (this.loginStatus == CONNECTION_STATUS.CONNECTED || this.loginStatus == CONNECTION_STATUS.LOGGEDIN)
            {
                int toRead = 4090;

                var data = this.Socket_read(toRead);
                var yd   = Encoding.UTF8.GetString(data);

                Console.WriteLine("data={0}", yd);

                this.loginStatus = yd == "Y"? CONNECTION_STATUS.LOGGEDIN: CONNECTION_STATUS.UNAUTHORIZED;
                return(true);
            }
            return(false);
        }
    public WhatsAppProtocol(WhatsappAccount _Acc)
    {
        this.messageQueue      = new List <ProtocolTreeNode>();
        WhatsAppProtocol.DEBUG = false;
        string[] dict = DecodeHelper.getDictionary();
        this.writer           = new BinTreeNodeWriter(dict);
        this.reader           = new BinTreeNodeReader(dict);
        this.loginStatus      = CONNECTION_STATUS.DISCONNECTED;
        this.whatsNetwork     = new WhatsNetwork(WhatsConstants.WhatsAppHost, WhatsConstants.WhatsPort, this.timeout);
        this.WhatsParser      = new WhatsParser(this.whatsNetwork, this.writer);
        this.WhatsSendHandler = this.WhatsParser.WhatsSendHandler;

        _incompleteBytes = new List <IncompleteMessageException>();

        Acc = _Acc;
    }
Esempio n. 15
0
        /// <summary>
        /// Default class constructor
        /// </summary>
        /// <param name="phoneNum">The phone number</param>
        /// <param name="imei">The imei / mac</param>
        /// <param name="nick">User nickname</param>
        /// <param name="debug">Debug on or off, false by default</param>
        public WhatsApp(string phoneNum, string imei, string nick, bool debug = false)
        {
            this.messageQueue = new List <ProtocolTreeNode>();
            this.phoneNumber  = phoneNum;
            this.imei         = imei;
            this.name         = nick;
            WhatsApp.DEBUG    = debug;
            string[] dict = DecodeHelper.getDictionary();
            this.writer           = new BinTreeNodeWriter(dict);
            this.reader           = new BinTreeNodeReader(dict);
            this.loginStatus      = CONNECTION_STATUS.DISCONNECTED;
            this.whatsNetwork     = new WhatsNetwork(WhatsConstants.WhatsAppHost, WhatsConstants.WhatsPort, this.timeout);
            this.WhatsParser      = new WhatsParser(this.whatsNetwork, this.writer);
            this.WhatsSendHandler = this.WhatsParser.WhatsSendHandler;

            _incompleteBytes = new List <IncompleteMessageException>();
        }
    protected void processInboundData(byte[] data)
    {
        try
        {
            var node = this.reader.nextTree(data);
            while (node != null)
            {
                this.WhatsParser.ParseProtocolNode(node);
                if (ProtocolTreeNode.TagEquals(node, "challenge"))
                {
                    this.processChallenge(node);
                }
                else if (ProtocolTreeNode.TagEquals(node, "success"))
                {
                    this.loginStatus = CONNECTION_STATUS.CONNECTED;
                    this.accountinfo = new AccountInfo(node.GetAttribute("status"),
                                                        node.GetAttribute("kind"),
                                                        node.GetAttribute("creation"),
                                                        node.GetAttribute("expiration"));
                }
                else if (ProtocolTreeNode.TagEquals(node, "failure"))
                {
                    this.loginStatus = CONNECTION_STATUS.DISCONNECTED;
                }
                if (ProtocolTreeNode.TagEquals(node, "message"))
                {
                    this.AddMessage(node);
                    this.sendMessageReceived(node);
                }
                if (ProtocolTreeNode.TagEquals(node, "stream:error"))
                {
                    Console.Write(node.NodeString());
                }
                if (ProtocolTreeNode.TagEquals(node, "iq")
                    && node.GetAttribute("type").Equals("get", StringComparison.OrdinalIgnoreCase)
                    && ProtocolTreeNode.TagEquals(node.children.First(), "ping"))
                {
                    this.Pong(node.GetAttribute("id"));
                }
                if (ProtocolTreeNode.TagEquals(node, "Replaced by new connection"))
                {
                    this.Connect();
                    this.Login();
                }
                node = this.reader.nextTree();
            }
        }
        catch (IncompleteMessageException e)
        {

        }
    }
Esempio n. 17
0
 public void Disconnect(Exception ex = null)
 {
     this.whatsNetwork.Disconenct();
     this.loginStatus = CONNECTION_STATUS.DISCONNECTED;
     this.FireOnDisconnect(ex);
 }
Esempio n. 18
0
 public void Disconnect(Exception ex = null)
 {
     this.whatsNetwork.Disconenct();
     this.loginStatus = CONNECTION_STATUS.DISCONNECTED;
     this.fireOnDisconnect(ex);
 }
Esempio n. 19
0
        /// <summary>
        /// Process inbound data
        /// </summary>
        /// <param name="data">Data to process</param>
        protected void processInboundData(byte[] data)
        {
            try
            {
                List<byte> foo = new List<byte>();
                if (this._incompleteBytes.Count > 0)
                {
                    foreach (IncompleteMessageException e in this._incompleteBytes)
                    {
                        foo.AddRange(e.getInput());
                    }
                    this._incompleteBytes.Clear();
                }
                if (data != null)
                {
                    foo.AddRange(data);
                }
                ProtocolTreeNode node = this.reader.nextTree(foo.ToArray());
                while (node != null)
                {
                    //this.WhatsParser.ParseProtocolNode(node);
                    if (node.tag == "iq"
                    && node.GetAttribute("type") == "error")
                    {
                        //this.AddMessage(node);
                        if (this.OnError != null)
                        {
                            this.OnError(node.GetAttribute("id"), node.GetAttribute("from"), Int32.Parse(node.GetChild("error").GetAttribute("code")), node.GetChild("error").GetAttribute("text"));
                        }
                    }
                    if (ProtocolTreeNode.TagEquals(node, "challenge"))
                    {
                        this.processChallenge(node);
                    }
                    else if (ProtocolTreeNode.TagEquals(node, "success"))
                    {
                        this.loginStatus = CONNECTION_STATUS.LOGGEDIN;
                        this.accountinfo = new AccountInfo(node.GetAttribute("status"),
                                                           node.GetAttribute("kind"),
                                                           node.GetAttribute("creation"),
                                                           node.GetAttribute("expiration"));
                        if (this.OnLoginSuccess != null)
                        {
                            this.OnLoginSuccess(node.GetData());
                        }
                    }
                    else if (ProtocolTreeNode.TagEquals(node, "failure"))
                    {
                        this.loginStatus = CONNECTION_STATUS.UNAUTHORIZED;
                        if (this.OnLoginFailed != null)
                        {
                            this.OnLoginFailed(node.children.First().tag);
                        }
                    }
                    if (ProtocolTreeNode.TagEquals(node, "message"))
                    {
                        if (node.GetChild("notify") != null)
                        {
                            string name = node.GetChild("notify").GetAttribute("name");
                            if (this.OnGetContactName != null)
                            {
                                this.OnGetContactName(node.GetAttribute("from"), name);
                            }
                        }
                        if (node.GetChild("body") != null)
                        {
                            //text message
                            if (this.OnGetMessage != null)
                            {
                                this.OnGetMessage(node.GetAttribute("from"), node.GetAttribute("id"), System.Text.Encoding.UTF8.GetString(node.GetChild("body").GetData()));
                            }
                        }
                        if (node.GetChild("received") != null)
                        {
                            //client received
                            if (this.OnGetMessageReceivedClient != null)
                            {
                                this.OnGetMessageReceivedClient(node.GetAttribute("from"), node.GetAttribute("id"));
                            }
                        }
                        if (node.GetChild("media") != null)
                        {
                            ProtocolTreeNode media = node.GetChild("media");
                            //media message

                            //define variables in switch
                            string file, url, from, id;
                            int size;
                            byte[] preview, dat;
                            id = node.GetAttribute("id");
                            from = node.GetAttribute("from");
                            switch (media.GetAttribute("type"))
                            {
                                case "image":
                                    if (this.OnGetMessageImage != null)
                                    {
                                        url = media.GetAttribute("url");
                                        file = media.GetAttribute("file");
                                        size = Int32.Parse(media.GetAttribute("size"));
                                        preview = media.GetData();
                                        this.OnGetMessageImage(from, id, file, size, url, preview);
                                    }
                                    break;
                                case "audio":
                                    if (this.OnGetMessageAudio != null)
                                    {
                                        file = media.GetAttribute("file");
                                        size = Int32.Parse(media.GetAttribute("size"));
                                        url = media.GetAttribute("url");
                                        preview = media.GetData();
                                        this.OnGetMessageAudio(from, id, file, size, url, preview);
                                    }
                                    break;
                                case "video":
                                    if(this.OnGetMessageVideo != null)
                                    {
                                        file = media.GetAttribute("file");
                                        size = Int32.Parse(media.GetAttribute("size"));
                                        url = media.GetAttribute("url");
                                        preview = media.GetData();
                                        this.OnGetMessageVideo(from, id, file, size, url, preview);
                                    }
                                    break;
                                case "location":
                                    if (this.OnGetMessageLocation != null)
                                    {
                                        double lon = double.Parse(media.GetAttribute("longitude"), System.Globalization.CultureInfo.InvariantCulture);
                                        double lat = double.Parse(media.GetAttribute("latitude"), System.Globalization.CultureInfo.InvariantCulture);
                                        preview = media.GetData();
                                        name = media.GetAttribute("name");
                                        url = media.GetAttribute("url");
                                        this.OnGetMessageLocation(from, id, lon, lat, url, name, preview);
                                    }
                                    break;
                                case "vcard":
                                    if (this.OnGetMessageVcard != null)
                                    {
                                        ProtocolTreeNode vcard = media.GetChild("vcard");
                                        name = vcard.GetAttribute("name");
                                        dat = vcard.GetData();
                                        this.OnGetMessageVcard(from, id, name, dat);
                                    }
                                    break;
                            }
                        }
                        ProtocolTreeNode x = node.GetChild("x");
                        if (x != null && x.GetAttribute("xmlns") == "jabber:x:event")
                        {
                            if (x.GetChild("server") != null && this.OnGetMessageReceivedServer != null)
                            {
                                this.OnGetMessageReceivedServer(node.GetAttribute("from"), node.GetAttribute("id"));
                            }
                        }
                        ProtocolTreeNode notification = node.GetChild("notification");
                        if (notification != null)
                        {
                            if (notification.GetAttribute("type") == "picture" && this.OnNotificationPicture != null)
                            {
                                this.OnNotificationPicture(notification.tag, notification.GetAttribute("jid"), notification.GetAttribute("id"));
                            }
                        }

                        if (node.GetChild("request") != null)
                        {
                            this.sendMessageReceived(node);
                        }
                        else if (node.GetChild("received") != null)
                        {
                            this.sendMessageReceived(node, "ack");
                        }
                        if (node.GetChild("composing") != null)
                        {
                            //typing
                            if (this.OnGetTyping != null)
                            {
                                this.OnGetTyping(node.GetAttribute("from"));
                            }
                        }
                        if (node.GetChild("paused") != null)
                        {
                            //paused
                            if (this.OnGetPaused != null)
                            {
                                this.OnGetPaused(node.GetAttribute("from"));
                            }
                        }
                    }
                    if (ProtocolTreeNode.TagEquals(node, "stream:error"))
                    {
                        Console.Write(node.NodeString());
                    }
                    if (ProtocolTreeNode.TagEquals(node, "iq")
                        && node.GetAttribute("type").Equals("result", StringComparison.OrdinalIgnoreCase)
                        && ProtocolTreeNode.TagEquals(node.children.First(), "query")
                        && node.children.First().GetAttribute("xmlns") == "jabber:iq:last"
                        )
                    {
                        //last seen
                        DateTime lastSeen = DateTime.Now.AddSeconds(double.Parse(node.children.First().GetAttribute("seconds")) * -1);
                        if(this.OnGetLastSeen != null)
                        {
                            this.OnGetLastSeen(node.GetAttribute("from"), lastSeen);
                        }
                    }
                    if (ProtocolTreeNode.TagEquals(node, "iq")
                        && node.GetAttribute("type").Equals("result", StringComparison.OrdinalIgnoreCase)
                        && (ProtocolTreeNode.TagEquals(node.children.First(), "media") || ProtocolTreeNode.TagEquals(node.children.First(), "duplicate"))
                        )
                    {
                        //media upload
                        this.uploadResponse = node;
                    }
                    if (ProtocolTreeNode.TagEquals(node, "iq")
                        && node.GetAttribute("type").Equals("result", StringComparison.OrdinalIgnoreCase)
                        && ProtocolTreeNode.TagEquals(node.children.First(), "picture")
                        )
                    {
                        //profile picture
                        string from = node.GetAttribute("from");
                        string id = node.GetChild("picture").GetAttribute("id");
                        byte[] dat = node.GetChild("picture").GetData();
                        string type = node.GetChild("picture").GetAttribute("type");
                        if (type == "preview")
                        {
                            if (this.OnGetPhotoPreview != null)
                            {
                                this.OnGetPhotoPreview(from, id, dat);
                            }
                        }
                        else
                        {
                            if (this.OnGetPhoto != null)
                            {
                                this.OnGetPhoto(from, id, dat);
                            }
                        }
                    }
                    if (ProtocolTreeNode.TagEquals(node, "iq")
                        && node.GetAttribute("type").Equals("get", StringComparison.OrdinalIgnoreCase)
                        && ProtocolTreeNode.TagEquals(node.children.First(), "ping"))
                    {
                        this.Pong(node.GetAttribute("id"));
                    }
                    if (ProtocolTreeNode.TagEquals(node, "iq")
                        && node.GetAttribute("type").Equals("result", StringComparison.OrdinalIgnoreCase)
                        && ProtocolTreeNode.TagEquals(node.children.First(), "group"))
                    {
                        //group(s) info
                        List<GroupInfo> groups = new List<GroupInfo>();
                        foreach (ProtocolTreeNode group in node.children)
                        {
                            groups.Add(new GroupInfo(
                                group.GetAttribute("id"),
                                group.GetAttribute("owner"),
                                long.Parse(group.GetAttribute("creation")),
                                group.GetAttribute("subject"),
                                long.Parse(group.GetAttribute("s_t")),
                                group.GetAttribute("s_o")
                                ));
                        }
                        if (this.OnGetGroups != null)
                        {
                            this.OnGetGroups(groups.ToArray());
                        }
                    }
                    if (ProtocolTreeNode.TagEquals(node, "iq")
                        && node.GetAttribute("type").Equals("result", StringComparison.OrdinalIgnoreCase)
                        && ProtocolTreeNode.TagEquals(node.children.First(), "participant"))
                    {
                        //group participants
                        List<string> participants = new List<string>();
                        foreach (ProtocolTreeNode part in node.GetAllChildren())
                        {
                            if (part.tag == "participant" && !string.IsNullOrEmpty(part.GetAttribute("jid")))
                            {
                                participants.Add(part.GetAttribute("jid"));
                            }
                        }
                        if (this.OnGetGroupParticipants != null)
                        {
                            this.OnGetGroupParticipants(node.GetAttribute("from"), participants.ToArray());
                        }
                    }

                    if (ProtocolTreeNode.TagEquals(node, "stream:error"))
                    {
                        var textNode = node.GetChild("text");
                        if (textNode != null)
                        {
                            string content = WhatsApp.SYSEncoding.GetString(textNode.GetData());
                            Console.WriteLine("Error : " + content);
                            if (content.Equals("Replaced by new connection", StringComparison.OrdinalIgnoreCase))
                            {
                                this.Disconnect(new Exception(content));
                                this.Connect();
                                this.Login();
                            }
                        }
                    }
                    if (ProtocolTreeNode.TagEquals(node, "presence"))
                    {
                        //presence node
                        if (this.OnGetPresence != null)
                        {
                            this.OnGetPresence(node.GetAttribute("from"), node.GetAttribute("type"));
                        }
                    }
                    node = this.reader.nextTree();
                }
            }
            catch (IncompleteMessageException ex)
            {
                this._incompleteBytes.Add(ex);
            }
        }
    private void NativeConnect(string relayServer)
    {
        sock = new WebSocket(new Uri(relayServer));
        CurrentConnectionStatus = CONNECTION_STATUS.OPENING;
        ErrorOccurred           = null;
        CloseOccurred           = null;
        PrepareCloseOccurred    = null;
        HeartbeatDisconnected   = null;
        WebSocket webSocket = sock;

        webSocket.OnOpen = (Action <WebSocket>) Delegate.Combine(webSocket.OnOpen, (Action <WebSocket>) delegate(WebSocket ws)
        {
            //IL_0044: Unknown result type (might be due to invalid IL or missing references)
            //IL_0072: Unknown result type (might be due to invalid IL or missing references)
            LogDebug("OnOpen {0}", ws.InternalRequest.Uri);
            ClearLastPacketReceivedTime();
            isConnect = true;
            CurrentConnectionStatus = CONNECTION_STATUS.CONNECTED;
            packetSendTime          = Time.get_time();
            this.StartCoroutine("Heartbeat");
            ReceivePacketAction = (Action <CoopPacket>)Delegate.Combine(ReceivePacketAction, new Action <CoopPacket>(CheckAndSendAck));
            this.StartCoroutine("ResendMonitor");
            ReceivePacketAction = (Action <CoopPacket>)Delegate.Combine(ReceivePacketAction, new Action <CoopPacket>(RemoveResendPacket));
        });
        WebSocket webSocket2 = sock;

        webSocket2.OnBinary = (Action <WebSocket, byte[]>) Delegate.Combine(webSocket2.OnBinary, (Action <WebSocket, byte[]>) delegate(WebSocket ws, byte[] binary)
        {
            ClearLastPacketReceivedTime();
            temporaryQueue.Enqueue(new PacketStream(binary));
        });
        WebSocket webSocket3 = sock;

        webSocket3.OnMessage = (Action <WebSocket, string>) Delegate.Combine(webSocket3.OnMessage, (Action <WebSocket, string>) delegate(WebSocket ws, string message)
        {
            ClearLastPacketReceivedTime();
            temporaryQueue.Enqueue(new PacketStream(message));
        });
        WebSocket webSocket4 = sock;

        webSocket4.OnClosed = (Action <WebSocket, ushort, string>) Delegate.Combine(webSocket4.OnClosed, (Action <WebSocket, ushort, string>) delegate(WebSocket ws, ushort code, string message)
        {
            OnPrepareClose(code, message);
            temporaryQueue.Clear();
            RemoveAllResendPackets();
            OnCloseOccurred(code, message);
            LogDebug("OnClosed Code {0}", code);
            LogDebug("OnClosed Message {0}", message);
        });
        WebSocket webSocket5 = sock;

        webSocket5.OnError = (Action <WebSocket, Exception>) Delegate.Combine(webSocket5.OnError, (Action <WebSocket, Exception>) delegate(WebSocket ws, Exception ex)
        {
            CurrentConnectionStatus = CONNECTION_STATUS.ERROR;
            OnErrorOccurred(ex);
            LogDebug("OnError Message {0}", ex.Message);
            LogDebug("OnError StackTrace {0}", ex.StackTrace);
        });
        WebSocket webSocket6 = sock;

        webSocket6.OnPong = (Action <WebSocket, byte[]>)Delegate.Combine(webSocket6.OnPong, (Action <WebSocket, byte[]>) delegate
        {
            ClearLastPacketReceivedTime();
        });
        sock.StartPingThread = true;
        sock.PingFrequency   = 3000;
        sock.Open();
    }
Esempio n. 21
0
        //protected void processInboundData(string data)
        protected void processInboundData(byte[] data)
        {
            try
            {
                List<byte> combined = new List<byte>();
                foreach (IncompleteMessageException e in _incompleteBytes)
                {
                    combined.AddRange(e.getInput());
                }
                _incompleteBytes.Clear();
                if (data !=null)
                    combined.AddRange(data);
                var node = this.reader.nextTree(combined.ToArray());
                //var node = this.reader.nextTree(data);

                while (node != null)
                {
                    //Console.WriteLine(node.NodeString());

                    this.WhatsParser.ParseProtocolNode(node);
                    if (ProtocolTreeNode.TagEquals(node, "challenge"))
                    {
                        this.processChallenge(node);
                    }
                    else if (ProtocolTreeNode.TagEquals(node,"success"))
                    {
                        this.loginStatus = CONNECTION_STATUS.CONNECTED;
                        this.accountinfo = new AccountInfo(node.GetAttribute("status"),
                                                           node.GetAttribute("kind"),
                                                           node.GetAttribute("creation"),
                                                           node.GetAttribute("expiration"));
                    }
                    else if (ProtocolTreeNode.TagEquals(node,"failure"))
                    {
                        this.loginStatus = CONNECTION_STATUS.DISCONNECTED;
                    }
                    if (ProtocolTreeNode.TagEquals(node,"message"))
                    {
                        this.AddMessage(node);
                        this.sendMessageReceived(node);
                    }

                    if (ProtocolTreeNode.TagEquals(node, "iq")
                        && node.GetAttribute("type").Equals("result", StringComparison.OrdinalIgnoreCase)
                        && ProtocolTreeNode.TagEquals(node.children.First(), "query"))
                    {
                        this.AddMessage(node);
                    }

                    if (ProtocolTreeNode.TagEquals(node, "iq")
                        && node.GetAttribute("type").Equals("result", StringComparison.OrdinalIgnoreCase)
                        && ProtocolTreeNode.TagEquals(node.children.First(), "picture"))
                    {
                        this.AddMessage(node);
                    }

                    if (ProtocolTreeNode.TagEquals(node, "presence"))
                    {
                        this.AddMessage(node);
                    }

                    if (ProtocolTreeNode.TagEquals(node,"stream:error"))
                    {
                        Console.Write(node.NodeString());
                    }
                    if (ProtocolTreeNode.TagEquals(node,"iq")
                        && node.GetAttribute("type").Equals("get", StringComparison.OrdinalIgnoreCase)
                        && ProtocolTreeNode.TagEquals(node.children.First(), "ping"))
                    {
                        this.Pong(node.GetAttribute("id"));
                    }
                    if (ProtocolTreeNode.TagEquals(node ,"stream:error"))
                    {
                        var textNode = node.GetChild("text");
                        if (textNode != null)
                        {
                            string content = WhatsApp.SYSEncoding.GetString(textNode.GetData());
                            Console.WriteLine("Error : " + content);
                            if (content.Equals("Replaced by new connection", StringComparison.OrdinalIgnoreCase))
                            {
                                this.Disconnect();
                                this.Connect();
                                this.Login();
                            }
                        }
                    }
                    node = this.reader.nextTree();
                }
            }
            catch (IncompleteMessageException e)
            {
                _incompleteBytes.Add(e);
                this.PollMessages();

                //Console.WriteLine("Error");

            }
        }
Esempio n. 22
0
        /// <summary>
        /// Default class constructor
        /// </summary>
        /// <param name="phoneNum">The phone number</param>
        /// <param name="imei">The imei / mac</param>
        /// <param name="nick">User nickname</param>
        /// <param name="debug">Debug on or off, false by default</param>
        public WhatsApp(string phoneNum, string imei, string nick, bool debug = false, bool hidden = false)
        {
            this.messageQueue = new List<ProtocolTreeNode>();
            this.phoneNumber = phoneNum;
            this.imei = imei;
            this.name = nick;
            this.hidden = hidden;
            WhatsApp.DEBUG = debug;
            this.reader = new BinTreeNodeReader();
            this.loginStatus = CONNECTION_STATUS.DISCONNECTED;
            this.whatsNetwork = new WhatsNetwork(WhatsConstants.WhatsAppHost, WhatsConstants.WhatsPort, this.timeout);
            this.WhatsParser = new WhatsParser(this.whatsNetwork, new BinTreeNodeWriter());
            this.WhatsSendHandler = this.WhatsParser.WhatsSendHandler;

            _incompleteBytes = new List<IncompleteMessageException>();
        }
Esempio n. 23
0
 /// <summary>
 /// Process inbound data
 /// </summary>
 /// <param name="data">Data to process</param>
 protected void processInboundData(byte[] data)
 {
     try
     {
         List<byte> foo = new List<byte>();
         if (this._incompleteBytes.Count > 0)
         {
             foreach (IncompleteMessageException e in this._incompleteBytes)
             {
                 foo.AddRange(e.getInput());
             }
             this._incompleteBytes.Clear();
         }
         if (data != null)
         {
             foo.AddRange(data);
         }
         ProtocolTreeNode node = this.reader.nextTree(foo.ToArray());
         while (node != null)
         {
             //this.WhatsParser.ParseProtocolNode(node);
             if (node.tag == "iq"
             && node.GetAttribute("type") == "error")
             {
                 this.AddMessage(node);
             }
             if (ProtocolTreeNode.TagEquals(node, "challenge"))
             {
                 this.processChallenge(node);
             }
             else if (ProtocolTreeNode.TagEquals(node, "success"))
             {
                 this.loginStatus = CONNECTION_STATUS.LOGGEDIN;
                 this.accountinfo = new AccountInfo(node.GetAttribute("status"),
                                                    node.GetAttribute("kind"),
                                                    node.GetAttribute("creation"),
                                                    node.GetAttribute("expiration"));
             }
             else if (ProtocolTreeNode.TagEquals(node, "failure"))
             {
                 this.loginStatus = CONNECTION_STATUS.UNAUTHORIZED;
             }
             if (ProtocolTreeNode.TagEquals(node, "message"))
             {
                 this.AddMessage(node);
                 if (node.GetChild("request") != null)
                 {
                     this.sendMessageReceived(node);
                 }
                 else if (node.GetChild("received") != null)
                 {
                     this.sendMessageReceived(node, "ack");
                 }
             }
             if (ProtocolTreeNode.TagEquals(node, "stream:error"))
             {
                 Console.Write(node.NodeString());
             }
             if (ProtocolTreeNode.TagEquals(node, "iq")
                 && node.GetAttribute("type").Equals("result", StringComparison.OrdinalIgnoreCase)
                 && ProtocolTreeNode.TagEquals(node.children.First(), "query")
                 )
             {
                 //last seen
                 this.AddMessage(node);
             }
             if (ProtocolTreeNode.TagEquals(node, "iq")
                 && node.GetAttribute("type").Equals("result", StringComparison.OrdinalIgnoreCase)
                 && (ProtocolTreeNode.TagEquals(node.children.First(), "media") || ProtocolTreeNode.TagEquals(node.children.First(), "duplicate"))
                 )
             {
                 //media upload
                 this.uploadResponse = node;
             }
             if (ProtocolTreeNode.TagEquals(node, "iq")
                 && node.GetAttribute("type").Equals("result", StringComparison.OrdinalIgnoreCase)
                 && ProtocolTreeNode.TagEquals(node.children.First(), "picture")
                 )
             {
                 //profile picture
                 this.AddMessage(node);
             }
             if (ProtocolTreeNode.TagEquals(node, "iq")
                 && node.GetAttribute("type").Equals("get", StringComparison.OrdinalIgnoreCase)
                 && ProtocolTreeNode.TagEquals(node.children.First(), "ping"))
             {
                 this.Pong(node.GetAttribute("id"));
             }
             if (ProtocolTreeNode.TagEquals(node, "stream:error"))
             {
                 var textNode = node.GetChild("text");
                 if (textNode != null)
                 {
                     string content = WhatsApp.SYSEncoding.GetString(textNode.GetData());
                     Console.WriteLine("Error : " + content);
                     if (content.Equals("Replaced by new connection", StringComparison.OrdinalIgnoreCase))
                     {
                         this.Disconnect();
                         this.Connect();
                         this.Login();
                     }
                 }
             }
             if (ProtocolTreeNode.TagEquals(node, "presence"))
             {
                 //presence node
                 this.AddMessage(node);
             }
             node = this.reader.nextTree();
         }
     }
     catch (IncompleteMessageException ex)
     {
         this._incompleteBytes.Add(ex);
     }
 }
Esempio n. 24
0
        /// <summary>
        /// Process inbound data
        /// </summary>
        /// <param name="data">Data to process</param>
        protected void processInboundData(bool autoReceipt = true)
        {
            try
            {
                byte[] msgdata = this.whatsNetwork.ReadNextNode();
                ProtocolTreeNode node = this.reader.nextTree(msgdata);
                while (node != null)
                {
                    if (node.tag == "iq"
                    && node.GetAttribute("type") == "error")
                    {
                        if (this.OnError != null)
                        {
                            this.OnError(node.GetAttribute("id"), node.GetAttribute("from"), Int32.Parse(node.GetChild("error").GetAttribute("code")), node.GetChild("error").GetAttribute("text"));
                        }
                    }
                    if (ProtocolTreeNode.TagEquals(node, "challenge"))
                    {
                        this.processChallenge(node);
                    }
                    else if (ProtocolTreeNode.TagEquals(node, "success"))
                    {
                        this.loginStatus = CONNECTION_STATUS.LOGGEDIN;
                        this.accountinfo = new AccountInfo(node.GetAttribute("status"),
                                                           node.GetAttribute("kind"),
                                                           node.GetAttribute("creation"),
                                                           node.GetAttribute("expiration"));
                        if (this.OnLoginSuccess != null)
                        {
                            this.OnLoginSuccess(node.GetData());
                        }
                    }
                    else if (ProtocolTreeNode.TagEquals(node, "failure"))
                    {
                        this.loginStatus = CONNECTION_STATUS.UNAUTHORIZED;
                        if (this.OnLoginFailed != null)
                        {
                            this.OnLoginFailed(node.children.FirstOrDefault().tag);
                        }
                    }
                    if (ProtocolTreeNode.TagEquals(node, "message"))
                    {
                        if (!string.IsNullOrEmpty(node.GetAttribute("notify")))
                        {
                            string name = node.GetAttribute("notify");
                            if (this.OnGetContactName != null)
                            {
                                this.OnGetContactName(node.GetAttribute("from"), name);
                            }
                        }
                        if (node.GetAttribute("type") == "error")
                        {
                            throw new NotImplementedException(node.NodeString());
                        }
                        if (node.GetChild("body") != null)
                        {
                            //text message
                            if (this.OnGetMessage != null)
                            {
                                this.OnGetMessage(node, node.GetAttribute("from"), node.GetAttribute("id"), node.GetAttribute("notify"), System.Text.Encoding.UTF8.GetString(node.GetChild("body").GetData()), autoReceipt);
                            }
                            if (autoReceipt)
                            {
                                this.sendMessageReceived(node);
                            }
                        }
                        if (node.GetChild("media") != null)
                        {
                            ProtocolTreeNode media = node.GetChild("media");
                            //media message

                            //define variables in switch
                            string file, url, from, id;
                            int size;
                            byte[] preview, dat;
                            id = node.GetAttribute("id");
                            from = node.GetAttribute("from");
                            switch (media.GetAttribute("type"))
                            {
                                case "image":
                                    if (this.OnGetMessageImage != null)
                                    {
                                        url = media.GetAttribute("url");
                                        file = media.GetAttribute("file");
                                        size = Int32.Parse(media.GetAttribute("size"));
                                        preview = media.GetData();
                                        this.OnGetMessageImage(from, id, file, size, url, preview);
                                    }
                                    break;
                                case "audio":
                                    if (this.OnGetMessageAudio != null)
                                    {
                                        file = media.GetAttribute("file");
                                        size = Int32.Parse(media.GetAttribute("size"));
                                        url = media.GetAttribute("url");
                                        preview = media.GetData();
                                        this.OnGetMessageAudio(from, id, file, size, url, preview);
                                    }
                                    break;
                                case "video":
                                    if (this.OnGetMessageVideo != null)
                                    {
                                        file = media.GetAttribute("file");
                                        size = Int32.Parse(media.GetAttribute("size"));
                                        url = media.GetAttribute("url");
                                        preview = media.GetData();
                                        this.OnGetMessageVideo(from, id, file, size, url, preview);
                                    }
                                    break;
                                case "location":
                                    if (this.OnGetMessageLocation != null)
                                    {
                                        double lon = double.Parse(media.GetAttribute("longitude"), System.Globalization.CultureInfo.InvariantCulture);
                                        double lat = double.Parse(media.GetAttribute("latitude"), System.Globalization.CultureInfo.InvariantCulture);
                                        preview = media.GetData();
                                        name = media.GetAttribute("name");
                                        url = media.GetAttribute("url");
                                        this.OnGetMessageLocation(from, id, lon, lat, url, name, preview);
                                    }
                                    break;
                                case "vcard":
                                    if (this.OnGetMessageVcard != null)
                                    {
                                        ProtocolTreeNode vcard = media.GetChild("vcard");
                                        name = vcard.GetAttribute("name");
                                        dat = vcard.GetData();
                                        this.OnGetMessageVcard(from, id, name, dat);
                                    }
                                    break;
                            }
                            this.sendMessageReceived(node);
                        }
                    }
                    if (ProtocolTreeNode.TagEquals(node, "iq"))
                    {
                        if (node.GetChild("sync") != null)
                        {
                            //sync result
                            ProtocolTreeNode sync = node.GetChild("sync");
                            ProtocolTreeNode existing = sync.GetChild("in");
                            ProtocolTreeNode nonexisting = sync.GetChild("out");
                            //process existing first
                            Dictionary<string, string> existingUsers = new Dictionary<string, string>();
                            foreach (ProtocolTreeNode child in existing.GetAllChildren())
                            {
                                existingUsers.Add(System.Text.Encoding.UTF8.GetString(child.GetData()), child.GetAttribute("jid"));
                            }
                            //now process failed numbers
                            List<string> failedNumbers = new List<string>();
                            foreach (ProtocolTreeNode child in nonexisting.GetAllChildren())
                            {
                                failedNumbers.Add(System.Text.Encoding.UTF8.GetString(child.GetData()));
                            }
                            int index = 0;
                            Int32.TryParse(sync.GetAttribute("index"), out index);
                            if (this.OnGetSyncResult != null)
                            {
                                this.OnGetSyncResult(index, sync.GetAttribute("sid"), existingUsers, failedNumbers.ToArray());
                            }
                        }
                        if (node.GetAttribute("type").Equals("result", StringComparison.OrdinalIgnoreCase)
                            && node.children.FirstOrDefault().tag == "query"
                            && node.children.FirstOrDefault().GetAttribute("xmlns") == "jabber:iq:last"
                        )
                        {
                            //last seen
                            DateTime lastSeen = DateTime.Now.AddSeconds(double.Parse(node.children.FirstOrDefault().GetAttribute("seconds")) * -1);
                            if (this.OnGetLastSeen != null)
                            {
                                this.OnGetLastSeen(node.GetAttribute("from"), lastSeen);
                            }
                        }
                        if (node.GetAttribute("type").Equals("result", StringComparison.OrdinalIgnoreCase)
                            && (ProtocolTreeNode.TagEquals(node.children.FirstOrDefault(), "media") || ProtocolTreeNode.TagEquals(node.children.FirstOrDefault(), "duplicate"))
                            )
                        {
                            //media upload
                            this.uploadResponse = node;
                        }
                        if (node.GetAttribute("type").Equals("result", StringComparison.OrdinalIgnoreCase)
                            && ProtocolTreeNode.TagEquals(node.children.FirstOrDefault(), "picture")
                            )
                        {
                            //profile picture
                            string from = node.GetAttribute("from");
                            string id = node.GetChild("picture").GetAttribute("id");
                            byte[] dat = node.GetChild("picture").GetData();
                            string type = node.GetChild("picture").GetAttribute("type");
                            if (type == "preview")
                            {
                                if (this.OnGetPhotoPreview != null)
                                {
                                    this.OnGetPhotoPreview(from, id, dat);
                                }
                            }
                            else
                            {
                                if (this.OnGetPhoto != null)
                                {
                                    this.OnGetPhoto(from, id, dat);
                                }
                            }
                        }
                        if (node.GetAttribute("type").Equals("get", StringComparison.OrdinalIgnoreCase)
                            && ProtocolTreeNode.TagEquals(node.children.FirstOrDefault(), "ping"))
                        {
                            this.Pong(node.GetAttribute("id"));
                        }
                        if (node.GetAttribute("type").Equals("result", StringComparison.OrdinalIgnoreCase)
                            && ProtocolTreeNode.TagEquals(node.children.FirstOrDefault(), "group"))
                        {
                            //group(s) info
                            List<GroupInfo> groups = new List<GroupInfo>();
                            foreach (ProtocolTreeNode group in node.children)
                            {
                                groups.Add(new GroupInfo(
                                    group.GetAttribute("id"),
                                    group.GetAttribute("owner"),
                                    long.Parse(group.GetAttribute("creation")),
                                    group.GetAttribute("subject"),
                                    long.Parse(group.GetAttribute("s_t")),
                                    group.GetAttribute("s_o")
                                    ));
                            }
                            if (this.OnGetGroups != null)
                            {
                                this.OnGetGroups(groups.ToArray());
                            }
                        }
                        if (node.GetAttribute("type").Equals("result", StringComparison.OrdinalIgnoreCase)
                            && ProtocolTreeNode.TagEquals(node.children.FirstOrDefault(), "participant"))
                        {
                            //group participants
                            List<string> participants = new List<string>();
                            foreach (ProtocolTreeNode part in node.GetAllChildren())
                            {
                                if (part.tag == "participant" && !string.IsNullOrEmpty(part.GetAttribute("jid")))
                                {
                                    participants.Add(part.GetAttribute("jid"));
                                }
                            }
                            if (this.OnGetGroupParticipants != null)
                            {
                                this.OnGetGroupParticipants(node.GetAttribute("from"), participants.ToArray());
                            }
                        }
                    }

                    if (ProtocolTreeNode.TagEquals(node, "stream:error"))
                    {
                        var textNode = node.GetChild("text");
                        if (textNode != null)
                        {
                            string content = WhatsApp.SYSEncoding.GetString(textNode.GetData());
                            Console.WriteLine("Error : " + content);
                            if (content.Equals("Replaced by new connection", StringComparison.OrdinalIgnoreCase))
                            {
                                this.Disconnect(new Exception(content));
                                this.Connect();
                                this.Login();
                            }
                        }
                    }
                    if (ProtocolTreeNode.TagEquals(node, "presence"))
                    {
                        //presence node
                        if (this.OnGetPresence != null)
                        {
                            this.OnGetPresence(node.GetAttribute("from"), node.GetAttribute("type"));
                        }
                    }

                    if (node.tag == "ib")
                    {
                        foreach (ProtocolTreeNode child in node.children)
                        {
                            switch (child.tag)
                            {
                                case "dirty":
                                    this.WhatsSendHandler.SendClearDirty(child.GetAttribute("type"));
                                    break;
                                case "offline":
                                    //this.SendQrSync(null);
                                    break;
                                default:
                                    throw new NotImplementedException(node.NodeString());
                            }
                        }
                    }

                    if (node.tag == "chatstate")
                    {
                        string state = node.children.FirstOrDefault().tag;
                        switch (state)
                        {
                            case "composing":
                                if (this.OnGetTyping != null)
                                {
                                    this.OnGetTyping(node.GetAttribute("from"));
                                }
                                break;
                            case "paused":
                                if (this.OnGetPaused != null)
                                {
                                    this.OnGetPaused(node.GetAttribute("from"));
                                }
                                break;
                            default:
                                throw new NotImplementedException(node.NodeString());
                        }
                    }

                    if (node.tag == "ack")
                    {
                        //do nothing
                        //throw new NotImplementedException(node.NodeString());
                    }

                    if (node.tag == "notification")
                    {
                        if(!String.IsNullOrEmpty(node.GetAttribute("notify")))
                        {
                            if(this.OnGetContactName != null)
                            {
                                this.OnGetContactName(node.GetAttribute("from"), node.GetAttribute("notify"));
                            }
                        }
                        string type = node.GetAttribute("type");
                        switch(type)
                        {
                            case "picture":
                                ProtocolTreeNode child = node.children.FirstOrDefault();
                                if (this.OnNotificationPicture != null)
                                {
                                    this.OnNotificationPicture(child.tag, child.GetAttribute("jid"), child.GetAttribute("id"));
                                }
                                break;
                            case "status":
                                ProtocolTreeNode child2 = node.children.FirstOrDefault();
                                if (this.OnGetStatus != null)
                                {
                                    this.OnGetStatus(node.GetAttribute("from"), child2.tag, node.GetAttribute("notify"), System.Text.Encoding.UTF8.GetString(child2.GetData()));
                                }
                                break;
                            default:
                                throw new NotImplementedException(node.NodeString());
                        }
                        this.SendNotificationAck(node);
                    }
                    node = this.reader.nextTree();
                }
            }
            catch (Exception e)
            {
                //whatever
                this._incompleteBytes.Clear();
            }
        }
Esempio n. 25
0
 /// <summary>
 /// Disconnect from the whatsapp network
 /// </summary>
 public void Disconnect()
 {
     this.whatsNetwork.Disconenct();
     this.loginStatus = CONNECTION_STATUS.DISCONNECTED;
 }
 public void Disconnect()
 {
     this.whatsNetwork.Connect();
     this.loginStatus = CONNECTION_STATUS.DISCONNECTED;
 }
Esempio n. 27
0
    private void NativeConnect(string relayServer)
    {
        sock = new WebSocket(new Uri(relayServer));
        CurrentConnectionStatus = CONNECTION_STATUS.OPENING;
        WebSocket webSocket = sock;

        webSocket.OnOpen = (Action <WebSocket>) Delegate.Combine(webSocket.OnOpen, (Action <WebSocket>) delegate(WebSocket ws)
        {
            LogDebug("OnOpen {0}", ws.InternalRequest.Uri);
            ClearLastPacketReceivedTime();
            isConnect = true;
            CurrentConnectionStatus = CONNECTION_STATUS.CONNECTED;
        });
        WebSocket webSocket2 = sock;

        webSocket2.OnBinary = (Action <WebSocket, byte[]>) Delegate.Combine(webSocket2.OnBinary, (Action <WebSocket, byte[]>) delegate(WebSocket ws, byte[] binary)
        {
            LogDebug("OnBinary {0}", binary.Length);
            ClearLastPacketReceivedTime();
            temporaryQueue.Enqueue(new PacketStream(binary));
        });
        WebSocket webSocket3 = sock;

        webSocket3.OnMessage = (Action <WebSocket, string>) Delegate.Combine(webSocket3.OnMessage, (Action <WebSocket, string>) delegate(WebSocket ws, string message)
        {
            LogDebug("OnMessage {0}", message);
            ClearLastPacketReceivedTime();
            temporaryQueue.Enqueue(new PacketStream(message));
        });
        WebSocket webSocket4 = sock;

        webSocket4.OnClosed = (Action <WebSocket, ushort, string>) Delegate.Combine(webSocket4.OnClosed, (Action <WebSocket, ushort, string>) delegate(WebSocket ws, ushort code, string message)
        {
            OnPrepareClose();
            temporaryQueue.Clear();
            if (this.OnClosed != null)
            {
                this.OnClosed();
            }
            LogDebug("OnClosed Code {0}", code);
            LogDebug("OnClosed Message {0}", message);
        });
        WebSocket webSocket5 = sock;

        webSocket5.OnError = (Action <WebSocket, Exception>) Delegate.Combine(webSocket5.OnError, (Action <WebSocket, Exception>) delegate(WebSocket ws, Exception ex)
        {
            CurrentConnectionStatus = CONNECTION_STATUS.ERROR;
            OnErrorOccurred(EventArgs.Empty, ex);
            LogDebug("OnError Message {0}", ex.Message);
            LogDebug("OnError StackTrace {0}", ex.StackTrace);
        });
        WebSocket webSocket6 = sock;

        webSocket6.OnPong = (Action <WebSocket, byte[]>)Delegate.Combine(webSocket6.OnPong, (Action <WebSocket, byte[]>) delegate
        {
            if (this.OnPong != null)
            {
                this.OnPong((DateTime.Now - lastPacketReceivedTime).TotalMilliseconds - 3000.0);
            }
            ClearLastPacketReceivedTime();
        });
        sock.StartPingThread = true;
        sock.PingFrequency   = 3000;
        sock.Open();
    }
Esempio n. 28
0
 /// <summary>
 /// Process inbound data
 /// </summary>
 /// <param name="data">Data to process</param>
 protected void processInboundData(byte[] data)
 {
     try
     {
         List <byte> foo = new List <byte>();
         if (this._incompleteBytes.Count > 0)
         {
             foreach (IncompleteMessageException e in this._incompleteBytes)
             {
                 foo.AddRange(e.getInput());
             }
             this._incompleteBytes.Clear();
         }
         if (data != null)
         {
             foo.AddRange(data);
         }
         ProtocolTreeNode node = this.reader.nextTree(foo.ToArray());
         while (node != null)
         {
             //this.WhatsParser.ParseProtocolNode(node);
             if (node.tag == "iq" &&
                 node.GetAttribute("type") == "error")
             {
                 this.AddMessage(node);
             }
             if (ProtocolTreeNode.TagEquals(node, "challenge"))
             {
                 this.processChallenge(node);
             }
             else if (ProtocolTreeNode.TagEquals(node, "success"))
             {
                 this.loginStatus = CONNECTION_STATUS.LOGGEDIN;
                 this.accountinfo = new AccountInfo(node.GetAttribute("status"),
                                                    node.GetAttribute("kind"),
                                                    node.GetAttribute("creation"),
                                                    node.GetAttribute("expiration"));
             }
             else if (ProtocolTreeNode.TagEquals(node, "failure"))
             {
                 this.loginStatus = CONNECTION_STATUS.UNAUTHORIZED;
             }
             if (ProtocolTreeNode.TagEquals(node, "message"))
             {
                 this.AddMessage(node);
                 if (node.GetChild("request") != null)
                 {
                     this.sendMessageReceived(node);
                 }
                 else if (node.GetChild("received") != null)
                 {
                     this.sendMessageReceived(node, "ack");
                 }
             }
             if (ProtocolTreeNode.TagEquals(node, "stream:error"))
             {
                 Console.Write(node.NodeString());
             }
             if (ProtocolTreeNode.TagEquals(node, "iq") &&
                 node.GetAttribute("type").Equals("result", StringComparison.OrdinalIgnoreCase) &&
                 ProtocolTreeNode.TagEquals(node.children.First(), "query")
                 )
             {
                 //last seen
                 this.AddMessage(node);
             }
             if (ProtocolTreeNode.TagEquals(node, "iq") &&
                 node.GetAttribute("type").Equals("result", StringComparison.OrdinalIgnoreCase) &&
                 (ProtocolTreeNode.TagEquals(node.children.First(), "media") || ProtocolTreeNode.TagEquals(node.children.First(), "duplicate"))
                 )
             {
                 //media upload
                 this.uploadResponse = node;
             }
             if (ProtocolTreeNode.TagEquals(node, "iq") &&
                 node.GetAttribute("type").Equals("result", StringComparison.OrdinalIgnoreCase) &&
                 ProtocolTreeNode.TagEquals(node.children.First(), "picture")
                 )
             {
                 //profile picture
                 this.AddMessage(node);
             }
             if (ProtocolTreeNode.TagEquals(node, "iq") &&
                 node.GetAttribute("type").Equals("get", StringComparison.OrdinalIgnoreCase) &&
                 ProtocolTreeNode.TagEquals(node.children.First(), "ping"))
             {
                 this.Pong(node.GetAttribute("id"));
             }
             if (ProtocolTreeNode.TagEquals(node, "stream:error"))
             {
                 var textNode = node.GetChild("text");
                 if (textNode != null)
                 {
                     string content = WhatsApp.SYSEncoding.GetString(textNode.GetData());
                     Console.WriteLine("Error : " + content);
                     if (content.Equals("Replaced by new connection", StringComparison.OrdinalIgnoreCase))
                     {
                         this.Disconnect();
                         this.Connect();
                         this.Login();
                     }
                 }
             }
             if (ProtocolTreeNode.TagEquals(node, "presence"))
             {
                 //presence node
                 this.AddMessage(node);
             }
             node = this.reader.nextTree();
         }
     }
     catch (IncompleteMessageException ex)
     {
         this._incompleteBytes.Add(ex);
     }
 }
Esempio n. 29
0
 private void OnPrepareClose()
 {
     ReceivePacketAction     = null;
     isConnect               = false;
     CurrentConnectionStatus = CONNECTION_STATUS.CLOSED;
 }