Repository navigation
Expand file tree
/
Copy pathSyncService.cs
More file actions
549 lines (473 loc) · 21.6 KB
/
Copy pathSyncService.cs
File metadata and controls
549 lines (473 loc) · 21.6 KB
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
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
// <copyright file="SyncService.cs" company="The Android Open Source Project, Ryan Conrad, Quamotion, yungd1plomat, wherewhere">
// Copyright (c) The Android Open Source Project, Ryan Conrad, Quamotion, yungd1plomat, wherewhere. All rights reserved.
// </copyright>
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Net;
using System.Runtime.CompilerServices;
namespace AdvancedSharpAdbClient
{
/// <summary>
/// Provides access to the sync service running on the Android device. Allows you to
/// list, download and upload files on the device.
/// </summary>
/// <example>
/// <para>To send files to or receive files from your Android device, you can use the following code:</para>
/// <code>
/// void DownloadFile()
/// {
/// var device = new AdbClient().GetDevices().First();
///
/// using (SyncService service = new SyncService(new AdbSocket(), device))
/// using (Stream stream = File.OpenWrite(@"C:\MyFile.txt"))
/// {
/// service.Pull("/data/MyFile.txt", stream, null, CancellationToken.None);
/// }
/// }
///
/// void UploadFile()
/// {
/// var device = new AdbClient().GetDevices().First();
///
/// using (SyncService service = new SyncService(new AdbSocket(), device))
/// using (Stream stream = File.OpenRead(@"C:\MyFile.txt"))
/// {
/// service.Push(stream, "/data/MyFile.txt", null, CancellationToken.None);
/// }
/// }
/// </code>
/// </example>
[DebuggerDisplay($"{{{nameof(GetType)}().{nameof(Type.ToString)}(),nq}} \\{{ {nameof(IsOpen)} = {{{nameof(IsOpen)}}}, {nameof(Device)} = {{{nameof(Device)}}}, {nameof(Socket)} = {{{nameof(Socket)}}}, {nameof(MaxBufferSize)} = {{{nameof(MaxBufferSize)}}} }}")]
public partial class SyncService : ISyncService, IInternalCloneable<SyncService>
#if HAS_WINRT
, ISyncService.IWinRT
#endif
{
/// <summary>
/// The maximum length of a path on the remote device.
/// </summary>
protected const int MaxPathLength = 1024;
/// <summary>
/// <see langword="true"/> if the <see cref="SyncService"/> is out of date; otherwise, <see langword="false"/>.
/// </summary>
/// <remarks>Need to invoke <see cref="Reopen"/> before using the <see cref="SyncService"/> again.</remarks>
protected internal bool IsOutdate = false;
/// <summary>
/// <see langword="true"/> if the <see cref="SyncService"/> is processing; otherwise, <see langword="false"/>.
/// </summary>
/// <remarks>Recommend to <see cref="Clone()"/> a new <see cref="ISyncService"/> or wait until the process is finished.</remarks>
protected internal bool IsProcessing = false;
/// <summary>
/// Initializes a new instance of the <see cref="SyncService"/> class.
/// </summary>
/// <param name="device">The device on which to interact with the files.</param>
public SyncService(DeviceData device)
: this(Factories.AdbSocketFactory(AdbClient.AdbServerEndPoint), device)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="SyncService"/> class.
/// </summary>
/// <param name="client">A connection to an adb server.</param>
/// <param name="device">The device on which to interact with the files.</param>
public SyncService(IAdbClient client, DeviceData device)
: this(Factories.AdbSocketFactory(client.EndPoint), device)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="SyncService"/> class.
/// </summary>
/// <param name="endPoint">The <see cref="EndPoint"/> at which the adb server is listening.</param>
/// <param name="device">The device on which to interact with the files.</param>
public SyncService(EndPoint endPoint, DeviceData device)
: this(Factories.AdbSocketFactory(endPoint), device)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="SyncService"/> class.
/// </summary>
/// <param name="socket">A <see cref="IAdbSocket"/> that enables to connection with the adb server.</param>
/// <param name="device">The device on which to interact with the files.</param>
public SyncService(IAdbSocket socket, DeviceData device)
{
Device = DeviceData.EnsureDevice(device);
Socket = socket ?? throw new ArgumentNullException(nameof(socket));
Open();
}
/// <summary>
/// Gets or sets the maximum size of data to transfer between the device and the PC in one block.
/// </summary>
public int MaxBufferSize { get; set; } = 64 * 1024;
/// <summary>
/// Gets the device on which the file operations are being executed.
/// </summary>
public DeviceData Device { get; }
/// <summary>
/// Gets the <see cref="IAdbSocket"/> that enables the connection with the adb server.
/// </summary>
public IAdbSocket Socket { get; protected set; }
/// <inheritdoc/>
public bool IsOpen => Socket?.Connected == true;
/// <inheritdoc/>
/// <remarks>This method has been invoked by the constructor.
/// Do not use it unless you have closed the connection.
/// Use <see cref="Reopen"/> to reopen the connection.</remarks>
public void Open()
{
// target a specific device
Socket.SetDevice(Device);
Socket.SendAdbRequest("sync:");
_ = Socket.ReadAdbResponse();
IsOutdate = false;
}
/// <inheritdoc/>
public void Reopen()
{
Socket.Reconnect(true);
Open();
}
/// <inheritdoc/>
public virtual void Push(Stream stream, string remotePath, UnixFileStatus permission, DateTimeOffset timestamp, Action<SyncProgressChangedEventArgs>? callback = null, bool useV2 = false, scoped in bool isCancelled = false)
{
if (IsProcessing) { throw new InvalidOperationException($"The {nameof(SyncService)} is currently processing a request. Please {nameof(Clone)} a new {nameof(ISyncService)} or wait until the process is finished."); }
ArgumentNullException.ThrowIfNull(stream);
ArgumentNullException.ThrowIfNull(remotePath);
if (remotePath.Length > MaxPathLength)
{
throw new ArgumentOutOfRangeException(nameof(remotePath), $"The remote path {remotePath} exceeds the maximum path size {MaxPathLength}");
}
if (IsOutdate) { Reopen(); }
try
{
if (useV2)
{
Socket.SendSyncRequest(SyncCommand.SND2, remotePath);
IsProcessing = true;
Socket.SendSyncRequest(SyncCommand.SND2, permission, SyncFlags.None);
}
else
{
Socket.SendSyncRequest(SyncCommand.SEND, remotePath, permission);
IsProcessing = true;
}
// create the buffer used to read.
// we read max SYNC_DATA_MAX.
byte[] buffer = new byte[MaxBufferSize];
// We need 4 bytes of the buffer to send the 'DATA' command,
// and an additional X bytes to inform how much data we are
// sending.
byte[] dataBytes = SyncCommand.DATA.GetBytes();
byte[] lengthBytes = BitConverter.GetBytes(MaxBufferSize);
int headerSize = dataBytes.Length + lengthBytes.Length;
int reservedHeaderSize = headerSize;
int maxDataSize = MaxBufferSize - reservedHeaderSize;
lengthBytes = BitConverter.GetBytes(maxDataSize);
// Try to get the total amount of bytes to transfer. This is not always possible, for example,
// for forward-only streams.
long totalBytesToProcess = stream.CanSeek ? stream.Length : 0;
long totalBytesRead = 0;
int read;
// look while there is something to read
while (!isCancelled && (read =
#if HAS_BUFFERS
stream.Read(buffer.AsSpan(headerSize, maxDataSize))
#else
stream.Read(buffer, headerSize, maxDataSize)
#endif
) > 0)
{
// read up to SYNC_DATA_MAX
totalBytesRead += read;
if (read != maxDataSize)
{
// At the end of the line, so we need to recalculate the length of the header
lengthBytes = BitConverter.GetBytes(read);
headerSize = dataBytes.Length + lengthBytes.Length;
}
int startPosition = reservedHeaderSize - headerSize;
Buffer.BlockCopy(dataBytes, 0, buffer, startPosition, dataBytes.Length);
Buffer.BlockCopy(lengthBytes, 0, buffer, startPosition + dataBytes.Length, lengthBytes.Length);
// now send the data to the device
#if COMP_NETSTANDARD2_1
Socket.Send(buffer.AsSpan(startPosition, read + dataBytes.Length + lengthBytes.Length));
#else
Socket.Send(buffer, startPosition, read + dataBytes.Length + lengthBytes.Length);
#endif
// Let the caller know about our progress, if requested
callback?.Invoke(new SyncProgressChangedEventArgs((ulong)totalBytesRead, (ulong)totalBytesToProcess));
}
// create the DONE message
int time = (int)timestamp.ToUnixTimeSeconds();
Socket.SendSyncRequest(SyncCommand.DONE, time);
// read the result, in a byte array containing 2 int
// (id, size)
SyncCommand result = Socket.ReadSyncResponse();
switch (result)
{
case SyncCommand.FAIL:
string message = Socket.ReadSyncString();
throw new AdbException(message);
case not SyncCommand.OKAY:
throw new AdbException($"The server sent an invalid response {result}");
}
}
finally
{
IsOutdate = true;
IsProcessing = false;
}
}
/// <inheritdoc/>
public virtual void Pull(string remoteFilePath, Stream stream, Action<SyncProgressChangedEventArgs>? callback = null, bool useV2 = false, scoped in bool isCancelled = false)
{
if (IsProcessing) { throw new InvalidOperationException($"The {nameof(SyncService)} is currently processing a request. Please {nameof(Clone)} a new {nameof(ISyncService)} or wait until the process is finished."); }
ArgumentNullException.ThrowIfNull(remoteFilePath);
ArgumentNullException.ThrowIfNull(stream);
if (IsOutdate) { Reopen(); }
// Gets file information, including the file size, used to calculate the total amount of bytes to receive.
ulong totalBytesToProcess = this.Stat(remoteFilePath, useV2).Size;
ulong totalBytesRead = 0;
byte[] buffer = new byte[MaxBufferSize];
try
{
if (useV2)
{
Socket.SendSyncRequest(SyncCommand.RCV2, remoteFilePath);
IsProcessing = true;
Socket.SendSyncRequest(SyncCommand.RCV2, (int)SyncFlags.None);
}
else
{
Socket.SendSyncRequest(SyncCommand.RECV, remoteFilePath);
IsProcessing = true;
}
while (!isCancelled)
{
SyncCommand response = Socket.ReadSyncResponse();
switch (response)
{
case SyncCommand.DONE:
goto finish;
case SyncCommand.FAIL:
string message = Socket.ReadSyncString();
throw new AdbException($"Failed to pull '{remoteFilePath}'. {message}");
case not SyncCommand.DATA:
throw new AdbException($"The server sent an invalid response {response}");
}
// The first 4 bytes contain the length of the data packet
byte[] reply = new byte[4];
_ = Socket.Read(reply);
int size = BitConverter.ToInt32(reply);
if (size > MaxBufferSize)
{
throw new AdbException($"The adb server is sending {size} bytes of data, which exceeds the maximum chunk size {MaxBufferSize}");
}
// now read the length we received
#if COMP_NETSTANDARD2_1
_ = Socket.Read(buffer.AsSpan(0, size));
#else
_ = Socket.Read(buffer, size);
#endif
#if HAS_BUFFERS
stream.Write(buffer.AsSpan(0, size));
#else
stream.Write(buffer, 0, size);
#endif
totalBytesRead += (uint)size;
// Let the caller know about our progress, if requested
callback?.Invoke(new SyncProgressChangedEventArgs(totalBytesRead, totalBytesToProcess));
}
finish: return;
}
finally
{
IsOutdate = true;
IsProcessing = false;
}
}
/// <inheritdoc/>
public FileStatistics Stat(string remotePath)
{
// create the stat request message.
Socket.SendSyncRequest(SyncCommand.STAT, remotePath);
SyncCommand response = Socket.ReadSyncResponse();
if (response != SyncCommand.STAT)
{
throw new AdbException($"The server returned an invalid sync response {response}.");
}
// read the result, in a byte array containing 3 int
// (mode, size, time)
FileStatistics value = ReadStatistics();
value.Path = remotePath;
return value;
}
/// <inheritdoc/>
public FileStatisticsEx StatEx(string remotePath)
{
// create the stat request message.
Socket.SendSyncRequest(SyncCommand.STA2, remotePath);
SyncCommand response = Socket.ReadSyncResponse();
if (response != SyncCommand.STA2)
{
throw new AdbException($"The server returned an invalid sync response {response}.");
}
FileStatisticsEx value = ReadStatisticsV2();
value.Path = remotePath;
return value;
}
/// <inheritdoc/>
public IEnumerable<FileStatistics> GetDirectoryListing(string remotePath)
{
if (IsProcessing) { throw new InvalidOperationException($"The {nameof(SyncService)} is currently processing a request. Please {nameof(Clone)} a new {nameof(ISyncService)} or wait until the process is finished."); }
if (IsOutdate) { Reopen(); }
bool isLocked = false;
try
{
start:
// create the stat request message.
Socket.SendSyncRequest(SyncCommand.LIST, remotePath);
IsProcessing = true;
while (true)
{
SyncCommand response = Socket.ReadSyncResponse();
switch (response)
{
case 0 when isLocked:
throw new AdbException("The server returned an empty sync response.");
case 0:
Reopen();
isLocked = true;
goto start;
case SyncCommand.DONE:
goto finish;
case not SyncCommand.DENT:
throw new AdbException($"The server returned an invalid sync response {response}.");
}
FileStatistics entry = ReadStatistics();
entry.Path = Socket.ReadSyncString();
yield return entry;
isLocked = true;
}
finish:
yield break;
}
finally
{
IsOutdate = true;
IsProcessing = false;
}
}
/// <inheritdoc/>
public IEnumerable<FileStatisticsEx> GetDirectoryListingEx(string remotePath)
{
if (IsProcessing) { throw new InvalidOperationException($"The {nameof(SyncService)} is currently processing a request. Please {nameof(Clone)} a new {nameof(ISyncService)} or wait until the process is finished."); }
if (IsOutdate) { Reopen(); }
bool isLocked = false;
try
{
start:
// create the stat request message.
Socket.SendSyncRequest(SyncCommand.LIS2, remotePath);
IsProcessing = true;
while (true)
{
SyncCommand response = Socket.ReadSyncResponse();
switch (response)
{
case 0 when isLocked:
throw new AdbException("The server returned an empty sync response.");
case 0:
Reopen();
isLocked = true;
goto start;
case SyncCommand.DONE:
goto finish;
case not SyncCommand.DNT2:
throw new AdbException($"The server returned an invalid sync response {response}.");
}
FileStatisticsEx entry = ReadStatisticsV2();
entry.Path = Socket.ReadSyncString();
yield return entry;
isLocked = true;
}
finish:
yield break;
}
finally
{
IsOutdate = true;
IsProcessing = false;
}
}
/// <summary>
/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
/// </summary>
protected virtual void Dispose(bool disposing)
{
if (disposing && Socket != null)
{
Socket.Dispose();
Socket = null!;
}
}
/// <inheritdoc/>
public void Dispose()
{
Dispose(disposing: true);
GC.SuppressFinalize(this);
}
/// <inheritdoc/>
public override string ToString() => $"{GetType()} {{ {nameof(Socket)} = {Socket}, {nameof(Device)} = {Device} }}";
/// <summary>
/// Creates a new <see cref="SyncService"/> object that is a copy of the current instance with new <see cref="Device"/>.
/// </summary>
/// <param name="device">The new <see cref="Device"/> to use.</param>
/// <returns>A new <see cref="SyncService"/> object that is a copy of this instance with new <see cref="Device"/>.</returns>
public virtual SyncService Clone(DeviceData device) =>
Socket is ICloneable<IAdbSocket> cloneable
? new SyncService(cloneable.Clone(), device)
: throw new NotSupportedException($"{Socket.GetType()} does not support cloning.");
/// <inheritdoc/>
public SyncService Clone() => Clone(Device);
/// <inheritdoc/>
object ICloneable.Clone() => Clone(Device);
/// <summary>
/// Reads the statistics of a file from the socket.
/// </summary>
/// <returns>A <see cref="FileStatistics"/> object that contains information about the file.</returns>
protected FileStatistics ReadStatistics()
{
#if COMP_NETSTANDARD2_1
scoped Span<byte> statResult = stackalloc byte[FileStatisticsData.Length];
_ = Socket.Read(statResult);
FileStatisticsData data = EnumerableBuilder.FileStatisticsDataCreator(statResult);
return new FileStatistics(data);
#else
byte[] statResult = new byte[FileStatisticsData.Length];
_ = Socket.Read(statResult);
scoped ref FileStatisticsData data = ref Unsafe.As<byte, FileStatisticsData>(ref statResult[0]);
return new FileStatistics(data);
#endif
}
/// <summary>
/// Reads the statistics of a file from the socket (v2).
/// </summary>
/// <returns>A <see cref="FileStatisticsEx"/> object that contains information about the file.</returns>
protected FileStatisticsEx ReadStatisticsV2()
{
#if COMP_NETSTANDARD2_1
scoped Span<byte> statResult = stackalloc byte[FileStatisticsDataEx.Length];
_ = Socket.Read(statResult);
FileStatisticsDataEx data = EnumerableBuilder.FileStatisticsDataV2Creator(statResult);
return new FileStatisticsEx(data);
#else
byte[] statResult = new byte[FileStatisticsDataEx.Length];
_ = Socket.Read(statResult);
scoped ref FileStatisticsDataEx data = ref Unsafe.As<byte, FileStatisticsDataEx>(ref statResult[0]);
return new FileStatisticsEx(data);
#endif
}
}
}