示例#1
0
        private async Task <bool> Handshake()
        {
            if (myIPs.Count == 1)
            {
                Debug.WriteLine("Device has only one IP, so IPFinder will not be called.");
                ipFinderResult = new IPDetectionCompletedEventArgs
                {
                    MyIP    = myIPs[0],
                    Success = true,
                };
                return(true);
            }

            ipFinder.IPDetectionCompleted += IpFinder_IPDetectionCompleted;
            ipFinderTcs = new TaskCompletionSource <bool>();
            if (await ipFinder.StartFindingMyLocalIP(myIPs))
            {
                await ipFinderTcs.Task.WithTimeout(handshakeTimeout);

                if (ipFinderResult != null)
                {
                    System.Diagnostics.Debug.WriteLine(ipFinderResult.MyIP);
                    return(true);
                }
            }

            Debug.WriteLine("Sending handshake message failed.");
            ipFinderResult = new IPDetectionCompletedEventArgs
            {
                Success = false,
            };
            return(false);
        }
示例#2
0
        private string WebServerFetched(IWebServer sender, RequestDetails request)
        {
            Debug.WriteLine("ServerIPFinder: Fetched. Stopping listeners...");
            StopListeners(servers);

            IPDetectionCompletedEventArgs ea;

            try
            {
                var query = QueryHelpers.ParseQuery(request.Url.Query);

                var success = (query["success"][0].ToLower() == "true");
                var message = "";

                if (!success)
                {
                    message = query["message"][0];
                }

                ea = new IPDetectionCompletedEventArgs()
                {
                    Success  = success,
                    Message  = message,
                    MyIP     = request.Host,
                    TargetIP = request.RemoteEndpointAddress
                };
            }
            catch (Exception ex)
            {
                ea = new IPDetectionCompletedEventArgs()
                {
                    Success  = false,
                    Message  = ex.Message,
                    MyIP     = request.Host,
                    TargetIP = request.RemoteEndpointAddress
                };
            }

            Task.Run(() =>
            {
                IPDetectionCompleted?.Invoke(this, ea);
            });

            return("success");
        }
示例#3
0
        public async Task <FileTransferResult> SendFile(CancellationToken cancellationToken, IFile file, string directory = "", bool isQueue = false)
        {
            if ((ipFinderResult == null) || (ipFinderResult.Success == false))
            {
                await Handshake();

                if (ipFinderResult == null)
                {
                    ipFinderResult = new IPDetectionCompletedEventArgs
                    {
                        Success = false,
                    }
                }
                ;
            }

            if (ipFinderResult.Success == false)
            {
                return(FileTransferResult.FailedOnHandshake);
            }

            InitServer();

            var key = GenerateUniqueRandomKey();

            var properties = await file.GetFileStats();

            var slicesCount = (uint)Math.Ceiling(((double)properties.Length) / ((double)Constants.FileSliceMaxLength));

            keyTable.Add(key, new FileDetails
            {
                storageFile       = file,
                lastPieceAccessed = 0,
                lastSliceSize     = (uint)((ulong)properties.Length % Constants.FileSliceMaxLength),
                lastSliceId       = slicesCount - 1
            });

            InitUrls(key, slicesCount);

            queueFinishTcs = null;
            fileSendTcs    = new TaskCompletionSource <string>();

            ClearInternalEventSubscribers();
            FileTransferProgressInternal += (s, ee) =>
            {
                FileTransferProgress?.Invoke(s, ee);
            };

            cancellationToken.Register(() =>
            {
                fileSendTcs?.TrySetResult(TRANSFER_CANCELLED_MESSAGE);
                server?.Dispose();
            });

            if (!(await BeginSending(key, slicesCount, file.Name, properties, directory, false)))
            {
                return(FileTransferResult.FailedOnPrepare);
            }

            return(await WaitForFinish(cancellationToken));
        }
示例#4
0
 private void IpFinder_IPDetectionCompleted(object sender, IPDetectionCompletedEventArgs e)
 {
     Debug.WriteLine("IpFinder_IPDetectionCompleted.");
     ipFinderResult = e;
     ipFinderTcs.SetResult(true);
 }
示例#5
0
        /// <param name="files">A list of Tuple(Relative directory path, StorageFile) objects.</param>
        public async Task <FileTransferResult> SendQueue(CancellationToken cancellationToken, List <Tuple <string, IFile> > files, string parentDirectoryName)
        {
            if ((ipFinderResult == null) || (ipFinderResult.Success == false))
            {
                await Handshake();

                if (ipFinderResult == null)
                {
                    ipFinderResult = new IPDetectionCompletedEventArgs
                    {
                        Success = false,
                    }
                }
                ;
            }

            if (ipFinderResult.Success == false)
            {
                return(FileTransferResult.FailedOnHandshake);
            }


            InitServer();

            Dictionary <IFile, string> sFileKeyPairs = new Dictionary <IFile, string>();

            IFileStats[] fs = new IFileStats[files.Count];

            ulong totalSlices = 0;

            for (int i = 0; i < files.Count; i++)
            {
                var item = files[i];

                var key = GenerateUniqueRandomKey();

                fs[i] = await item.Item2.GetFileStats();

                var slicesCount = (uint)Math.Ceiling(((double)fs[i].Length) / ((double)Constants.FileSliceMaxLength));

                totalSlices += slicesCount;

                keyTable.Add(key, new FileDetails
                {
                    storageFile       = item.Item2,
                    lastPieceAccessed = 0,
                    lastSliceSize     = (uint)((ulong)fs[i].Length % Constants.FileSliceMaxLength),
                    lastSliceId       = slicesCount - 1
                });

                sFileKeyPairs.Add(item.Item2, key);

                InitUrls(key, slicesCount);
            }

            var queueFinishKey = RandomFunctions.RandomString(15);

            server.AddResponseUrl("/" + queueFinishKey + "/finishQueue/", (Func <IWebServer, RequestDetails, string>)QueueFinished);
            System.Diagnostics.Debug.WriteLine("/" + queueFinishKey + "/finishQueue/");

            queueFinishTcs = new TaskCompletionSource <string>();
            fileSendTcs    = null;

            ulong finishedSlices = 0;

            ClearInternalEventSubscribers();
            FileTransferProgressInternal += (s, ee) =>
            {
                FileTransferProgress?.Invoke(s, new FileTransferProgressEventArgs
                {
                    State       = ee.State,
                    CurrentPart = finishedSlices + ee.CurrentPart,
                    Total       = totalSlices
                });

                if (ee.State == FileTransferState.Finished)
                {
                    finishedSlices += ee.Total;
                }
            };

            cancellationToken.Register(() =>
            {
                queueFinishTcs?.TrySetResult(TRANSFER_CANCELLED_MESSAGE);
                server?.Dispose();
            });

            if (await SendQueueInit(totalSlices, queueFinishKey, parentDirectoryName) == false)
            {
                return(FileTransferResult.FailedOnQueueInit);
            }

            bool infoSendResult = await SendQueueInfo(files, sFileKeyPairs, fs);

            return(await WaitQueueToFinish(cancellationToken));
        }