-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathApiManager.cs
212 lines (184 loc) · 6.09 KB
/
ApiManager.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
using System.Collections;
using System.Runtime.InteropServices;
using Assets.Scripts.Interfaces;
using Assets.Scripts.Models;
using Assets.Scripts.Utils;
using TMPro;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.Networking;
namespace Assets.Scripts.Managers
{
[System.Serializable]
internal class ApiInitializedEvent : UnityEvent<GameModel>
{
}
[System.Serializable]
internal class ApiUpdateEvent : UnityEvent<UpdateEventModel>
{
}
/// <summary>
/// API manager which handles calling the API every x seconds.
/// As soon as the API request has been done, the data will be parsed through a custom parse function and the data will be fired through the ApiChangeUnityEventManager.
/// </summary>
internal class ApiManager : Singleton<ApiManager>
{
private string _gameEndpoint;
private const string HubListenerName = "SendUpdateToClients";
private SignalRLib _srLib;
[SerializeField] public GameObject AlertCanvas;
private TMP_Text _alertText;
[Header("LOADING SCREEN")] public GameObject LoadingMenu;
private string _hubEndpoint;
public ApiInitializedEvent ApiInitializedEvent = new ApiInitializedEvent();
public ApiUpdateEvent ApiUpdateEvent = new ApiUpdateEvent();
// Start is called before the first frame update
void Start()
{
// Wait until the settings and assets are loaded, otherwise we don't know our base url and endpoints
AssetsManager.Instance.AssetsLoaded.AddListener(LoadApiData);
LoadingMenu.SetActive(true);
_alertText = AlertCanvas.GetComponentInChildren<TMP_Text>();
}
/// <summary>
/// Start loading the API data as soon as the assets are loaded.
/// </summary>
private void LoadApiData()
{
Debug.Log("Loading API data");
_gameEndpoint = SettingsManager.Instance.Settings.Api.BaseUrl +
SettingsManager.Instance.Settings.Api.GameEndpoint;
_hubEndpoint = SettingsManager.Instance.Settings.Api.BaseUrl +
SettingsManager.Instance.Settings.Api.EventHubEndpoint;
StartCoroutine(LoadDataFromApi());
AlertCanvas.SetActive(false);
}
/// <summary>
/// Try to start the SignalR connection with the server.
/// </summary>
private void StartSignalR()
{
if (string.IsNullOrEmpty(SettingsManager.Instance.Settings.Api.EventHubEndpoint))
{
Debug.LogWarning("SignalR is not enabled, no endpoint is set. Real-time data is unavailable.");
return;
}
_srLib = new SignalRLib();
_srLib.Init(_hubEndpoint, HubListenerName);
_srLib.Error += (sender, e) =>
{
_alertText.text =
$"Error retrieving live data from server! Server seems to be down.";
AlertCanvas.SetActive(true);
#if UNITY_EDITOR
Debug.LogError($"SignalR gives an error: {e.Message}");
#endif
};
_srLib.ConnectionStarted += (sender, e) => { Debug.Log("Connection with server established."); };
_srLib.MessageReceived += (sender, e) =>
{
// Disable alerting text if server went back up
if (_alertText.gameObject.activeSelf)
_alertText.gameObject.SetActive(false);
UpdateEventModel updateEventModel = JsonParser.ParseUpdateEvent(e.Message);
if (Application.isEditor && updateEventModel.UpdatedLayerValues == null)
Debug.Log(e.Message);
ApiUpdateEvent?.Invoke(updateEventModel);
};
}
/// <summary>
/// Function to kill a object through the API.
/// </summary>
/// <returns></returns>
public IEnumerator KillVisualizedObject(IVisualizedObject building, bool force = false)
{
using (UnityWebRequest webRequest =
UnityWebRequest.Delete($"{_gameEndpoint}?identifier={building.Identifier}&force={force}"))
{
// Request and wait for the desired page.
webRequest.timeout = 10;
yield return webRequest.SendWebRequest();
if (webRequest.isNetworkError || webRequest.isHttpError)
{
Debug.LogError($"Webrequest failed! Error: {webRequest.error}");
}
yield return null;
}
yield return null;
}
/// <summary>
/// Function to load the first data from the API.
/// </summary>
/// <returns></returns>
private IEnumerator LoadDataFromApi()
{
using (UnityWebRequest webRequest = UnityWebRequest.Get(_gameEndpoint))
{
// Request and wait for the desired page.
webRequest.timeout = 10;
yield return webRequest.SendWebRequest();
LoadingMenu.SetActive(false);
if (webRequest.isNetworkError || webRequest.isHttpError)
{
Debug.LogError($"Webrequest failed! Error: {webRequest.error}");
_alertText.text =
$"Error retrieving data from API. Please connect to the VPN\r\nPress {KeyCode.Escape} to return to the main menu";
AlertCanvas.SetActive(true);
}
else
{
AlertCanvas.SetActive(false);
GameModel gameModel = JsonParser.ParseGameModel(webRequest.downloadHandler.text);
ApiInitializedEvent?.Invoke(gameModel);
LoadingMenu.SetActive(false);
StartSignalR();
}
yield return null;
}
yield return null;
}
/// <summary>
/// Function to open the web browser of the device to a specific url that belongs to a neighbourhood.
/// </summary>
/// <returns></returns>
public IEnumerator OpenNeighbourhoodUrl(string neighbourhoodName)
{
using (UnityWebRequest webRequest =
UnityWebRequest.Get($"{_gameEndpoint}/url?identifier={neighbourhoodName}"))
{
// Request and wait for the desired page.
webRequest.timeout = 10;
yield return webRequest.SendWebRequest();
if (webRequest.isNetworkError || webRequest.isHttpError)
{
Debug.LogWarning($"Cannot find url of neighbourhood. Error: {webRequest.error}");
}
else
{
string url = JsonParser.ParseNeighbourhoodUrl(webRequest.downloadHandler.text);
if (!string.IsNullOrEmpty(url))
{
#if UNITY_WEBGL && !UNITY_EDITOR
openPage(url);
#else
Application.OpenURL(url);
#endif
}
}
yield return null;
}
yield return null;
}
/// <summary>
/// Kill the connection with SignalR when the API manager is being destroyed.
/// </summary>
void OnDestroy()
{
if (_srLib == null) return;
Debug.Log("Disconnecting from server.");
_srLib.Exit();
}
[DllImport("__Internal")]
private static extern void openPage(string url);
}
}