-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathClient.cs
More file actions
384 lines (339 loc) · 14.4 KB
/
Copy pathClient.cs
File metadata and controls
384 lines (339 loc) · 14.4 KB
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
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
using System;
using System.Collections;
using System.Collections.Generic;
using System.Net;
using Newtonsoft.Json;
using UnityEngine;
using UnityEngine.Networking;
using System.Text.RegularExpressions;
namespace OpenAPE
{
/// <summary>
/// The LoginResponse class.
/// Contains a representation of the response that is received from the server on login.
/// </summary>
internal class LoginResponse
{
/// <summary>
/// The exact time the reponse was received.
/// </summary>
/// <remarks>
/// Used to calculate the expiration of the token
/// </remarks>
private readonly DateTime _created = DateTime.Now;
/// <summary>
/// The token that was received.
/// </summary>
[JsonProperty("access_token")]
internal string Token { get; set; }
/// <summary>
/// The expiration of the token.
/// </summary>
/// <remarks>
/// In seconds since token creation. Use isValid to check for expiration.
/// </remarks>
[JsonProperty("expires_in")]
internal int Expiration { get; set; }
/// <summary>
/// Whether the token is still valid.
/// </summary>
/// <remarks>
/// Only checks whether the token should still be valid according to the expiration date.
/// The server might still reject it for some other reason.
/// </remarks>
internal bool IsValid => (DateTime.Now - _created).TotalSeconds < Expiration;
}
/// <summary>
/// The UserContextResponse class.
/// Contains a representation of the response that is received from the server on getting a user context.
/// </summary>
internal class UserContextResponse
{
/// <summary>
/// The default preferences in this profile.
/// </summary>
/// <remarks>
/// The others are currently ignored if present.
/// </remarks>
[JsonProperty("default")]
internal UserPreferences UserPreferences { get; set; }
}
/// <summary>
/// The UserPreferences class.
/// Contains the data of a specific preference set.
/// </summary>
internal class UserPreferences
{
/// <summary>
/// The human-readable name of this preference set.
/// </summary>
[JsonProperty("name")]
internal string Name { get; set; }
/// <summary>
/// The list of preferences of this preference set.
/// </summary>
[JsonProperty("preferences")]
internal PreferenceTermsDictionary PreferenceTerms { get; set; }
}
/// <summary>
/// The PreferenceTerms class.
/// Contains a list of preferences.
/// </summary>
/// <inheritdoc cref="Dictionary{TKey,TValue}" />
public class PreferenceTermsDictionary : Dictionary<string, string>
{
}
/// <summary>
/// The completion handler called when a response was reveived.
/// </summary>
/// <param name="response">The response text.</param>
internal delegate void OnResponseReceived(string response);
/// <summary>
/// The completion handler called when an error occured was reveived.
/// </summary>
/// <param name="message">The error message.</param>
internal delegate void OnErrorReceived(string message);
/// <summary>
/// The completion handler called when a rest call is completed.
/// </summary>
/// <param name="status">Whether or not the call succeeded.</param>
/// <param name="result">The resulting object. May be null on error or when no result is needed.</param>
public delegate void OnCompletion<T>(bool status, T result);
/// <summary>
/// The main Client class.
/// Is used to communicate with the OpenAPE server.
/// </summary>
public class Client
{
/// <summary>
/// The base url of the server.
/// </summary>
private string BaseUrl;
/// <summary>
/// The latest response received.
/// </summary>
private LoginResponse _loginResponse;
/// <summary>
/// The user which was last logged in.
/// </summary>
private String _loggedInUser;
/// <summary>
/// The latest response received.
/// </summary>
private UserContextResponse _userContextResponse;
/// <summary>
/// The Parent context that can execute Coroutines.
/// </summary>
private ICoroutineExecutor _parent;
/// <summary>
/// Creates a new instance of the client.
/// </summary>
/// <remarks>
/// The server config is loaded from a text file just containing the target.
/// This enables changing the server on device without recompiling the Unity app.
/// </remarks>
/// <param name="serverConfigPath">The server that is used.</param>
public Client(ICoroutineExecutor parent, string serverConfigPath = null)
{
_parent = parent;
// using either supplied path or a default path depending on the runtime context.
var path = serverConfigPath ??
#if UNITY_EDITOR
Application.dataPath + "/Resources/OpenAPEServer.txt";
#else
Application.persistentDataPath + "/OpenAPEServer.txt";
#endif
// Replacing new line character if we accidently read one.
BaseUrl = Regex.Replace(BaseUrl, @"\t|\n|\r", String.Empty);
}
/// <summary>
/// Login with the given username and password.
/// </summary>
/// <remarks>
/// You will need to do this before loading any profiles.
/// Also please note, that the result of this operation is always null!
/// </remarks>
/// <param name="username">The username that is used.</param>
/// <param name="password">The password that is used.</param>
/// <param name="onCompletion">The completion handler returns whether the login succeeded.</param>
public bool Login(string username, string password, OnCompletion<object> onCompletion)
{
if (username == null || username.Equals("") || password == null || password.Equals(""))
{
Debug.Log("Please supply all expected parameters");
onCompletion(false, null);
return false;
}
if ((_loggedInUser != null && username.Equals(_loggedInUser)) &&
(_loginResponse != null && _loginResponse.IsValid))
{
Debug.Log("Login is still valid!");
onCompletion(true, null);
return true; // TODO remove
}
_parent.StartChildCoroutine(_LoginCoroutine(username, password, response =>
{
_loginResponse = JsonConvert.DeserializeObject<LoginResponse>(response);
_loggedInUser = username;
onCompletion(true, null);
}, message =>
{
Debug.Log("An error occured while logging in...");
Debug.Log(message);
onCompletion(false, null);
}));
return true; // TODO remove
}
/// <summary>
/// Retrieves the user profile with the given id.
/// </summary>
/// <remarks>
/// You have to be logged in with a valid token and the user needs to have access to the supplied profile. This means
/// the user owns it or it is public.
/// </remarks>
/// <param name="id">The profile's id</param>
/// <param name="onCompletion">The completion handler returns whether the getting of the profile succeeded.
/// The result is where the preferenceTerms are stored in. May be null on error.</param>
internal bool GetProfile(string id, OnCompletion<PreferenceTerms> onCompletion)
{
if (id == null || id.Equals(""))
{
Debug.Log("Please supply all expected parameters");
onCompletion(false, null);
return false;
}
if (_loginResponse?.Token == null)
{
Debug.Log("You need to login first!");
onCompletion(false, null);
return false; // TODO remove
}
if (!_loginResponse.IsValid)
{
Debug.Log("Login has expired!");
onCompletion(false, null);
return false; // TODO remove
}
_parent.StartChildCoroutine(_GetProfileCoroutine(id, response =>
{
_userContextResponse = JsonConvert.DeserializeObject<UserContextResponse>(response);
onCompletion(true, new PreferenceTerms(_userContextResponse.UserPreferences.PreferenceTerms));
}, message =>
{
Debug.Log("An error occured while getting user profile...");
Debug.Log("Are you sure you are logged in with the right user? " + _loggedInUser + " is logged in.");
Debug.Log(message);
onCompletion(false, null);
}));
return true; // TODO remove
}
/// <summary>
/// Updates the user profile with the given id.
/// </summary>
/// <param name="id">The profile's id</param>
/// <param name="preferenceTerms">The updated preference terms to save.</param>
/// <param name="onCompletion">The completion handler returns whether the update of the profile succeeded.</param>
internal bool UpdateProfile(string id, PreferenceTerms preferenceTerms, OnCompletion<object> onCompletion)
{
if (_loginResponse?.Token == null)
{
Debug.Log("You need to login first!");
onCompletion(false, null);
return false; // TODO remove
}
if (!_loginResponse.IsValid)
{
Debug.Log("Login has expired!");
onCompletion(false, null);
return false; // TODO remove
}
_parent.StartChildCoroutine(_UpdateProfileCoroutine(id, preferenceTerms, response => { onCompletion(true, null); }, message =>
{
Debug.Log("An error occured while updating user profile...");
Debug.Log(message);
onCompletion(false, null);
}));
return true; // TODO remove
}
/// <summary>
/// Handles the login as a coroutine.
/// </summary>
/// <param name="username">The username that is used.</param>
/// <param name="password">The password that is used.</param>
/// <param name="onResponseReceived">The handler to call on success.</param>
/// <param name="onErrorReceived">The handler to call on error.</param>
/// <returns>An enumerator.</returns>
private IEnumerator _LoginCoroutine(string username, string password, OnResponseReceived onResponseReceived, OnErrorReceived onErrorReceived)
{
var form = new WWWForm();
form.AddField("grant_type", "password");
form.AddField("username", username);
form.AddField("password", password);
using (var req = UnityWebRequest.Post(BaseUrl + "token", form))
{
req.SetRequestHeader("grant_type", "application/x-www-form-urlencoded");
req.downloadHandler = new DownloadHandlerBuffer();
yield return req.SendWebRequest();
if (req.isNetworkError || req.isHttpError)
{
onErrorReceived(req.error);
}
else
{
onResponseReceived(req.downloadHandler.text);
}
}
}
/// <summary>
/// Handles the getting of a profile as a coroutine.
/// </summary>
/// <param name="id">The profile's id</param>
/// <param name="onResponseReceived">The handler to call on success.</param>
/// <param name="onErrorReceived">The handler to call on error.</param>
/// <returns>An enumerator.</returns>
private IEnumerator _GetProfileCoroutine(string id, OnResponseReceived onResponseReceived, OnErrorReceived onErrorReceived)
{
using (var req = UnityWebRequest.Get(BaseUrl + "api/user-contexts/" + id))
{
req.SetRequestHeader("content-type", "application/json");
req.SetRequestHeader("authorization", _loginResponse.Token);
req.downloadHandler = new DownloadHandlerBuffer();
yield return req.SendWebRequest();
if (req.isNetworkError || req.isHttpError)
{
onErrorReceived(req.error);
}
else
{
onResponseReceived(req.downloadHandler.text);
}
}
}
/// <summary>
/// Handles the updating of a profile as a coroutine.
/// </summary>
/// <param name="id">The profile's id</param>
/// <param name="preferenceTerms">The new and updated preference terms.</param>
/// <param name="onResponseReceived">The handler to call on success.</param>
/// <param name="onErrorReceived">The handler to call on error.</param>
/// <returns>An enumerator.</returns>
private IEnumerator _UpdateProfileCoroutine(string id, PreferenceTerms preferenceTerms, OnResponseReceived onResponseReceived, OnErrorReceived onErrorReceived)
{
using (var req = UnityWebRequest.Put(BaseUrl + "api/user-contexts/" + id, JsonConvert.SerializeObject(preferenceTerms)))
{
req.SetRequestHeader("content-type", "application/json");
req.SetRequestHeader("authorization", _loginResponse.Token);
req.downloadHandler = new DownloadHandlerBuffer();
yield return req.SendWebRequest();
if (req.isNetworkError || req.isHttpError)
{
onErrorReceived(req.error);
}
else
{
onResponseReceived(req.downloadHandler.text);
}
}
}
}
}