forked from microsoft/kiota-dotnet
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMultipartBody.cs
More file actions
268 lines (249 loc) · 10.2 KB
/
Copy pathMultipartBody.cs
File metadata and controls
268 lines (249 loc) · 10.2 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
// ------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
// ------------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using Microsoft.Kiota.Abstractions.Extensions;
using Microsoft.Kiota.Abstractions.Serialization;
namespace Microsoft.Kiota.Abstractions;
/// <summary>
/// Represents a multipart body for a request or a response.
/// </summary>
public class MultipartBody : IParsable
{
private readonly Lazy<string> _boundary = new Lazy<string>(() => Guid.NewGuid().ToString("N"));
/// <summary>
/// The boundary to use for the multipart body.
/// </summary>
public string Boundary => _boundary.Value;
/// <summary>
/// The request adapter to use for serialization.
/// </summary>
public IRequestAdapter? RequestAdapter { get; set; }
/// <summary>
/// Adds or replaces a part to the multipart body.
/// </summary>
/// <typeparam name="T">The type of the part value.</typeparam>
/// <param name="partName">The name of the part.</param>
/// <param name="contentType">The content type of the part.</param>
/// <param name="partValue">The value of the part.</param>
/// <param name="fileName">An optional file name for the part.</param>
public void AddOrReplacePart<T>(string partName, string contentType, T partValue, string? fileName = null)
{
if(string.IsNullOrEmpty(partName))
{
throw new ArgumentNullException(nameof(partName));
}
if(string.IsNullOrEmpty(contentType))
{
throw new ArgumentNullException(nameof(contentType));
}
if(partValue == null)
{
throw new ArgumentNullException(nameof(partValue));
}
var key = (partName, fileName ?? "");
var value = new Part(partName, partValue, contentType, fileName);
if(!_parts.TryAdd(key, value))
{
_parts[key] = value;
}
}
// TODO: Remove with next major release
/// <summary>
/// Gets the value of a part from the multipart body.
/// </summary>
/// <typeparam name="T">The type of the part value.</typeparam>
/// <param name="partName">The name of the part.</param>
/// <returns>The value of the part.</returns>
public T? GetPartValue<T>(string partName)
{
var value = GetPartValue<T>(partName, null);
if(EqualityComparer<T?>.Default.Equals(value, default))
{
foreach(var key in _parts.Keys)
{
if(key.Item1 == partName)
{
value = GetPartValue<T>(partName, key.Item2);
break;
}
}
}
return value;
}
/// <summary>
/// Gets the value of a part from the multipart body.
/// </summary>
/// <typeparam name="T">The type of the part value.</typeparam>
/// <param name="partName">The name of the part.</param>
/// <param name="fileName">An optional file name for the part.</param>
/// <returns>The value of the part.</returns>
public T? GetPartValue<T>(string partName, string? fileName)
{
if(string.IsNullOrEmpty(partName))
{
throw new ArgumentNullException(nameof(partName));
}
if(_parts.TryGetValue((partName, fileName ?? ""), out var value))
{
if(value == null)
return default;
return (T)value.Content;
}
return default;
}
// TODO: Remove with next major release
/// <summary>
/// Removes a part from the multipart body.
/// </summary>
/// <param name="partName">The name of the part.</param>
/// <returns>True if the part was removed, false otherwise.</returns>
public bool RemovePart(string partName)
{
bool success = RemovePart(partName, null);
if(!success)
{
foreach(var key in _parts.Keys)
{
if(key.Item1 == partName)
{
success = RemovePart(partName, key.Item2);
break;
}
}
}
return success;
}
/// <summary>
/// Removes a part from the multipart body.
/// </summary>
/// <param name="partName">The name of the part.</param>
/// <param name="fileName">An optional file name for the part.</param>
/// <returns>True if the part was removed, false otherwise.</returns>
public bool RemovePart(string partName, string? fileName)
{
if(string.IsNullOrEmpty(partName))
{
throw new ArgumentNullException(nameof(partName));
}
return _parts.Remove((partName, fileName ?? ""));
}
private readonly Dictionary<ValueTuple<string, string>, Part> _parts = new Dictionary<ValueTuple<string, string>, Part>(new ValueTupleComparer());
/// <inheritdoc />
public IDictionary<string, Action<IParseNode>> GetFieldDeserializers() => throw new NotImplementedException();
private const char DoubleQuote = '"';
/// <inheritdoc />
public void Serialize(ISerializationWriter writer)
{
if(writer == null)
{
throw new ArgumentNullException(nameof(writer));
}
if(RequestAdapter?.SerializationWriterFactory == null)
{
throw new InvalidOperationException(nameof(RequestAdapter.SerializationWriterFactory));
}
if(_parts.Count == 0)
{
throw new InvalidOperationException("No parts to serialize");
}
var first = true;
var contentDispositionBuilder = new StringBuilder();
foreach(var part in _parts.Values)
{
try
{
if(first)
first = false;
else
AddNewLine(writer);
writer.WriteStringValue(string.Empty, $"--{Boundary}");
writer.WriteStringValue("Content-Type", part.ContentType);
contentDispositionBuilder.Clear();
contentDispositionBuilder.Append("form-data; name=\"");
contentDispositionBuilder.Append(part.Name);
contentDispositionBuilder.Append(DoubleQuote);
if(part.FileName != null)
{
contentDispositionBuilder.Append("; filename=\"");
contentDispositionBuilder.Append(part.FileName);
contentDispositionBuilder.Append(DoubleQuote);
}
writer.WriteStringValue("Content-Disposition", contentDispositionBuilder.ToString());
AddNewLine(writer);
if(part.Content is IParsable parsable)
{
using var partWriter = RequestAdapter.SerializationWriterFactory.GetSerializationWriter(part.ContentType);
partWriter.WriteObjectValue(string.Empty, parsable);
WriteSerializedContent(writer, partWriter);
}
else if(part.Content is string currentString)
{
using var partWriter = RequestAdapter.SerializationWriterFactory.GetSerializationWriter(part.ContentType);
partWriter.WriteStringValue(string.Empty, currentString);
WriteSerializedContent(writer, partWriter);
}
else if(part.Content is MemoryStream originalMemoryStream)
{
writer.WriteByteArrayValue(string.Empty, originalMemoryStream.ToArray());
}
else if(part.Content is Stream currentStream)
{
if(currentStream.CanSeek)
currentStream.Seek(0, SeekOrigin.Begin);
using var ms = new MemoryStream();
currentStream.CopyTo(ms);
writer.WriteByteArrayValue(string.Empty, ms.ToArray());
}
else if(part.Content is byte[] currentBinary)
{
writer.WriteByteArrayValue(string.Empty, currentBinary);
}
else
{
throw new InvalidOperationException($"Unsupported type {part.Content.GetType().Name} for part {part.Name}");
}
}
catch(InvalidOperationException) when(part?.Content is byte[] currentBinary)
{ // binary payload
writer.WriteByteArrayValue(part.Name, currentBinary);
}
}
AddNewLine(writer);
writer.WriteStringValue(string.Empty, $"--{Boundary}--");
}
private static void AddNewLine(ISerializationWriter writer) => writer.WriteStringValue(string.Empty, string.Empty);
private static void WriteSerializedContent(ISerializationWriter writer, ISerializationWriter partWriter)
{
using var partContent = partWriter.GetSerializedContent();
if(partContent.CanSeek)
partContent.Seek(0, SeekOrigin.Begin);
using var ms = new MemoryStream();
partContent.CopyTo(ms);
writer.WriteByteArrayValue(string.Empty, ms.ToArray());
}
private sealed class Part(string name, object content, string contentType, string? fileName)
{
public string Name { get; } = name;
public object Content { get; } = content;
public string ContentType { get; } = contentType;
public string? FileName { get; } = fileName;
}
private sealed class ValueTupleComparer : IEqualityComparer<ValueTuple<string, string>>
{
public bool Equals((string, string) x, (string, string) y)
{
return StringComparer.Ordinal.Equals(x.Item1, y.Item1) &&
StringComparer.Ordinal.Equals(x.Item2, y.Item2);
}
public int GetHashCode(ValueTuple<string, string?> obj)
{
int hash1 = StringComparer.Ordinal.GetHashCode(obj.Item1);
int hash2 = obj.Item2 != null ? StringComparer.Ordinal.GetHashCode(obj.Item2) : 0;
return hash1 ^ hash2;
}
}
}