ContentfulManager.cs
8.91 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
using Contentful.Core;
using Contentful.Core.Configuration;
using Contentful.Core.Models;
using Contentful.Core.Search;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using UnityEngine;
using UnityEngine.Networking;
namespace Contentful.Globacore
{
public enum RequestType
{
FETCH,
CREATE
};
public class Request
{
public Action<Response> onComplete { get; set; }
public object data { get; set; }
public string contentType { get; set; }
public RequestType requestType { get; set; } = RequestType.FETCH;
public string searchField { get; set; }
public string query { get; set; }
/// <summary>
/// Send request to Contentful DB. Make sure to pass to initialization data to the request object manually before calling this
/// </summary>
public void Send()
{
ContentfulManager.Instance.Create(this);
}
/// <summary>
/// Send request to Contentful DB. Asusumes the Contentful ContentType name is the same as the name of the class being passed
/// </summary>
/// <typeparam name="T"></typeparam>
public void Send<T>()
{
contentType = FormatContentType(typeof(T).ToString());
ContentfulManager.Instance.Create(this);
}
public void Send<T>(string contentType)
{
this.contentType = contentType;
ContentfulManager.Instance.Create(this);
}
/// <summary>
/// Send request to post content to Contentful DB
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="obj"></param>
/// <param name="contentType"></param>
public void Send<T>(T obj, string contentType)
{
requestType = RequestType.CREATE;
data = obj;
this.contentType = contentType;
ContentfulManager.Instance.Create(this);
}
/// <summary>
/// Send request to post content to Contentful DB. Asusumes the Contentful ContentType name is the same as the name of the class being passed
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="obj"></param>
/// <param name="contentType"></param>
public void Send<T>(T obj)
{
contentType = FormatContentType(typeof(T).ToString());
requestType = RequestType.CREATE;
data = obj;
ContentfulManager.Instance.Create(this);
}
public void Send<T>(string searchField, string query)
{
contentType = FormatContentType(typeof(T).ToString());
this.searchField = searchField;
this.query = query;
ContentfulManager.Instance.Create(this);
}
private string FormatContentType(string txt)
{
return (System.Char.ToLowerInvariant(txt[0]) + txt.Substring(1));
}
}
public class Response
{
public Request request { get; set; }
public ContentfulCollection<object> rawResponse { get; set; }
/// <summary>
/// Cast response from Contentful as type List<T>
/// </summary>
/// <typeparam name="T"></typeparam>
/// <returns></returns>
public List<T> GetAll<T>()
{
var result = new List<T>();
foreach(var item in rawResponse)
{
var obj = (Newtonsoft.Json.Linq.JObject)item;
result.Add(obj.ToObject<T>());
}
return result;
}
/// <summary>
/// Get first result from Contentful response as type T
/// </summary>
/// <typeparam name="T"></typeparam>
/// <returns></returns>
public T GetFirst<T>()
{
var first = (Newtonsoft.Json.Linq.JObject) rawResponse.FirstOrDefault();
var obj = first.ToObject<T>();
return obj;
}
}
public class ContentfulManager : Singleton<ContentfulManager>
{
#region Init
[SerializeField]
private string _spaceId, _deliveryToken, _managementToken;
private ContentfulClient _client;
private ContentfulManagementClient _mClient;
private void Awake()
{
ContentfulOptions options = new ContentfulOptions()
{
ManagementApiKey = _managementToken,
DeliveryApiKey = _deliveryToken,
SpaceId = _spaceId
};
_client = new ContentfulClient(new HttpClient(), options);
_mClient = new ContentfulManagementClient(new HttpClient(), options);
StartCoroutine(JobQueue());
}
public void Create(Request request)
{
_activeRequests.Enqueue(request);
}
private Queue<Request> _activeRequests = new Queue<Request>();
private IEnumerator JobQueue()
{
while (true)
{
while (_activeRequests.Count == 0) yield return null;
var thisReq = _activeRequests.Dequeue();
Coroutine reqCoroutine = null;
switch (thisReq.requestType)
{
case RequestType.FETCH:
reqCoroutine = StartCoroutine(FetchRequest(thisReq));
break;
case RequestType.CREATE:
reqCoroutine = StartCoroutine(CreateRequest(thisReq));
break;
}
yield return reqCoroutine;
}
}
#endregion
private IEnumerator FetchRequest(Request req)
{
string search = "fields." + req.searchField;
var queryBuilder = new QueryBuilder<object>().ContentTypeIs(req.contentType).FieldEquals(search, req.query).Include(10);
var fetchReq = _client.GetEntries(queryBuilder);
while (!fetchReq.IsCompleted) yield return null;
Response thisResp = new Response()
{
request = req,
rawResponse = fetchReq.Result
};
req.onComplete?.Invoke(thisResp);
}
private IEnumerator CreateRequest(Request req)
{
var entry = GenerateEntry(req.data, req.GetType().ToString());
var createEntry = _mClient.CreateEntry(entry, contentTypeId: req.contentType);
while (!createEntry.IsCompleted) yield return null;
print(createEntry.Result.GetType());
print(Newtonsoft.Json.JsonConvert.SerializeObject(createEntry));
var createdEntry = createEntry.Result;
var publishEntry = _mClient.PublishEntry(createdEntry.SystemProperties.Id, 1);
while (!publishEntry.IsCompleted) yield return null;
Debug.Log(publishEntry.Result.ToString());
Response thisResp = new Response()
{
request = req,
//rawResponse = publishEntry.Result
};
req.onComplete?.Invoke(thisResp);
}
private Entry<dynamic> GenerateEntry<T>(T obj, string contentType)
{
Type type = obj.GetType();
var entry = new Entry<dynamic>();
entry.SystemProperties = new SystemProperties();
entry.SystemProperties.Id = contentType;
var dict = new Dictionary<string, object>();
foreach (var prop in type.GetProperties())
{
if (prop.PropertyType == typeof(SystemProperties)) continue;
// ignore what ought be ignored
if (Attribute.IsDefined(prop, typeof(Newtonsoft.Json.JsonIgnoreAttribute))) continue;
dict.Add(prop.Name, new Dictionary<string, object>()
{
{ "en-US", prop.GetValue(obj) }
});
}
foreach (var prop in type.GetFields())
{
if (prop.FieldType == typeof(SystemProperties)) continue;
// ignore what ought be ignored
if (Attribute.IsDefined(prop, typeof(Newtonsoft.Json.JsonIgnoreAttribute))) continue;
dict.Add(prop.Name, new Dictionary<string, object>()
{
{ "en-US", prop.GetValue(obj) }
});
}
entry.Fields = dict;
return entry;
}
public void GetAsset(string id, string url, Action<byte[]> onComplete)
{
StartCoroutine(GetAssetCoroutine(id, url, onComplete));
}
private IEnumerator GetAssetCoroutine(string id, string url, Action<byte[]> onComplete)
{
Debug.Log(url);
var www = UnityWebRequest.Get(url);
yield return www.SendWebRequest();
onComplete?.Invoke(www.downloadHandler.data);
}
}
}