You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
Zero/ZeroLevel/Services/Network/FileTransfer/FileClient.cs

96 lines
3.5 KiB

6 years ago
using System;
using System.Threading;
using ZeroLevel.Models;
6 years ago
6 years ago
namespace ZeroLevel.Network.FileTransfer
6 years ago
{
public sealed class FileClient
: BaseFileTransfer, IFileClient
{
private readonly ExClient _client;
6 years ago
private readonly string _baseFolder;
private readonly ClientFolderNameMapper _nameMapper;
private readonly bool _disposeClient;
internal FileClient(ExClient client, string baseFolder, ClientFolderNameMapper nameMapper, bool disposeClient)
6 years ago
: base(baseFolder)
{
_client = client ?? throw new Exception(nameof(client));
_baseFolder = baseFolder ?? throw new Exception(nameof(baseFolder));
_nameMapper = nameMapper ?? throw new Exception(nameof(nameMapper));
_disposeClient = disposeClient;
_client.Router.RegisterInbox<FileStartFrame>("__upload_file_start", (c, f) => Receiver.Incoming(f, nameMapper(c)));
_client.Router.RegisterInbox<FileFrame>("__upload_file_frame", (c, f) => Receiver.Incoming(f));
_client.Router.RegisterInbox<FileEndFrame>("__upload_file_complete", (c, f) => Receiver.Incoming(f));
6 years ago
}
public void Dispose()
{
if (_disposeClient)
{
_client?.Dispose();
}
}
public void Send(string fileName, Action<string> completeHandler = null, Action<string, string> errorHandler = null)
{
PushTransferTask(fileName, completeHandler, errorHandler);
}
internal override void ExecuteSendFile(FileReader reader, FileTransferTask task)
{
Log.Info($"Start upload file {reader.Path}");
var startinfo = reader.GetStartInfo();
using (var signal = new ManualResetEvent(false))
6 years ago
{
bool next = false;
if (false == _client.Request<FileStartFrame, InvokeResult>("__upload_file_start", startinfo,
r =>
{
next = r.Success;
signal.Set();
}).Success)
{
next = false;
signal.Set();
}
signal.WaitOne(5000);
if (next)
{
foreach (var chunk in reader.Read())
{
signal.Reset();
if (_client.Request<FileFrame, InvokeResult>("__upload_file_frame", chunk, r =>
{
next = r.Success;
signal.Set();
}).Success == false)
{
next = false;
signal.Set();
}
signal.WaitOne();
if (!next)
{
break;
}
}
}
if (next)
{
_client.Request<FileEndFrame, InvokeResult>("__upload_file_complete", reader.GetCompleteInfo(), r =>
{
if (r.Success == false)
{
Log.Warning($"Unsuccess send file. {r.Comment}");
}
});
}
6 years ago
}
Log.Debug($"Stop upload file {reader.Path}");
6 years ago
}
}
}

Powered by TurnKey Linux.