-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathHttpDownLoadContinueHelper.cs
More file actions
542 lines (509 loc) · 21 KB
/
Copy pathHttpDownLoadContinueHelper.cs
File metadata and controls
542 lines (509 loc) · 21 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
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Windows.Storage.Streams;
using WinRtHttpHelper.Data;
namespace WinRtHttpHelper
{
public class HttpDownLoadContinueHelper : IDisposable, IContinueDownLoad
{
/*#region Singleton
private static HttpDownLoadContinueHelper _instance = null;
private static readonly object lockObject = new object();
public static HttpDownLoadContinueHelper Instance
{
get
{
if (_instance == null)
{
lock (lockObject)
{
_instance = new HttpDownLoadContinueHelper();
_instance.hc = new HttpClient();
_instance.cts = new CancellationTokenSource();
if(_instance.DownloadBytesCount == null)
{
_instance.DownloadBytesCount = new DownLoadBytes();
}
_instance.Bytes = new List<byte>();
}
}
return _instance;
}
}
#endregion*/
private HttpClient hc = null;
private CancellationTokenSource cts = null;
private HttpRequestMessage request = null;
private HttpResponseMessage response = null;
//切片大小
private long percentage = 0;
//切片块数 进度系数 已完成的比例
private int percentageCoefficient = 0, progressCoefficient = 0, completePercentage = 0;
//下载拼装的所有字节数
private List<byte> Bytes = null;
//下载是否为暂停,默认为false没有暂停
private bool isPause = false;
//是否服务器支持断点续传
private bool isRange = true;
//不声明委托
//public delegate void DownLoadChanging(object sender, DownLoadChangingEventArgs args);
/// <summary>
/// 下载的实时进度事件
/// </summary>
public event EventHandler<DownLoadChangingEventArgs> DownLoadChanging;
public event EventHandler<DownLoadCompleteEventArgs> DownLoadComplete;
/// <summary>
/// 已下载的字节数和总的字节数
/// </summary>
public DownLoadBytes DownloadBytesCount
{
get;
private set;
}
public HttpDownLoadContinueHelper()
{
hc = new HttpClient();
cts = new CancellationTokenSource();
if (DownloadBytesCount == null)
{
DownloadBytesCount = new DownLoadBytes();
}
Bytes = new List<byte>();
}
private void TriggerDownLoadChanging(DownLoadChangingEventArgs e)
{
EventHandler<DownLoadChangingEventArgs> handler = DownLoadChanging;
if (handler != null)
{
handler(this, e);
}
}
private void TriggerDownLoadComplete(DownLoadCompleteEventArgs e)
{
EventHandler<DownLoadCompleteEventArgs> handler = DownLoadComplete;
if (handler != null)
{
handler(this, e);
}
}
//暂时弃用
private async Task<long> ReadBytesFromServer(Stream stream, List<byte> byteAll, CancellationToken ct)
{
if (stream == null)
{
return 0;
}
int readCount = 0;
byte[] hasRead = new byte[1024];
long read = DownloadBytesCount.BytesReceived;
try
{
do
{
if (ct.IsCancellationRequested)
{
break;
}
readCount = await stream.ReadAsync(hasRead, 0, hasRead.Length, ct);
read += readCount;
double percent = (double)read * 100 / (double)DownloadBytesCount.BytesReceived;
percent = Math.Round(percent, MidpointRounding.ToEven);
TriggerDownLoadChanging(new DownLoadChangingEventArgs(DownloadBytesCount, Convert.ToInt32(percent), null));
if (readCount == 1024)
{
byteAll.AddRange(hasRead);
}
else
{
byte[] canbeAddBytes = hasRead.Take(readCount).ToArray();
byteAll.AddRange(canbeAddBytes);
}
} while (readCount != 0 && read <= DownloadBytesCount.TotalBytesToReceive);
}
catch (TaskCanceledException)
{
return read;
}
return read;
}
/// <summary>
/// 分析下载的资源大小,按照规则分配下载的策略
/// </summary>
/// <param name="uri"></param>
/// <returns></returns>
private async Task<long> GetTotalBytes(Uri uri)
{
request = new HttpRequestMessage(HttpMethod.Get, uri);
request.Headers.Range = new RangeHeaderValue(0, 0);
response = await hc.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, cts.Token);
if (response.Content.Headers.ContentRange != null)
DownloadBytesCount.TotalBytesToReceive = response.Content.Headers.ContentRange.Length.Value;
else
{
isRange = false;
return DownloadBytesCount.TotalBytesToReceive = response.Content.Headers.ContentLength.Value;
}
if (response.Content.Headers.ContentRange.Length.Value > 10000)
{
percentageCoefficient = 100;
progressCoefficient = 1;
}
if (response.Content.Headers.ContentRange.Length.Value > 1000 && response.Content.Headers.ContentRange.Length.Value < 10000)
{
percentageCoefficient = progressCoefficient = 10;
}
if (response.Content.Headers.ContentRange.Length.Value < 1000)
{
percentageCoefficient = 1;
progressCoefficient = 100;
}
percentage = DownloadBytesCount.TotalBytesToReceive / percentageCoefficient;
completePercentage = Convert.ToInt32(DownloadBytesCount.BytesReceived / percentage);
return response.Content.Headers.ContentRange.Length.Value;
}
//0-100 101-200 101得到已下载大小 from 需要 -1,(from - 1)
//0-100 101-200 100得到已下载大小 from 不需要 -1,(from)
private async Task<long> GetTotalBytes(Uri uri, long fromBytes = 0)
{
if (DownloadBytesCount == null)
{
DownloadBytesCount = new DownLoadBytes();
}
request = new HttpRequestMessage(HttpMethod.Get, uri);
request.Headers.Range = new RangeHeaderValue(0, 0);
response = await hc.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, cts.Token);
DownloadBytesCount.TotalBytesToReceive = response.Content.Headers.ContentRange.Length.Value;
if (response.Content.Headers.ContentRange.Length.Value > 10000)
{
percentageCoefficient = 100;
progressCoefficient = 1;
}
if (response.Content.Headers.ContentRange.Length.Value > 1000 && response.Content.Headers.ContentRange.Length.Value < 10000)
{
percentageCoefficient = progressCoefficient = 10;
}
if (response.Content.Headers.ContentRange.Length.Value < 1000)
{
percentageCoefficient = 1;
progressCoefficient = 100;
}
percentage = DownloadBytesCount.TotalBytesToReceive / percentageCoefficient;
//completePercentage = Convert.ToInt32((fromBytes - 1) / percentage);
completePercentage = Convert.ToInt32((fromBytes) / percentage);
DownloadBytesCount.BytesReceived = fromBytes;
return response.Content.Headers.ContentRange.Length.Value;
}
//暂时不实现
private async Task<long> GetTotalBytes(Uri uri, long fromBytes = 0, long toBytes = 0)
{
return 0;
}
//分段设置的方法
private async Task<IRandomAccessStream> DownLoadIRandomAccessStream(Uri uri, long rangeFromValue, long rangeToValue, CancellationToken ct)
{
request = new HttpRequestMessage(HttpMethod.Get, uri);
//var request = new HttpRequestMessage(HttpMethod.Get, uri);
request.Headers.Add("keepAlive", "false");
//request.Headers.Range = new RangeHeaderValue(0, 500);
if (rangeToValue > 0 && rangeToValue > rangeFromValue)
{
request.Headers.Add("Range", "bytes=" + rangeFromValue + "-" + rangeToValue);
}
else
{
request.Headers.Add("Range", "bytes=" + rangeFromValue + "-");
}
response = await hc.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, ct);
//response = await hc.SendAsync(request, HttpCompletionOption.ResponseHeadersRead);
using (Stream responseStream = await response.Content.ReadAsStreamAsync())
{
if (responseStream != null)
{
var randomAccessStream = new InMemoryRandomAccessStream();
var outputStream = randomAccessStream.GetOutputStreamAt(0);
await RandomAccessStream.CopyAsync(responseStream.AsInputStream(), outputStream);
DownloadBytesCount.BytesReceived = Convert.ToInt64(randomAccessStream.Size);
return randomAccessStream as IRandomAccessStream;
}
return null;
}
}
//下载全部
private async Task<IRandomAccessStream> DownLoadIRandomAccessStream(Uri uri, CancellationToken ct)
{
request = new HttpRequestMessage(HttpMethod.Get, uri);
request.Headers.Add("keepAlive", "false");
response = await hc.SendAsync(request, ct);
DownloadBytesCount.TotalBytesToReceive = response.Content.Headers.ContentLength.Value;
byte[] bytes = await response.Content.ReadAsByteArrayAsync();
InMemoryRandomAccessStream randomAccessStream = await ByteToInMemoryRandomAccessStream(bytes);
DownloadBytesCount.BytesReceived = Convert.ToInt64(randomAccessStream.Size);
return randomAccessStream as IRandomAccessStream;
}
public void Dispose()
{
CancelDownload();
hc.Dispose();
}
/// <summary>
/// 暂停下载
/// </summary>
/// <returns></returns>
public async Task<IRandomAccessStream> SuspendDownload()
{
if (!isPause)
{
isPause = true;
CancelDownload();
return (await this.ByteToInMemoryRandomAccessStream(Bytes.ToArray()));
}
return null;
}
/// <summary>
/// 继续下载
/// </summary>
/// <param name="uri"></param>
/// <param name="formBytes"></param>
/// <param name="toBytes"></param>
/// <returns></returns>
public async Task<IRandomAccessStream> ContinueDownload(Uri uri, long fromBytes = 0, long toBytes = 0, byte[] CompletedBytes = null)
{
if (isRange)
{
hc = new HttpClient();
cts = new CancellationTokenSource();
byte[] bytes = null;
if (Bytes == null)
{
Bytes = new List<byte>();
}
Bytes.AddRange(CompletedBytes);
IRandomAccessStream idaStream = null;
try
{
idaStream = await DownLoadIRandomAccessStream(uri, fromBytes, toBytes, cts.Token);
bytes = Combine(idaStream);
TriggerDownLoadComplete(new DownLoadCompleteEventArgs((await this.ByteToInMemoryRandomAccessStream((byte[])bytes.Clone()))));
return (await this.ByteToInMemoryRandomAccessStream(bytes));
}
catch (Exception ex)
{
//return null;
Debug.WriteLine(ex.Message);
return this.ByteToInMemoryRandomAccessStream(bytes).Result;
}
}
return null;
}
/// <summary>
/// 继续下载
/// </summary>
/// <param name="uri"></param>
/// <param name="fromBytes"></param>
/// <returns></returns>
public async Task<IRandomAccessStream> ContinueDownload(Uri uri, long fromBytes = 0, byte[] CompletedBytes = null)
{
if (isRange)
{
hc = new HttpClient();
cts = new CancellationTokenSource();
if (Bytes == null)
{
Bytes = new List<byte>();
}
//防止字节数组传递到事件,修改数组内容,所以拼大数组时,做了一个拷贝浅表副本
Bytes.AddRange((byte[])CompletedBytes.Clone());
byte[] bytes = null;
IRandomAccessStream idaStream = null;
await GetTotalBytes(uri, fromBytes);
TriggerDownLoadChanging(new DownLoadChangingEventArgs(DownloadBytesCount, completePercentage, CompletedBytes));
try
{
//100, 10, 1
for (int i = completePercentage; i < percentageCoefficient; )
{
if (cts.IsCancellationRequested)
{
return (await this.ByteToInMemoryRandomAccessStream(bytes));
}
if (i == 0)
{
idaStream = (await DownLoadIRandomAccessStream(uri, i * percentage, (i + 1) * percentage, cts.Token));
}
else
{
idaStream = (await DownLoadIRandomAccessStream(uri, i * percentage + 1, (i + 1) * percentage, cts.Token));
}
if (idaStream != null)
{
bytes = Combine(idaStream);
DownloadBytesCount.BytesReceived = (i + 1) * percentage;
i++;
TriggerDownLoadChanging(new DownLoadChangingEventArgs(DownloadBytesCount, i * progressCoefficient, bytes));
if (i * progressCoefficient == 100)
{
TriggerDownLoadComplete(new DownLoadCompleteEventArgs((await this.ByteToInMemoryRandomAccessStream(bytes))));
}
}
else
{
return (await this.ByteToInMemoryRandomAccessStream(Bytes.ToArray()));
}
}
return (await this.ByteToInMemoryRandomAccessStream(bytes));
}
catch (Exception ex)
{
Debug.WriteLine(ex.Message);
return this.ByteToInMemoryRandomAccessStream(bytes).Result;
}
}
return null;
}
/// <summary>
/// 继续下载
/// </summary>
/// <param name="uri"></param>
/// <returns></returns>
public async Task<IRandomAccessStream> ContinueDownload(Uri uri)
{
if (isRange)
{
if (isPause)
{
isPause = false;
return (await Download(uri, DownLoadState.Continue));
}
}
else
{
return (await Download(uri, DownLoadState.Start));
}
return null;
}
/// <summary>
/// 取消下载
/// </summary>
public void CancelDownload()
{
cts.Cancel();
cts.Dispose();
request.Dispose();
response.Dispose();
}
/// <summary>
/// 开始下载
/// </summary>
/// <param name="uri"></param>
/// <returns></returns>
public async Task<IRandomAccessStream> StartDownload(Uri uri)
{
isPause = false;
return (await Download(uri));
}
//下载
private async Task<IRandomAccessStream> Download(Uri uri, DownLoadState downLoadState = DownLoadState.Start)
{
hc = new HttpClient();
cts = new CancellationTokenSource();
byte[] bytes = null;
IRandomAccessStream idaStream = null;
if (downLoadState == DownLoadState.Start)
{
DownloadBytesCount = new DownLoadBytes();
Bytes = new List<byte>();
TriggerDownLoadChanging(new DownLoadChangingEventArgs(DownloadBytesCount, 0, bytes));
if (percentage == 0)
{
await GetTotalBytes(uri);
}
}
if (downLoadState == DownLoadState.Continue)
{
await GetTotalBytes(uri);
}
if (isRange)
{
try
{
//100, 10, 1
for (int i = completePercentage; i < percentageCoefficient; )
{
if (cts.IsCancellationRequested)
{
return (await this.ByteToInMemoryRandomAccessStream(bytes));
}
if (i == 0)
{
idaStream = (await DownLoadIRandomAccessStream(uri, i * percentage, (i + 1) * percentage, cts.Token));
}
else
{
idaStream = (await DownLoadIRandomAccessStream(uri, i * percentage + 1, (i + 1) * percentage, cts.Token));
}
if (idaStream != null)
{
bytes = Combine(idaStream);
DownloadBytesCount.BytesReceived = (i + 1) * percentage;
i++;
TriggerDownLoadChanging(new DownLoadChangingEventArgs(DownloadBytesCount, i * progressCoefficient, bytes));
if (i * progressCoefficient == 100)
{
TriggerDownLoadComplete(new DownLoadCompleteEventArgs((await this.ByteToInMemoryRandomAccessStream(bytes))));
}
}
else
{
return (await this.ByteToInMemoryRandomAccessStream(Bytes.ToArray()));
}
}
return (await this.ByteToInMemoryRandomAccessStream(bytes));
}
catch (Exception ex)
{
Debug.WriteLine(ex.Message);
return this.ByteToInMemoryRandomAccessStream(bytes).Result;
}
}
else
{
idaStream = await DownLoadIRandomAccessStream(uri, 0, -1, cts.Token);
TriggerDownLoadComplete(new DownLoadCompleteEventArgs(idaStream));
return idaStream;
}
}
//合成数据
private byte[] Combine(IRandomAccessStream iRandomAccessStream)
{
Stream stream = WindowsRuntimeStreamExtensions.AsStreamForRead(iRandomAccessStream.GetInputStreamAt(0));
byte[] buffer = new byte[16 * 1024];
using (MemoryStream ms = new MemoryStream())
{
int read;
while ((read = stream.Read(buffer, 0, buffer.Length)) > 0)
{
ms.Write(buffer, 0, read);
}
Bytes.AddRange(ms.ToArray());
return Bytes.ToArray();
}
}
//字节数组转换InMemoryRandomAccessStream数据流
private async Task<InMemoryRandomAccessStream> ByteToInMemoryRandomAccessStream(byte[] bytes)
{
InMemoryRandomAccessStream memoryStream = new InMemoryRandomAccessStream();
DataWriter datawriter = new DataWriter(memoryStream.GetOutputStreamAt(0));
datawriter.WriteBytes(bytes);
await datawriter.StoreAsync();
return memoryStream;
}
}
}