forked from nearby-sharing/android
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathNearShareSender.cs
198 lines (167 loc) · 8.14 KB
/
NearShareSender.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
using ShortDev.Microsoft.ConnectedDevices.Exceptions;
using ShortDev.Microsoft.ConnectedDevices.Messages;
using ShortDev.Microsoft.ConnectedDevices.Messages.Session;
using ShortDev.Microsoft.ConnectedDevices.NearShare.Apps;
using ShortDev.Microsoft.ConnectedDevices.NearShare.Messages;
using ShortDev.Microsoft.ConnectedDevices.Platforms;
using ShortDev.Microsoft.ConnectedDevices.Serialization;
namespace ShortDev.Microsoft.ConnectedDevices.NearShare;
public sealed class NearShareSender(ConnectedDevicesPlatform platform)
{
public ConnectedDevicesPlatform Platform { get; } = platform;
async Task<SenderStateMachine> PrepareTransferInternalAsync(CdpDevice device, CancellationToken cancellationToken)
{
var session = await Platform.ConnectAsync(device);
Guid operationId = Guid.NewGuid();
HandshakeHandler handshake = new(Platform);
using var handShakeChannel = await session.StartClientChannelAsync(NearShareHandshakeApp.Id, NearShareHandshakeApp.Name, handshake, cancellationToken);
var handshakeResultMsg = await handshake.Execute(operationId);
// ToDo: CorrelationVector
// var cv = handshakeResultMsg.Header.TryGetCorrelationVector() ?? throw new InvalidDataException("No Correlation Vector");
SenderStateMachine senderStateMachine = new(Platform);
var channel = await session.StartClientChannelAsync(operationId.ToString("D").ToUpper(), NearShareApp.Name, senderStateMachine, handShakeChannel.Socket, cancellationToken);
return senderStateMachine;
}
public async Task SendUriAsync(CdpDevice device, Uri uri, CancellationToken cancellationToken = default)
{
using var senderStateMachine = await PrepareTransferInternalAsync(device, cancellationToken);
await senderStateMachine.SendUriAsync(uri);
}
public async Task SendFileAsync(CdpDevice device, CdpFileProvider file, IProgress<NearShareProgress> progress, CancellationToken cancellationToken = default)
=> await SendFilesAsync(device, new[] { file }, progress, cancellationToken);
public async Task SendFilesAsync(CdpDevice device, IReadOnlyList<CdpFileProvider> files, IProgress<NearShareProgress> progress, CancellationToken cancellationToken = default)
{
using var senderStateMachine = await PrepareTransferInternalAsync(device, cancellationToken);
await senderStateMachine.SendFilesAsync(files, progress, cancellationToken);
}
sealed class HandshakeHandler(ConnectedDevicesPlatform cdp) : CdpAppBase(cdp)
{
readonly TaskCompletionSource<CdpMessage> _promise = new();
public Task<CdpMessage> Execute(Guid operationId)
{
ValueSet msg = new();
msg.Add("ControlMessage", (uint)NearShareControlMsgType.HandShakeRequest);
msg.Add("MaxPlatformVersion", 1u);
msg.Add("MinPlatformVersion", 1u);
msg.Add("OperationId", operationId);
SendValueSet(msg, msgId: 0);
return _promise.Task;
}
public override void HandleMessage(CdpMessage msg)
{
msg.ReadBinary(out ValueSet payload, out _);
var handshakeResult = payload.Get<uint>("VersionHandShakeResult");
if (handshakeResult != 1)
_promise.SetException(new CdpProtocolException("Handshake failed"));
_promise.SetResult(msg);
}
}
sealed class SenderStateMachine(ConnectedDevicesPlatform cdp) : CdpAppBase(cdp)
{
readonly TaskCompletionSource _promise = new();
public async Task SendUriAsync(Uri uri)
{
ValueSet valueSet = new();
valueSet.Add("ControlMessage", (uint)NearShareControlMsgType.StartTransfer);
valueSet.Add("DataKind", (uint)DataKind.Uri);
valueSet.Add("BytesToSend", 0);
valueSet.Add("FileCount", 0);
valueSet.Add("Uri", uri.ToString());
SendValueSet(valueSet, 10);
await _promise.Task;
}
IReadOnlyList<CdpFileProvider>? _files;
IProgress<NearShareProgress>? _fileProgress;
CancellationToken? _fileCancellationToken;
ulong _bytesToSend;
public async Task SendFilesAsync(IReadOnlyList<CdpFileProvider> files, IProgress<NearShareProgress> progress, CancellationToken cancellationToken)
{
_files = files;
_fileProgress = progress;
_fileCancellationToken = cancellationToken;
uint fileCount = (uint)files.Count;
_bytesToSend = CalcBytesToSend(files);
ValueSet valueSet = new();
valueSet.Add("ControlMessage", (uint)NearShareControlMsgType.StartTransfer);
valueSet.Add("DataKind", (uint)DataKind.File);
valueSet.Add<ulong>("BytesToSend", _bytesToSend);
valueSet.Add<uint>("FileCount", fileCount);
valueSet.Add<uint[]>("ContentIds", GenerateContentIds(fileCount));
valueSet.Add<ulong[]>("ContentSizes", files.Select(x => x.FileSize).ToArray());
valueSet.Add<string[]>("FileNames", files.Select(x => x.FileName).ToArray());
SendValueSet(valueSet, 10);
cancellationToken.Register(() =>
{
ValueSet request = new();
request.Add("ControlMessage", (uint)NearShareControlMsgType.CancelTransfer);
SendValueSet(request, 11);
_promise.TrySetCanceled();
});
await _promise.Task;
}
static uint[] GenerateContentIds(uint fileCount)
{
var ids = new uint[fileCount];
for (uint i = 0; i < fileCount; i++)
ids[i] = i;
return ids;
}
static ulong CalcBytesToSend(IReadOnlyList<CdpFileProvider> files)
{
ulong sum = 0;
for (int i = 0; i < files.Count; i++)
sum += files[i].FileSize;
return sum;
}
public override void HandleMessage(CdpMessage msg)
{
if (_fileCancellationToken?.IsCancellationRequested == true)
return;
msg.ReadBinary(out ValueSet payload, out var header);
try
{
var controlMsg = (NearShareControlMsgType)payload.Get<uint>("ControlMessage");
switch (controlMsg)
{
case NearShareControlMsgType.FetchDataRequest:
HandleDataRequest(header, payload);
break;
case NearShareControlMsgType.CompleteTransfer:
_promise.TrySetResult();
break;
case NearShareControlMsgType.CancelTransfer:
_promise.TrySetCanceled();
break;
default:
throw new CdpProtocolException($"Unexpected {controlMsg}");
}
}
catch (Exception ex)
{
_promise.TrySetException(ex);
}
}
ulong _bytesSent = 0;
void HandleDataRequest(BinaryMsgHeader header, ValueSet payload)
{
var contentId = payload.Get<uint>("ContentId");
var start = payload.Get<ulong>("BlobPosition");
var length = payload.Get<uint>("BlobSize");
var fileProvider = _files?[(int)contentId] ?? throw new NullReferenceException("Could not access files to transfer");
var blob = fileProvider.ReadBlob(start, length);
_fileProgress?.Report(new()
{
BytesSent = Interlocked.Add(ref _bytesSent, length),
FilesSent = contentId + 1, // ToDo: How to calculate?
TotalBytesToSend = _bytesToSend,
TotalFilesToSend = (uint)_files.Count
});
ValueSet response = new();
response.Add("ControlMessage", (uint)NearShareControlMsgType.FetchDataResponse);
response.Add("ContentId", contentId);
response.Add("BlobPosition", start);
response.Add("DataBlob", blob.ToArray().ToList()); // ToDo: Remove allocation
SendValueSet(response, header.MessageId);
}
}
}