-
Notifications
You must be signed in to change notification settings - Fork 33
/
MultipartBody.cs
199 lines (187 loc) · 7.84 KB
/
MultipartBody.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
// ------------------------------------------------------------------------------
// 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 value = new Part(partName, partValue, contentType, fileName);
if(!_parts.TryAdd(partName, value))
{
_parts[partName] = 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>
/// <returns>The value of the part.</returns>
public T? GetPartValue<T>(string partName)
{
if(string.IsNullOrEmpty(partName))
{
throw new ArgumentNullException(nameof(partName));
}
if(_parts.TryGetValue(partName, out var value))
{
if(value == null)
return default;
return (T)value.Content;
}
return default;
}
/// <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)
{
if(string.IsNullOrEmpty(partName))
{
throw new ArgumentNullException(nameof(partName));
}
return _parts.Remove(partName);
}
private readonly Dictionary<string, Part> _parts = new Dictionary<string, Part>(StringComparer.OrdinalIgnoreCase);
/// <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;
}
}