/// <summary> /// Will send a file to client. /// </summary> /// <param name="context">HTTP context containing outbound stream.</param> /// <param name="response">Response containing headers.</param> /// <param name="stream">File stream</param> private void SendFile(IHttpContext context, Stream stream, string url) { var worker = new HTTPFileUploader(bufferService, uploadLimiter); TransferSession session = null; try { if (stream.Length > Model.FREE_FILE_LIMIT) { session = new TransferSession(worker); model.TransferSessions.Add(session); } //Try to find the username of the request string userName = context.RemoteEndPoint.Address.ToString(); Node search = model.Network.Nodes.ToList().Where(n => n.NodeType != ClientType.Overlord && n.Host == userName). FirstOrDefault(); if (null != search && !string.IsNullOrEmpty(search.Nickname)) { userName = search.Nickname; } worker.DoUpload(context, stream, userName, url); //Add log of the upload double seconds = (DateTime.Now - worker.TransferStart).TotalSeconds; var txlog = new TransferLog(); txlog.Nickname = userName; txlog.Completed = DateTime.Now; txlog.Filename = Path.GetFileName(url); txlog.Path = Path.GetDirectoryName(url); if (!string.IsNullOrEmpty(txlog.Path)) { txlog.Path = txlog.Path.Replace('\\', '/'); if (txlog.Path.StartsWith("/")) { txlog.Path = txlog.Path.Substring(1); } } txlog.Size = worker.Length - worker.ResumePoint; if (txlog.Size < 0) { txlog.Size = 0; } if (0 != seconds) { txlog.Speed = (int)(txlog.Size / seconds); } model.CompletedUploads.Add(txlog); } finally { if (null != session) { model.TransferSessions.Remove(session); } } }
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { TransferSession s = value as TransferSession; if (null != s) { if (s.IsDownload) { return("/Fap.Presentation;component/Images/Download.png"); } else { return("/Fap.Presentation;component/Images/Upload.png"); } } return(string.Empty); }
protected virtual OperationResponse HandleOperationTransferSession(OperationRequest operationRequest) { var operation = new TransferSession(this.Protocol, operationRequest); if (!operation.IsValid) { return(operation.GetResponse((short)ResultCode.InvalidOperationParameter, operation.GetErrorMessage())); } MasterClientPeer clientPeer; if (Application.MasterLobby.Clients.TryGetClient(operation.SessionId, out clientPeer)) { // this will make sure the client will finish its current request clientPeer.RequestFiber.Enqueue(() => clientPeer.TransferWorld(operation.WorldId)); } return(null); }
public void Dispose() { if (m_EndEvent != null) { m_EndEvent.Reset(); m_EndEvent = null; } if (this.m_fileStream != null) { this.m_fileStream.Close(); this.m_fileStream = null; } if (UpLoadInfo != null) { UpLoadInfo = null; } if (TransferStep != null) { TransferStep = null; } if (TransferComplete != null) { TransferComplete = null; } if (StartTransfer != null) { StartTransfer = null; } if (StopTransfer != null) { StopTransfer = null; } if (this.Session != null) { this.Session.Close(); this.Session = null; } }
private void ScanForDownloads() { lock (sync) { foreach (DownloadRequest item in model.DownloadQueue.List.ToList()) { switch (item.State) { case DownloadRequestState.Downloaded: //Remove completed items if they have some how leaked in, this should never occur. model.DownloadQueue.List.Remove(item); break; case DownloadRequestState.Error: //Set items to retry if (item.NextTryTime < Environment.TickCount) { item.State = DownloadRequestState.None; } break; } } var downloads = from download in model.DownloadQueue.List.ToList().Where(d => d.State == DownloadRequestState.None) group download by download.ClientID into g select new { Downloads = g, ID = g.First().ClientID, }; foreach (var group in downloads) { //Check if the client is online Node client = model.Network.Nodes.ToList().Where(p => p.ID == group.ID).FirstOrDefault(); if (null == client) { client = model.Network.Nodes.ToList().Where(c => c.Nickname == group.Downloads.First().Nickname). FirstOrDefault(); } if (null != client) { foreach (DownloadRequest item in group.Downloads) { if (item.State == DownloadRequestState.None) { bool addedDownload = false; if (workers.Where(w => w.Node == client).Count() < model.MaxDownloadsPerUser && workers.Count < model.MaxDownloads) { addedDownload = true; //Max workers not reached, add download via new worker. var worker = new DownloadWorkerService(client, model, bufferService); worker.OnWorkerFinished += worker_OnWorkerFinished; workers.Add(worker); worker.AddDownload(item); model.TransferSessions.Add(new TransferSession(worker) { Status = "Connecting..", User = client.Nickname, Size = item.Size, IsDownload = true }); } else { //Max downloaders reached, try to add to an existing queue foreach (DownloadWorkerService worker in workers.Where(w => w.Node == client)) { if (!worker.IsQueueFull) { worker.AddDownload(item); addedDownload = true; break; } } } if (!addedDownload) { //Could not place the download so skip the rest of the queue for this host break; } } } } } //Remove redundant workers foreach (DownloadWorkerService worker in workers.Where(w => w.IsComplete).ToList()) { worker.OnWorkerFinished -= worker_OnWorkerFinished; workers.Remove(worker); TransferSession session = model.TransferSessions.ToList().Where(t => t.Worker == worker).FirstOrDefault(); if (null != session) { model.TransferSessions.Remove(session); } } } }
public UpLoadServerEngine(TransferSession session) { this.Session = session; }
private bool HandleGet(RequestEventArgs e, NetworkRequest req) { //No url? if (string.IsNullOrEmpty(req.Param)) { return(false); } string[] possiblePaths; if (shareInfoService.ToLocalPath(req.Param, out possiblePaths)) { foreach (string possiblePath in possiblePaths) { if (File.Exists(possiblePath)) { var ffu = new FAPFileUploader(bufferService, serverUploadLimiterService); var session = new TransferSession(ffu); model.TransferSessions.Add(session); try { //Try to find the username of the request string userName = e.Context.RemoteEndPoint.Address.ToString(); Node search = model.Network.Nodes.ToList().Where(n => n.ID == req.SourceID).FirstOrDefault(); if (null != search && !string.IsNullOrEmpty(search.Nickname)) { userName = search.Nickname; } using ( FileStream fs = File.Open(possiblePath, FileMode.Open, FileAccess.Read, FileShare.Read)) { ffu.DoUpload(e.Context, fs, userName, possiblePath); } //Add log of upload double seconds = (DateTime.Now - ffu.TransferStart).TotalSeconds; var txlog = new TransferLog(); txlog.Nickname = userName; txlog.Completed = DateTime.Now; txlog.Filename = Path.GetFileName(possiblePath); txlog.Path = Path.GetDirectoryName(req.Param); if (!string.IsNullOrEmpty(txlog.Path)) { txlog.Path = txlog.Path.Replace('\\', '/'); if (txlog.Path.StartsWith("/")) { txlog.Path = txlog.Path.Substring(1); } } txlog.Size = ffu.Length - ffu.ResumePoint; if (txlog.Size < 0) { txlog.Size = 0; } if (0 != seconds) { txlog.Speed = (int)(txlog.Size / seconds); } model.CompletedUploads.Add(txlog); } finally { model.TransferSessions.Remove(session); } return(true); } } } e.Response.Status = HttpStatusCode.NotFound; var generator = new ResponseWriter(); generator.SendHeaders(e.Context, e.Response); return(true); }
void transferServer_NewSessionConnected(TransferSession session) { session.UpLoadEngine.StartTransfer += (e) => { lock (lockobj) { DataRow row = null; var rows = dtFile.Select(string.Format("ProjectId='{0}'", e.ProjectId)); if (rows.Length > 0) { row = rows[0]; } else { row = dtFile.NewRow(); dtFile.Rows.Add(row); } row["IsUpLoading"] = true; row["FileName"] = e.FileName; row["SaveName"] = e.SaveName; row["FileSize"] = e.FileSize; row["TransferPos"] = e.TransferPos; row["TransferLength"] = e.TransferLength; row["ProjectId"] = e.ProjectId; row.AcceptChanges(); } Application.DoEvents(); }; DateTime dtTime = DateTime.Now; session.UpLoadEngine.TransferStep += (e) => { lock (lockobj) { var row = dtFile.Select(string.Format("ProjectId='{0}'", e.ProjectId))[0]; row["TransferedLength"] = e.TransferLen;// session.UpLoadEngine.TransferedLength; var second = (DateTime.Now - dtTime).Seconds; if (second != 0) { row["Speed"] = string.Format("{0}Mb/s", e.TransferLen / (1024 * 1024) / second); } row.AcceptChanges(); } Application.DoEvents(); }; session.UpLoadEngine.TransferComplete += (e) => { lock (lockobj) { var row = dtFile.Select(string.Format("ProjectId='{0}'", e.ProjectId))[0]; row["IsUpLoading"] = false; row.AcceptChanges(); } Application.DoEvents(); }; session.UpLoadEngine.StopTransfer += (e) => { lock (lockobj) { var drs = dtFile.Select(string.Format("ProjectId='{0}'", e.ProjectId)); if (drs.Length > 0) { var dr = drs[0]; dr["Status"] = false; dr.AcceptChanges(); } } Application.DoEvents(); }; }
void transferServer_SessionClosed(TransferSession session, SuperSocket.SocketBase.CloseReason value) { }