Ejemplo n.º 1
0
        private void OnFileTransferStateChanged(FileTransferState state, FileTransferStateChangeReason reason)
        {
            Console.WriteLine(MSG_PREFIX + "OnFileTransferStateChanged: state {0}, reason {1}",
                              state.ToString(), reason.ToString());

            switch (state)
            {
            case FileTransferState.Open:
                s = new System.Net.Sockets.Socket(AddressFamily.Unix, SocketType.Stream, ProtocolType.IP);
                EndPoint ep = new UnixEndPoint(socket_addr);
                s.Connect(ep);
                if (transfer_initiator == self_handle)
                {
                    Console.WriteLine(MSG_PREFIX + "Sending file");
                    ThreadPool.QueueUserWorkItem(delegate { SendFile(); });
                }
                else
                {
                    Console.WriteLine(MSG_PREFIX + "Receiving file");
                    ThreadPool.QueueUserWorkItem(delegate { ReceiveFile(); });
                }
                break;

            case FileTransferState.Completed:
                Console.WriteLine(MSG_PREFIX + "Transfer completed.");
                ift.Close();
                break;
            }
        }
        private void OnFileTransferStateChanged(FileTransferState state, FileTransferStateChangeReason reason)
        {
            //Console.WriteLine ("OnFileTransferStateChanged: state {0}", state);

            switch (state)
            {
            case FileTransferState.Open:
                if (pf_result != null)
                {
                    address   = pf_caller.EndInvoke(pf_result);
                    pf_result = null;
                }

                OnChannelReady(EventArgs.Empty);
                break;

            case FileTransferState.Completed:
                Close();
                break;

            case FileTransferState.Cancelled:
                Close();
                break;
            }
        }
Ejemplo n.º 3
0
        private void StopTransfer(string trID, FileTransferState newState, bool isOutgoing)
        {
            TransferItem fileTransfer;

            SendData(TransferCommands.StopTransfer + TRANSFERS_COMMAND_SEPARATOR +
                     (int)newState + TRANSFERS_COMMAND_SEPARATOR +
                     "1" + TRANSFERS_COMMAND_SEPARATOR + trID + TRANSFERS_COMMAND_SEPARATOR);

            fileTransfer = isOutgoing ? outgoing.GetTransferItem(trID) : incoming.GetTransferItem(trID);

            if (fileTransfer != null)
            {
                List <ITransferItem> tempList = new List <ITransferItem>();
                tempList.Add(fileTransfer);
                if (fileStreams.ContainsKey(fileTransfer.TrId) && fileStreams[fileTransfer.TrId] != null)
                {
                    incoming.TransferedBytes += fileTransfer.FileSize - fileStreams[fileTransfer.TrId].Position;
                }
                OnTransferError(new TransferErrorEventArgs(tempList, fileTransfer.OtherSideURI, newState, !isOutgoing));

                if (isOutgoing)
                {
                    outgoing.CurrentIndex++;
                }
                else
                {
                    incoming.CurrentIndex++;
                }

                FinalizeTransfer(fileTransfer, newState);
            }
        }
Ejemplo n.º 4
0
        private void FinalizeTransfer(string trId, FileTransferState newState)
        {
            TransferItem finalizingTransfer =
                incoming.GetTransferItem(trId) == null?outgoing.GetTransferItem(trId) : incoming.GetTransferItem(trId);

            FinalizeTransfer(finalizingTransfer, newState);
        }
        /// <summary>
        /// Starts file read (download from device) operation
        /// </summary>
        /// <param name="in_file_name"></param>
        public void FileDownloadStart(string in_file_name, FileTransferCallback in_callback)
        {
            // sanity check
            if (m_file_transfer_state != FileTransferState.Idle)
            {
                throw new Exception("File transfer already pending.");
            }

            // initialize file transfer info
            m_file_transfer_callback = in_callback;

            m_file_transfer_state            = FileTransferState.ReadInfo;
            m_file_transfer_current_name     = in_file_name;
            m_file_transfer_current_position = 0;
            m_file_transfer_current_size     = 0;

            UpdateFileTransferState();

            // file info packet
            PacketFileInfoRequest request_packet = new PacketFileInfoRequest();

            request_packet.FileName = in_file_name;

            FileOperationStart(request_packet, null);
        }
        /// <summary>
        /// Starts file write (upload to the device) operation
        /// </summary>
        /// <param name="in_file_id"></param>
        /// <param name="in_file_pos"></param>
        /// <param name="in_data"></param>
        /// <param name="in_callback"></param>
        /// <returns></returns>
        public void FileUploadStart(byte in_file_id, UInt32 in_file_pos, byte[] in_data, FileTransferCallback in_callback)
        {
            // sanity check
            if (m_file_transfer_state != FileTransferState.Idle)
            {
                throw new Exception("File transfer already pending.");
            }

            // init file transfer
            m_file_transfer_callback         = in_callback;
            m_file_transfer_state            = FileTransferState.WriteData;
            m_file_transfer_current_position = in_file_pos;
            m_file_transfer_current_id       = in_file_id;

            // create write packet
            PacketFileDataWriteRequestHeader request_packet;

            // create file write packet
            request_packet     = new PacketFileDataWriteRequestHeader((byte)in_data.Length);
            request_packet.ID  = m_file_transfer_current_id;
            request_packet.Pos = m_file_transfer_current_position;

            // starts file operation
            FileOperationStart(request_packet, in_data, null);
        }
Ejemplo n.º 7
0
        private void TryPauseTransfer()
        {
            if (State != FileTransferState.Uploading && State != FileTransferState.Downloading)
            {
                return;
            }

            State = FileTransferState.PausedByFriend;
        }
        /// <summary>
        /// Processes received file data write response
        /// </summary>
        private void ProcessFileDataWriteResponse()
        {
            string file_operation_id;
            PendingFileOperationInfo    file_operation_info;
            PacketFileDataWriteResponse packet = (PacketFileDataWriteResponse)CommunicationManager.Default.ReceiverQueue.Pop(typeof(PacketFileDataWriteResponse));

            CommunicationManager.Default.PacketLogWrite("R", packet);

            // check file operation ID
            file_operation_id = packet.FileOperationID;
            if (!m_pending_file_operations.ContainsKey(file_operation_id))
            {
                return;
            }

            // check pending file operation
            file_operation_info = m_pending_file_operations[file_operation_id];
            if (file_operation_info.Packet.PacketType != PacketType.FileDataWriteRequest)
            {
                return;
            }

            // remove file operation from the peding list
            FileOperationEnd(packet);

            // if no callback if defined, this is regular system file operation
            if (file_operation_info.Callback == null)
            {
                // file transfer state: idle
                m_file_transfer_state = FileTransferState.Idle;

                if (packet.ID == InvalidSystemFileID)
                {
                    // if file not found -> error
                    CallFileTransferFinishedCallback(new FileTransferResultInfo(FileTransferResult.NotFound));
                }
                else
                {
                    if (packet.Error == 0)
                    {
                        // call transfer callback
                        CallFileTransferFinishedCallback(new FileTransferResultInfo(FileTransferResult.Success, m_file_transfer_current_id, ""));
                    }
                    else
                    {
                        // call transfer callback
                        CallFileTransferFinishedCallback(new FileTransferResultInfo(FileTransferResult.Error));
                    }
                }
            }
            else
            {
                file_operation_info.Callback(packet);
            }
        }
Ejemplo n.º 9
0
        private void OnEndFileTransfer()
        {
            _fileTransferState = FileTransferState.None;

            // Returns reconstructed received file data to event listeners
            if (ReceiveFileFinished != null)
            {
                byte[] data = _fileMemoryStream.ToArray();
                ReceiveFileFinished(data);
            }
        }
Ejemplo n.º 10
0
        public void ClearAllTransfers(FileTransferState clearingState)
        {
            while (incoming.Files.Count > 0)
            {
                FinalizeTransfer(Incoming.Files[0].TrId, clearingState);
            }

            while (outgoing.Files.Count > 0)
            {
                FinalizeTransfer(outgoing.Files[0].TrId, clearingState);
            }
        }
Ejemplo n.º 11
0
        private void OnStartFileTransfer(int fileSize)
        {
            _fileTransferState = FileTransferState.Receiving;

            // Notify event listener about start of file receival
            if (ReceiveFileStarted != null)
            {
                ReceiveFileStarted(fileSize);
            }

            // Allocate a temporary memory stream for incoming file
            _fileMemoryStream = new MemoryStream(fileSize);
        }
Ejemplo n.º 12
0
        public void PauseTransfer()
        {
            if (State != FileTransferState.Downloading && State != FileTransferState.Uploading)
            {
                return;
            }

            var successfulSend = _toxModel.FileControl(_friendNumber, _fileNumber, ToxFileControl.Pause);

            if (successfulSend)
            {
                State = FileTransferState.PausedByUser;
            }
        }
Ejemplo n.º 13
0
        /// <summary>
        /// Initiates transfer of <paramref name="data"/> to all other players.
        /// </summary>
        /// <param name="data">
        /// The data to transfer.
        /// </param>
        /// <param name="chunkSize">
        /// The size of chunks to split the file into.
        /// </param>
        public void TransmitFile(byte[] data, int chunkSize) {
            if (_fileTransferState != FileTransferState.None) {
                throw new IOException("File transfer already in progress");
            }

            _fileTransferState = FileTransferState.Transmitting;

            int dataSize = data.Length;
            int transmittedSize = 0;

            // Calculate number of chunks
            int chunksCount = data.Length / chunkSize + 1;

            // Notify listeners that transfer has started
            if (TransmitFileStarted != null)
                TransmitFileStarted(dataSize);

            // Send an RPC to notify other players about start of transfer
            _networkView.RPC("OnStartFileTransfer", RPCMode.Others, dataSize);
            for (int i = 0; i < chunksCount; i++) {
                // Calculate size of current chunk. It is usually smaller than chunkSize 
                // for the last chunk
                int currentChunkSize = chunkSize;
                if (transmittedSize + chunkSize > dataSize) {
                    currentChunkSize = dataSize - transmittedSize;
                    if (currentChunkSize == 0)
                        break;
                }

                // Allocate an array for a chunk, fill it and send over network
                byte[] chunk = new byte[currentChunkSize];
                Array.Copy(data, transmittedSize, chunk, 0, currentChunkSize);
                _networkView.RPC("ProcessFileChunk", RPCMode.Others, chunk);

                transmittedSize += currentChunkSize;

                // Notify listeners about new chunk transfer
                if (TransmitFileChunk != null)
                    TransmitFileChunk(dataSize);
            }

            // Send an RPC to notify other players about end of transfer
            _networkView.RPC("OnEndFileTransfer", RPCMode.Others);

            _fileTransferState = FileTransferState.None;

            // Notify event listeners about end of transfer
            if (TransmitFileFinished != null)
                TransmitFileFinished();
        }
Ejemplo n.º 14
0
        private void FileChunkReceivedHandler(object sender, ToxEventArgs.FileChunkEventArgs e)
        {
            if (IsPlaceholder || !IsThisTransfer(e))
            {
                return;
            }

            PutNextChunk(e);

            if (IsFinished)
            {
                _fileTransferResumer.RemoveTransfer(_friendNumber, _fileNumber);
                State = FileTransferState.Finished;
            }
        }
Ejemplo n.º 15
0
        private void ProcessFileChunk(byte[] data)
        {
            // Check if we can receive a chunk
            if (_fileTransferState != FileTransferState.Receiving)
            {
                _fileTransferState = FileTransferState.None;
                Debug.LogError("Received a file chunk when not in receival mode");
                return;
            }

            // Notify event listeners about new incoming chunk
            if (ReceiveFileChunk != null)
            {
                ReceiveFileChunk(data.Length);
            }

            // Save chunk data
            _fileMemoryStream.Write(data, 0, data.Length);
        }
Ejemplo n.º 16
0
        private void FileChunkRequestedHandler(object sender, ToxEventArgs.FileRequestChunkEventArgs e)
        {
            if (IsPlaceholder || !IsThisTransfer(e))
            {
                return;
            }

            var chunk = GetNextChunk(e);
            var successfulChunkSend = _toxModel.FileSendChunk(e.FriendNumber, e.FileNumber, e.Position, chunk);

            if (successfulChunkSend)
            {
                if (IsFinished)
                {
                    _fileTransferResumer.RemoveTransfer(_friendNumber, _fileNumber);
                    State = FileTransferState.Finished;
                }
            }
        }
Ejemplo n.º 17
0
        public async Task AcceptTransfer(StorageFile file)
        {
            var fileStream = (await file.OpenAsync(FileAccessMode.ReadWrite)).AsStream();

            // Replace the dummy stream set previously in FileSendRequestReceivedHandler():
            ReplaceStream(fileStream);

            var successfulSend = _toxModel.FileControl(_friendNumber, _fileNumber, ToxFileControl.Resume);

            if (successfulSend)
            {
                _fileTransferResumer.RecordTransfer(file, _friendNumber, _fileNumber, TransferDirection.Down);
                State = FileTransferState.Downloading;
            }
            else
            {
                ReplaceStream(null);
                fileStream.Dispose();
            }
        }
Ejemplo n.º 18
0
 internal bool FireTransferEvent(FileTransferState state, String filename, long bytes)
 {
     try
     {
         if (TransferEvents != null)
         {
             return(TransferEvents(state, filename, bytes));
         }
         else
         {
             return(true);
         }
     }
     catch (Exception ex)
     {
         System.Diagnostics.Trace.WriteLine("WARNING! Exception caught in Maverick.NET event handler: " + ex.Message);
         System.Diagnostics.Trace.WriteLine(ex.StackTrace);
         return(true);
     }
 }
Ejemplo n.º 19
0
        private void FileControlReceivedHandler(object sender, ToxEventArgs.FileControlEventArgs e)
        {
            if (IsPlaceholder || !IsThisTransfer(e))
            {
                return;
            }

            switch (e.Control)
            {
            case ToxFileControl.Cancel:
                _fileTransferResumer.RemoveTransfer(_friendNumber, _fileNumber);
                State = FileTransferState.Cancelled;
                return;

            case ToxFileControl.Pause:
                TryPauseTransfer();
                return;

            case ToxFileControl.Resume:
                TryResumeTransfer();
                return;
            }
        }
Ejemplo n.º 20
0
        private void FinalizeTransfer(TransferItem finalizingTransfer, FileTransferState newState)
        {
            if (finalizingTransfer == null)
            {
                return;
            }

            if (finalizingTransfer.State != newState)
            {
                finalizingTransfer.State = newState;
            }

            if (fileStreams.ContainsKey(finalizingTransfer.TrId) && fileStreams[finalizingTransfer.TrId] != null)
            {
                fileStreams[finalizingTransfer.TrId].Close();
            }

            fileStreams.Remove(finalizingTransfer.TrId);

            incoming.RemoveTransferItem(finalizingTransfer);
            outgoing.RemoveTransferItem(finalizingTransfer);

            if (incoming.Files.Count == 0)
            {
                incoming.Initialize();
            }

            if (outgoing.Files.Count == 0)
            {
                outgoing.Initialize();
            }

            List <ITransferItem> tempList = new List <ITransferItem>();

            tempList.Add(finalizingTransfer);
            OnTransferEnded(new TransfersManagerEventArgs(tempList, finalizingTransfer.OtherSideURI));
        }
 public FileTransferManager()
 {
     m_pending_file_operations    = new Dictionary <string, PendingFileOperationInfo>();
     m_file_transfer_state        = FileTransferState.Idle;
     m_file_transfer_current_file = null;
 }
Ejemplo n.º 22
0
        public void PauseTransfer()
        {
            if (State != FileTransferState.Downloading && State != FileTransferState.Uploading)
                return;

            var successfulSend = ToxModel.Instance.FileControl(_friendNumber, _fileNumber, ToxFileControl.Pause);

            if (successfulSend)
            {
                State = FileTransferState.PausedByUser;
            }
        }
Ejemplo n.º 23
0
        public async Task AcceptTransfer(StorageFile file)
        {
            var fileStream = (await file.OpenAsync(FileAccessMode.ReadWrite)).AsStream();

            // Replace the dummy stream set previously in FileSendRequestReceivedHandler():
            ReplaceStream(fileStream);

            var successfulSend = ToxModel.Instance.FileControl(_friendNumber, _fileNumber, ToxFileControl.Resume);

            if (successfulSend)
            {
                FileTransferResumer.Instance.RecordTransfer(file, _friendNumber, _fileNumber, TransferDirection.Down);
                State = FileTransferState.Downloading;
            }
            else
            {
                ReplaceStream(null);
                fileStream.Dispose();
            }
        }
Ejemplo n.º 24
0
        private void FileChunkReceivedHandler(object sender, ToxEventArgs.FileChunkEventArgs e)
        {
            if (IsPlaceholder || !IsThisTransfer(e))
                return;

            PutNextChunk(e);

            if (IsFinished)
            {
                FileTransferResumer.Instance.RemoveTransfer(_friendNumber, _fileNumber);
                State = FileTransferState.Finished;
            }
        }
Ejemplo n.º 25
0
        private void FileChunkRequestedHandler(object sender, ToxEventArgs.FileRequestChunkEventArgs e)
        {
            if (IsPlaceholder || !IsThisTransfer(e))
                return;

            var chunk = GetNextChunk(e);
            var successfulChunkSend = ToxModel.Instance.FileSendChunk(e.FriendNumber, e.FileNumber, e.Position, chunk);

            if (successfulChunkSend)
            {
                if (IsFinished)
                {
                    FileTransferResumer.Instance.RemoveTransfer(_friendNumber, _fileNumber);
                    State = FileTransferState.Finished;
                }
            }
        }
Ejemplo n.º 26
0
        /// <summary>
        /// Initiates transfer of <paramref name="data"/> to all other players.
        /// </summary>
        /// <param name="data">
        /// The data to transfer.
        /// </param>
        /// <param name="chunkSize">
        /// The size of chunks to split the file into.
        /// </param>
        public void TransmitFile(byte[] data, int chunkSize)
        {
            if (_fileTransferState != FileTransferState.None)
            {
                throw new IOException("File transfer already in progress");
            }

            _fileTransferState = FileTransferState.Transmitting;

            int dataSize        = data.Length;
            int transmittedSize = 0;

            // Calculate number of chunks
            int chunksCount = data.Length / chunkSize + 1;

            // Notify listeners that transfer has started
            if (TransmitFileStarted != null)
            {
                TransmitFileStarted(dataSize);
            }

            // Send an RPC to notify other players about start of transfer
            _networkView.RPC("OnStartFileTransfer", RPCMode.Others, dataSize);
            for (int i = 0; i < chunksCount; i++)
            {
                // Calculate size of current chunk. It is usually smaller than chunkSize
                // for the last chunk
                int currentChunkSize = chunkSize;
                if (transmittedSize + chunkSize > dataSize)
                {
                    currentChunkSize = dataSize - transmittedSize;
                    if (currentChunkSize == 0)
                    {
                        break;
                    }
                }

                // Allocate an array for a chunk, fill it and send over network
                byte[] chunk = new byte[currentChunkSize];
                Array.Copy(data, transmittedSize, chunk, 0, currentChunkSize);
                _networkView.RPC("ProcessFileChunk", RPCMode.Others, chunk);

                transmittedSize += currentChunkSize;

                // Notify listeners about new chunk transfer
                if (TransmitFileChunk != null)
                {
                    TransmitFileChunk(dataSize);
                }
            }

            // Send an RPC to notify other players about end of transfer
            _networkView.RPC("OnEndFileTransfer", RPCMode.Others);

            _fileTransferState = FileTransferState.None;

            // Notify event listeners about end of transfer
            if (TransmitFileFinished != null)
            {
                TransmitFileFinished();
            }
        }
        /// <summary>
        /// Processes file information response packet
        /// </summary>
        private void ProcessFileInfoResponse()
        {
            string file_operation_id;
            PendingFileOperationInfo file_operation_info;
            PacketFileInfoResponse   packet = (PacketFileInfoResponse)CommunicationManager.Default.ReceiverQueue.Pop(typeof(PacketFileInfoResponse));

            CommunicationManager.Default.PacketLogWrite("R", packet);

            // check file operation ID
            file_operation_id = packet.FileOperationID;
            if (!m_pending_file_operations.ContainsKey(file_operation_id))
            {
                return;
            }

            // check pending file operation
            file_operation_info = m_pending_file_operations[file_operation_id];
            if (file_operation_info.Packet.PacketType != PacketType.FileInfoRequest)
            {
                return;
            }

            // remove file operation from the peding list
            FileOperationEnd(packet);

            // if no callback if defined, this is regular system file operation
            if (file_operation_info.Callback == null)
            {
                if (packet.ID == InvalidSystemFileID)
                {
                    // if file not found -> error
                    m_file_transfer_state = FileTransferState.Idle;

                    CallFileTransferFinishedCallback(new FileTransferResultInfo(FileTransferResult.NotFound));
                }
                else
                {
                    m_file_transfer_current_position = 0;
                    m_file_transfer_current_size     = packet.Length;
                    m_file_transfer_current_id       = packet.ID;

                    string cached_file_name = m_file_transfer_current_name + "[" + CommunicationManager.Default.ConnectedDeviceUniqueID.ToString("x4") + "]";

                    // file exists -> check file in the cache
                    if (DeviceFileCache.IsFileExists(cached_file_name, packet.Length, packet.Hash))
                    {
                        // file exists in the cache -> call callback with success code
                        string file_path;
                        file_path = Path.Combine(DeviceFileCache.GetFileCachePath(), cached_file_name);

                        m_file_transfer_current_position = m_file_transfer_current_size;
                        m_file_transfer_state            = FileTransferState.Idle;

                        UpdateFileTransferState();

                        CallFileTransferFinishedCallback(new FileTransferResultInfo(FileTransferResult.Success, m_file_transfer_current_id, file_path));
                    }
                    else
                    {
                        // file doesn't exists in the cache create file in the cache and download it
                        m_file_transfer_current_file = DeviceFileCache.CreateFile(cached_file_name, 0);

                        // start download
                        m_file_transfer_state = FileTransferState.ReadData;

                        UpdateFileTransferState();

                        SendFileDataReadRequest();
                    }
                }
            }
            else
            {
                file_operation_info.Callback(packet);
            }
        }
Ejemplo n.º 28
0
        private static void InvokeProgressEvent(uint currentFileSlicesCount, uint currentFileSlice, FileTransferState state)
        {
            if (state == FileTransferState.Finished)
            {
                throw new InvalidOperationException();
            }

            FileTransferProgressEventArgs ea = null;

            if (!isQueue)
            {
                ea = new FileTransferProgressEventArgs {
                    CurrentPart = currentFileSlice + 1, Total = currentFileSlicesCount, State = FileTransferState.DataTransfer, Guid = requestGuid, SenderName = senderName, TotalFiles = filesCount
                };
                System.Diagnostics.Debug.WriteLine(ea.CurrentPart + " / " + ea.Total);
            }
            else if (state == FileTransferState.QueueList)
            {
                ea = new FileTransferProgressEventArgs {
                    CurrentPart = 0, Total = 0, State = FileTransferState.QueueList, Guid = requestGuid, SenderName = senderName, TotalFiles = filesCount
                };
                System.Diagnostics.Debug.WriteLine("Downloading queue data...");
            }
            else
            {
                ea = new FileTransferProgressEventArgs {
                    CurrentPart = (ulong)(queueSlicesFinished + currentFileSlice + 1), Total = (ulong)queueTotalSlices, State = FileTransferState.QueueList, Guid = requestGuid, SenderName = senderName, TotalFiles = filesCount
                };
                System.Diagnostics.Debug.WriteLine(ea.CurrentPart + " / " + ea.Total);
            }

            FileTransferProgress?.Invoke(ea);
        }
Ejemplo n.º 29
0
 public TransferErrorEventArgs(IEnumerable <ITransferItem> items, string fromUri, FileTransferState itemsState, bool isLocal)
     : base(items, fromUri)
 {
     this.ItemsState = itemsState;
     this.IsLocal    = isLocal;
 }
Ejemplo n.º 30
0
 public StateChangeEventArg(FileTransferState arg)
 {
     FileTransferState = arg;
 }
Ejemplo n.º 31
0
        private void OnEndFileTransfer() {
            _fileTransferState = FileTransferState.None;

            // Returns reconstructed received file data to event listeners
            if (ReceiveFileFinished != null) {
                byte[] data = _fileMemoryStream.ToArray();
                ReceiveFileFinished(data);
            }
        }
Ejemplo n.º 32
0
        private void ProcessFileChunk(byte[] data) {
            // Check if we can receive a chunk
            if (_fileTransferState != FileTransferState.Receiving) {
                _fileTransferState = FileTransferState.None;
                Debug.LogError("Received a file chunk when not in receival mode");
                return;
            }

            // Notify event listeners about new incoming chunk
            if (ReceiveFileChunk != null)
                ReceiveFileChunk(data.Length);

            // Save chunk data
            _fileMemoryStream.Write(data, 0, data.Length);
        }
Ejemplo n.º 33
0
        private void FileControlReceivedHandler(object sender, ToxEventArgs.FileControlEventArgs e)
        {
            if (IsPlaceholder || !IsThisTransfer(e))
                return;

            switch (e.Control)
            {
                case ToxFileControl.Cancel:
                    FileTransferResumer.Instance.RemoveTransfer(_friendNumber, _fileNumber);
                    State = FileTransferState.Cancelled;
                    return;
                case ToxFileControl.Pause:
                    TryPauseTransfer();
                    return;
                case ToxFileControl.Resume:
                    TryResumeTransfer();
                    return;
            }
        }
        /// <summary>
        /// Processes received file data block
        /// </summary>
        private void ProcessFileDataReadResponse()
        {
            byte[]   packet;
            byte     packet_length;
            byte     interface_index;
            DateTime packet_timestamp;
            PacketFileDataReadResponseHeader packet_header;
            int    data_offset;
            int    data_length;
            string file_operation_id;
            PendingFileOperationInfo file_operation_info;

            if (CommunicationManager.Default.ReceiverQueue.PopBegin(out packet, out packet_length, out interface_index, out packet_timestamp))
            {
                // get packet header
                packet_header = (PacketFileDataReadResponseHeader)RawBinarySerialization.DeserializeObject(packet, typeof(PacketFileDataReadResponseHeader));
                CommunicationManager.Default.PacketLogWrite("R", packet_header);

                // check pending file operation
                file_operation_id = packet_header.FileOperationID;
                if (m_pending_file_operations.ContainsKey(file_operation_id))
                {
                    file_operation_info = m_pending_file_operations[file_operation_id];

                    // finish file operation
                    FileOperationEnd(packet_header);

                    if (file_operation_info.Packet.PacketType == PacketType.FileDataReadRequest)
                    {
                        // determine file data block position and length within the packet
                        data_offset = Marshal.SizeOf(typeof(PacketFileDataReadResponseHeader));
                        data_length = packet_header.PacketLength - PacketConstants.PacketCRCLength - Marshal.SizeOf(typeof(PacketFileDataReadResponseHeader));

                        // if no callback if defined, this is regular system file operation
                        if (file_operation_info.Callback == null)
                        {
                            m_file_transfer_current_file.Write(packet, data_offset, data_length);

                            m_file_transfer_current_position += (uint)data_length;

                            UpdateFileTransferState();

                            if (m_file_transfer_current_position < m_file_transfer_current_size)
                            {
                                SendFileDataReadRequest();
                            }
                            else
                            {
                                m_file_transfer_current_file.Close();

                                m_file_transfer_state = FileTransferState.Idle;

                                CallFileTransferFinishedCallback(new FileTransferResultInfo(FileTransferResult.Success, m_file_transfer_current_id, m_file_transfer_current_file.FullFilePath));
                                m_file_transfer_current_file.Dispose();
                                m_file_transfer_current_file = null;
                            }
                        }
                        else
                        {
                            // prepare deserialized packet for further file data processing
                            PacketFileDataReadResponse response = new PacketFileDataReadResponse(packet_header);

                            response.SetData(packet, data_offset, data_length);

                            file_operation_info.Callback(response);
                        }
                    }
                }

                // close packet processing
                CommunicationManager.Default.ReceiverQueue.PopEnd();
            }
        }
Ejemplo n.º 35
0
        private void TryPauseTransfer()
        {
            if (State != FileTransferState.Uploading && State != FileTransferState.Downloading)
                return;

            State = FileTransferState.PausedByFriend;
        }
        /// <summary>
        /// Handles timeout condition
        /// </summary>
        public void FileOperationTimeOutHandler()
        {
            DateTime      current_time            = DateTime.Now;
            List <string> file_operations_timeout = new List <string>();

            lock (m_pending_file_operations)
            {
                // check all pending file operation
                foreach (KeyValuePair <string, PendingFileOperationInfo> pending_operation in m_pending_file_operations)
                {
                    if ((current_time - pending_operation.Value.SendTime).TotalMilliseconds > FileOperationTimeout)
                    {
                        if (pending_operation.Value.RetryCount > FileOperationMaxRetryCount)
                        {
                            // operation failed
                            file_operations_timeout.Add(pending_operation.Key);
                        }
                        else
                        {
                            // resend oroginal packet again
                            pending_operation.Value.RetryCount++;
                            pending_operation.Value.SendTime = current_time;

                            if (pending_operation.Value.Data == null)
                            {
                                CommunicationManager.Default.SendPacket(pending_operation.Value.Packet);
                                CommunicationManager.Default.PacketLogWrite("S+", pending_operation.Value.Packet);
                            }
                            else
                            {
                                CommunicationManager.Default.SendPacket(pending_operation.Value.Packet, pending_operation.Value.Data);
                                CommunicationManager.Default.PacketLogWrite("S+", pending_operation.Value.Packet);
                            }
                        }
                    }
                }
            }

            // handle failed operations
            foreach (string operation_id in file_operations_timeout)
            {
                PendingFileOperationInfo file_operation_info = m_pending_file_operations[operation_id];

                // remove operation from pending list
                lock (m_pending_file_operations)
                {
                    m_pending_file_operations.Remove(operation_id);
                }

                // if no callback if defined, this is regular system file operation
                if (file_operation_info.Callback == null)
                {
                    // file transfer state: idle
                    m_file_transfer_state = FileTransferState.Idle;

                    // call file transfer callback with error
                    CallFileTransferFinishedCallback(new FileTransferResultInfo(FileTransferResult.Error));
                }
                else
                {
                    file_operation_info.Callback(null);
                }
            }
        }
Ejemplo n.º 37
0
        private void OnStartFileTransfer(int fileSize) {
            _fileTransferState = FileTransferState.Receiving;

            // Notify event listener about start of file receival
            if (ReceiveFileStarted != null)
                ReceiveFileStarted(fileSize);

            // Allocate a temporary memory stream for incoming file
            _fileMemoryStream = new MemoryStream(fileSize);
        }