GenerateId() публичный статический Метод

public static GenerateId ( ) : string
Результат string
Пример #1
0
        /// <summary>
        /// Send a status update
        /// </summary>
        /// <param name="status">The status</param>
        /// <param name="onSuccess">Action to execute when the request was successful</param>
        /// <param name="onError">Action to execute when the request failed</param>
        public void SendStatusUpdate(string status, Action onComplete, Action <int> onError)
        {
            string   id          = TicketManager.GenerateId();
            FMessage message     = new FMessage(new FMessage.FMessageIdentifierKey("s.us", true, id));
            var      messageNode = GetMessageNode(message, new ProtocolTreeNode("body", null, WhatsApp.SYSEncoding.GetBytes(status)));

            this.whatsNetwork.SendData(this._binWriter.Write(messageNode));
        }
Пример #2
0
        public void SendStatusUpdate(string status)
        {
            string   id          = TicketManager.GenerateId();
            FMessage message     = new FMessage(new FMessage.FMessageIdentifierKey("s.us", true, id));
            var      messageNode = GetMessageNode(message, new ProtocolTreeNode("body", null, WhatsApp.SYSEncoding.GetBytes(status)));

            this.SendNode(messageNode);
        }
Пример #3
0
        /// <summary>
        /// Send a message to a person
        /// </summary>
        /// <param name="to">The phone number to send</param>
        /// <param name="txt">The text that needs to be send</param>
        public void Message(string to, string txt)
        {
            var tmpMessage = new FMessage(this.GetJID(to), true)
            {
                identifier_key = { id = TicketManager.GenerateId() }, data = txt
            };

            this.WhatsParser.WhatsSendHandler.SendMessage(tmpMessage);
        }
Пример #4
0
        /// <summary>
        /// Make a request to retrieve the status for specific jabber id.
        /// </summary>
        /// <param name="jid">The jabber id the the status should be retrieved from.</param>
        public void SendGetStatus(string jid)
        {
            int index = jid.IndexOf('@');

            if (index > 0)
            {
                jid = string.Format("{0}@{1}", jid.Substring(0, index), "s.us");
                string v    = TicketManager.GenerateId();
                var    node = new ProtocolTreeNode("message", new[] { new KeyValue("to", jid), new KeyValue("type", "action"), new KeyValue("id", v) },
                                                   new ProtocolTreeNode("action", new[] { new KeyValue("type", "get") }));
                this.whatsNetwork.SendData(this._binWriter.Write(node));
            }
        }
Пример #5
0
        public void SendStatusUpdate(string status, Action onComplete, Action <int> onError)
        {
            string   id      = TicketManager.GenerateId();
            FMessage message = new FMessage(new FMessage.Key("s.us", true, id));
            //ErrorHandler handler = new ErrorHandler
            //{
            //    OnCompleted = onComplete,
            //    OnError = onError
            //};
            //trackedMessages.Add(message.key, handler);
            var messageNode = GetMessageNode(message, new ProtocolTreeNode("body", null, status));

            this.whatsNetwork.SendNode(messageNode);
        }
Пример #6
0
        /// <summary>
        /// Send an image to a person
        /// </summary>
        /// <param name="msgid">The id of the message</param>
        /// <param name="to">the reciepient</param>
        /// <param name="url">The url to the image</param>
        /// <param name="file">Filename</param>
        /// <param name="size">The size of the image in string format</param>
        /// <param name="icon">Icon</param>
        public void MessageImage(string to, string filepath)
        {
            to = this.GetJID(to);
            FileInfo finfo = new FileInfo(filepath);
            string   type  = string.Empty;

            switch (finfo.Extension)
            {
            case ".png":
                type = "image/png";
                break;

            case ".gif":
                type = "image/gif";
                break;

            default:
                type = "image/jpeg";
                break;
            }

            //create hash
            string filehash = string.Empty;

            using (FileStream fs = File.OpenRead(filepath))
            {
                using (BufferedStream bs = new BufferedStream(fs))
                {
                    using (HashAlgorithm sha = HashAlgorithm.Create("sha256"))
                    {
                        byte[] raw = sha.ComputeHash(bs);
                        filehash = Convert.ToBase64String(raw);
                    }
                }
            }

            //request upload
            UploadResponse response = this.UploadFile(filehash, "image", finfo.Length, filepath, to, type);

            if (response != null && !String.IsNullOrEmpty(response.url))
            {
                //send message
                FMessage msg = new FMessage(to, true)
                {
                    identifier_key = { id = TicketManager.GenerateId() }, media_wa_type = FMessage.Type.Image, media_mime_type = response.mimetype, media_name = response.url.Split('/').Last(), media_size = response.size, media_url = response.url, binary_data = this.CreateThumbnail(filepath)
                };
                this.WhatsSendHandler.SendMessage(msg);
            }
        }
Пример #7
0
        //send broadcast
        public void SendMessageBroadcast(string[] to, FMessage message)
        {
            if (to != null && to.Length > 0 && message != null && !string.IsNullOrEmpty(message.data))
            {
                ProtocolTreeNode child;
                if (message.media_wa_type == FMessage.Type.Undefined)
                {
                    //text broadcast
                    child = new ProtocolTreeNode("body", null, null, WhatsApp.SYSEncoding.GetBytes(message.data));
                }
                else
                {
                    throw new NotImplementedException();
                }

                //compose broadcast envelope
                ProtocolTreeNode xnode = new ProtocolTreeNode("x", new KeyValue[] {
                    new KeyValue("xmlns", "jabber:x:event")
                }, new ProtocolTreeNode("server", null));
                List <ProtocolTreeNode> toNodes = new List <ProtocolTreeNode>();
                foreach (string target in to)
                {
                    toNodes.Add(new ProtocolTreeNode("to", new KeyValue[] { new KeyValue("jid", WhatsAppApi.WhatsApp.GetJID(target)) }));
                }

                ProtocolTreeNode broadcastNode = new ProtocolTreeNode("broadcast", null, toNodes);
                ProtocolTreeNode messageNode   = new ProtocolTreeNode("message", new KeyValue[] {
                    new KeyValue("to", "broadcast"),
                    new KeyValue("type", "chat"),
                    new KeyValue("id", TicketManager.GenerateId())
                }, new ProtocolTreeNode[] {
                    broadcastNode,
                    xnode,
                    child
                });
                this.SendNode(messageNode);
            }
        }
Пример #8
0
        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", to),
                new KeyValue("type", "set"),
                new KeyValue("xmlns", "w:m")
            }, media);

            this.uploadResponse = null;
            this.SendNode(node);
            int i = 0;

            while (this.uploadResponse == null && i <= 100)
            {
                if (m_usePoolMessages)
                {
                    System.Threading.Thread.Sleep(500);
                }
                else
                {
                    this.pollMessage();
                }
                i++;
            }
            if (this.uploadResponse != null && this.uploadResponse.GetChild("duplicate") != null)
            {
                WaUploadResponse res = new WaUploadResponse(this.uploadResponse);
                this.uploadResponse = null;
                return(res);
            }
            else
            {
                try
                {
                    string uploadUrl = this.uploadResponse.GetChild("media").GetAttribute("url");
                    this.uploadResponse = null;

                    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", WhatsConstants.UserAgent);
                    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);
        }
Пример #9
0
 internal FMessage(string remote_jid, bool from_me)
 {
     this.status         = Status.Undefined;
     this.gap_behind     = true;
     this.identifier_key = new FMessageIdentifierKey(remote_jid, from_me, TicketManager.GenerateId());
 }
Пример #10
0
 internal FMessage(WhatsAppApi.Account.WhatsUser remote_user, bool from_me)
 {
     this.status         = Status.Undefined;
     this.gap_behind     = true;
     this.User           = remote_user;
     this.identifier_key = new FMessageIdentifierKey(remote_user.GetFullJid(), from_me, TicketManager.GenerateId());
 }
Пример #11
0
        protected async Task <UploadResponse> 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", Constants.Information.WhatsAppServer),
                new KeyValue("type", "set"),
                new KeyValue("xmlns", "w:m")
            }, media);

            this.uploadResponse = null;
            this.SendNode(node);
            int i = 0;

            IAsyncOperation <bool> taskLoad = this.pollMessage().AsAsyncOperation <bool>();

            taskLoad.AsTask().Wait(5000);

            if (this.uploadResponse == null)
            {
                IAsyncOperation <bool> taskLoad2 = this.pollMessage().AsAsyncOperation <bool>();
                taskLoad.AsTask().Wait(5000);
            }

            if (this.uploadResponse != null && this.uploadResponse.GetChild("duplicate") != null)
            {
                UploadResponse res = new UploadResponse(this.uploadResponse);
                this.uploadResponse = null;
                return(res);
            }
            else
            {
                try
                {
                    if (this.uploadResponse == null)
                    {
                        return(null);
                    }
                    string uploadUrl = this.uploadResponse.GetChild("media").GetAttribute("url");
                    this.uploadResponse = null;

                    Uri uri = new Uri(uploadUrl);

                    string        hashname = string.Empty;
                    byte[]        buff     = System.Text.Encoding.GetEncoding(Constants.Information.ASCIIEncoding).GetBytes(MD5.Encrypt(System.Text.Encoding.GetEncoding(Constants.Information.ASCIIEncoding).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;

                    Dictionary <string, string> headers = new Dictionary <string, string>();
                    headers.Add("User-Agent", Constants.Information.UserAgent);
                    headers.Add("Content-Length", clength.ToString());

                    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));

                    var response = await HttpRequest.UploadPhotoContinueAsync(buf.ToArray(), uploadUrl, boundary, headers);

                    buff = await response.Content.ReadAsByteArrayAsync();

                    string result = Encoding.UTF8.GetString(buff, 0, buff.Length);
                    foreach (string line in result.Split(new string[] { "\n" }, StringSplitOptions.RemoveEmptyEntries))
                    {
                        if (line.StartsWith("{"))
                        {
                            string         fooo = line.TrimEnd(new char[] { (char)0 });
                            UploadResponse resp = JsonConvert.DeserializeObject <UploadResponse>(fooo);
                            if (!String.IsNullOrEmpty(resp.url))
                            {
                                return(resp);
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    WhatsAPI.UniversalApps.Libs.Utils.Logger.Log.Write("Error when upload media : " + ex.Message);
                }
            }
            return(null);
        }