예제 #1
0
        private async Task <bool> HandShake()
        {
            string reqid = Guid.NewGuid().ToString();

            Utils.LogUtils("Event: Start Handshake, ReqId: " + reqid + ", ClientId: " + clientId);
            bool status;
            var  res = await mSkynet.sendRequest(serverToxId, new ToxRequest {
                url        = "/handshake",
                method     = "get",
                uuid       = reqid,
                fromNodeId = clientId,
                fromToxId  = mSkynet.tox.Id.ToString(),
                toToxId    = serverToxId.ToString(),
                toNodeId   = "",
                time       = Utils.UnixTimeNow(),
            }, out status);

            if (res == null)
            {
                Utils.LogUtils("Event: Handshake Failed, ReqId: " + reqid + ", ClientId: " + clientId);
                return(false);
            }
            else
            {
                Utils.LogUtils("Event: Handshake Success, ReqId: " + reqid + ", ClientId: " + clientId);
                return(true);
            }
        }
예제 #2
0
        public void CopyToxIdToClipboard()
        {
            var dataPackage = new DataPackage {
                RequestedOperation = DataPackageOperation.Copy
            };

            dataPackage.SetText(TextId.ToString());
            Clipboard.SetContent(dataPackage);
            Clipboard.Flush();
        }
예제 #3
0
        public async Task <bool> HandShake(ToxId target, int timeout = 20)
        {
            string reqid = Guid.NewGuid().ToString();

            Utils.Utils.Log("Event: Start Handshake , ReqId: " + reqid, true);
            Console.WriteLine("Event: Start Handshake , ReqId: " + reqid);
            bool status;
            var  res = await sendRequest(target, new ToxRequest
            {
                url        = "/handshake",
                method     = "get",
                uuid       = reqid,
                fromNodeId = reqid,
                fromToxId  = tox.Id.ToString(),
                toToxId    = target.ToString(),
                toNodeId   = "",
                time       = Utils.Utils.UnixTimeNow(),
            }, out status, timeout);

            if (res == null)
            {
                Utils.Utils.Log("Event: Handshake Failed, ReqId: " + reqid, true);
                Console.WriteLine("Event: Handshake failed, ReqId: " + reqid);
                return(false);
            }
            else
            {
                Utils.Utils.Log("Event: Handshake Success, ReqId: " + reqid, true);
                Console.WriteLine("Event: Handshake Success, ReqId: " + reqid);
                return(true);
            }
        }
예제 #4
0
        public bool sendMsg(ToxId toxid, string msg)
        {
            // check if this message is send to itself
            if (toxid.ToString() == tox.Id.ToString())
            {
                return(false); // this is not allowed
            }
            // wait toxcore online
            int maxOnlineWaitTime = 20000; // 20s
            int onlineWaitCount   = 0;

            while (!tox.IsConnected)
            {
                Thread.Sleep(10);
                onlineWaitCount += 10;
                if (onlineWaitCount > maxOnlineWaitTime)
                {
                    return(false);
                }
            }

            ToxKey toxkey    = toxid.PublicKey;
            int    friendNum = tox.GetFriendByPublicKey(toxkey);

            if (friendNum == -1)
            {
                int res = tox.AddFriend(toxid, "add friend");
                if (res != (int)ToxErrorFriendAdd.Ok)
                {
                    return(false);
                }
                friendNum = tox.GetFriendByPublicKey(toxkey);
            }
            int waitCount = 0;
            int maxCount  = 500;

            if (connectedList.IndexOf(toxkey.GetString()) == -1)
            {
                maxCount = 200 * 1000; // first time wait for 200s
            }
            while (tox.GetFriendConnectionStatus(friendNum) == ToxConnectionStatus.None && waitCount < maxCount)
            {
                if (waitCount % 1000 == 0)
                {
                    Console.WriteLine("target is offline." + waitCount / 1000);
                }
                waitCount += 10;
                Thread.Sleep(10);
            }
            if (waitCount == maxCount)
            {
                Console.WriteLine("Connect Failed");
                connectedList.Remove(toxkey.GetString());
                return(false);
            }
            connectedList.Add(toxkey.GetString());
            int msgRes = tox.SendMessage(friendNum, msg, ToxMessageType.Message);

            return(msgRes > 0);
        }
예제 #5
0
        public Task <ToxResponse> sendRequest(ToxId toxid, ToxRequest req, out bool status)
        {
            if (toxid.ToString() == tox.Id.ToString())
            {
                // request was sent to itself
                status = true;
                return(RequestProxy.sendRequest(this, req));
            }

            string reqContent = JsonConvert.SerializeObject(req);
            int    packageNum = reqContent.Length / MAX_MSG_LENGTH + 1;
            bool   res        = false;

            for (int i = 0; i < packageNum; i++)
            {
                string mcontent = "";
                if (i * MAX_MSG_LENGTH + MAX_MSG_LENGTH > reqContent.Length)
                {
                    mcontent = reqContent.Substring(i * MAX_MSG_LENGTH);
                }
                else
                {
                    mcontent = reqContent.Substring(i * MAX_MSG_LENGTH, MAX_MSG_LENGTH);
                }
                res = sendMsg(toxid, JsonConvert.SerializeObject(new Package
                {
                    uuid         = req.uuid,
                    totalCount   = packageNum,
                    currentCount = i,
                    content      = mcontent,
                }));
                if (!res)
                {
                    status = false;
                    return(Task.Factory.StartNew <ToxResponse>(() => {
                        return null;
                    }));
                }
            }
            status = res;
            bool        isResponseReceived = false;
            ToxResponse mRes = null;

            if (res)
            {
                mPendingReqList.Add(req.uuid, (response) => {
                    isResponseReceived = true;
                    mRes = response;
                });
            }
            return(Task.Factory.StartNew(() =>
            {
                while (!isResponseReceived)
                {
                    Thread.Sleep(10);
                }
                return mRes;
            }));
        }
예제 #6
0
        public void sendRequestNoReplay(ToxId toxid, ToxRequest req, out bool status)
        {
            status = true;

            try
            {
                if (toxid.ToString() == tox.Id.ToString())
                {
                    // request was sent to itself
                    status = true;
                }
            }
            catch (ObjectDisposedException)
            {
                status = false;
                return;
            }


            byte[] reqContent = req.getBytes();
            int    packageNum = reqContent.Length / MAX_MSG_LENGTH + 1;
            bool   res        = false;

            for (int i = 0; i < packageNum; i++)
            {
                byte[] mcontent = null;
                if (i * MAX_MSG_LENGTH + MAX_MSG_LENGTH > reqContent.Length)
                {
                    mcontent = Utils.Utils.subArray(reqContent, i * MAX_MSG_LENGTH);
                }
                else
                {
                    mcontent = Utils.Utils.subArray(reqContent, i * MAX_MSG_LENGTH, MAX_MSG_LENGTH);
                }
                res = sendMsg(toxid, new Package
                {
                    uuid         = req.uuid,
                    totalCount   = packageNum,
                    currentCount = i,
                    content      = mcontent,
                    totalSize    = (uint)reqContent.Length,
                    startIndex   = (uint)(i * MAX_MSG_LENGTH),
                }.toBytes());
                if (!res)
                {
                    status = false;
                }
            }
        }
예제 #7
0
        public Task <ToxResponse> sendRequest(ToxId toxid, ToxRequest req, out bool status, int timeout = 200)
        {
            try
            {
                if (toxid.ToString() == tox.Id.ToString())
                {
                    // request was sent to itself
                    status = true;
                    return(RequestProxy.sendRequest(this, req));
                }
            }
            catch (ObjectDisposedException)
            {
                status = false;
                return(Task.Factory.StartNew <ToxResponse>(() =>
                {
                    return null;
                }, TaskCreationOptions.LongRunning));
            }

            byte[] reqContent = req.getBytes();
            int    packageNum = reqContent.Length / MAX_MSG_LENGTH + 1;
            bool   res        = false;

            ToxResponse mRes    = null;
            object      reslock = new object();
            bool        resFlag = false;

            lock (mPendingReqLock)
            {
                mPendingReqList.Add(req.uuid, (response) =>
                {
                    mRes = response;
                    lock (reslock)
                    {
                        resFlag = true;
                        Utils.Utils.Log("Event: Callback called, ReqId: " + req.uuid);
                        Monitor.PulseAll(reslock);
                        Utils.Utils.Log("Event: Pulse Lock, ReqId: " + req.uuid);
                    }
                });
            }

            for (int i = 0; i < packageNum; i++)
            {
                byte[] mcontent;
                if (i * MAX_MSG_LENGTH + MAX_MSG_LENGTH > reqContent.Length)
                {
                    mcontent = Utils.Utils.subArray(reqContent, i * MAX_MSG_LENGTH);
                }
                else
                {
                    mcontent = Utils.Utils.subArray(reqContent, i * MAX_MSG_LENGTH, MAX_MSG_LENGTH);
                }
                res = sendMsgDebug(toxid, new Package
                {
                    uuid         = req.uuid,
                    totalCount   = packageNum,
                    currentCount = i,
                    content      = mcontent,
                    totalSize    = (uint)reqContent.Length,
                    startIndex   = (uint)(i * MAX_MSG_LENGTH),
                }, timeout);

                if (!res)
                {
                    status = false;
                    return(Task.Factory.StartNew <ToxResponse>(() =>
                    {
                        lock (mPendingReqLock)
                        {
                            mPendingReqList.Remove(req.uuid);
                        }
                        return null;
                    }, TaskCreationOptions.LongRunning));
                }
            }
            status = res;

            Utils.Utils.Log("Event: return async, ReqId: " + req.uuid);

            return(Task.Factory.StartNew(() =>
            {
                Task.Run(() =>
                {
                    // timeout count thread
                    int timeoutCount = 0;
                    while (timeoutCount < timeout * 1000)
                    {
                        Thread.Sleep(1);
                        timeoutCount += 1;
                        lock (mPendingReqLock)
                        {
                            if (!mPendingReqList.Keys.Contains(req.uuid))
                            {
                                // already received response
                                return;
                            }
                        }
                    }
                    Console.WriteLine(Utils.Utils.UnixTimeNow() + " Timeout Happends ReqId: " + req.uuid);
                    lock (mPendingReqLock)
                    {
                        if (mPendingReqList.Keys.Contains(req.uuid))
                        {
                            mRes = null;
                            mPendingReqList.Remove(req.uuid);
                            lock (reslock)
                            {
                                resFlag = true;
                                Utils.Utils.Log("Event: Callback Timeout, ReqId: " + req.uuid);
                                Monitor.PulseAll(reslock);
                                Utils.Utils.Log("Event: Pulse Lock, ReqId: " + req.uuid);
                            }
                        }
                    }
                });
                Utils.Utils.Log("Event: Response locked, ReqId: " + req.uuid);
                lock (reslock)
                {
                    while (!resFlag)
                    {
                        Monitor.Wait(reslock);
                    }
                }
                Utils.Utils.Log("Event: Response unlocked, ReqId: " + req.uuid);
                return mRes;
            }, TaskCreationOptions.LongRunning));
        }
예제 #8
0
        public bool sendMsg(ToxId toxid, byte[] msg, int timeout = 20)
        {
            try
            {
                lock (sendLock)
                {
                    // check if this message is send to itself
                    if (toxid.ToString() == tox.Id.ToString())
                    {
                        return(false); // this is not allowed
                    }

                    // wait toxcore online
                    int maxOnlineWaitTime = 200000; // 200s
                    int onlineWaitCount   = 0;
                    while (!tox.IsConnected)
                    {
                        Thread.Sleep(10);
                        onlineWaitCount += 10;
                        if (onlineWaitCount > maxOnlineWaitTime)
                        {
                            return(false);
                        }
                    }

                    ToxKey toxkey    = toxid.PublicKey;
                    int    friendNum = tox.GetFriendByPublicKey(toxkey);
                    if (friendNum == -1)
                    {
                        int res = tox.AddFriend(toxid, "add friend");
                        if (res != (int)ToxErrorFriendAdd.Ok)
                        {
                            return(false);
                        }
                        friendNum = tox.GetFriendByPublicKey(toxkey);
                    }

                    if (tox.GetFriendConnectionStatus(friendNum) == ToxConnectionStatus.None)
                    {
                        return(false);
                    }

                    var mesError = new ToxErrorFriendCustomPacket();
                    // retry send message
                    int retryCount = 0;
                    while (retryCount < 60)
                    {
                        byte[] msgToSend = new byte[msg.Length + 1];
                        msgToSend[0] = 170; // The first byte must be in the range 160-191.
                        msg.CopyTo(msgToSend, 1);
                        bool msgRes = tox.FriendSendLosslessPacket(friendNum, msgToSend, out mesError);
                        if (msgRes)
                        {
                            break;
                        }

                        Utils.Utils.Log("Event: " + mesError, true);
                        Console.WriteLine(Utils.Utils.UnixTimeNow() + " Event: " + mesError);
                        if (mesError == ToxErrorFriendCustomPacket.SendQ)
                        {
                            Thread.Sleep(20);
                            continue;
                        }
                        retryCount++;
                        Thread.Sleep(100);
                    }
                    if (retryCount == 60)
                    {
                        tox.DeleteFriend(friendNum);
                        return(false);
                    }

                    return(true);
                }
            }
            catch (Exception e)
            {
                Utils.Utils.Log(e.StackTrace, true);
                return(false);
            }
        }
예제 #9
0
        public Task <ToxResponse> sendRequest(ToxId toxid, ToxRequest req, out bool status)
        {
            if (toxid.ToString() == tox.Id.ToString())
            {
                // request was sent to itself
                status = true;
                return(RequestProxy.sendRequest(this, req));
            }

            byte[] reqContent = req.getBytes();
            int    packageNum = reqContent.Length / MAX_MSG_LENGTH + 1;
            bool   res        = false;

            ToxResponse mRes    = null;
            object      reslock = new object();
            bool        resFlag = false;

            lock (mPendingReqLock) {
                mPendingReqList.Add(req.uuid, (response) => {
                    mRes = response;
                    lock (reslock) {
                        resFlag = true;
                        Utils.Utils.LogUtils("Event: Callback called, ReqId: " + req.uuid);
                        Monitor.PulseAll(reslock);
                        Utils.Utils.LogUtils("Event: Pulse Lock, ReqId: " + req.uuid);
                    }
                });
            }

            for (int i = 0; i < packageNum; i++)
            {
                byte[] mcontent;
                if (i * MAX_MSG_LENGTH + MAX_MSG_LENGTH > reqContent.Length)
                {
                    mcontent = Utils.Utils.subArray(reqContent, i * MAX_MSG_LENGTH);
                }
                else
                {
                    mcontent = Utils.Utils.subArray(reqContent, i * MAX_MSG_LENGTH, MAX_MSG_LENGTH);
                }
                res = sendMsg(toxid, new Package {
                    uuid         = req.uuid,
                    totalCount   = packageNum,
                    currentCount = i,
                    content      = mcontent,
                    totalSize    = (uint)reqContent.Length,
                    startIndex   = (uint)(i * MAX_MSG_LENGTH),
                }.toBytes());
                if (!res)
                {
                    status = false;
                    return(Task.Factory.StartNew <ToxResponse> (() => {
                        mPendingReqList.Remove(req.uuid);
                        return null;
                    }, TaskCreationOptions.LongRunning));
                }
            }
            status = res;

            Utils.Utils.LogUtils("Event: return async, ReqId: " + req.uuid);

            return(Task.Factory.StartNew(() => {
                Utils.Utils.LogUtils("Event: Response locked, ReqId: " + req.uuid);
                lock (reslock) {
                    while (!resFlag)
                    {
                        Monitor.Wait(reslock);
                    }
                }
                Utils.Utils.LogUtils("Event: Response unlocked, ReqId: " + req.uuid);
                return mRes;
            }, TaskCreationOptions.LongRunning));
        }
예제 #10
0
        public bool sendMsg(ToxId toxid, byte[] msg)
        {
            lock (sendLock) {
                // check if this message is send to itself
                if (toxid.ToString() == tox.Id.ToString())
                {
                    return(false);                    // this is not allowed
                }

                // wait toxcore online
                int maxOnlineWaitTime = 20000;                 // 20s
                int onlineWaitCount   = 0;
                while (!tox.IsConnected)
                {
                    Thread.Sleep(10);
                    onlineWaitCount += 10;
                    if (onlineWaitCount > maxOnlineWaitTime)
                    {
                        return(false);
                    }
                }

                ToxKey toxkey    = toxid.PublicKey;
                int    friendNum = tox.GetFriendByPublicKey(toxkey);
                if (friendNum == -1)
                {
                    int res = tox.AddFriend(toxid, "add friend");
                    if (res != (int)ToxErrorFriendAdd.Ok)
                    {
                        return(false);
                    }
                    friendNum = tox.GetFriendByPublicKey(toxkey);
                }

                int waitCount = 0;
                int maxCount  = 500;
                if (connectedList.IndexOf(toxkey.GetString()) == -1)
                {
                    maxCount = 200 * 1000;                     // first time wait for 200s
                }
                while (tox.GetFriendConnectionStatus(friendNum) == ToxConnectionStatus.None && waitCount < maxCount)
                {
                    if (waitCount % 1000 == 0)
                    {
                        Utils.Utils.LogUtils("Event: target is offline " + waitCount / 1000);
                    }
                    waitCount += 10;
                    Thread.Sleep(10);
                }
                if (waitCount == maxCount)
                {
                    Utils.Utils.LogUtils("Event: Connect Failed");
                    connectedList.Remove(toxkey.GetString());
                    return(false);
                }
                if (connectedList.IndexOf(toxkey.GetString()) == -1)
                {
                    connectedList.Add(toxkey.GetString());
                }

                var mesError = new ToxErrorFriendCustomPacket();
                // retry send message
                int retryCount = 0;
                while (retryCount < 10)
                {
                    byte[] msgToSend = new byte[msg.Length + 1];
                    msgToSend [0] = 170;                     // The first byte must be in the range 160-191.
                    msg.CopyTo(msgToSend, 1);
                    bool msgRes = tox.FriendSendLosslessPacket(friendNum, msgToSend, out mesError);
                    if (msgRes)
                    {
                        break;
                    }

                    Utils.Utils.LogUtils("Event: " + mesError);
                    if (mesError == ToxErrorFriendCustomPacket.SendQ)
                    {
                        Thread.Sleep(10);
                        continue;
                    }
                    retryCount++;
                    Thread.Sleep(100);
                }
                if (retryCount == 10)
                {
                    return(false);
                }
                return(true);
            }
        }