-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathRequest.cs
246 lines (228 loc) · 9.69 KB
/
Request.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
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
using System.Collections;
using UnityEngine;
using UnityEngine.Networking;
using System;
using System.Collections.Generic;
namespace Cisco.Spark
{
/// <summary>
/// Handles building and making web requests to the Spark service.
/// </summary>
[RequireComponent(typeof(SparkResources))]
public class Request : MonoBehaviour
{
/// <summary>
/// Singleton for a Request instance.
/// </summary>
public static Request Instance;
/// <summary>
/// Base URL for the Spark API.
/// </summary>
public const string BaseUrl = "https://api.ciscospark.com/v1";
/// <summary>
/// The access token to make requests with.
/// The Person (or bot) associated with this token is stored in <see cref="Person.AuthenticatedUser"/>.
/// </summary>
public string AccessToken = "";
/// <summary>
/// True if initial Setup has completed.
/// Calls using <see cref="Person.AuthenticatedUser"/> must wait for this to be true.
/// </summary>
public bool SetupComplete { get; private set; }
/// <summary>
/// SparkSDK Ready Event.
/// </summary>
public event EventHandler SetupFinished;
void Awake()
{
// Assign singleton.
Instance = this;
}
void Start()
{
StartCoroutine(Setup());
}
/// <summary>
/// Request setup should run as early as possible, in case requests are made on Start() elsewhere.
/// </summary>
private IEnumerator Setup()
{
Debug.Log("Waiting for AccessToken to be set...");
yield return new WaitUntil(() => (AccessToken != null && AccessToken.Length > 0));
Debug.Log("AccessToken has been set!");
// Reference to Authenticated User.
StartCoroutine(Person.GetMyself(error =>
{
throw new Exception("Couldn't set the Authenticated User");
}, success =>
{
SetupComplete = true;
if (SetupFinished != null)
{
SetupFinished(this, EventArgs.Empty);
}
Debug.Log("Cisco Spark SDK Ready! Authenticated as: " + Person.AuthenticatedUser.DisplayName);
}));
}
/// <summary>
/// Generate a Web Request to Spark.
/// </summary>
/// <param name="resource">Resource.</param>
/// <param name="requestType">Request type.</param>
/// <param name="data">Data to upload.</param>
public UnityWebRequest Generate(string resource, string requestType, byte[] data = null)
{
// Setup Headers.
var www = new UnityWebRequest(BaseUrl + "/" + resource);
www.SetRequestHeader("Authorization", "Bearer " + AccessToken);
www.SetRequestHeader("Content-type", "application/json; charset=utf-8");
www.method = requestType;
www.downloadHandler = new DownloadHandlerBuffer();
// Is there data to upload?
if (data != null)
{
www.uploadHandler = new UploadHandlerRaw(data);
}
return www;
}
/// <summary>
/// Retrieves an existing record from the Spark service by ID.
/// </summary>
/// <returns>The record's data.</returns>
/// <param name="id">Identifier.</param>
/// <param name="type">SparkType being retrieved.</param>
/// <param name="error">Error.</param>
/// <param name="result">Result.</param>
public IEnumerator GetRecord(string id, SparkType type, Action<SparkMessage> error, Action<Dictionary<string, object>> result)
{
var url = string.Format("{0}/{1}", type.GetEndpoint(), id);
var send = SendRequest(url, UnityWebRequest.kHttpVerbGET, null, error, result);
yield return StartCoroutine(send);
}
/// <summary>
/// Creates the record.
/// </summary>
/// <returns>The record.</returns>
/// <param name="data">Data.</param>
/// <param name="type">Type.</param>
/// <param name="error">Error.</param>
/// <param name="result">Result.</param>
public IEnumerator CreateRecord(Dictionary<string, object> data, SparkType type, Action<SparkMessage> error, Action<Dictionary<string, object>> result)
{
// Create request.
var recordDetails = System.Text.Encoding.UTF8.GetBytes(Json.Serialize(data));
var url = type.GetEndpoint();
var send = SendRequest(url, UnityWebRequest.kHttpVerbPOST, recordDetails, error, result);
yield return StartCoroutine(send);
}
/// <summary>
/// Updates the record.
/// </summary>
/// <returns>The record.</returns>
/// <param name="id">Identifier.</param>
/// <param name="data">Data.</param>
/// <param name="type">Type.</param>
/// <param name="error">Error.</param>
/// <param name="result">Result.</param>
public IEnumerator UpdateRecord(string id, Dictionary<string, object> data, SparkType type, Action<SparkMessage> error, Action<Dictionary<string, object>> result)
{
// Update Record.
var recordDetails = System.Text.Encoding.UTF8.GetBytes(Json.Serialize(data));
var url = type.GetEndpoint() + "/" + id;
var send = SendRequest(url, UnityWebRequest.kHttpVerbPUT, recordDetails, error, result);
yield return StartCoroutine(send);
}
/// <summary>
/// Deletes the record from Spark.
/// </summary>
/// <returns>The record.</returns>
/// <param name="id">Identifier.</param>
/// <param name="type">Type.</param>
/// <param name="error">Error.</param>
/// <param name="success">Success.</param>
public IEnumerator DeleteRecord(string id, SparkType type, Action<SparkMessage> error, Action<bool> success)
{
// Create Request.
var url = type.GetEndpoint() + "/" + id;
var send = SendRequest(url, UnityWebRequest.kHttpVerbDELETE, null, error, result =>
{
success(true);
});
yield return StartCoroutine(send);
}
/// <summary>
/// Retrieves multiple records from the Spark service.
/// </summary>
/// <param name="constraints">Any constraints on the results returned. See ApiConstrains.json for SparkType specific options.</param>
/// <param name="type">The SparkType to retrieve.</param>
/// <param name="error">Error from Spark, if any.</param>
/// <param name="result">List of de-serialised results as dictionaries.</param>
public IEnumerator ListRecords(Dictionary<string, string> constraints, SparkType type, Action<SparkMessage> error, Action<List<object>> result)
{
string queryString = System.Text.Encoding.UTF8.GetString(UnityWebRequest.SerializeSimpleForm(constraints));
string url = string.Format("{0}?{1}", type.GetEndpoint(), queryString);
var operation = SendRequest(url, UnityWebRequest.kHttpVerbGET, null, error, data =>
{
var items = data["items"] as List<object>;
result(items);
});
yield return StartCoroutine(operation);
}
/// <summary>
/// Makes a request so Spark and parses the response.
/// </summary>
/// <param name="url">URL to send request.</param>
/// <param name="requestType">Request Type.</param>
/// <param name="data">Data to upload, if any.</param>
/// <param name="error">SparkMessage to return.</param>
/// <param name="result">Result dictionary to return.</param>
IEnumerator SendRequest(string url, string requestType, byte[] data, Action<SparkMessage> error, Action<Dictionary<string, object>> result)
{
using (var www = Generate(url, requestType, data))
{
#if UNITY_5_4 || UNITY_5_5
yield return www.Send();
if (www.isError)
#else
yield return www.SendWebRequest();
if (www.isNetworkError)
#endif
{
// Unity couldn't make the Web Request.
throw new Exception(www.error);
}
else
{
// Handle an empty response.
try
{
var returnedData = Json.Deserialize(www.downloadHandler.text) as Dictionary<string, object>;
if (www.responseCode == 200)
{
result(returnedData);
}
else
{
error(new SparkMessage(returnedData, www));
}
}
catch (OverflowException)
{
// Response Body was empty.
if (www.responseCode == 204)
{
// This is actually a deletion success (it returns no body).
result(null);
}
else
{
// Unknown error occurred.
Debug.LogWarning("HTTP Error: " + www.error + " (" + www.responseCode + ")");
error(new SparkMessage(www));
}
}
}
}
}
}
}