-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathUPnP.cs
615 lines (560 loc) · 31.8 KB
/
UPnP.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
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.Net.Sockets;
using System.Net;
using System.Net.NetworkInformation;
using System.Xml;
using System.IO;
using System.Linq;
using System.Web;
using System.Xml.Linq; // Be sure to set "Target framework:" to non-client, e.g. framework 4.0.
namespace UPnP
{
/// <summary>
/// The Discovery class does the UDP broadcast and holds the Sonos topology info in various dictionaries.
/// </summary>
public class Discovery
{
// Discovery parameter that may need to be changed.
static TimeSpan _timeout = new TimeSpan(0, 0, 0, 5); // fourth parameter is seconds
static string _broadcastIP = "239.255.255.250";
static int _broadcastPort = 1900;
static string _searchTarget = "upnp:rootdevice";
// Define properties and backing objects.
public TimeSpan TimeOut
{ get { return _timeout; } set { _timeout = value; } }
static public Dictionary<string, string> ZoneTable
{ get { return _zoneTable; } set { _zoneTable = value; } }
static public Dictionary<string, string> ZoneTypes
{ get { return _zoneTypes; } set { _zoneTypes = value; } }
static public Dictionary<string, string> ZoneIDs
{ get { return _zoneIDs; } set { _zoneIDs = value; } }
static public Dictionary<string, bool> ZoneMasters
{ get { return _zoneMasters; } set { _zoneMasters = value; } }
static public ArrayList Zones
{ get { return _zones; } set { _zones = value; } }
static ArrayList _zones = new ArrayList();
static Dictionary<string, string> _zoneTable = new Dictionary<string, string>();
static Dictionary<string, string> _zoneTypes = new Dictionary<string, string>();
static Dictionary<string, string> _zoneIDs = new Dictionary<string, string>();
static Dictionary<string, bool> _zoneMasters = new Dictionary<string, bool>();
/// <summary>
/// Sends a UDP package over the specified broadcast IP and port and waits for responses.
/// Some background: http://www.upnp-hacks.org/upnp.html, http://upnp.org/specs/arch/UPnP-arch-DeviceArchitecture-v1.0.pdf
/// Refactored May 2016 Chris Fox, using code/structures from DeviceSpy - see http://www.meshcommander.com/upnptools
/// </summary>
///
public void Discover() // this cannot be a static class because it uses async callbacks
{
// create the discovery message to broadcast..
HTTPMessage request = new HTTPMessage();
IPEndPoint RemoteEP = new IPEndPoint(IPAddress.Parse(_broadcastIP), _broadcastPort);
request.Directive = "M-SEARCH";
request.DirectiveObj = "*";
request.AddTag("ST", _searchTarget);
request.AddTag("MX", "2");
request.AddTag("MAN", "\"ssdp:discover\"");
request.AddTag("HOST", RemoteEP.ToString()); // "239.255.255.250:1900"
byte[] buffer = UTF8Encoding.UTF8.GetBytes(request.StringPacket);
// get the local network interfaces... we will braodcast and receive responses on each interface we find...
ArrayList AddressTable = new ArrayList();
Hashtable Sessions = new Hashtable(); // used to keep track of reponses
NetworkInterface[] interfaces = NetworkInterface.GetAllNetworkInterfaces();
foreach (NetworkInterface i in interfaces)
{
if (i.IsReceiveOnly == false && i.OperationalStatus == OperationalStatus.Up && i.SupportsMulticast == true)
{
IPInterfaceProperties i2 = i.GetIPProperties();
foreach (UnicastIPAddressInformation i3 in i2.UnicastAddresses)
{
if (!AddressTable.Contains(i3.Address) &&
!i3.Address.Equals(IPAddress.IPv6Loopback) &&
!i3.Address.Equals(IPAddress.Loopback))
{
AddressTable.Add(i3.Address);
}
}
}
}
// AddressTable now contains a list of non-loopback network interfaces that are up
//Now broadcast via each of them..
foreach (IPAddress localaddr in AddressTable)
{
// set up a listener...
// Look up in Sessions keyed by local addr - if not found, create and add
UdpClient cl = (UdpClient)Sessions[localaddr]; // get previusly-used client
if (cl == null)
{
cl = new UdpClient(new IPEndPoint(localaddr, 0)); // make a new one - bound to local address and random port
cl.EnableBroadcast = true;
cl.BeginReceive(new AsyncCallback(OnReceive), cl); // set up an async receive, pass in the UDP Client details
Sessions[localaddr] = cl;
}
if (RemoteEP.AddressFamily != cl.Client.AddressFamily) continue;
if ((RemoteEP.AddressFamily == AddressFamily.InterNetworkV6) && ((IPEndPoint)cl.Client.LocalEndPoint).Address.IsIPv6LinkLocal == true && RemoteEP != OpenSource.UPnP.Utils.UpnpMulticastV6EndPoint2) continue;
if ((RemoteEP.AddressFamily == AddressFamily.InterNetworkV6) && ((IPEndPoint)cl.Client.LocalEndPoint).Address.IsIPv6LinkLocal == false && RemoteEP != OpenSource.UPnP.Utils.UpnpMulticastV6EndPoint1) continue;
IPEndPoint lep = (IPEndPoint)cl.Client.LocalEndPoint;
if (cl.Client.AddressFamily == AddressFamily.InterNetwork)
{
cl.Client.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.MulticastInterface, localaddr.GetAddressBytes());
}
else if (cl.Client.AddressFamily == AddressFamily.InterNetworkV6)
{
cl.Client.SetSocketOption(SocketOptionLevel.IPv6, SocketOptionName.MulticastInterface, BitConverter.GetBytes((int)localaddr.ScopeId));
}
cl.Send(buffer, buffer.Length, RemoteEP); // and do the broadcast
}
// now wait a little while for the replies to come back...
System.Threading.Thread.Sleep(_timeout);
} // Discover
public void OnReceive(IAsyncResult ar)
// a reply has arrived...
{
UdpClient client = (UdpClient)ar.AsyncState;
IPEndPoint ep = null;
byte[] buf = client.EndReceive(ar, ref ep); // get the response
if (buf != null)
{
client.BeginReceive(new AsyncCallback(OnReceive), client); // set up for another message to arrive
try
{
HTTPMessage msg = HTTPMessage.ParseByteArray(buf, 0, buf.Length);
// here filter to replies containing 'sonos' and add to zones..
if (msg.StringPacket.ToLower().Contains("sonos"))
{
string loc = msg.GetTag("Location");
if (!_zones.Contains(loc))
{
_zones.Add(loc);
_zoneTable.Add(loc, ""); // Will fill in zone friendly name later.
}
}
}
catch
{
// a problem dealing with the reply message, so ignore it
}
return;
}
} // OnReceive
} // Dscovery
/// <summary>
/// The QueryDevice class does the following:
/// 1. Queries (SOAP) zone attributes to get zone friendly name.
/// 2. Queries (HTTP) zone player xml to get zone type and ID.
/// 3. Queries (SOAP) zone transports to see if zone is a master.
/// 4. Queries (SOAP) zone content directory to get playlist list.
/// 5. Queries (SOAP) zone content directory to get one playlist's content or a count of items.
/// 6.
/// </summary>
public static class QueryDevice
{
// Properties and backing objects.
public static Dictionary<string, string> Playlists
{ get { return _playlists; } set { _playlists = value; } }
public enum PlaylistAction { Count, Save };
static public Dictionary<string, string> _playlists = new Dictionary<string, string>();
static int _maxPlaylistPagingResults = 100;
static int _maxPlaylistsReturned = 100;
/// <summary>
/// Get attributes for each zone in the Sonos topology.
/// </summary>
public static void QueryZoneAttributes()
{
if (UPnP.Discovery.ZoneTable.Count > 0)
{
foreach (string zone in UPnP.Discovery.Zones)
{
// Query to get zone attributes.
string path = "/DeviceProperties/Control";
Uri uri = new Uri(zone);
string host = uri.Scheme + "://" + uri.Host + ":" + uri.Port.ToString();
string soapAction = "urn:upnp-org:serviceId:DeviceProperties#GetZoneAttributes";
string soapBody = "<u:GetZoneAttributes xmlns:u=\"urn:schemas-upnp-org:service:DeviceProperties:1\">" +
"</u:GetZoneAttributes>";
XmlDocument resp = SOAPRequest(path, host, soapBody, soapAction);
string zoneName = resp.SelectSingleNode("//CurrentZoneName").InnerText;
UPnP.Discovery.ZoneTable[zone] = zoneName;
}
}
}
/// <summary>
/// Gets the zoneplayer xml file to read two pieces of information, the zone ID and type. We
/// could use this xml to figure out the friendly name of the zone but we do that elsewhere.
/// </summary>
public static void QueryZonePlayerXml()
{
if (UPnP.Discovery.ZoneTable.Count > 0)
{
foreach (string zone in UPnP.Discovery.Zones)
{
if (!UPnP.Discovery.ZoneTable[zone].ToLower().Contains("bridge"))
{
string path = "/xml/device_description.xml"; // "/xml/zone_player.xml";
Uri uri = new Uri(zone);
string host = uri.Scheme + "://" + uri.Host + ":" + uri.Port.ToString();
XmlDocument resp = GetWebResponse(path, host);
XmlNamespaceManager nsm = new XmlNamespaceManager(resp.NameTable);
nsm.AddNamespace("zp", "urn:schemas-upnp-org:device-1-0");
string zoneType = resp.SelectSingleNode("//zp:modelNumber", nsm).InnerText;
UPnP.Discovery.ZoneTypes[zone] = zoneType;
string uuid = resp.SelectSingleNode("//zp:UDN", nsm).InnerText;
UPnP.Discovery.ZoneIDs[zone] = uuid.Substring(5, uuid.Length - 5); // need to remove uuid:
}
else
{
UPnP.Discovery.ZoneIDs[zone] = "....";
UPnP.Discovery.ZoneTypes[zone] = "ZoneBridge";
}
}
}
}
/// <summary>
/// Iterates through zones and figures out if the zone is a master.
/// </summary>
public static void FindMasters()
{
if (UPnP.Discovery.ZoneTable.Count > 0)
{
foreach (string zone in UPnP.Discovery.Zones)
{
if (!UPnP.Discovery.ZoneTable[zone].ToLower().Contains("bridge"))
{
try
{
string path = "/MediaRenderer/AVTransport/Control";
Uri uri = new Uri(zone);
string host = uri.Scheme + "://" + uri.Host + ":" + uri.Port.ToString();
string soapAction = "uurn:schemas-upnp-org:service:AVTransport:1#GetPositionInfo";
string soapBody = "<u:GetPositionInfo xmlns:u=\"urn:schemas-upnp-org:service:AVTransport:1\">" +
"<InstanceID>0</InstanceID>" +
"<Channel>Master</Channel>" +
"</u:GetPositionInfo>";
XmlDocument resp = SOAPRequest(path, host, soapBody, soapAction);
string trackURI = resp.SelectSingleNode("//TrackURI").InnerText;
// check SOAP for TrackURI for x-rincon:RINCON
UPnP.Discovery.ZoneMasters[zone] = (!trackURI.StartsWith("x-rincon:RINCON") | trackURI == String.Empty);
}
catch (Exception e)
{
// It was reported that some devices throw an error as reported by a reader, adding try to catch this.
// Currently set message but don't use it. Consider surfacing in .xaml
string err = e.Message;
UPnP.Discovery.ZoneMasters[zone] = false;
}
}
else
{
UPnP.Discovery.ZoneMasters[zone] = false;
}
}
}
}
/// <summary>
/// Gets all playlists defined for the Sonos topology.
/// </summary>
public static void GetPlaylists()
{
if (UPnP.Discovery.Zones.Count > 0)
{
string zone = UPnP.Discovery.Zones[0].ToString(); // use first in list if it isn't a bridge
if (UPnP.Discovery.ZoneTable[zone].ToLower().Contains("bridge"))
{
zone = UPnP.Discovery.Zones[1].ToString(); // use second
}
string path = "/MediaServer/ContentDirectory/Control";
Uri uri = new Uri(zone);
string host = uri.Scheme + "://" + uri.Host + ":" + uri.Port.ToString();
string soapAction = "urn:schemas-upnp-org:service:ContentDirectory:1#Browse";
string soapBody = "<u:Browse xmlns:u=\"urn:schemas-upnp-org:service:ContentDirectory:1\">" +
"<ObjectID>SQ:</ObjectID>" +
"<BrowseFlag>BrowseDirectChildren</BrowseFlag>" +
"<Filter></Filter>" +
"<StartingIndex>0</StartingIndex>" +
"<RequestedCount>" + _maxPlaylistsReturned.ToString() + "</RequestedCount>" +
"<SortCriteria></SortCriteria>" +
"</u:Browse>";
XmlDocument resp = SOAPRequest(path, host, soapBody, soapAction);
XmlNamespaceManager nsm = new XmlNamespaceManager(resp.NameTable);
nsm.AddNamespace("dc", "http://purl.org/dc/elements/1.1/");
XmlDocument resultNode = new XmlDocument();
resultNode.LoadXml(resp.SelectSingleNode("*//Result").InnerText);
XmlNodeList playlists = resultNode.SelectNodes("//dc:title", nsm);
foreach (XmlNode xn in playlists)
{
string id = xn.ParentNode.Attributes["id"].Value;
if (!_playlists.ContainsKey(id))
{
_playlists.Add(id, xn.InnerText);
}
}
}
}
/// <summary>
/// Gets a playlist.
/// </summary>
/// <param name="playlistID">The playlist ID in the system, like "SQ:14" - for Saved Queue.</param>
/// <param name="action">What to find out about the playlist, either return the items in the playlist or a count of the items.</param>
/// <returns></returns>
public static string GetPlaylist(string playlistID, PlaylistAction action, int index)
{
string zone = UPnP.Discovery.Zones[0].ToString(); // use first in list
string path = "/MediaServer/ContentDirectory/Control";
string numResults = String.Empty;
string retVal = String.Empty;
Uri uri = new Uri(zone);
string host = uri.Scheme + "://" + uri.Host + ":" + uri.Port.ToString();
string soapAction = "urn:schemas-upnp-org:service:ContentDirectory:1#Browse";
string soapBody = "<u:Browse xmlns:u=\"urn:schemas-upnp-org:service:ContentDirectory:1\">" +
"<ObjectID>" + playlistID + "</ObjectID>" +
"<BrowseFlag>BrowseDirectChildren</BrowseFlag>" +
"<Filter></Filter>" +
"<StartingIndex>" + (_maxPlaylistPagingResults * (index)).ToString() + "</StartingIndex>" +
"<RequestedCount>" + (_maxPlaylistPagingResults).ToString() + "</RequestedCount>" +
"<SortCriteria></SortCriteria>" +
"</u:Browse>";
XmlDocument resp = SOAPRequest(path, host, soapBody, soapAction);
XmlNamespaceManager nsm = new XmlNamespaceManager(resp.NameTable);
nsm.AddNamespace("dc", "http://purl.org/dc/elements/1.1/");
XmlDocument resultNode = new XmlDocument();
numResults = resp.SelectSingleNode("*//TotalMatches").InnerText;
switch (action)
{
default:
case PlaylistAction.Count:
retVal = numResults;
break;
case PlaylistAction.Save:
if (Int32.Parse(numResults) > _maxPlaylistPagingResults * (index + 1) /* zero-based index */)
{
index += 1;
// Get playlist items recursively.
XDocument recurVal = XDocument.Parse(GetPlaylist(playlistID, action, index));
XDocument currVal = XDocument.Parse(resp.SelectSingleNode("*//Result").InnerText);
currVal.Root.Add(recurVal.Root.Elements());
retVal = currVal.ToString();
}
else
{
retVal = resp.SelectSingleNode("*//Result").InnerText;
}
break;
}
return retVal;
}
public static string CreateM3UPlaylist(string content)
{
StringBuilder sb = new StringBuilder();
sb.Append("#EXTM3U");
sb.Append(System.Environment.NewLine);
sb.Append(System.Environment.NewLine);
// Then we iterate through the DIDL xml item by item
string DIDLTemplate = "<DIDL-Lite xmlns:dc=\"http://purl.org/dc/elements/1.1/\" " +
"xmlns:upnp=\"urn:schemas-upnp-org:metadata-1-0/upnp/\" " +
"xmlns:r=\"urn:schemas-rinconnetworks-com:metadata-1-0/\" " +
"xmlns=\"urn:schemas-upnp-org:metadata-1-0/DIDL-Lite/\">{0}" +
"</DIDL-Lite>";
int musicTracksSent = 0;
XmlDocument DIDLXml = new XmlDocument();
DIDLXml.LoadXml(SanitizeXmlString(content));
XmlNamespaceManager nsm = new XmlNamespaceManager(DIDLXml.NameTable);
nsm.AddNamespace("didl", "urn:schemas-upnp-org:metadata-1-0/DIDL-Lite/");
nsm.AddNamespace("dc", "http://purl.org/dc/elements/1.1/"); // not required for below currently
nsm.AddNamespace("upnp", "urn:schemas-upnp-org:metadata-1-0/upnp/"); // not required for below currently
XmlNodeList nl = DIDLXml.SelectNodes("//didl:item", nsm);
foreach (XmlNode node in nl)
{
string location = node.SelectSingleNode("didl:res", nsm).InnerText;
location = location.Remove(0, 12); // Remove x-file-cifs:
location = HttpUtility.UrlDecode(location);
string name = node.SelectSingleNode("dc:title", nsm).InnerText;
string creator = "";
if (node.SelectSingleNode("dc:creator", nsm) != null)
{
creator = node.SelectSingleNode("dc:creator", nsm).InnerText;
}
string oneItemDIDL = HttpUtility.HtmlEncode(String.Format(DIDLTemplate, node.OuterXml));
//oneItemDIDL = System.Security.SecurityElement.Escape(oneItemDIDL);
sb.Append("#EXTINF:0," + creator + " - " + name);
sb.Append(System.Environment.NewLine);
sb.Append(location.Replace("/", "\\"));
sb.Append(System.Environment.NewLine);
sb.Append(System.Environment.NewLine);
musicTracksSent += 1;
// Report on items written?
}
return sb.ToString();
}
/// <summary>
/// Imports playlist content from a string into a master controller queue.
/// </summary>
/// <param name="content">The XML string that represents the playlist.</param>
/// <param name="masterZoneAddress">The master zone address, like "192.168.2.5"</param>
/// <param name="name">The name to give the playlist.</param>
public static void ImportPlaylist(string content, string masterZoneAddress, string name)
{
// First we clear items in the queue
string path = "/MediaRenderer/AVTransport/Control";
string host = "http://" + masterZoneAddress + ":1400";
string soapAction = "urn:schemas-upnp-org:service:AVTransport:1#RemoveAllTracksFromQueue";
string soapBody = "<u:RemoveAllTracksFromQueue xmlns:u=\"urn:schemas-upnp-org:service:AVTransport:1\">" +
"<InstanceID>0</InstanceID>" +
"</u:RemoveAllTracksFromQueue>";
XmlDocument resp = SOAPRequest(path, host, soapBody, soapAction);
// Then we iterate through the DIDL xml item by item
string DIDLTemplate = "<DIDL-Lite xmlns:dc=\"http://purl.org/dc/elements/1.1/\" " +
"xmlns:upnp=\"urn:schemas-upnp-org:metadata-1-0/upnp/\" " +
"xmlns:r=\"urn:schemas-rinconnetworks-com:metadata-1-0/\" " +
"xmlns=\"urn:schemas-upnp-org:metadata-1-0/DIDL-Lite/\">{0}" +
"</DIDL-Lite>";
int musicTracksSent = 0;
XmlDocument DIDLXml = new XmlDocument();
DIDLXml.LoadXml(SanitizeXmlString(content));
XmlNamespaceManager nsm = new XmlNamespaceManager(DIDLXml.NameTable);
nsm.AddNamespace("didl", "urn:schemas-upnp-org:metadata-1-0/DIDL-Lite/");
nsm.AddNamespace("dc", "http://purl.org/dc/elements/1.1/"); // not required for below currently
nsm.AddNamespace("upnp", "urn:schemas-upnp-org:metadata-1-0/upnp/"); // not required for below currently
XmlNodeList nl = DIDLXml.SelectNodes("//didl:item", nsm);
foreach (XmlNode node in nl)
{
// Create a command
string protocol = node.SelectSingleNode("didl:res", nsm).InnerText;
string oneItemDIDL = HttpUtility.HtmlEncode(String.Format(DIDLTemplate, node.OuterXml));
//oneItemDIDL = System.Security.SecurityElement.Escape(oneItemDIDL);
string title = name;
// Now put the element in the queue
soapAction = "urn:schemas-upnp-org:service:AVTransport:1#AddURIToQueue";
soapBody = "<u:AddURIToQueue xmlns:u=\"urn:schemas-upnp-org:service:AVTransport:1\">" +
"<InstanceID>0</InstanceID>" +
"<EnqueuedURI>" + protocol + "</EnqueuedURI>" +
"<EnqueuedURIMetaData>" + oneItemDIDL + "</EnqueuedURIMetaData>" +
"<DesiredFirstTrackNumberEnqueued>0</DesiredFirstTrackNumberEnqueued>" +
"<EnqueueAsNext>0</EnqueueAsNext>" +
"</u:AddURIToQueue>";
resp = SOAPRequest(path, host, soapBody, soapAction);
musicTracksSent += 1;
// Process return parameters to provide info about has been put into queue?
}
if (musicTracksSent > 0)
{
// At least one thing was written so try to save. If program exits before this point then items
// are in queue in master zone and can be manually saved.
name = name.Substring(0, Math.Min(20, name.Length)); // Limit on playlist length.
soapAction = "urn:schemas-upnp-org:service:AVTransport:1#SaveQueue";
soapBody = "<u:SaveQueue xmlns:u=\"urn:schemas-upnp-org:service:AVTransport:1\">" +
"<InstanceID>0</InstanceID>" +
"<Title>" + name + "</Title>" +
"<ObjectID></ObjectID>" +
"</u:SaveQueue>";
resp = SOAPRequest(path, host, soapBody, soapAction);
}
}
/// <summary>
/// Gets the response to an HTTP request.
/// </summary>
/// <param name="path">URL path, like "/xml/zoneplayer.xml"</param>
/// <param name="host">Host, like "192.168.2.5"</param>
/// <returns></returns>
private static XmlDocument GetWebResponse(string path, string host)
{
HttpWebRequest webReq = (HttpWebRequest)WebRequest.Create(host + path);
webReq.Method = "GET";
//Get the response handle, no response yet.
HttpWebResponse webResp = (HttpWebResponse)webReq.GetResponse();
//Get response
Stream strm = webResp.GetResponseStream();
StreamReader strmReader = new StreamReader(strm);
string data = strmReader.ReadToEnd();
XmlDocument resp = new XmlDocument();
resp.LoadXml(SanitizeXmlString(data));
strmReader.Close();
strm.Close();
webResp.Close();
return resp;
}
/// <summary>
/// Gets the response to a HTTP request with SOAP body.
/// </summary>
/// <param name="path">URL path, like "/MediaRenderer/AVTransport/Control"</param>
/// <param name="host">Host, like "192.168.2.5"</param>
/// <param name="soapBody">The SOAP envelope containing the parameters of the request.</param>
/// <param name="soapAction">The SOAP action, like "Browse" or "SaveQueue".</param>
/// <returns></returns>
private static XmlDocument SOAPRequest(string path, string host, string soapBody, string soapAction)
{
string reqBody = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
"<s:Envelope xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\" s:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\">" +
"<s:Body>" +
soapBody +
"</s:Body>" +
"</s:Envelope>";
HttpWebRequest webReq = (HttpWebRequest)WebRequest.Create(host + path);
webReq.Method = "POST";
byte[] buffer = Encoding.UTF8.GetBytes(reqBody);
webReq.Headers.Add("SOAPACTION", "\"" + soapAction + "\"");
webReq.ContentType = "text/xml; charset=\"utf-8\"";
webReq.ContentLength = reqBody.Length;
// Open a stream for writing. Close.
Stream postData = webReq.GetRequestStream();
postData.Write(buffer, 0, buffer.Length);
postData.Close();
//Get the response handle, no response yet.
HttpWebResponse webResp = (HttpWebResponse)webReq.GetResponse();
//Get response
int contentLength = (int)webResp.ContentLength;
// CF160509 - if the response doesn't set the ContentLength header, the value will be -1
// So just read the stream to the end
//char[] data = new char[contentLength];
Stream strm = webResp.GetResponseStream();
StreamReader strmReader = new StreamReader(strm);
//int chunkSize = 256;
//if (contentLength <= chunkSize)
//{
// strmReader.Read(data, 0, contentLength);
//}
//else
//{
// int count = strmReader.Read(data, 0, chunkSize);
// int indx = count;
// while (count > 0)
// {
// int inc = (contentLength - chunkSize) >= indx ? chunkSize : contentLength - indx;
// count = strmReader.Read(data, indx, inc);
// indx += count;
// }
//}
XmlDocument resp = new XmlDocument();
//resp.LoadXml("<root>" + SanitizeXmlString(new String(data)) + "</root>");
resp.LoadXml("<root>" + SanitizeXmlString(strmReader.ReadToEnd()) + "</root>");
strmReader.Close();
strm.Close();
webResp.Close();
return resp;
}
/// <summary>
/// Removes junk from an XML string that doesn't belong there.
/// Source: http://seattlesoftware.wordpress.com/2008/09/11/hexadecimal-value-0-is-an-invalid-character/
/// Would be best to follow advice in link and build functionality into StreamReader.
/// </summary>
/// <param name="xml">XML to check.</param>
/// <returns></returns>
public static string SanitizeXmlString(string xml)
{
if (xml == null)
{
throw new ArgumentNullException("xml");
}
StringBuilder buffer = new StringBuilder(xml.Length);
foreach (char c in xml)
{
if (XmlConvert.IsXmlChar(c))
{
buffer.Append(c);
}
}
return buffer.ToString();
}
}
}