summaryrefslogtreecommitdiff
path: root/DSACore/Hubs/ChatHub.cs
blob: 1994164b5090667e24e531867b59defc88fab991 (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
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
using DSACore.DSA_Game.Characters;
using DSACore.FireBase;
using DSACore.Models.Network;
using Microsoft.AspNetCore.SignalR;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CSharp.Syntax;

namespace DSACore.Hubs
{
    public class ChatHub : Hub
    {
        //private static Dictionary<string, User> UserGroup = new Dictionary<string, User>();
   
        private const string receiveMethod = "ReceiveMessage";//receiveMethod;

        private static List<Group> DSAGroups = new List<Group>();

        static ChatHub()
        {
            DSAGroups = Database.GetGroups().Result;
            DSAGroups.Add(new Group("login", ""));
            DSAGroups.Add(new Group("online", ""));
            //AddGroups();
        }

        private static async void AddGroups()
        {
            await Database.AddGroup(new Models.Database.Group { Name = "HalloWelt", Password = "valid" });
            await Database.AddGroup(new Models.Database.Group { Name = "Die Krassen Gamer", Password = "valid" });
            await Database.AddGroup(new Models.Database.Group { Name = "DSA", Password = "valid" });
            await Database.AddGroup(new Models.Database.Group { Name = "Die Überhelden", Password = "valid" });
        }

        public async Task SendMessage(string user, string message)
        {
            try
            {
                string group = getGroup(Context.ConnectionId).Name;
            }
            catch (InvalidOperationException e)
            {
                //await Clients.Caller.SendCoreAsync(receiveMethod,
                   // new object[] { "Nutzer ist in keiner Gruppe. Erst joinen!" });
            }

            if (message[0] == '/')
            {
                var args = message.Split(' ', StringSplitOptions.RemoveEmptyEntries).ToList();

                bool Timon = args.Any(x => x == "hallo");

                var ident = args.First().Replace("/", "");
                if (args.Count > 0)
                {
                    args.RemoveAt(0);
                }

                var ret = Commands.CommandHandler.ExecuteCommand(new Command
                {
                    CharId = 0,
                    CmdIdentifier = ident,
                    CmdTexts = args,
                    Name = user
                });

                switch (ret.ResponseType)
                {
                    case ResponseType.Caller:
                    case ResponseType.Error:
                        await Clients.Caller.SendAsync(receiveMethod, ret.message);
                        break;
                    case ResponseType.Broadcast:
                        await SendToGroup(ret.message);
                        break;
                }

                
            }
            else
            {
                await SendToGroup(message);
            }

        }

        private Task SendToGroup(string message)
        {
            try
            {
                string group = getGroup(Context.ConnectionId).Name;
                return Clients.Group(group).SendCoreAsync(receiveMethod,
                    new object[] {getUser(Context.ConnectionId).Name, message});
            }
            catch (InvalidOperationException e)
            {
                return Clients.Caller.SendCoreAsync(receiveMethod,
                    new object[] { "Nutzer ist in keiner Gruppe. Erst joinen!" });
            }
        }

        private Models.Network.Group getGroup(string id)
        {
            return DSAGroups.First(x => x.Users.Exists(y => y.ConnectionId.Equals(id)));
        }

        private User getUser(string id)
        {
            return DSAGroups.First(x => x.Users.Exists(y => y.ConnectionId.Equals(id))).Users.First(z => z.ConnectionId.Equals(id));
        }

        public async Task GetGroups()
        {
            var test = Database.GetGroups();
            test.Wait();
            foreach (var group in test.Result)
            {
                if (!DSAGroups.Exists(x => x.Name.Equals(group.Name)))
                {
                    DSAGroups.Add(group);
                }
            }

            await Clients.Caller.SendCoreAsync("ListGroups", new object[] { DSAGroups.Select(x => x.SendGroup()) });
            //throw new NotImplementedException("add database call to get groups");
        }

        public async Task AddGroup(string group, string password)
        {
            DSAGroups.Add(new Group(group, password));
            var Dgroup = new DSACore.Models.Database.Group { Name = group, Id = DSAGroups.Count - 1 };
            //Database.AddGroup(Dgroup);
            await Clients.Caller.SendCoreAsync(receiveMethod, new[] { $"group {@group} sucessfully added" });
            //throw new NotImplementedException("add database call to add groups");
        }

        public async Task UploadChar(string xml)
        {
            var group = getGroup(Context.ConnectionId);

            await Database.AddChar(new Character(new MemoryStream(Encoding.UTF8.GetBytes(xml))), group);
            //throw new NotImplementedException("add database call to add groups");
        }

        public async Task Login(string group, string user, string hash)
        {
            //string password = System.Text.Encoding.UTF8.GetString(hash);
            if (hash == DSAGroups.First(x => x.Name == group).Password)
            {
                var gGroup = DSAGroups.First(x => x.Name.Equals(group));
                if (!gGroup.Users.Exists(x => x.Name.Equals(user)))
                {
                    await Groups.RemoveFromGroupAsync(Context.ConnectionId, "login");
                    await Groups.AddToGroupAsync(Context.ConnectionId, group);
                    gGroup.Users.Add(new User { ConnectionId = Context.ConnectionId, Name = user });
                    await SendToGroup("Ein neuer Nutzer hat die Gruppe betreten");
                    await Clients.Caller.SendAsync("LoginResponse", 0);
                    await Clients.Caller.SendAsync("PlayerStatusChanged", new[] {user, "online"});
                }
                else
                {
                    await Clients.Caller.SendAsync("LoginResponse", 1);
                }
            }
            else
            {
                await Clients.Caller.SendAsync("LoginResponse", 2);
                //await Clients.Caller.SendAsync(receiveMethod, "Falsches Passwort!");
            }
        }

        public override Task OnDisconnectedAsync(Exception exception)
        {
            Disconnect().Wait();
            return base.OnDisconnectedAsync(exception);
        }

        public override Task OnConnectedAsync()
        {
            Groups.AddToGroupAsync(Context.ConnectionId, "login").Wait();
            Groups.AddToGroupAsync(Context.ConnectionId, "online").Wait();
            return base.OnConnectedAsync();
        }

        public async Task Disconnect()
        {
            await Groups.RemoveFromGroupAsync(Context.ConnectionId, "online");
            if (DSAGroups.Exists(x => x.Users.Exists(y => y.ConnectionId == Context.ConnectionId)))
            {
                try
                {
                    var group = getGroup(Context.ConnectionId);


                    var user = getUser(Context.ConnectionId);

                    await Clients.Caller.SendAsync("PlayerStatusChanged", new[] { user.Name, "offline" });
                    //await SendToGroup(user.Name + " disconnected from the Server");
                    group.Users.Remove(user);
                    await Groups.RemoveFromGroupAsync(Context.ConnectionId, group.Name);
                }
                catch (Exception e)
                {
                    Console.WriteLine(e);
                    //throw;
                }
            }

        }

    }
}