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; } }
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); }
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; } }
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")); } }
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); }
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 : child.GetDataString(); if (subject != null) { WhatsEventHandler.OnGroupNewSubjectEventHandler(tmpFrom, uJid, subject, int.Parse(tmpT, CultureInfo.InvariantCulture)); } if (flag) { this.sendHandler.SendSubjectReceived(tmpFrom, tmpId); } }
/// <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); } }
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); }
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(), 0, child2.GetData().Length)); 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(), 0, node.GetChild("body").GetData().Length), Helpers.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"), Helpers.GetDateTimeFromTimestamp(t)); } else if (child3.tag == "remove") { this.fireOnGetParticipantRemoved(gjid, child3.GetAttribute("jid"), child3.GetAttribute("author"), Helpers.GetDateTimeFromTimestamp(t)); } else if (child3.tag == "modify") { this.fireOnGetParticipantRenamed(gjid, child3.GetAttribute("remove"), child3.GetAttribute("add"), Helpers.GetDateTimeFromTimestamp(t)); } } break; } this.SendNotificationAck(node); }
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>(); 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); this.fireOnGetSyncResult(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); this.fireOnGetLastSeen(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") { this.fireOnGetPhotoPreview(from, id, dat); } else { this.fireOnGetPhoto(from, id, dat); } } if (node.GetAttribute("type").Equals("get", StringComparison.OrdinalIgnoreCase) && ProtocolTreeNode.TagEquals(node.children.FirstOrDefault(), "ping")) { this.SendPong(node.GetAttribute("id")); } if (node.GetAttribute("type").Equals("result", StringComparison.OrdinalIgnoreCase) && ProtocolTreeNode.TagEquals(node.children.FirstOrDefault(), "group")) { //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"), long.Parse(group.GetAttribute("creation")), group.GetAttribute("subject"), long.Parse(group.GetAttribute("s_t")), group.GetAttribute("s_o") )); } this.fireOnGetGroups(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")); } } 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())); } } }
protected WaUploadResponse UploadFile(string b64hash, string type, long size, byte[] fileData, string to, string contenttype, string extension) { ProtocolTreeNode media = new ProtocolTreeNode("media", new KeyValue[] { new KeyValue("hash", b64hash), new KeyValue("type", type), new KeyValue("size", size.ToString()) }); string id = TicketManager.GenerateId(); ProtocolTreeNode node = new ProtocolTreeNode("iq", new KeyValue[] { new KeyValue("id", id), new KeyValue("to", WhatsConstants.WhatsAppServer), new KeyValue("type", "set"), new KeyValue("xmlns", "w:m") }, media); ProtocolTreeNode uploadResponse = null; this.SendNode(node); int i = 0; do { if (!IsUserPolling) { this.pollMessage(); } lock (this.uploadResponses) { if (uploadResponses.TryGetValue(id, out uploadResponse)) { uploadResponses.Remove(id); break; } } Thread.Sleep(200); ++i; }while(i <= 10); if (uploadResponse != null && uploadResponse.GetChild("duplicate") != null) { WaUploadResponse res = new WaUploadResponse(uploadResponse); return(res); } else { try { string uploadUrl = uploadResponse.GetChild("media").GetAttribute("url"); Uri uri = new Uri(uploadUrl); string hashname = string.Empty; byte[] buff = MD5.Create().ComputeHash(System.Text.Encoding.Default.GetBytes(b64hash)); StringBuilder sb = new StringBuilder(); foreach (byte b in buff) { sb.Append(b.ToString("X2")); } hashname = String.Format("{0}.{1}", sb.ToString(), extension); string boundary = "zzXXzzYYzzXXzzQQ"; sb = new StringBuilder(); sb.AppendFormat("--{0}\r\n", boundary); sb.Append("Content-Disposition: form-data; name=\"to\"\r\n\r\n"); sb.AppendFormat("{0}\r\n", to); sb.AppendFormat("--{0}\r\n", boundary); sb.Append("Content-Disposition: form-data; name=\"from\"\r\n\r\n"); sb.AppendFormat("{0}\r\n", this.phoneNumber); sb.AppendFormat("--{0}\r\n", boundary); sb.AppendFormat("Content-Disposition: form-data; name=\"file\"; filename=\"{0}\"\r\n", hashname); sb.AppendFormat("Content-Type: {0}\r\n\r\n", contenttype); string header = sb.ToString(); sb = new StringBuilder(); sb.AppendFormat("\r\n--{0}--\r\n", boundary); string footer = sb.ToString(); long clength = size + header.Length + footer.Length; sb = new StringBuilder(); sb.AppendFormat("POST {0}\r\n", uploadUrl); sb.AppendFormat("Content-Type: multipart/form-data; boundary={0}\r\n", boundary); sb.AppendFormat("Host: {0}\r\n", uri.Host); sb.AppendFormat("User-Agent: {0}\r\n", this.Registration.GetUserAgent()); sb.AppendFormat("Content-Length: {0}\r\n\r\n", clength); string post = sb.ToString(); TcpClient tc = new TcpClient(uri.Host, 443); SslStream ssl = new SslStream(tc.GetStream()); try { ssl.AuthenticateAsClient(uri.Host); } catch (Exception e) { throw e; } List <byte> buf = new List <byte>(); buf.AddRange(Encoding.UTF8.GetBytes(post)); buf.AddRange(Encoding.UTF8.GetBytes(header)); buf.AddRange(fileData); buf.AddRange(Encoding.UTF8.GetBytes(footer)); ssl.Write(buf.ToArray(), 0, buf.ToArray().Length); //moment of truth... buff = new byte[1024]; ssl.Read(buff, 0, 1024); string result = Encoding.UTF8.GetString(buff); foreach (string line in result.Split(new string[] { "\n" }, StringSplitOptions.RemoveEmptyEntries)) { if (line.StartsWith("{")) { string fooo = line.TrimEnd(new char[] { (char)0 }); JavaScriptSerializer jss = new JavaScriptSerializer(); WaUploadResponse resp = jss.Deserialize <WaUploadResponse>(fooo); if (!String.IsNullOrEmpty(resp.url)) { return(resp); } } } } catch (Exception) { } } return(null); }
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 : child.GetDataString(); string subject = (child == null) ? null : WhatsAppProtocol.SYSEncoding.GetString(child.GetData()); if (subject != null) { WhatsEventHandler.OnGroupNewSubjectEventHandler(tmpFrom, uJid, subject, int.Parse(tmpT, CultureInfo.InvariantCulture)); } if (flag) { this.sendHandler.SendSubjectReceived(tmpFrom, tmpId); } }
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")) { } 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) { } } } } else { // todo: implent } } 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)) { } else if ((str11 == null) || "available".Equals(str11)) { } } 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); } else if ((ProtocolTreeNode.TagEquals(protNode, "ib") /*&& (this.EventHandler != null)*/) && (protNode.GetChild("offline") != null)) { } }
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(); } }
protected bool processInboundData(byte[] msgdata, bool autoReceipt = true) { try { ProtocolTreeNode node = this.reader.nextTree(msgdata); if (node != null) { 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")); this.fireOnLoginSuccess(this.phoneNumber, node.GetData()); } else if (ProtocolTreeNode.TagEquals(node, "failure")) { this.loginStatus = CONNECTION_STATUS.UNAUTHORIZED; this.fireOnLoginFailed(node.children.FirstOrDefault().tag); } if (ProtocolTreeNode.TagEquals(node, "receipt")) { string from = node.GetAttribute("from"); string id = node.GetAttribute("id"); string type = node.GetAttribute("type") ?? "delivery"; switch (type) { case "delivery": //delivered to target this.fireOnGetMessageReceivedClient(from, id); break; case "read": //read by target //todo break; case "played": //played by target //todo break; } //send ack SendNotificationAck(node, type); } if (ProtocolTreeNode.TagEquals(node, "message")) { this.handleMessage(node, autoReceipt); } if (ProtocolTreeNode.TagEquals(node, "iq")) { this.handleIq(node); } 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); } this.Disconnect(); } if (ProtocolTreeNode.TagEquals(node, "presence")) { //presence node this.fireOnGetPresence(node.GetAttribute("from"), node.GetAttribute("type")); } if (node.tag == "ib") { foreach (ProtocolTreeNode child in node.children) { switch (child.tag) { case "dirty": this.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": this.fireOnGetTyping(node.GetAttribute("from")); break; case "paused": this.fireOnGetPaused(node.GetAttribute("from")); break; default: throw new NotImplementedException(node.NodeString()); } } if (node.tag == "ack") { string cls = node.GetAttribute("class"); if (cls == "message") { //server receipt this.fireOnGetMessageReceivedServer(node.GetAttribute("from"), node.GetAttribute("id")); } } if (node.tag == "notification") { this.handleNotification(node); } return(true); } } catch (Exception e) { throw e; } return(false); }
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(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(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(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(from, id, lon, lat, url, name, preview); break; case "vcard": ProtocolTreeNode vcard = media.GetChild("vcard"); name = vcard.GetAttribute("name"); dat = vcard.GetData(); this.fireOnGetMessageVcard(from, id, name, dat); break; } this.sendMessageReceived(node); } }
protected void handleIq(ProtocolTreeNode node) { #region error iq if (node.GetAttribute("type") == "error") { this.fireOnError(node.GetAttribute("id"), node.GetAttribute("from"), node.GetChild("error").GetAttribute("code"), node.GetChild("error").GetAttribute("text")); } #endregion #region sync 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>(); 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()); } #endregion #region type iq 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); } } #endregion #region ping iq if (node.GetAttribute("type").Equals("get", StringComparison.OrdinalIgnoreCase) && node.GetChild("ping") != null) { this.SendPong(node.GetAttribute("id")); } #endregion #region group result iq 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()); } #endregion #region participant result iq 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()); } #endregion #region status result iq 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())); } } #endregion #region privacy result iq 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); } #endregion #region cipherKeys iq BRIAN ProtocolTreeNode[] pnodes = ProcessIqTreeNode(node); if (pnodes != null) { foreach (ProtocolTreeNode pnode in pnodes) { this.handleMessage(pnode, true); } } #endregion }
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")) { } 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) { } } } } else { // todo: implent } } 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)) { } else if ((str11 == null) || "available".Equals(str11)) { } } 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); } else if ((ProtocolTreeNode.TagEquals(protNode, "ib") /*&& (this.EventHandler != null)*/) && (protNode.GetChild("offline") != null)) { } }
protected void ProcessMessages(ProtocolTreeNode[] nodes) { foreach (ProtocolTreeNode node in nodes) { if (node.tag.Equals("message")) { ProtocolTreeNode body = node.GetChild("body"); ProtocolTreeNode media = node.GetChild("media"); ProtocolTreeNode paused = node.GetChild("paused"); ProtocolTreeNode composing = node.GetChild("composing"); ProtocolTreeNode notification = node.GetChild("notification"); string jid = node.GetAttribute("from"); if (body != null || media != null) { //extract and save nickname if (node.GetChild("notify") != null && node.GetChild("notify").GetAttribute("name") != null) { string nick = node.GetChild("notify").GetAttribute("name"); Contact c = ContactStore.GetContactByJid(jid); if (c != null) { c.nickname = nick; ContactStore.UpdateNickname(c); } } try { this.getChat(jid, true, false).AddMessage(node); } catch (Exception) { } //refresh list this._loadConversations(); } if (paused != null) { try { if (this.getChat(jid, false, false) != null) { this.getChat(jid, false, false).SetOnline(); } } catch (Exception e) { //throw e; } } if (composing != null) { try { if (this.getChat(jid, false, false) != null) { this.getChat(jid, false, false).SetTyping(); } } catch (Exception e) { //throw e; } } if (notification != null) { if (notification.GetAttribute("type") == "picture") { ChatWindow.GetImageAsync(notification.GetChild("set").GetAttribute("jid"), false); } } } else if (node.tag.Equals("presence")) { string jid = node.GetAttribute("from"); if (node.GetAttribute("type") != null && node.GetAttribute("type").Equals("available")) { try { if (this.getChat(jid, false, false) != null) { this.getChat(jid, false, false).SetOnline(); } } catch (Exception e) { //throw e; } } if (node.GetAttribute("type") != null && node.GetAttribute("type").Equals("unavailable")) { try { if (this.getChat(jid, false, false) != null) { this.getChat(jid, false, false).SetUnavailable(); } } catch (Exception e) { //throw e; } } } else if (node.tag.Equals("iq")) { string jid = node.GetAttribute("from"); if (node.children.First().tag.Equals("query")) { DateTime lastseen = DateTime.Now; int seconds = Int32.Parse(node.GetChild("query").GetAttribute("seconds")); lastseen = lastseen.Subtract(new TimeSpan(0, 0, seconds)); try { if (this.getChat(jid, false, false) != null) { getChat(jid, false, false).SetLastSeen(lastseen); } } catch (Exception e) { //throw e; } } else if (node.children.First().tag.Equals("group")) { string subject = node.children.First().GetAttribute("subject"); Contact cont = ContactStore.GetContactByJid(jid); if (cont != null) { cont.nickname = subject; ContactStore.UpdateNickname(cont); } else { } } else if (node.children.First().tag.Equals("picture")) { string pjid = node.GetAttribute("from"); string id = node.GetAttribute("id"); byte[] rawpicture = node.GetChild("picture").GetData(); Contact c = ContactStore.GetContactByJid(pjid); if (c != null) { Image img = null; using (var ms = new MemoryStream(rawpicture)) { try { img = Image.FromStream(ms); string targetdir = Directory.GetCurrentDirectory() + "\\data\\profilecache"; if (!Directory.Exists(targetdir)) { Directory.CreateDirectory(targetdir); } img.Save(targetdir + "\\" + c.jid + ".jpg"); try { if (this.getChat(pjid, false, false) != null) { this.getChat(pjid, false, false).SetPicture(img); } } catch (Exception e) { throw e; } } catch (Exception e) { throw e; } } } if (picturesToSync.Remove(pjid)) { this.requestProfilePicture(); } } else if (node.children.First().tag.Equals("error") && node.children.First().GetAttribute("code") == "404") { string pjid = node.GetAttribute("from"); picturesToSync.Remove(pjid); this.requestProfilePicture(); } } } }