Welcome to mirror list, hosted at ThFree Co, Russian Federation.

CsvConnectionsDeserializerRdmFormat.cs « RemoteDesktopManager « Csv « ConnectionSerializers « Serializers « Config « mRemoteNG - github.com/mRemoteNG/mRemoteNG.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: de04077657a7a9b5fc2bcaa6c911de03e04d52f0 (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
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
#region

using System;
using System.Collections.Generic;
using System.Linq;
using mRemoteNG.Connection;
using mRemoteNG.Connection.Protocol;
using mRemoteNG.Container;
using mRemoteNG.Tree;

#endregion

namespace mRemoteNG.Config.Serializers.ConnectionSerializers.Csv.RemoteDesktopManager;

public partial class CsvConnectionsDeserializerRdmFormat : IDeserializer<string, ConnectionTreeModel>
{
    private readonly List<RemoteDesktopManagerConnectionInfo> _connectionTypes;
    private readonly HashSet<string> _groups;

    public CsvConnectionsDeserializerRdmFormat()
    {
        _connectionTypes = new List<RemoteDesktopManagerConnectionInfo>
        {
            new(ProtocolType.RDP, "RDP (Microsoft Remote Desktop)", 3389),
            new(ProtocolType.SSH2, "SSH Shell", 22)
        };

        _groups = new HashSet<string>();

        Containers = new List<ContainerInfo>();
    }

    private List<ContainerInfo> Containers { get; }

    public ConnectionTreeModel Deserialize(string serializedData)
    {
        var lines = serializedData.Split(new[] { "\r\n", "\r", "\n" }, StringSplitOptions.RemoveEmptyEntries);
        var csvHeaders = new List<string>();

        var connections = new List<(ConnectionInfo, string)>(); // (ConnectionInfo, group)

        for (var lineNumber = 0; lineNumber < lines.Length; lineNumber++)
        {
            var line = lines[lineNumber].Split(',');
            if (lineNumber == 0)
            {
                csvHeaders = line.ToList();
            }
            else
            {
                var (connectionInfo, group) = ParseConnectionInfo(csvHeaders, line);
                if (connectionInfo == default) continue;

                connections.Add((connectionInfo, group));
            }
        }

        var connectionTreeModel = new ConnectionTreeModel();
        var unsortedConnections = new ContainerInfo { Name = "Unsorted" };

        foreach (var containerInfo in Containers) connectionTreeModel.AddRootNode(containerInfo);

        var allChildren = Containers.SelectMany(x => x.GetRecursiveChildList().Select(y => (ContainerInfo)y)).ToList();

        foreach (var (connection, path) in connections)
            if (string.IsNullOrEmpty(path))
            {
                unsortedConnections.AddChild(connection);
            }
            else
            {
                var container = allChildren.FirstOrDefault(x => x.ConstantID == path);
                if (container == default) continue;

                container.AddChild(connection);
            }

        connectionTreeModel.AddRootNode(unsortedConnections);

        return connectionTreeModel;
    }

    private (ConnectionInfo connectionInfo, string) ParseConnectionInfo(IList<string> headers, IReadOnlyList<string> connectionCsv)
    {
        if (headers.Count != connectionCsv.Count) return default;

        var hostString = connectionCsv[headers.IndexOf("Host")].Trim();
        if (string.IsNullOrEmpty(hostString)) return default;

        var hostType = Uri.CheckHostName(hostString);
        if (hostType == UriHostNameType.Unknown) return default;

        var connectionTypeString = connectionCsv[headers.IndexOf("ConnectionType")];
        if (string.IsNullOrEmpty(connectionTypeString)) return default;

        var connectionType = _connectionTypes.FirstOrDefault(x => x.Name == connectionTypeString);
        if (connectionType == default) return default;

        var portString = connectionCsv[headers.IndexOf("Port")] ?? connectionType.Port.ToString();
        if (!int.TryParse(portString, out var port)) port = connectionType.Port;

        var name = connectionCsv[headers.IndexOf("Name")];
        var description = connectionCsv[headers.IndexOf("Description")];
        var group = connectionCsv[headers.IndexOf("Group")];

        var username = connectionCsv[headers.IndexOf("CredentialUserName")];
        var domain = connectionCsv[headers.IndexOf("CredentialDomain")];
        var password = connectionCsv[headers.IndexOf("CredentialPassword")];

        var connectionInfo = new ConnectionInfo(Guid.NewGuid().ToString())
        {
            Name = name,
            Hostname = hostString,
            Port = port,
            Username = username,
            Password = password,
            Domain = domain,
            Description = description,
            Protocol = connectionType.Protocol
        };

        if (!string.IsNullOrEmpty(group))
            if (group.Contains('\\'))
            {
                var groupParts = group.Split('\\').ToList();
                var parentContainerName = groupParts[0];
                var parentContainer = Containers.FirstOrDefault(x => x.Name == parentContainerName);
                if (parentContainer == default)
                {
                    parentContainer = new ContainerInfo(group) { Name = parentContainerName };
                    Containers.Add(parentContainer);
                }

                groupParts.RemoveAt(0);

                AddChildrenRecursive(group, groupParts, parentContainer);
            }

        return string.IsNullOrEmpty(group) ? (connectionInfo, default) : (connectionInfo, group);
    }

    private void AddChildrenRecursive(string group, IList<string> groupParts, ContainerInfo parentContainer)
    {
        if (_groups.Contains(group)) return;

        var groupCount = groupParts.Count;
        while (groupCount > 0)
        {
            var childName = groupParts[0];
            var newContainer = new ContainerInfo(group) { Name = childName };

            var childrenNames = parentContainer.GetRecursiveChildList().Select(x => x.Name).ToList();
            if (!childrenNames.Any())
            {
                groupCount = AddChild(parentContainer, newContainer, groupCount);
                _groups.Add(group);
                continue;
            }

            if (groupParts.Count > 1)
            {
                var childContainer = (ContainerInfo)parentContainer.Children.FirstOrDefault(x => x.Name == childName);
                if (childContainer == default)
                {
                    groupCount = AddChild(parentContainer, newContainer, groupCount);
                    continue;
                }

                AddChildrenRecursive(group, groupParts.Skip(1).ToList(), childContainer);
            }
            else
            {
                parentContainer.AddChild(newContainer);
                _groups.Add(group);
            }

            groupCount--;
        }
    }

    private static int AddChild(ContainerInfo parentContainer, ContainerInfo newContainer, int groupCount)
    {
        parentContainer.AddChild(newContainer);
        groupCount--;
        return groupCount;
    }
}

internal sealed record RemoteDesktopManagerConnectionInfo(ProtocolType Protocol, string Name, int Port);