-
Notifications
You must be signed in to change notification settings - Fork 76
/
Copy pathUPnPAction.cs
358 lines (301 loc) · 10.6 KB
/
UPnPAction.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
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
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
using System;
using System.IO;
using System.Collections.Generic;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
namespace Waher.Networking.UPnP
{
/// <summary>
/// Contains information about an action.
/// </summary>
public class UPnPAction
{
private readonly Dictionary<string, UPnPArgument> argumentByName = new Dictionary<string, UPnPArgument>();
private readonly ServiceDescriptionDocument parent;
private readonly XmlElement xml;
private readonly UPnPArgument[] arguments;
private readonly string name;
internal UPnPAction(XmlElement Xml, ServiceDescriptionDocument Parent)
{
List<UPnPArgument> Arguments = new List<UPnPArgument>();
this.parent = Parent;
this.xml = Xml;
foreach (XmlNode N in Xml.ChildNodes)
{
switch (N.LocalName)
{
case "name":
this.name = N.InnerText;
break;
case "argumentList":
foreach (XmlNode N2 in N.ChildNodes)
{
if (N2.LocalName == "argument")
{
UPnPArgument Argument = new UPnPArgument((XmlElement)N2);
Arguments.Add(Argument);
this.argumentByName[Argument.Name] = Argument;
}
}
break;
}
}
this.arguments = Arguments.ToArray();
}
/// <summary>
/// Underlying XML definition.
/// </summary>
public XmlElement Xml => this.xml;
/// <summary>
/// Action Name
/// </summary>
public string Name => this.name;
/// <summary>
/// Service Arguments.
/// </summary>
public UPnPArgument[] Arguments => this.arguments;
/// <summary>
/// Parent Service Description Document object.
/// </summary>
public ServiceDescriptionDocument ServiceDescriptionDocument => this.parent;
/// <summary>
/// Invokes the action.
/// </summary>
/// <param name="InputValues">Input values.</param>
/// <param name="OutputValues">Any Output values found in response.</param>
/// <returns>Return value, if any, null otherwise.</returns>
public object Invoke(out Dictionary<string, object> OutputValues, params KeyValuePair<string, object>[] InputValues)
{
return this.Invoke(out OutputValues, 10000, InputValues);
}
/// <summary>
/// Invokes the action.
/// </summary>
/// <param name="InputValues">Input values.</param>
/// <param name="OutputValues">Any Output values found in response.</param>
/// <returns>Return value, if any, null otherwise.</returns>
public object Invoke(Dictionary<string, object> InputValues, out Dictionary<string, object> OutputValues)
{
return this.Invoke(InputValues, out OutputValues, 10000);
}
/// <summary>
/// Invokes the action.
/// </summary>
/// <param name="InputValues">Input values.</param>
/// <param name="OutputValues">Any Output values found in response.</param>
/// <param name="Timeout">Timeout, in milliseconds.</param>
/// <returns>Return value, if any, null otherwise.</returns>
public object Invoke(out Dictionary<string, object> OutputValues, int Timeout, params KeyValuePair<string, object>[] InputValues)
{
Dictionary<string, object> InputValues2 = new Dictionary<string, object>();
foreach (KeyValuePair<string, object> P in InputValues)
InputValues2[P.Key] = P.Value;
return this.Invoke(InputValues2, out OutputValues, Timeout);
}
/// <summary>
/// Invokes the action.
/// </summary>
/// <param name="InputValues">Input values.</param>
/// <param name="OutputValues">Any Output values found in response.</param>
/// <param name="Timeout">Timeout, in milliseconds.</param>
/// <returns>Return value, if any, null otherwise.</returns>
public object Invoke(Dictionary<string, object> InputValues, out Dictionary<string, object> OutputValues, int Timeout)
{
KeyValuePair<object, Dictionary<string, object>> Result = this.InvokeAsync(InputValues, Timeout).Result;
OutputValues = Result.Value;
return Result.Key;
}
/// <summary>
/// Invokes the action.
/// </summary>
/// <param name="InputValues">Input values.</param>
/// <param name="Timeout">Timeout, in milliseconds.</param>
/// <returns>Return value, if any, null otherwise, together with any output values found in response.</returns>
public Task<KeyValuePair<object, Dictionary<string, object>>> InvokeAsync(int Timeout, params KeyValuePair<string, object>[] InputValues)
{
Dictionary<string, object> InputValues2 = new Dictionary<string, object>();
foreach (KeyValuePair<string, object> P in InputValues)
InputValues2[P.Key] = P.Value;
return this.InvokeAsync(InputValues2, Timeout);
}
/// <summary>
/// Invokes the action.
/// </summary>
/// <param name="InputValues">Input values.</param>
/// <param name="Timeout">Timeout, in milliseconds.</param>
/// <returns>Return value, if any, null otherwise, together with any output values found in response.</returns>
public async Task<KeyValuePair<object, Dictionary<string, object>>> InvokeAsync(Dictionary<string, object> InputValues, int Timeout)
{
Dictionary<string, object> OutputValues;
StringBuilder Soap = new StringBuilder();
UPnPStateVariable Variable;
object Result = null;
object First = null;
Soap.AppendLine("<?xml version=\"1.0\"?>");
Soap.AppendLine("<s:Envelope xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\" s:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\">");
Soap.AppendLine("<s:Body>");
Soap.Append("<u:");
Soap.Append(this.name);
Soap.Append(" xmlns:u=\"");
Soap.Append(XmlAttributeEncode(this.parent.Service.ServiceType));
Soap.AppendLine("\">");
foreach (UPnPArgument Argument in this.arguments)
{
if (Argument.Direction == ArgumentDirection.In)
{
Soap.Append("<");
Soap.Append(Argument.Name);
Soap.Append(">");
if (InputValues.TryGetValue(Argument.Name, out object Value) &&
!((Variable = this.parent.GetVariable(Argument.RelatedStateVariable)) is null))
{
Soap.Append(XmlAttributeEncode(await Variable.ValueToXmlString(Value)));
}
Soap.Append("</");
Soap.Append(Argument.Name);
Soap.Append(">");
}
}
Soap.Append("</u:");
Soap.Append(this.name);
Soap.AppendLine(">");
Soap.AppendLine("</s:Body>");
Soap.AppendLine("</s:Envelope>");
using (HttpClient HttpClient = new HttpClient())
{
HttpClient.Timeout = TimeSpan.FromMilliseconds(Timeout);
HttpClient.DefaultRequestHeaders.ExpectContinue = false;
HttpContent Body = new StringContent(Soap.ToString(), Encoding.UTF8, "text/xml");
Body.Headers.Add("SOAPACTION", "\"" + this.parent.Service.ServiceType + "#" + this.name + "\"");
XmlDocument ResponseXml;
HttpResponseMessage Response = await HttpClient.PostAsync(this.parent.Service.ControlURI, Body);
Stream Stream = await Response.Content.ReadAsStreamAsync(); // Regardless of status code, we check for XML content.
ResponseXml = new XmlDocument()
{
PreserveWhitespace = true
};
ResponseXml.Load(Stream);
if (ResponseXml.DocumentElement is null ||
ResponseXml.DocumentElement.LocalName != "Envelope" ||
ResponseXml.DocumentElement.NamespaceURI != "http://schemas.xmlsoap.org/soap/envelope/")
{
throw new Exception("Unexpected response returned.");
}
XmlElement ResponseBody = GetChildElement(ResponseXml.DocumentElement, "Body", "http://schemas.xmlsoap.org/soap/envelope/")
?? throw new Exception("Response body not found.");
XmlElement ActionResponse = GetChildElement(ResponseBody, this.name + "Response", this.parent.Service.ServiceType);
if (ActionResponse is null)
{
XmlElement ResponseFault = GetChildElement(ResponseBody, "Fault", "http://schemas.xmlsoap.org/soap/envelope/")
?? throw new Exception("Unable to parse response.");
string FaultCode = string.Empty;
string FaultString = string.Empty;
string UPnPErrorCode = string.Empty;
string UPnPErrorDescription = string.Empty;
foreach (XmlNode N in ResponseFault.ChildNodes)
{
switch (N.LocalName)
{
case "faultcode":
FaultCode = N.InnerText;
break;
case "faultstring":
FaultString = N.InnerText;
break;
case "detail":
foreach (XmlNode N2 in N.ChildNodes)
{
switch (N2.LocalName)
{
case "UPnPError":
foreach (XmlNode N3 in N2.ChildNodes)
{
switch (N3.LocalName)
{
case "errorCode":
UPnPErrorCode = N3.InnerText;
break;
case "errorDescription":
UPnPErrorDescription = N3.InnerText;
break;
}
}
break;
}
}
break;
}
}
throw new UPnPException(FaultCode, FaultString, UPnPErrorCode, UPnPErrorDescription);
}
XmlElement E;
OutputValues = new Dictionary<string, object>();
foreach (XmlNode N in ActionResponse.ChildNodes)
{
E = N as XmlElement;
if (E is null)
continue;
if (this.argumentByName.TryGetValue(E.LocalName, out UPnPArgument Argument2))
{
if (!((Variable = this.parent.GetVariable(Argument2.RelatedStateVariable)) is null))
{
object Value2 = Variable.XmlStringToValue(E.InnerText);
OutputValues[E.LocalName] = Value2;
if (First is null)
First = Value2;
if (Argument2.ReturnValue && Result is null)
Result = Value2;
}
else
{
if (First is null)
First = E.InnerXml;
OutputValues[E.LocalName] = E.InnerXml;
}
}
else
{
if (First is null)
First = E.InnerXml;
OutputValues[E.LocalName] = E.InnerXml;
}
}
}
if (Result is null)
Result = First;
return new KeyValuePair<object, Dictionary<string, object>>(Result, OutputValues);
}
private static XmlElement GetChildElement(XmlElement E, string LocalName, string Namespace)
{
XmlElement E2;
foreach (XmlNode N in E.ChildNodes)
{
E2 = N as XmlElement;
if (E2 is null)
continue;
if (E2.LocalName == LocalName && E2.NamespaceURI == Namespace)
return E2;
}
return null;
}
/// <summary>
/// Encodes an XML attribute.
/// </summary>
/// <param name="AttributeValue">Attribute value.</param>
/// <returns>Encoded attribute value.</returns>
public static string XmlAttributeEncode(string AttributeValue)
{
if (AttributeValue is null || AttributeValue.IndexOfAny(reservedCharacters) < 0)
return AttributeValue;
return AttributeValue.
Replace("&", "&").
Replace("<", "<").
Replace(">", ">").
Replace("\"", """).
Replace("'", "'");
}
private static readonly char[] reservedCharacters = new char[] { '&', '<', '>', '"', '\'' };
}
}