Skip to content

Commit a9d1cc3

Browse files
committed
Fix the access to a property, Improve the download efficient
1 parent 184b1cf commit a9d1cc3

3 files changed

Lines changed: 33 additions & 33 deletions

File tree

WebUntisAPI.Client/Models/Messages/Attachment.cs

Lines changed: 24 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -34,15 +34,16 @@ public struct Attachment
3434
/// <summary>
3535
/// Get the content of the attachment as stream with a progress report
3636
/// </summary>
37-
/// <param name="client">The client with them you got this instane (It doesn't have to be the same client but the same account)</param>
38-
/// <param name="timeout">The time after that the download of the content will cancelled (In miliseconds)</param>
37+
/// <param name="client">The client with them you got this instance (It doesn't have to be the same client but the same account)</param>
38+
/// <param name="targetStream">The stream to write the download to</param>
39+
/// <param name="timeout">The time after that the download of the content will cancelled (In milliseconds)</param>
3940
/// <param name="progress">The progress of the download in percent</param>
4041
/// <param name="ct">Cancellation token</param>
4142
/// <returns>The attachment as stream</returns>
4243
/// <exception cref="ObjectDisposedException">Thrown when the instance was disposed</exception>
4344
/// <exception cref="UnauthorizedAccessException">Thrown when you're logged in</exception>
4445
/// <exception cref="HttpRequestException">Thrown when an error happened while the http request</exception>
45-
public async Task<Stream> DownloadContentAsStreamAsync(WebUntisClient client, TimeSpan timeout, IProgress<double> progress = null, CancellationToken ct = default)
46+
public async Task DownloadContentAsStreamAsync(WebUntisClient client, Stream targetStream, TimeSpan timeout, IProgress<double> progress = null, CancellationToken ct = default)
4647
{
4748
string storageResponseString = await client.MakeAPIGetRequestAsync($"/WebUntis/api/rest/view/v1/messages/{Id}/attachmentstorageurl", ct);
4849

@@ -69,41 +70,33 @@ public async Task<Stream> DownloadContentAsStreamAsync(WebUntisClient client, Ti
6970
downloadClient.Timeout = timeout;
7071
HttpResponseMessage response = await downloadClient.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, ct);
7172

72-
using (MemoryStream content = new MemoryStream())
73+
using (Stream contentStream = await response.Content.ReadAsStreamAsync())
7374
{
74-
using (Stream contentStream = await response.Content.ReadAsStreamAsync())
75-
{
76-
int totalBytes = (int?)response.Content.Headers.ContentLength ?? -1;
77-
int totalRecievedBytes = 0;
75+
int totalBytes = (int?)response.Content.Headers.ContentLength ?? -1;
76+
int totalReceivedBytes = 0;
7877

79-
int bytesRead = 0;
80-
byte[] buffer = new byte[8192];
81-
while ((bytesRead = await contentStream.ReadAsync(buffer, 0, buffer.Length, ct)) > 0)
82-
{
83-
if (ct.IsCancellationRequested)
84-
return default;
78+
int bytesRead = 0;
79+
byte[] buffer = new byte[4096];
80+
while ((bytesRead = await contentStream.ReadAsync(buffer, 0, buffer.Length, ct)) > 0)
81+
{
82+
if (ct.IsCancellationRequested)
83+
return;
8584

86-
content.Write(buffer, 0, bytesRead);
87-
totalRecievedBytes += bytesRead;
88-
progress?.Report((double)totalRecievedBytes / totalBytes * 100d);
89-
}
85+
targetStream.Write(buffer, 0, bytesRead);
86+
totalReceivedBytes += bytesRead;
87+
progress?.Report((double)totalReceivedBytes / totalBytes * 100d);
9088
}
89+
}
9190

92-
if (ct.IsCancellationRequested)
93-
return default;
91+
if (ct.IsCancellationRequested)
92+
return;
9493

95-
// Verify response
96-
if (response.StatusCode == HttpStatusCode.Unauthorized || response.StatusCode == HttpStatusCode.Forbidden)
97-
{
98-
string detail = Regex.Match(Encoding.UTF8.GetString(content.ToArray()), @"<Message>([a-zA-z0-9\s]+)</Message>").Groups[1].Value; // Get the error message
99-
throw new UnauthorizedAccessException($"Invalid authentication. Detail: {detail}");
100-
}
101-
102-
if (response.StatusCode != HttpStatusCode.OK)
103-
throw new HttpRequestException($"There was an error while the http request (Code: {response.StatusCode}).");
94+
// Verify response
95+
if (response.StatusCode == HttpStatusCode.Unauthorized || response.StatusCode == HttpStatusCode.Forbidden)
96+
throw new UnauthorizedAccessException($"Invalid authentication.");
10497

105-
return content;
106-
}
98+
if (response.StatusCode != HttpStatusCode.OK)
99+
throw new HttpRequestException($"There was an error while the http request (Code: {response.StatusCode}).");
107100
}
108101
}
109102
}

WebUntisAPI.Client/Models/Messages/MessagePreview.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -53,7 +53,7 @@ public class MessagePreview
5353
/// </summary>
5454
[JsonProperty("sentDateTime")]
5555
[JsonConverter(typeof(APIDateTimeJsonConverter))]
56-
DateTime SentTime { get; set; }
56+
public DateTime SentTime { get; set; }
5757

5858
/// <summary>
5959
/// Is allowed to delete the message

WebUntisAPI.Client/WebUntisClient.Messages.cs

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -167,7 +167,14 @@ public async Task<MessagePreview> SendMessageAsync(Draft draft, MessagePerson[]
167167
Dictionary<string, Task<Stream>> attachmentTasks = new Dictionary<string, Task<Stream>>();
168168

169169
foreach (Attachment attachment in draft.Attachments)
170-
attachmentTasks.Add(attachment.Name, attachment.DownloadContentAsStreamAsync(this, timeout, ct: ct));
170+
{
171+
attachmentTasks.Add(attachment.Name, Task.Run(async () =>
172+
{
173+
Stream stream = new MemoryStream();
174+
await attachment.DownloadContentAsStreamAsync(this, stream, timeout, ct: ct);
175+
return stream;
176+
}));
177+
}
171178

172179
await Task.WhenAll(attachmentTasks.Values);
173180
attachments = attachmentTasks.Select(attachment => new Tuple<string, Stream>(attachment.Key, attachment.Value.Result)).ToArray();

0 commit comments

Comments
 (0)