GetChild() public method

public GetChild ( string tag ) : ProtocolTreeNode
tag string
return ProtocolTreeNode
Example #1
0
 public WappMessage(ProtocolTreeNode node, string jid)
 {
     ProtocolTreeNode body = node.GetChild("body");
     ProtocolTreeNode media = node.GetChild("media");
     if (node.tag == "message")
     {
         if (node.GetAttribute("type") == "subject")
         {
             Contact c = ContactStore.GetContactByJid(node.GetAttribute("author"));
             this.data = c.ToString() + " changed subject to \"" + Encoding.ASCII.GetString(node.GetChild("body").GetData()) + "\"";
         }
         else
         {
             if (body != null)
             {
                 this.data = Encoding.ASCII.GetString(node.GetChild("body").GetData());
                 this.type = "text";
             }
             else if (media != null)
             {
                 this.type = media.GetAttribute("type");
                 if (media.data != null && media.data.Length > 0)
                 {
                     this.preview = Convert.ToBase64String(media.data);
                 }
                 this.data = media.GetAttribute("url");
             }
         }
         this.from_me = false;
         this.timestamp = DateTime.UtcNow;
         this.jid = jid;
     }
 }
Example #2
0
 public WaUploadResponse(ProtocolTreeNode node)
 {
     node = node.GetChild("duplicate");
     if (node != null)
     {
         int oSize, oWidth, oHeight, oDuration, oAsampfreq, oAbitrate;
         this.url = node.GetAttribute("url");
         this.mimetype = node.GetAttribute("mimetype");
         Int32.TryParse(node.GetAttribute("size"), out oSize);
         this.filehash = node.GetAttribute("filehash");
         this.type = node.GetAttribute("type");
         Int32.TryParse(node.GetAttribute("width"), out oWidth);
         Int32.TryParse(node.GetAttribute("height"), out oHeight);
         Int32.TryParse(node.GetAttribute("duration"), out oDuration);
         this.acodec = node.GetAttribute("acodec");
         Int32.TryParse(node.GetAttribute("asampfreq"), out oAsampfreq);
         this.asampfmt = node.GetAttribute("asampfmt");
         Int32.TryParse(node.GetAttribute("abitrate"), out oAbitrate);
         this.size = oSize;
         this.width = oWidth;
         this.height = oHeight;
         this.duration = oDuration;
         this.asampfreq = oAsampfreq;
         this.abitrate = oAbitrate;
     }
 }
Example #3
0
 public WappMessage(ProtocolTreeNode node, string jid)
 {
     if (node.tag == "message")
     {
         if (node.GetAttribute("type") == "subject")
         {
             Contact c = ContactStore.GetContactByJid(node.GetAttribute("author"));
             this.data = c.ToString() + " changed subject to \"" + Encoding.ASCII.GetString(node.GetChild("body").GetData()) + "\"";
         }
         else
         {
             this.data = Encoding.ASCII.GetString(node.GetChild("body").GetData());
         }
         this.from_me = false;
         this.timestamp = DateTime.UtcNow;
         this.jid = jid;
     }
 }
Example #4
0
 protected void handleNotification(ProtocolTreeNode node)
 {
     if (!String.IsNullOrEmpty(node.GetAttribute("notify")))
     {
         this.fireOnGetContactName(node.GetAttribute("from"), node.GetAttribute("notify"));
     }
     string type = node.GetAttribute("type");
     switch (type)
     {
         case "picture":
             ProtocolTreeNode child = node.children.FirstOrDefault();
             this.fireOnNotificationPicture(child.tag, 
                 child.GetAttribute("jid"), 
                 child.GetAttribute("id"));
             break;
         case "status":
             ProtocolTreeNode child2 = node.children.FirstOrDefault();
             this.fireOnGetStatus(node.GetAttribute("from"), 
                 child2.tag, 
                 node.GetAttribute("notify"), 
                 System.Text.Encoding.UTF8.GetString(child2.GetData()));
             break;
         case "subject":
             //fire username notify
             this.fireOnGetContactName(node.GetAttribute("participant"),
                 node.GetAttribute("notify"));
             //fire subject notify
             this.fireOnGetGroupSubject(node.GetAttribute("from"),
                 node.GetAttribute("participant"),
                 node.GetAttribute("notify"),
                 System.Text.Encoding.UTF8.GetString(node.GetChild("body").GetData()),
                 GetDateTimeFromTimestamp(node.GetAttribute("t")));
             break;
         case "contacts":
             //TODO
             break;
         case "participant":
             string gjid = node.GetAttribute("from");
             string t = node.GetAttribute("t");
             foreach (ProtocolTreeNode child3 in node.GetAllChildren())
             {
                 if (child3.tag == "add")
                 {
                     this.fireOnGetParticipantAdded(gjid, 
                         child3.GetAttribute("jid"), 
                         GetDateTimeFromTimestamp(t));
                 }
                 else if (child3.tag == "remove")
                 {
                     this.fireOnGetParticipantRemoved(gjid, 
                         child3.GetAttribute("jid"), 
                         child3.GetAttribute("author"), 
                         GetDateTimeFromTimestamp(t));
                 }
                 else if (child3.tag == "modify")
                 {
                     this.fireOnGetParticipantRenamed(gjid,
                         child3.GetAttribute("remove"),
                         child3.GetAttribute("add"),
                         GetDateTimeFromTimestamp(t));
                 }
             }
             break;
     }
     this.SendNotificationAck(node);
 }
Example #5
0
 protected void handleIq(ProtocolTreeNode node)
 {
     if (node.GetAttribute("type") == "error")
     {
         this.fireOnError(node.GetAttribute("id"), node.GetAttribute("from"), Int32.Parse(node.GetChild("error").GetAttribute("code")), node.GetChild("error").GetAttribute("text"));
     }
     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>();
         if (existing != null)
         {
             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>();
         if (nonexisting != null)
         {
             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);
         this.fireOnGetSyncResult(index, sync.GetAttribute("sid"), existingUsers, failedNumbers.ToArray());
     }
     if (node.GetAttribute("type").Equals("result", StringComparison.OrdinalIgnoreCase)
         && node.GetChild("query") != null
     )
     {
         //last seen
         DateTime lastSeen = DateTime.Now.AddSeconds(double.Parse(node.children.FirstOrDefault().GetAttribute("seconds")) * -1);
         this.fireOnGetLastSeen(node.GetAttribute("from"), lastSeen);
     }
     if (node.GetAttribute("type").Equals("result", StringComparison.OrdinalIgnoreCase)
         && (node.GetChild("media") != null || node.GetChild("duplicate") != null)
         )
     {
         //media upload
         this.uploadResponse = node;
     }
     if (node.GetAttribute("type").Equals("result", StringComparison.OrdinalIgnoreCase)
         && node.GetChild("picture") != null
         )
     {
         //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")
         {
             this.fireOnGetPhotoPreview(from, id, dat);
         }
         else
         {
             this.fireOnGetPhoto(from, id, dat);
         }
     }
     if (node.GetAttribute("type").Equals("get", StringComparison.OrdinalIgnoreCase)
         && node.GetChild("ping") != null)
     {
         this.SendPong(node.GetAttribute("id"));
     }
     if (node.GetAttribute("type").Equals("result", StringComparison.OrdinalIgnoreCase)
         && node.GetChild("group") != null)
     {
         //group(s) info
         List<WaGroupInfo> groups = new List<WaGroupInfo>();
         foreach (ProtocolTreeNode group in node.children)
         {
             groups.Add(new WaGroupInfo(
                 group.GetAttribute("id"),
                 group.GetAttribute("owner"),
                 group.GetAttribute("creation"),
                 group.GetAttribute("subject"),
                 group.GetAttribute("s_t"),
                 group.GetAttribute("s_o")
                 ));
         }
         this.fireOnGetGroups(groups.ToArray());
     }
     if (node.GetAttribute("type").Equals("result", StringComparison.OrdinalIgnoreCase)
         && node.GetChild("participant") != null)
     {
         //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"));
             }
         }
         this.fireOnGetGroupParticipants(node.GetAttribute("from"), participants.ToArray());
     }
     if (node.GetAttribute("type") == "result" && node.GetChild("status") != null)
     {
         foreach (ProtocolTreeNode status in node.GetChild("status").GetAllChildren())
         {
             this.fireOnGetStatus(status.GetAttribute("jid"),
                 "result",
                 null,
                 WhatsApp.SYSEncoding.GetString(status.GetData()));
         }
     }
     if (node.GetAttribute("type") == "result" && node.GetChild("privacy") != null)
     {
         Dictionary<VisibilityCategory, VisibilitySetting> settings = new Dictionary<VisibilityCategory, VisibilitySetting>();
         foreach (ProtocolTreeNode child in node.GetChild("privacy").GetAllChildren("category"))
         {
             settings.Add(this.parsePrivacyCategory(
                 child.GetAttribute("name")), 
                 this.parsePrivacySetting(child.GetAttribute("value"))
             );
         }
         this.fireOnGetPrivacySettings(settings);
     }
 }
Example #6
0
        protected void handleMessage(ProtocolTreeNode node, bool autoReceipt)
        {
            if (!string.IsNullOrEmpty(node.GetAttribute("notify")))
            {
                string name = node.GetAttribute("notify");
                this.fireOnGetContactName(node.GetAttribute("from"), name);
            }
            if (node.GetAttribute("type") == "error")
            {
                throw new NotImplementedException(node.NodeString());
            }
            if (node.GetChild("body") != null)
            {
                //text message
                this.fireOnGetMessage(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":
                        url = media.GetAttribute("url");
                        file = media.GetAttribute("file");
                        size = Int32.Parse(media.GetAttribute("size"));
                        preview = media.GetData();
                        this.fireOnGetMessageImage(node, from, id, file, size, url, preview);
                        break;
                    case "audio":
                        file = media.GetAttribute("file");
                        size = Int32.Parse(media.GetAttribute("size"));
                        url = media.GetAttribute("url");
                        preview = media.GetData();
                        this.fireOnGetMessageAudio(node, from, id, file, size, url, preview);
                        break;
                    case "video":
                        file = media.GetAttribute("file");
                        size = Int32.Parse(media.GetAttribute("size"));
                        url = media.GetAttribute("url");
                        preview = media.GetData();
                        this.fireOnGetMessageVideo(node, from, id, file, size, url, preview);
                        break;
                    case "location":
                        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.fireOnGetMessageLocation(node, from, id, lon, lat, url, name, preview);
                        break;
                    case "vcard":
                        ProtocolTreeNode vcard = media.GetChild("vcard");
                        name = vcard.GetAttribute("name");
                        dat = vcard.GetData();
                        this.fireOnGetMessageVcard(node, from, id, name, dat);
                        break;
                }
                this.sendMessageReceived(node);
            }
        }
 /// <summary>
 /// Type subject
 /// </summary>
 /// <param name="messageNode"></param>
 /// <param name="tmpFrom"></param>
 /// <param name="uJid"></param>
 /// <param name="tmpId"></param>
 /// <param name="tmpT"></param>
 private void TypeSubject(ProtocolTreeNode messageNode, string tmpFrom, string uJid, string tmpId, string tmpT)
 {
     bool flag = false;
     foreach (ProtocolTreeNode item in messageNode.GetAllChildren("request"))
     {
         if (item.GetAttribute("xmlns").Equals("urn:xmpp:receipts"))
         {
             flag = true;
         }
     }
     ProtocolTreeNode child = messageNode.GetChild("body");
     string subject = (child == null) ? null : WhatsApp.SYSEncoding.GetString(child.GetData());
     if (subject != null)
     {
         WhatsEventHandler.OnGroupNewSubjectEventHandler(tmpFrom, uJid, subject, int.Parse(tmpT, CultureInfo.InvariantCulture));
     }
     if (flag)
     {
         this.sendHandler.SendSubjectReceived(tmpFrom, tmpId);
     }
 }
Example #8
0
        protected void sendMessageReceived(ProtocolTreeNode msg)
        {
            //this.WhatsParser.WhatsSendHandler.SendMessageReceived();
            ProtocolTreeNode requestNode = msg.GetChild("request");
            if (requestNode == null ||
                !requestNode.GetAttribute("xmlns").Equals("urn:xmpp:receipts", StringComparison.OrdinalIgnoreCase))
                return;

            FMessage tmpMessage = new FMessage(new FMessage.Key(msg.GetAttribute("from"), true, msg.GetAttribute("id")));
            this.WhatsParser.WhatsSendHandler.SendMessageReceived(tmpMessage);
            //var receivedNode = new ProtocolTreeNode("received",
            //                                        new[] {new KeyValue("xmlns", "urn:xmpp:receipts")});

            //var messageNode = new ProtocolTreeNode("message",
            //                                       new[]
            //                                           {
            //                                               new KeyValue("to", msg.GetAttribute("from")),
            //                                               new KeyValue("type", "chat"),
            //                                               new KeyValue("id", msg.GetAttribute("id"))
            //                                           },
            //                                       new[] {receivedNode});
            //this.whatsNetwork.SendNode(messageNode);
        }
Example #9
0
 /// <summary>
 /// Parse a tree node
 /// </summary>
 /// <param name="protNode">An instance of the ProtocolTreeNode class that needs to be parsed.</param>
 public void ParseProtocolNode(ProtocolTreeNode protNode)
 {
     if (ProtocolTreeNode.TagEquals(protNode, "iq"))
     {
         string attributeValue = protNode.GetAttribute("type");
         string id = protNode.GetAttribute("id");
         string str3 = protNode.GetAttribute("from");
         if (attributeValue == null)
         {
             throw new Exception("Message-Corrupt: missing 'type' attribute in iq stanza");
         }
         if (!attributeValue.Equals("result"))
         {
             if (!attributeValue.Equals("get"))
             {
                 if (!attributeValue.Equals("set"))
                 {
                     throw new Exception("Message-Corrupt: unknown iq type attribute: " + attributeValue);
                 }
                 ProtocolTreeNode child = protNode.GetChild("query");
                 if (child != null)
                 {
                     string str8 = child.GetAttribute("xmlns");
                     if ("jabber:iq:roster" == str8)
                     {
                         foreach (ProtocolTreeNode node5 in child.GetAllChildren("item"))
                         {
                             node5.GetAttribute("jid");
                             node5.GetAttribute("subscription");
                             node5.GetAttribute("ask");
                         }
                     }
                 }
             }
             else
             {
                 ProtocolTreeNode node3 = protNode.GetChild("ping");
                 if ((!ProtocolTreeNode.TagEquals(node3, "query") || (str3 == null)) && (ProtocolTreeNode.TagEquals(node3, "relay")  && (str3 != null)))
                 {
                     int num;
                     string pin = node3.GetAttribute("pin");
                     string tmpTimeout = node3.GetAttribute("timeout");
                     if ( !int.TryParse(tmpTimeout ?? "0", WhatsConstants.WhatsAppNumberStyle, CultureInfo.InvariantCulture, out num))
                     {
                         throw new CorruptStreamException("relay-iq exception parsing timeout attribute: " + tmpTimeout);
                     }
                 }
             }
         }
     }
     else if (ProtocolTreeNode.TagEquals(protNode, "presence"))
     {
         string str9 = protNode.GetAttribute("xmlns");
         string jid = protNode.GetAttribute("from");
         if (((str9 == null) || "urn:xmpp".Equals(str9)) && (jid != null))
         {
             string str11 = protNode.GetAttribute("type");
         }
         else if ("w".Equals(str9) && (jid != null))
         {
             string str12 = protNode.GetAttribute("add");
             string str13 = protNode.GetAttribute("remove");
             string str14 = protNode.GetAttribute("status");
             if (str12 == null)
             {
                 if (str13 == null)
                 {
                     if ("dirty".Equals(str14))
                     {
                         Dictionary<string, long> categories = ParseCategories(protNode);
                     }
                 }
             }
         }
     }
     else if (ProtocolTreeNode.TagEquals(protNode, "message"))
     {
         this.messResponseHandler.ParseMessageRecv(protNode);
     }
 }
Example #10
0
 public UploadResponse(ProtocolTreeNode node)
 {
     node = node.GetChild("duplicate");
     if (node != null)
     {
         this.url = node.GetAttribute("url");
         this.mimetype = node.GetAttribute("mimetype");
         this.size = Int32.Parse(node.GetAttribute("size"));
         this.filehash = node.GetAttribute("filehash");
         this.type = node.GetAttribute("type");
         this.width = Int32.Parse(node.GetAttribute("width"));
         this.height = Int32.Parse(node.GetAttribute("height"));
     }
 }
Example #11
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="node"></param>
        /// <returns></returns>
        public ProtocolTreeNode processEncryptedNode(ProtocolTreeNode node)
        {
            string from    = node.GetAttribute("from");
            string author  = string.Empty;
            string version = string.Empty;
            string encType = string.Empty;

            byte[]           encMsg  = null;
            ProtocolTreeNode rtnNode = null;

            if (from.IndexOf("s.whatsapp.net", 0) > -1)
            {
                author  = ExtractNumber(node.GetAttribute("from"));
                version = node.GetChild("enc").GetAttribute("v");
                encType = node.GetChild("enc").GetAttribute("type");
                encMsg  = node.GetChild("enc").GetData();

                if (!ContainsSession(new AxolotlAddress(author, 1)))
                {
                    //we don't have the session to decrypt, save it in pending and process it later
                    addPendingNode(node);
                    Helper.DebugAdapter.Instance.fireOnPrintDebug("info : Requesting cipher keys from " + author);
                    sendGetCipherKeysFromUser(author);
                }
                else
                {
                    //decrypt the message with the session
                    if (node.GetChild("enc").GetAttribute("count") == "")
                    {
                        setRetryCounter(node.GetAttribute("id"), 1);
                    }
                    if (version == "2")
                    {
                        if (!v2Jids.Contains(author))
                        {
                            v2Jids.Add(author);
                        }
                    }

                    object plaintext = decryptMessage(from, encMsg, encType, node.GetAttribute("id"), node.GetAttribute("t"));

                    if (plaintext.GetType() == typeof(bool) && false == (bool)plaintext)
                    {
                        sendRetry(node, from, node.GetAttribute("id"), node.GetAttribute("t"));
                        Helper.DebugAdapter.Instance.fireOnPrintDebug("info : " + string.Format("Couldn't decrypt message id {0} from {1}. Retrying.", node.GetAttribute("id"), author));
                        return(node); // could not decrypt
                    }

                    // success now lets clear all setting and return node
                    if (retryCounters.ContainsKey(node.GetAttribute("id")))
                    {
                        retryCounters.Remove(node.GetAttribute("id"));
                    }
                    if (retryNodes.ContainsKey(node.GetAttribute("id")))
                    {
                        retryNodes.Remove(node.GetAttribute("id"));
                    }

                    switch (node.GetAttribute("type"))
                    {
                    case "text":
                        //Convert to list.
                        List <ProtocolTreeNode> children      = node.children.ToList();
                        List <KeyValue>         attributeHash = node.attributeHash.ToList();
                        children.Add(new ProtocolTreeNode("body", null, null, (byte[])plaintext));
                        rtnNode = new ProtocolTreeNode(node.tag, attributeHash.ToArray(), children.ToArray(), node.data);
                        break;

                    case "media":
                        // NOT IMPLEMENTED YET
                        break;
                    }

                    Helper.DebugAdapter.Instance.fireOnPrintDebug("info : " + string.Format("Decrypted message with {0} id from {1}", node.GetAttribute("id"), author));
                    return(rtnNode);
                }
            }
            return(node);
        }
Example #12
0
        /// <summary>
        /// Tell the server we recieved the message
        /// </summary>
        /// <param name="msg">The ProtocolTreeNode that contains the message</param>
        protected void sendMessageReceived(ProtocolTreeNode msg)
        {
            ProtocolTreeNode requestNode = msg.GetChild("request");
            if (requestNode == null ||
                !requestNode.GetAttribute("xmlns").Equals("urn:xmpp:receipts", StringComparison.OrdinalIgnoreCase))
                return;

            FMessage tmpMessage = new FMessage(new FMessage.Key(msg.GetAttribute("from"), true, msg.GetAttribute("id")));
            this.WhatsParser.WhatsSendHandler.SendMessageReceived(tmpMessage);
        }
Example #13
0
 public void ParseProtocolNode(ProtocolTreeNode protNode)
 {
     if (ProtocolTreeNode.TagEquals(protNode, "iq"))
     {
         string attributeValue = protNode.GetAttribute("type");
         string id = protNode.GetAttribute("id");
         string str3 = protNode.GetAttribute("from");
         if (attributeValue == null)
         {
             throw new Exception("Message-Corrupt: missing 'type' attribute in iq stanza");
         }
         if (!attributeValue.Equals("result"))
         {
             if (attributeValue.Equals("error"))
             {
                 //IqResultHandler handler2 = this.PopIqHandler(id);
                 //if (handler2 != null)
                 //{
                 //    handler2.ErrorNode(node);
                 //}
             }
             else if (!attributeValue.Equals("get"))
             {
                 if (!attributeValue.Equals("set"))
                 {
                     throw new Exception("Message-Corrupt: unknown iq type attribute: " + attributeValue);
                 }
                 ProtocolTreeNode child = protNode.GetChild("query");
                 if (child != null)
                 {
                     string str8 = child.GetAttribute("xmlns");
                     if ("jabber:iq:roster" == str8)
                     {
                         foreach (ProtocolTreeNode node5 in child.GetAllChildren("item"))
                         {
                             node5.GetAttribute("jid");
                             node5.GetAttribute("subscription");
                             node5.GetAttribute("ask");
                         }
                     }
                 }
             }
             else
             {
                 ProtocolTreeNode node3 = protNode.GetChild("ping");
                 if (node3 != null)
                 {
                     //this.EventHandler.OnPing(id);
                 }
                 else if ((!ProtocolTreeNode.TagEquals(node3, "query")
                           || (str3 == null))
                          && (ProtocolTreeNode.TagEquals(node3, "relay")
                              && (str3 != null)))
                 {
                     int num;
                     string pin = node3.GetAttribute("pin");
                     string tmpTimeout = node3.GetAttribute("timeout");
                     if (
                         !int.TryParse(tmpTimeout ?? "0", WhatsConstants.WhatsAppNumberStyle, CultureInfo.InvariantCulture,
                                       out num))
                     {
                         //throw new CorruptStreamException(
                         //    "relay-iq exception parsing timeout attribute: " + tmpTimeout);
                     }
                     if (pin != null)
                     {
                         //this.EventHandler.OnRelayRequest(pin, num, id);
                     }
                 }
             }
         }
         else
         {
             //IqResultHandler handler = this.PopIqHandler(id);
             //if (handler != null)
             //{
             //    handler.Parse(node, str3);
             //}
             //else if (id.StartsWith(this.Login.User))
             //{
             //    ProtocolNode node2 = node.GetChild(0);
             //    ProtocolNode.Require(node2, "account");
             //    string str4 = node2.GetAttribute("kind");
             //    if ("paid".Equals(str4))
             //    {
             //        this.account_kind = AccountKind.Paid;
             //    }
             //    else if ("free".Equals(str4))
             //    {
             //        this.account_kind = AccountKind.Free;
             //    }
             //    else
             //    {
             //        this.account_kind = AccountKind.Unknown;
             //    }
             //    string s = node2.GetAttribute("expiration");
             //    if (s == null)
             //    {
             //        throw new IOException("no expiration");
             //    }
             //    try
             //    {
             //        this.expire_date = long.Parse(s, CultureInfo.InvariantCulture);
             //    }
             //    catch (FormatException)
             //    {
             //        throw new IOException("invalid expire date: " + s);
             //    }
             //    this.EventHandler.OnAccountChange(this.account_kind, this.expire_date);
             //}
         }
     }
     else if (ProtocolTreeNode.TagEquals(protNode, "presence"))
     {
         string str9 = protNode.GetAttribute("xmlns");
         string jid = protNode.GetAttribute("from");
         if (((str9 == null) || "urn:xmpp".Equals(str9)) && (jid != null))
         {
             string str11 = protNode.GetAttribute("type");
             if ("unavailable".Equals(str11))
             {
                 //this.EventHandler.OnAvailable(jid, false);
             }
             else if ((str11 == null) || "available".Equals(str11))
             {
                 //this.EventHandler.OnAvailable(jid, true);
             }
         }
         else if ("w".Equals(str9) && (jid != null))
         {
             string str12 = protNode.GetAttribute("add");
             string str13 = protNode.GetAttribute("remove");
             string str14 = protNode.GetAttribute("status");
             if (str12 == null)
             {
                 if (str13 == null)
                 {
                     if ("dirty".Equals(str14))
                     {
                         Dictionary<string, long> categories = ParseCategories(protNode);
                         //this.EventHandler.OnDirty(categories);
                     }
                 }
                 //else if (this.GroupEventHandler != null)
                 //{
                 //    this.GroupEventHandler.OnGroupRemoveUser(jid, str13);
                 //}
             }
             //else if (this.GroupEventHandler != null)
             //{
             //    this.GroupEventHandler.OnGroupAddUser(jid, str12);
             //}
         }
     }
     else if (ProtocolTreeNode.TagEquals(protNode, "message"))
     {
         this.messResponseHandler.ParseMessageRecv(protNode);
     }
     else if ((ProtocolTreeNode.TagEquals(protNode, "ib") /*&& (this.EventHandler != null)*/) &&
              (protNode.GetChild("offline") != null))
     {
         //this.EventHandler.OnOfflineMessagesCompleted();
     }
 }
Example #14
0
        private void PopulateNewMessage(ProtocolTreeNode protocolNode)
        {
            string mfrom = protocolNode.GetAttribute("from");
            string mtype = protocolNode.GetAttribute("type");
            string mid = protocolNode.GetAttribute("id");
            string mt = protocolNode.GetAttribute("t");
            string mdata = "";
            string mname = "";
            string mdata_binary = "";
            string murl = "";
            string mfile = "";
            string msize = "";
            string mmimetype = "";
            string mwidth = "";
            string mheight = "";
            string mduration = "";
            string mlatitude = "";
            string mlongitude = "";

            //Console.WriteLine(protocolNode.NodeString());

            if (ProtocolTreeNode.TagEquals(protocolNode, "iq") && protocolNode.GetAttribute("type").Equals("result", StringComparison.OrdinalIgnoreCase) && ProtocolTreeNode.TagEquals(protocolNode.children.First(), "query"))
            {
                /*
                <iq from="*****@*****.**" id="last_0" type="result">
                  <query xmlns="jabber:iq:last" seconds="3644"></query>
                </iq>
                */

                string from = mfrom.Substring(0, 11);
                if (from == this.phoneNum) return;

                double seconds = 0;
                Double.TryParse(protocolNode.GetChild("query").GetAttribute("seconds").ToString(), out seconds);

                try
                {
                    string LastTime = "";
                    if (seconds > 0)
                    {
                        LastTime = WpfsAppStrings.ult_vez + " ";
                        DateTime UserLastTime = DateTime.Now.AddSeconds(-seconds);
                        if (UserLastTime.Date == DateTime.Now.Date)
                        {
                            LastTime += WpfsAppStrings.hoy;
                        }
                        else
                        {
                            LastTime += UserLastTime.ToShortDateString();
                        }
                        LastTime += " " + WpfsAppStrings.a_las + " " + UserLastTime.ToShortTimeString();
                    }

                    if (!this.userLast.ContainsKey(from))
                    {
                        this.userLast.Add(from, LastTime);
                    }
                    else if(this.userLast[from].Equals(""))
                    {
                        this.userLast[from] = LastTime;
                    }

                }
                catch (Exception) { }

                return;

            }
            else if (ProtocolTreeNode.TagEquals(protocolNode, "iq") && protocolNode.GetAttribute("type").Equals("result", StringComparison.OrdinalIgnoreCase) && ProtocolTreeNode.TagEquals(protocolNode.children.First(), "picture"))
            {

                string from = protocolNode.GetAttribute("from").Substring(0, 11);

                if (from == this.phoneNum)
                {
                    BitmapImage bi = new BitmapImage();
                    bi.BeginInit();
                    bi.StreamSource = new MemoryStream(protocolNode.children.First().data);
                    bi.EndInit();
                    this.imgUser.Source = bi;
                    this.lblUser.Content = this.phoneNick;
                    this.imgUser.Visibility = Visibility.Visible;
                    this.lblUser.Visibility = Visibility.Visible;
                }
                else if (!this.userImgs.ContainsKey(from))
                {
                    this.userImgs.Add(from, protocolNode.children.First().data);
                }

            }
            else if (ProtocolTreeNode.TagEquals(protocolNode, "presence"))
            {
                /*
                 <presence from="*****@*****.**" type="available"></presence>
                 <presence from="*****@*****.**" type="unavailable"></presence>
                 */

                if (mfrom.Substring(0, 11) == this.phoneNum) return;

                if (mfrom != null && mtype != null && !mfrom.Equals("") && !mtype.Equals(""))
                {
                    string from = mfrom.Substring(0, 11);
                    if (from == this.phoneNum) return;

                    if (mtype.Equals("available"))
                    {
                        if (!this.userList.ContainsKey(from)) this.userList[from].Last = WpfsAppStrings.en_linea;
                    }
                    else
                    {
                        if (!this.userList.ContainsKey(from)) this.userList[from].Last = "";
                        if (!this.userLast.ContainsKey(from)) this.userLast[from] = "";
                    }
                }

            }
            else if (ProtocolTreeNode.TagEquals(protocolNode, "message") && ProtocolTreeNode.TagEquals(protocolNode.children.First(), "composing"))
            {
                /*
                <message from="*****@*****.**" type="chat" t="1354049335">
                  <composing xmlns="http://jabber.org/protocol/chatstates"></composing>
                </message>
                */

                if (mfrom.Substring(0, 11) == this.phoneNum) return;

                if (MessageEvent != null)
                {
                    MessageEvent(this, new MessageEventArgs(protocolNode.GetAttribute("from").ToString(), "composing"));
                }

            }
            else if (ProtocolTreeNode.TagEquals(protocolNode, "message") && ProtocolTreeNode.TagEquals(protocolNode.children.First(), "paused"))
            {
                /*
                 <message from="*****@*****.**" type="chat" t="1354049335">
                  <paused xmlns="http://jabber.org/protocol/chatstates"></paused>
                </message>
                 */

                if (mfrom.Substring(0, 11) == this.phoneNum) return;

                if (MessageEvent != null)
                {
                    MessageEvent(this, new MessageEventArgs(protocolNode.GetAttribute("from").ToString(), "paused"));
                }

            }
            else if (ProtocolTreeNode.TagEquals(protocolNode, "message") && mid != null && mid != "")
            {

                if (mfrom.Substring(0, 11) == this.phoneNum) return;

                bool notify = true;
                bool insert = true;

                if (protocolNode.children != null && protocolNode.children.Count() > 0)
                {
                    foreach (var item in protocolNode.children)
                    {

                        if (ProtocolTreeNode.TagEquals(item, "body"))
                        {
                            mdata = WhatsApp.SYSEncoding.GetString(item.data);
                        }
                        else if (ProtocolTreeNode.TagEquals(item, "received"))
                        {
                            /*
                            <message from="*****@*****.**" id="1354199546-11" type="chat" t="1354199627">
                              <received xmlns="urn:xmpp:receipts"></received>
                            </message>
                            */
                            notify = false;
                            insert = false;
                            Database.MessageReceived(this.phoneNum, mid);

                        }
                        else if (ProtocolTreeNode.TagEquals(item, "notify"))
                        {
                            mname = item.GetAttribute("name");
                        }
                        else if (ProtocolTreeNode.TagEquals(item, "media"))
                        {
                            if (item.GetAttribute("type") == "image")
                            {
                                mtype = "image";
                                murl = item.GetAttribute("url");
                                mfile = item.GetAttribute("file");
                                msize = item.GetAttribute("size");
                                mmimetype = item.GetAttribute("mimetype");
                                mwidth = item.GetAttribute("width");
                                mheight = item.GetAttribute("height");
                                if (item.data.Length > 0)
                                {
                                    mdata_binary = Convert.ToBase64String(item.data);
                                }
                            }
                            else if (item.GetAttribute("type") == "audio")
                            {
                                mtype = "audio";
                                murl = item.GetAttribute("url");
                                mfile = item.GetAttribute("file");
                                msize = item.GetAttribute("size");
                                mmimetype = item.GetAttribute("mimetype");
                                mduration = item.GetAttribute("duration");
                                if (item.data.Length > 0)
                                {
                                    mtype = "video";
                                    mdata_binary = Convert.ToBase64String(item.data);
                                }
                            }
                            else if (item.GetAttribute("type") == "video")
                            {
                                mtype = "video";
                                murl = item.GetAttribute("url");
                                mfile = item.GetAttribute("file");
                                msize = item.GetAttribute("size");
                                mmimetype = item.GetAttribute("mimetype");
                                mduration = item.GetAttribute("duration");
                                if (item.data.Length > 0)
                                {
                                    mdata_binary = Convert.ToBase64String(item.data);
                                }
                            }
                            else if (item.GetAttribute("type") == "location")
                            {
                                mtype = "map";
                                mlatitude = item.GetAttribute("latitude");
                                mlongitude = item.GetAttribute("longitude");
                                if (item.data.Length > 0)
                                {
                                    mdata_binary = Convert.ToBase64String(item.data);
                                }
                            }
                            else
                            {
                                mtype = "unknown";
                                Console.WriteLine("{0}: {1}", WpfsAppStrings.tipo_no_soportado, item.GetAttribute("type"));
                            }
                        }
                    }

                    if (insert)
                    {
                        Database.InsertMessage("", mfrom, mtype, mid, mt, mdata, mname, mdata_binary, murl, mfile, msize, mmimetype, mwidth, mheight, mduration, mlatitude, mlongitude, this.phoneNum, "0", "1");
                    }

                    if (MessageEvent != null)
                    {
                        MessageEvent(this, new MessageEventArgs(mfrom, "message"));
                    }

                    this.LoadPrintUsers();

                    if (notify && Properties.Settings.Default.aviso)
                    {
                        System.Media.SystemSounds.Hand.Play();
                    }

                    if (notify && Properties.Settings.Default.mensaje)
                    {
                        string infoUser = mfrom.Substring(2, 9);
                        if (!mname.Equals(""))
                        {
                            infoUser = mname;
                        }
                        this.av.SetMessage(mfrom.Substring(0, 9), string.Format(WpfsAppStrings.nuevo_mensaje, infoUser));
                        this.av.Prepare();
                        this.av.Show();
                    }

                }
            }
        }