forked from Necrobot-Private/NecroBot
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathWebSocketInterface.cs
210 lines (184 loc) · 6.28 KB
/
WebSocketInterface.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
#region using directives
using System;
using System.Collections.Generic;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using PoGo.NecroBot.CLI.WebSocketHandler;
using PoGo.NecroBot.Logic.Common;
using PoGo.NecroBot.Logic.Event;
using PoGo.NecroBot.Logic.Logging;
using PoGo.NecroBot.Logic.State;
using PoGo.NecroBot.Logic.Tasks;
using SuperSocket.SocketBase;
using SuperSocket.SocketBase.Config;
using SuperSocket.WebSocket;
#endregion
namespace PoGo.NecroBot.CLI
{
public class WebSocketInterface
{
private readonly WebSocketServer _server;
private readonly Session _session;
private readonly WebSocketEventManager _websocketHandler;
private PokeStopListEvent _lastPokeStopList;
private ProfileEvent _lastProfile;
public WebSocketInterface(int port, Session session)
{
_session = session;
var translations = session.Translation;
_server = new WebSocketServer();
_websocketHandler = WebSocketEventManager.CreateInstance();
var config = new ServerConfig
{
Name = "NecroWebSocket",
Mode = SocketMode.Tcp,
MaxRequestLength = int.MaxValue ,
Certificate = new CertificateConfig
{
FilePath = @"cert.pfx",
Password = "necro"
},
Listeners = new List<ListenerConfig>
{
new ListenerConfig
{
Ip = "Any",
Port = port,
Security = "tls"
},
new ListenerConfig
{
Ip = "Any",
Port = port + 1,
Security = "none"
}
}
};
var setupComplete = _server.Setup(config);
if (setupComplete == false)
{
Logger.Write(translations.GetTranslation(TranslationString.WebSocketFailStart, port), LogLevel.Error);
return;
}
_server.NewMessageReceived += HandleMessage;
_server.NewSessionConnected += HandleSession;
_server.Start();
}
private void Broadcast(string message)
{
foreach (var session in _server.GetAllSessions())
{
try
{
session.Send(message);
}
catch
{
// ignored
}
}
}
private void HandleEvent(PokeStopListEvent evt)
{
if(_lastPokeStopList != null)
{
_lastPokeStopList.Forts.AddRange(evt.Forts);
}
else
_lastPokeStopList = evt;
}
private void HandleEvent(ProfileEvent evt)
{
_lastProfile = evt;
}
private async void HandleMessage(WebSocketSession session, string message)
{
switch (message)
{
case "PokemonList":
await PokemonListTask.Execute(_session);
break;
case "EggsList":
await EggsListTask.Execute(_session);
break;
case "InventoryList":
await InventoryListTask.Execute(_session);
break;
case "PokemonSnipeList":
await HumanWalkSnipeTask.ExecuteFetchData(_session);
break;
}
// Setup to only send data back to the session that requested it.
try
{
dynamic decodedMessage = JObject.Parse(message);
var handle = _websocketHandler?.Handle(_session, session, decodedMessage);
if (handle != null)
await handle;
}
catch (Exception)
{
// ignored
}
// When we first get a message from the web socket, turn off log buffering.
// This allows us to flush out buffered LogEvent messages to the GUI.
Logger.TurnOffLogBuffering();
}
private void HandleSession(WebSocketSession session)
{
if (_lastProfile != null)
session.Send(Serialize(_lastProfile));
if (_lastPokeStopList != null)
session.Send(Serialize(_lastPokeStopList));
try
{
session.Send(Serialize(new UpdatePositionEvent
{
Latitude = _session.Client.CurrentLatitude,
Longitude = _session.Client.CurrentLongitude
}));
}
catch (Exception)
{
// ignored
}
}
public void Listen(IEvent evt, Session session)
{
dynamic eve = evt;
try
{
HandleEvent(eve);
}
catch
{
// ignored
}
Broadcast(Serialize(eve));
}
private static string Serialize(dynamic evt)
{
var jsonSerializerSettings = new JsonSerializerSettings {TypeNameHandling = TypeNameHandling.All};
// Add custom seriaizer to convert uong to string (ulong shoud not appear to json according to json specs)
jsonSerializerSettings.Converters.Add(new IdToStringConverter());
return JsonConvert.SerializeObject(evt, Formatting.None, jsonSerializerSettings);
}
}
public class IdToStringConverter : JsonConverter
{
public override object ReadJson(JsonReader reader, Type objectType, object existingValue,
JsonSerializer serializer)
{
var jt = JToken.ReadFrom(reader);
return jt.Value<long>();
}
public override bool CanConvert(Type objectType)
{
return typeof(long) == objectType || typeof(ulong) == objectType;
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
serializer.Serialize(writer, value.ToString());
}
}
}