aboutsummaryrefslogtreecommitdiff
path: root/RSSDP/SsdpHelper.cs
blob: 2eacf3c11b6f432417957073ddae172b6de50ea1 (plain)
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
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using MediaBrowser.Model.Net;
using MediaBrowser.Model.Text;

namespace RSSDP
{
    public class SsdpHelper
    {
        private readonly ITextEncoding _encoding;

        public SsdpHelper(ITextEncoding encoding)
        {
            _encoding = encoding;
        }

        public SsdpMessageInfo ParseSsdpResponse(byte[] data)
        {
            using (var ms = new MemoryStream(data))
            {
                using (var reader = new StreamReader(ms, _encoding.GetASCIIEncoding()))
                {
                    var proto = (reader.ReadLine() ?? string.Empty).Trim();
                    var method = proto.Split(new[] { ' ' }, 2)[0];
                    var headers = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
                    for (var line = reader.ReadLine(); line != null; line = reader.ReadLine())
                    {
                        line = line.Trim();
                        if (string.IsNullOrEmpty(line))
                        {
                            break;
                        }
                        var parts = line.Split(new[] { ':' }, 2);

                        if (parts.Length >= 2)
                        {
                            headers[parts[0]] = parts[1].Trim();
                        }
                    }

                    return new SsdpMessageInfo
                    {
                        Method = method,
                        Headers = headers,
                        Message = data
                    };
                }
            }
        }

        public static string BuildMessage(string header, Dictionary<string, string> values)
        {
            var builder = new StringBuilder();

            const string argFormat = "{0}: {1}\r\n";

            builder.AppendFormat("{0}\r\n", header);

            foreach (var pair in values)
            {
                builder.AppendFormat(argFormat, pair.Key, pair.Value);
            }

            builder.Append("\r\n");

            return builder.ToString();
        }
    }

    public class SsdpMessageInfo
    {
        public string Method { get; set; }

        public IpEndPointInfo EndPoint { get; set; }

        public Dictionary<string, string> Headers { get; set; }

        public IpEndPointInfo LocalEndPoint { get; set; }
        public byte[] Message { get; set; }

        public SsdpMessageInfo()
        {
            Headers = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
        }
    }
}