-
-
Notifications
You must be signed in to change notification settings - Fork 49
Expand file tree
/
Copy pathHttpClientDownloadWithProgress.cs
More file actions
210 lines (194 loc) · 8.71 KB
/
Copy pathHttpClientDownloadWithProgress.cs
File metadata and controls
210 lines (194 loc) · 8.71 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
using gamevault.Models;
using gamevault.UserControls;
using gamevault.ViewModels;
using LiveChartsCore.Kernel;
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.Tasks;
namespace gamevault.Helper
{
public class HttpClientDownloadWithProgress
{
private readonly string DownloadUrl;
private readonly string DestinationFolderPath;
private string FileName;
private string FallbackFileName;
private Dictionary<string, string>? AdditionalHeader;
private bool Cancelled = false;
private bool Paused = false;
private long ResumePosition = -1;
private long PreResumeSize = -1;
private DateTime LastTime;
public delegate void ProgressChangedHandler(long totalFileSize, long currentBytesDownloaded, long totalBytesDownloaded, double? progressPercentage, long resumePosition);
public event ProgressChangedHandler ProgressChanged;
public HttpClientDownloadWithProgress(string downloadUrl, string destinationFolderPath, string fallbackFileName, Dictionary<string, string>? additionalHeader = null)
{
DownloadUrl = downloadUrl;
DestinationFolderPath = destinationFolderPath;
FallbackFileName = fallbackFileName;
AdditionalHeader = additionalHeader;
}
public async Task StartDownload(bool tryResume = false)
{
if (tryResume)
{
InitResume();
}
else
{
//Edge case where the Library download overrrides the current download. But if its was a paused download, we also have to reset the metadata
if (File.Exists($"{DestinationFolderPath}\\gamevault-metadata"))
File.Delete($"{DestinationFolderPath}\\gamevault-metadata");
}
using (HttpResponseMessage response = await WebHelper.GetAsync(DownloadUrl, AdditionalHeader, HttpCompletionOption.ResponseHeadersRead))
await DownloadFileFromHttpResponseMessage(response);
}
private void InitResume()
{
string resumeData = Preferences.Get(AppConfigKey.DownloadProgress, $"{DestinationFolderPath}\\gamevault-metadata");
if (!string.IsNullOrEmpty(resumeData))
{
try
{
string[] resumeDataToProcess = resumeData.Split(";");
ResumePosition = long.Parse(resumeDataToProcess[0]);
PreResumeSize = long.Parse(resumeDataToProcess[1]);
if (AdditionalHeader == null)
{
AdditionalHeader = new Dictionary<string, string>();
}
AdditionalHeader?.Add("Range", $"bytes={ResumePosition}-");
}
catch { }
}
}
private async Task DownloadFileFromHttpResponseMessage(HttpResponseMessage response)
{
try
{
FileName = response.Content.Headers.ContentDisposition.FileName.Replace("\"", "");
if (string.IsNullOrEmpty(FileName))
{
throw new Exception("Missing response header (Content-Disposition)");
}
}
catch
{
FileName = FallbackFileName;
}
var responseContentLength = response.Content.Headers.ContentLength;
if (responseContentLength == null || responseContentLength == 0)
{
if (response.Headers.TryGetValues("X-Download-Size", out var headerValues) && long.TryParse(headerValues.First(), out long length))
{
responseContentLength = length;
}
else
{
throw new Exception("Missing response header (Content-Length/X-Download-Size)");
}
}
using (var contentStream = await response.Content.ReadAsStreamAsync())
await ProcessContentStream(responseContentLength.Value, contentStream);
}
private async Task ProcessContentStream(long currentDownloadSize, Stream contentStream)
{
long currentBytesRead = 0;
byte[] buffer = new byte[8192];
bool isMoreToRead = true;
LastTime = DateTime.Now;
string fullFilePath = $"{DestinationFolderPath}\\{FileName}";
using (var fileStream = new FileStream(fullFilePath, ResumePosition == -1 ? FileMode.Create : FileMode.Open, FileAccess.Write, FileShare.None, 8192, true))
{
try
{
if (ResumePosition != -1)
{
fileStream.Position = ResumePosition;
}
do
{
if (Cancelled)
{
if (Paused)
{
Preferences.Set(AppConfigKey.DownloadProgress, $"{fileStream.Position};{(PreResumeSize == -1 ? currentDownloadSize : PreResumeSize)}", $"{DestinationFolderPath}\\gamevault-metadata");
TriggerProgressChanged(currentDownloadSize, 0, fileStream.Position);
fileStream.Close();
return;
}
fileStream.Close();
try
{
await Task.Delay(1000);
File.Delete($"{DestinationFolderPath}\\gamevault-metadata");
File.Delete(fullFilePath);
}
catch { }
return;
}
var bytesRead = await contentStream.ReadAsync(buffer, 0, buffer.Length);
if (bytesRead == 0)
{
isMoreToRead = false;
TriggerProgressChanged(currentDownloadSize, currentBytesRead, fileStream.Position);
fileStream.Close();
continue;
}
await fileStream.WriteAsync(buffer, 0, bytesRead);
currentBytesRead += bytesRead;
if ((DateTime.Now - LastTime).TotalMilliseconds > 2000)
{
//Save checkpoints all two seconds in case the app is closed by the user, or hardly crashed
Preferences.Set(AppConfigKey.DownloadProgress, $"{fileStream.Position};{(PreResumeSize == -1 ? currentDownloadSize : PreResumeSize)}", $"{DestinationFolderPath}\\gamevault-metadata");
TriggerProgressChanged(currentDownloadSize, currentBytesRead, fileStream.Position);
LastTime = DateTime.Now;
}
}
while (isMoreToRead);
}
catch (Exception ex)//On exception try to save the download progress and forward the exception
{
if (currentBytesRead > 0)
{
Preferences.Set(AppConfigKey.DownloadProgress, $"{fileStream.Position};{(PreResumeSize == -1 ? currentDownloadSize : PreResumeSize)}", $"{DestinationFolderPath}\\gamevault-metadata");
}
throw;
}
}
}
private void TriggerProgressChanged(long totalDownloadSize, long currentBytesRead, long totalBytesRead)
{
if (ProgressChanged == null)
return;
totalDownloadSize = PreResumeSize == -1 ? totalDownloadSize : PreResumeSize;
double progressPercentage = (double)totalBytesRead / totalDownloadSize * 100;
ProgressChanged(totalDownloadSize, currentBytesRead, totalBytesRead, progressPercentage, ResumePosition);
}
public void Cancel()
{
if (Paused)
{
try
{
File.Delete($"{DestinationFolderPath}\\gamevault-metadata");
File.Delete($"{DestinationFolderPath}\\{FileName}");
}
catch { }
return;
}
Cancelled = true;
}
public void Pause()
{
Paused = true;
Cancelled = true;
}
}
}