-
Notifications
You must be signed in to change notification settings - Fork 1
/
Content.cs
227 lines (164 loc) · 5.87 KB
/
Content.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
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
using System;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;
using Fody;
using Microsoft.IO;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Yove.Http.Exceptions;
namespace Yove.Http;
[ConfigureAwait(false)]
public class Content : IDisposable
{
#region Public
public bool IsDisposed { get; set; }
#endregion
#region Private
private HttpResponse _response { get; }
#endregion
#region Internal
private RecyclableMemoryStreamManager _streamManager = new();
internal RecyclableMemoryStream Stream { get; set; }
#endregion
internal Content(HttpResponse response)
{
_response = response;
}
public async Task<string> ReadAsString()
{
if (IsDisposed)
throw new ObjectDisposedException("Object disposed.");
if (_response.IsEmpytyBody)
throw new HttpResponseException("Content not found.");
else if (_response.ContentLength.HasValue && _response.ContentLength > int.MaxValue)
throw new HttpResponseException("The data array is too large (Use ToFile).");
RecyclableMemoryStream outputStream = await ReadAsStream() as RecyclableMemoryStream;
if (outputStream.Length > int.MaxValue)
{
outputStream.Dispose();
throw new HttpResponseException("The data array is too large (Use ToFile).");
}
byte[] buffer = outputStream.GetBuffer();
return _response.CharacterSet.GetString(buffer, 0, (int)outputStream.Length);
}
public async Task<JToken> ReadAsJson()
{
string body = await ReadAsString();
if (string.IsNullOrEmpty(body))
throw new HttpResponseException("Content not found.");
return JToken.Parse(body);
}
public async Task<T> ReadAsJson<T>()
{
string body = await ReadAsString();
if (string.IsNullOrEmpty(body))
throw new HttpResponseException("Content not found.");
return JsonConvert.DeserializeObject<T>(body);
}
public async Task<byte[]> ReadAsBytes()
{
if (_response.IsEmpytyBody)
throw new HttpResponseException("Content not found.");
if (_response.ContentLength.HasValue && _response.ContentLength > int.MaxValue)
throw new HttpResponseException("The data array is too large (Use ToFile).");
RecyclableMemoryStream outputStream = await ReadAsStream() as RecyclableMemoryStream;
if (outputStream.Length > int.MaxValue)
{
outputStream.Dispose();
throw new HttpResponseException("The data array is too large (Use ToFile).");
}
return outputStream.GetBuffer();
}
public async Task<Stream> ReadAsStream()
{
if (IsDisposed)
throw new ObjectDisposedException("Object disposed.");
if (_response.IsEmpytyBody)
throw new HttpResponseException("Content not found.");
Stream ??= _streamManager.GetStream();
if (Stream.Length == 0)
{
await foreach (Memory<byte> source in _response.GetBodyContent())
await Stream.WriteAsync(source);
}
Stream.Seek(0, SeekOrigin.Begin);
return Stream;
}
public async IAsyncEnumerable<Memory<byte>> ReadAsStreamEnumerable()
{
if (IsDisposed)
throw new ObjectDisposedException("Object disposed.");
if (_response.IsEmpytyBody)
throw new HttpResponseException("Content not found.");
await foreach (Memory<byte> source in _response.GetBodyContent())
yield return source;
}
public async Task<string> ToFile(string filepath)
{
if (string.IsNullOrEmpty(filepath))
throw new NullReferenceException("filepath is null or empty.");
string path = Path.GetDirectoryName(filepath);
string filename = Path.GetFileName(filepath);
return await ToFile(path, filename);
}
public async Task<string> ToFile(string localPath, string filename = null)
{
if (IsDisposed)
throw new ObjectDisposedException("Object disposed.");
if (_response.IsEmpytyBody)
throw new NullReferenceException("Content not found.");
if (string.IsNullOrEmpty(localPath))
throw new NullReferenceException("Path is null or empty.");
if (filename == null)
{
if (_response.Headers["Content-Disposition"] != null)
{
filename = $"{localPath.TrimEnd('/')}/{HttpUtils.Parser("filename=\"", _response.Headers["Content-Disposition"], "\"")}";
}
else
{
filename = Path.GetFileName(new Uri(_response.Address.AbsoluteUri).LocalPath);
if (string.IsNullOrEmpty(filename))
throw new NullReferenceException("Could not find filename.");
}
}
string outputPath = Path.Join(localPath.TrimEnd('/'), filename);
Stream ??= _streamManager.GetStream();
using FileStream fileStream = new(outputPath, FileMode.OpenOrCreate);
if (Stream.Length == 0)
{
await foreach (Memory<byte> source in _response.GetBodyContent())
await fileStream.WriteAsync(source);
}
else
{
Stream.Seek(0, SeekOrigin.Begin);
await Stream.CopyToAsync(fileStream);
}
return outputPath;
}
protected virtual void Dispose(bool disposing)
{
if (!IsDisposed)
{
if (disposing)
{
Stream?.Close();
Stream?.Dispose();
}
_streamManager = null;
Stream = null;
IsDisposed = true;
}
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
~Content()
{
Dispose(false);
}
}