/// <summary> /// Sends the file. /// </summary> /// <param name="request">The request.</param> /// <returns>The HTTP content.</returns> async Task <string> ITransferService.SendFile(SendFileRequest request) { if (request == null) { throw new ArgumentNullException(nameof(request)); } if (string.IsNullOrWhiteSpace(request.Url)) { throw new ArgumentException(nameof(request.Url)); } var httpContent = new StringContent(request.StringContent, Encoding.UTF8, request.ContentType); using (var httpClient = new HttpClient()) { var credentials = Encoding.ASCII.GetBytes($"{request.UserName}:{request.Password}"); var authParameter = Convert.ToBase64String(credentials); var authHeader = new AuthenticationHeaderValue(ApplicationConstants.BasicAuthScheme, authParameter); // Set the Authorization header: httpClient.DefaultRequestHeaders.Authorization = authHeader; // Send a POST request: var httpResponse = await httpClient.PostAsync(request.Url, httpContent); // Get the content of the response: if (httpResponse.Content != null) { return(await httpResponse.Content.ReadAsStringAsync()); } } return(string.Empty); }
Result <FileTransfer> GetInboundFileTransfer(SendFileRequest sendFileRequest) { FileTransfer inboundFileTransfer; var fileTransferId = sendFileRequest.RemoteServerTransferId; if (fileTransferId > 0) { var getinboundFileTransfer = GetFileTransferById(fileTransferId); if (getinboundFileTransfer.Failure) { return(Result.Fail <FileTransfer>(getinboundFileTransfer.Error)); } inboundFileTransfer = getinboundFileTransfer.Value; UpdateInboundFileTransferDetails(sendFileRequest, inboundFileTransfer); return(Result.Ok(inboundFileTransfer)); } inboundFileTransfer = InitializeFileTransfer( TransferDirection.Inbound, FileTransferInitiator.RemoteServer, sendFileRequest.RemoteServerInfo, sendFileRequest.FileName, sendFileRequest.FileSizeInBytes, sendFileRequest.LocalFolderPath, sendFileRequest.RemoteFolderPath, sendFileRequest.FileTransferResponseCode, sendFileRequest.RetryLimit, 0); return(Result.Ok(inboundFileTransfer)); }
public Result HandleInboundFileTransferRequest(SendFileRequest sendFileRequest) { var getFileTransfer = GetInboundFileTransfer(sendFileRequest); if (getFileTransfer.Failure) { return(Result.Fail(getFileTransfer.Error)); } var inboundFileTransfer = getFileTransfer.Value; if (!File.Exists(inboundFileTransfer.LocalFilePath)) { PendingFileTransfer?.Invoke(this, PendingFileTransfers.Count); return(Result.Ok()); } var error = $"The request below was rejected because \"{inboundFileTransfer.FileName}\" " + "already exists at the specified location:" + Environment.NewLine + Environment.NewLine + inboundFileTransfer.InboundRequestDetails(false); inboundFileTransfer.Status = FileTransferStatus.Rejected; inboundFileTransfer.ErrorMessage = error; RejectPendingFileTransfer(inboundFileTransfer); ReportError(error); InboundFileAlreadyExists?.Invoke(this, sendFileRequest); return(Result.Fail(error)); }
/// <summary> /// 发送文件消息 /// 文档:https://work.weixin.qq.com/api/doc#10167 /// </summary> /// <param name="request">请求参数</param> /// <returns>返回结果</returns> public SendMessageResult SendFile(SendFileRequest request) { if (request.agentid == 0) { request.agentid = Client.AgentId; } return(Send(request)); }
public SendFileResponse SendFile(SendFileRequest request) { var userAuthentication = userAuthenticationRepository.GetById(request.AuthKey); if (userAuthentication is null || userAuthentication.ExpireAt < DateTime.Now) { return(new SendFileResponse { Code = "-1", Completed = false, Message = "Not Authenticated" }); } var user = userRepository.GetById(userAuthentication.UserId); var company = companyAccountRepository.GetFirstOrDefault(x => x.Identifier == request.ReceiverIdentifier); if (company is null) { return(new SendFileResponse { Code = "-1", Completed = false, Message = "Receiver Company Not Found!" }); } var fileBytes = Convert.FromBase64String(request.FileBase64Content); var outFile = new OutFileDocumentModel { FileName = request.DocumentName, InsertTime = DateTime.Now, FileSize = fileBytes.Length }; outFileDocumentRepository.Create(outFile, fileBytes); outFileRepository.Create(new Library.MsSqlDataAccess.Entity.OutFile { CompanyId = user.CompanyId, DocumentName = request.DocumentName, InsertAt = DateTime.Now, OutFileId = outFile.Id.ToString(), ReceiverIdentifier = request.ReceiverIdentifier, State = (int)FileState.Received }); bus.Publish <IFileReceived>(new { CompanyId = user.CompanyId, FileID = outFile.Id.ToString() }); return(new SendFileResponse { Completed = true, Code = "1", Message = "File Received" }); }
public async Task <Message> SendFile(string filename, Stream stream) { var request = new SendFileRequest(_channel.Id) { Filename = filename, Stream = stream }; var response = await _channel.Client.ClientAPI.Send(request).ConfigureAwait(false); return(Add(response, (_channel as Channel).CurrentUser)); }
async void HandleOutboundFileTransferRequest(object sender, GetFileRequest getFileRequest) { // TODO: Create logic to check file transfers that are under lockout and if this request matches remoteserver info + localfilepath, send a new filetranserresponse = rejected_retrylimitexceeded. maybe we should penalize them for trying to subvert our lockout policy? _eventLog.Add(new ServerEvent { EventType = EventType.ReceivedOutboundFileTransferRequest, RemoteFolder = getFileRequest.RemoteFolderPath, LocalFolder = getFileRequest.LocalFolderPath, FileName = getFileRequest.FileName, RemoteServerIpAddress = getFileRequest.RemoteServerInfo.SessionIpAddress, RemoteServerPortNumber = getFileRequest.RemoteServerInfo.PortNumber }); EventOccurred?.Invoke(this, _eventLog.Last()); var handleTransferRequest = FileTransferHandler.HandleOutboundFileTransferRequest(getFileRequest); if (handleTransferRequest.Failure) { return; } var fileTransfer = handleTransferRequest.Value; var sendFileRequest = new SendFileRequest { LocalServerInfo = MyInfo, RemoteServerInfo = fileTransfer.RemoteServerInfo, FileName = fileTransfer.FileName, FileSizeInBytes = fileTransfer.FileSizeInBytes, RemoteFolderPath = fileTransfer.RemoteFolderPath, LocalFolderPath = fileTransfer.LocalFolderPath, FileTransferResponseCode = fileTransfer.TransferResponseCode, RemoteServerTransferId = fileTransfer.RemoteServerTransferId, RetryLimit = fileTransfer.RemoteServerRetryLimit, RetryCounter = fileTransfer.RetryCounter, Status = RequestStatus.InProgress, Direction = TransferDirection.Outbound }; await _requestHandler.SendRequestAsync(sendFileRequest); SuccessfullyProcessedRequest?.Invoke(this, getFileRequest); }
Task <Result> SendOutboundFileTransferRequestAsync(FileTransfer fileTransfer) { var sendFileRequest = new SendFileRequest { LocalServerInfo = MyInfo, RemoteServerInfo = fileTransfer.RemoteServerInfo, FileName = fileTransfer.FileName, FileSizeInBytes = fileTransfer.FileSizeInBytes, RemoteFolderPath = fileTransfer.RemoteFolderPath, LocalFolderPath = fileTransfer.LocalFolderPath, FileTransferResponseCode = fileTransfer.TransferResponseCode, RemoteServerTransferId = fileTransfer.RemoteServerTransferId, RetryLimit = fileTransfer.RemoteServerRetryLimit, RetryCounter = fileTransfer.RetryCounter, Status = RequestStatus.InProgress, Direction = TransferDirection.Outbound }; return(_requestHandler.SendRequestAsync(sendFileRequest)); }
protected async void SendNotificationFileAlreadyExists(object sender, SendFileRequest sendFileRequest) { var rejectFileTransfer = new FileTransferResponse(RequestType.FileTransferRejected) { LocalServerInfo = MyInfo, RemoteServerInfo = sendFileRequest.RemoteServerInfo, TransferResponseCode = sendFileRequest.FileTransferResponseCode, RemoteServerTransferId = sendFileRequest.Id, Status = RequestStatus.InProgress, Direction = TransferDirection.Outbound }; var sendRequest = await _requestHandler.SendRequestAsync(rejectFileTransfer); if (sendRequest.Failure) { return; } SuccessfullyProcessedRequest?.Invoke(this, sendFileRequest); }
public async Task <Message> SendFile(string filename, Stream stream) { if (filename == null) { throw new ArgumentNullException(nameof(filename)); } if (stream == null) { throw new ArgumentNullException(nameof(stream)); } var request = new SendFileRequest(Id) { Filename = filename, Stream = stream }; var model = await Client.ClientAPI.Send(request).ConfigureAwait(false); var msg = AddMessage(model.Id, IsPrivate ? Client.PrivateUser : Server.CurrentUser, model.Timestamp.Value); msg.Update(model); return(msg); }
void HandleInboundFileTransferRequest(object sender, SendFileRequest sendFileRequest) { _eventLog.Add(new ServerEvent { EventType = EventType.ReceivedInboundFileTransferRequest, LocalFolder = sendFileRequest.LocalFolderPath, FileName = sendFileRequest.FileName, FileSizeInBytes = sendFileRequest.FileSizeInBytes, RemoteServerIpAddress = sendFileRequest.RemoteServerInfo.SessionIpAddress, RemoteServerPortNumber = sendFileRequest.RemoteServerInfo.PortNumber }); EventOccurred?.Invoke(this, _eventLog.Last()); var handleTransferRequest = FileTransferHandler.HandleInboundFileTransferRequest(sendFileRequest); if (handleTransferRequest.Failure) { return; } SuccessfullyProcessedRequest?.Invoke(this, sendFileRequest); }
void UpdateInboundFileTransferDetails(SendFileRequest sendFileRequest, FileTransfer fileTransfer) { fileTransfer.TransferResponseCode = sendFileRequest.FileTransferResponseCode; fileTransfer.FileSizeInBytes = sendFileRequest.FileSizeInBytes; fileTransfer.RemoteServerRetryLimit = sendFileRequest.RetryLimit; if (sendFileRequest.RetryCounter == 1) { return; } fileTransfer.RetryCounter = sendFileRequest.RetryCounter; fileTransfer.Status = FileTransferStatus.Pending; fileTransfer.ErrorMessage = string.Empty; fileTransfer.RequestInitiatedTime = DateTime.Now; fileTransfer.TransferStartTime = DateTime.MinValue; fileTransfer.TransferCompleteTime = DateTime.MinValue; fileTransfer.CurrentBytesReceived = 0; fileTransfer.TotalBytesReceived = 0; fileTransfer.BytesRemaining = 0; fileTransfer.PercentComplete = 0; }
public async Task<Message> SendFile(string filename, Stream stream) { if (filename == null) throw new ArgumentNullException(nameof(filename)); if (stream == null) throw new ArgumentNullException(nameof(stream)); var request = new SendFileRequest(Id) { Filename = filename, Stream = stream }; var model = await Client.ClientAPI.Send(request).ConfigureAwait(false); var msg = AddMessage(model.Id, IsPrivate ? Client.PrivateUser : Server.CurrentUser, model.Timestamp.Value); msg.Update(model); return msg; }
/// <summary> /// Metodo per il download di un file /// </summary> /// <param name="request">Informazioni sul file da scricare</param> /// <returns>Informazioni sul file scaricato e riferimento all'oggetto responsabile della gestione dello streaming dati</returns> RemoteFileInfo IFileManager.DownloadFile(SendFileRequest request) { logger.Debug("BEGIN"); DocsPaVO.utente.InfoUtente infoUtente = new DocsPaVO.utente.InfoUtente() { idAmministrazione = request.AdministrationId }; FileRequest fr = new FileRequest() { docServerLoc = request.DocumentServerLocation, path = request.FilePath, fileName = request.FileName, docNumber = request.DocumentNumber, versionId = request.VersionId, versionLabel = request.VersionLabel, version = request.Version }; byte[] lastTSR = null; try { lastTSR = BusinessLogic.Interoperabilità.InteroperabilitaUtils.GetTSRForDocument(infoUtente, fr); } catch { } FileDocumento docFile = BusinessLogic.Documenti.FileManager.getFileFirmato( fr, infoUtente, false); if (lastTSR != null) { logger.Debug("TSR presente, incapsulo in TSDiS"); //controllo il match if (!BusinessLogic.Interoperabilità.InteroperabilitaUtils.MatchTSR(lastTSR, docFile.content)) { lastTSR = null; } //Gestione TSDis (DOC+TSR) //Siccome non si possono mandare piu file allo stesso tempo, ne è possibile alterare la struttura //si è pensato: //In fase di invio, in caso di documenti con TSR associato, l'invio dello stesso un formato //TSD, come marca verrà presa l'ultima disponibile, e unita al documento, creadno un file con estensione TSDis //In fase di ricezione il TsdIs, sarà poi spacchettato, il TSR messo in DPA_TIMESTAMP dopo verifica hash e //infine il payload messo in documentale con la putfile. //tsr presente, combino il tutto per creare un TSDis if (lastTSR != null) { try { BusinessLogic.Documenti.DigitalSignature.PKCS_Utils.tsd tsdMgr = new BusinessLogic.Documenti.DigitalSignature.PKCS_Utils.tsd(); BusinessLogic.Documenti.DigitalSignature.PKCS_Utils.CryptoFile file = new BusinessLogic.Documenti.DigitalSignature.PKCS_Utils.CryptoFile { Content = docFile.content, Name = docFile.name, MessageFileType = BusinessLogic.Documenti.DigitalSignature.PKCS_Utils.fileType.Binary }; List <BusinessLogic.Documenti.DigitalSignature.PKCS_Utils.CryptoFile> tsrLst = new List <BusinessLogic.Documenti.DigitalSignature.PKCS_Utils.CryptoFile>(); BusinessLogic.Documenti.DigitalSignature.PKCS_Utils.CryptoFile tsrfile = new BusinessLogic.Documenti.DigitalSignature.PKCS_Utils.CryptoFile { Content = lastTSR, MessageFileType = BusinessLogic.Documenti.DigitalSignature.PKCS_Utils.fileType.Binary }; tsrLst.Add(tsrfile); docFile.content = tsdMgr.create(file, tsrLst.ToArray()).Content; request.FileName = request.FileName + ".TSDis"; } catch (Exception e) { logger.ErrorFormat("Error creating TSDID {0} {1}", e.Message, e.StackTrace); //Manca il logger pdpdpdpdp } } } //FileDocumento docFile = BusinessLogic.Documenti.FileManager.getFileFirmato( // new FileRequest() // { // docServerLoc = request.DocumentServerLocation, // path = request.FilePath, // fileName = request.FileName, // docNumber = request.DocumentNumber, // versionId = request.VersionId, // versionLabel = request.VersionLabel // }, // new DocsPaVO.utente.InfoUtente() // { // idAmministrazione = request.AdministrationId // }, // false); logger.Debug("END"); return(new RemoteFileInfo { FileData = new MemoryStream(docFile.content, false), FileTransferInfo = new FileTransferInfo() { FileName = request.FileName, FileLength = docFile.content.Length } }); }