WebRequest.cs 14.6 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 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451
using UnityEngine;
using UnityEngine.Networking;
using System.Collections;
using System.Collections.Generic;
using Newtonsoft.Json;
using System.IO;

/// <summary>
/// Usage: Create new Request object, specify web address, callback functions, request method, etc.
/// Then call yourRequest.Send()
/// If you specify a callback function when a request completes, it requires an argument of type ResponseData to be passed
/// Note that due to apparent licensing weirdness around mp3 files with Unity, FetchType.AUDIOCLIP will only work with wav / ogg files
/// </summary>
namespace WebKit
{
    public class Utility
    {
        public static T DeserializeData<T>(string json)
        {
            return JsonConvert.DeserializeObject<T>(json);
        }
    }

    public enum RequestMethod
    {
        GET,
        POST,
        PUT,
        PATCH,
        DELETE
    };

    public enum FetchType
    {
        JSON,
        TEXTURE,
        AUDIOCLIP,
        ASSETBUNDLE
    };

    [System.Serializable]
	public class Request
	{
        /// <summary>
        /// The url you want to send / recieve data from
        /// </summary>
        public string url { get; set; }
		
        /// <summary>
        /// If token / auth is required
        /// </summary>
		public string authentication { get; set; }

        /// <summary>
        /// The type of request you wish to make. Defaults to JSON
        /// </summary>
        public FetchType fetchType { get; set; }

        /// <summary>
        /// The REST request type
        /// </summary>
		public RequestMethod method { get; set; }

        /// <summary>
        /// Data to be sent with request
        /// </summary>
        public object data { get; set; }

        /// <summary>
        /// Form data to be sent with request
        /// </summary>
        public Dictionary<string, string> formData { get; set; }

        /// <summary>
        /// Additional headers needed to complete request
        /// </summary>
		public Dictionary <string, string> headers { get; set; }

        /// <summary>
        /// Callback called on completion of request
        /// </summary>
		public System.Action <Response> onComplete { get; set; }

        /// <summary>
        /// Callback to provide progress on request
        /// </summary>
        public System.Action<float> onUpdate { get; set; }

        //private System.DateTime _timeStamp;

        /// <summary>
        /// Timestamp on object creation
        /// </summary>
        public System.DateTime timeStamp { get; set; }
        //public System.DateTime timeStamp { get { return _timeStamp; } }

        /// <summary>
        /// Adds request to the queue
        /// </summary>
        public void Send()
        {
            WebRequest.Create(this);
        }
	}

    public class Response
    {
        /// <summary>
        /// The request that was sent
        /// </summary>
        public Request request { get; set; }
		
        /// <summary>
        /// If there was an error in the request
        /// </summary>
        public string error { get; set; }

        /// <summary>
        /// Converts JSON data from CMS into type T
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        public T GetParsedJsonObject<T>()
        {
            return Utility.DeserializeData<T>(text);
        }

        /// <summary>
        /// Texture2D fetched from server
        /// </summary>
        public Texture2D texture { get; set; }

        /// <summary>
        /// AudioClip fetched from the server
        /// </summary>
        public AudioClip audioClip { get; set; }

        /// <summary>
        /// AssetBundle fetched from the server
        /// </summary>
        public AssetBundle assetBundle { get; set; }

        /// <summary>
        /// Raw response from the CMS
        /// </summary>
        public string text { get; set; }

        /// <summary>
        /// Any non-text object returned from your request will wind up here (ex. Texture2D, AudioClip, etc)
        /// </summary>
        public byte[] bytes { get; set; }
    }
	
	public class WebRequest : MonoBehaviour
	{
        private static bool _cacheRequests = true;

        public static bool cacheRequests
        {
            get
            {
                return _cacheRequests;
            }
            set
            {
                _cacheRequests = value;
            }
        }

		private static WebRequest _instance = null;
		private static WebRequest instance
		{
			get
			{
				if (_instance == null)
				{
					_instance = FindObjectOfType (typeof (WebRequest)) as WebRequest;
					if (_instance == null)
						_instance = new GameObject ("CMSRequestManager").AddComponent <WebRequest> ();
				}
				
				return _instance;
			}
		}
		
		void Awake ()
		{
			DontDestroyOnLoad (this);

            if (cacheRequests)
                FetchCachedRequests();

            StartCoroutine(RequestQueue());
		}

        [System.Serializable]
        private class CachedRequest
        {
            public string url, authentication;
            public System.DateTime timeStamp;
            public object data;
            public Dictionary<string, string> formData;
            public Dictionary<string, string> headers;
            public FetchType fetchType;
            public RequestMethod method;
        }

        private Queue<Request> _requests = new Queue<Request>();
        private const string _cacheLocation = "/requestCache/";

        private void FetchCachedRequests()
        {
            if (!Directory.Exists(Application.persistentDataPath + _cacheLocation))
                Directory.CreateDirectory(Application.persistentDataPath + _cacheLocation);

            string[] files = Directory.GetFiles(Application.persistentDataPath + _cacheLocation);
            foreach (string contents in files)
            {
                CachedRequest thisCache = JsonConvert.DeserializeObject<CachedRequest>(File.ReadAllText(contents));
                Request thisReq = new Request()
                {
                    url = thisCache.url,
                    authentication = thisCache.authentication,
                    timeStamp = thisCache.timeStamp,
                    data = thisCache.data,
                    formData = thisCache.formData,
                    headers = thisCache.headers,
                    fetchType = thisCache.fetchType,
                    method = thisCache.method
                };

                _requests.Enqueue(thisReq);
            }
        }

        /// <summary>
        /// Create a new CMS request
        /// </summary>
        /// <param name="request"></param>
		public static void Create (Request request)
        {
            request.timeStamp = System.DateTime.Now;

            if (cacheRequests)
                instance.CacheRequest(request);

            instance._requests.Enqueue(request);
		}

        private void CacheRequest(Request request)
        {
            var cachedReq = new CachedRequest()
            {
                url = request.url,
                authentication = request.authentication,
                timeStamp = request.timeStamp,
                data = request.data,
                formData = request.formData,
                headers = request.headers,
                fetchType = request.fetchType,
                method = request.method
            };

            string contents = JsonConvert.SerializeObject(cachedReq);
            
            //dumb hack - for some reason, serializing and deserializing the timestamp 
            //rounds everything, so files are never found properly. this fixes it
            long time = request.timeStamp.ToFileTime() / 10000 * 10000;

            string path = Application.persistentDataPath + 
                _cacheLocation + time;

            File.WriteAllText(path, contents);
        }

        private void DestroyCachedRequest(Request request)
        {
            long time = request.timeStamp.ToFileTime() / 10000 * 10000;
            string path = Application.persistentDataPath +
                _cacheLocation + time;

            if (File.Exists(path))
                File.Delete(path);
        }

        private IEnumerator RequestQueue()
        {
            while (true)
            {
                while (_requests.Count > 0)
                {
                    Request requestData = _requests.Peek();
                    if (!cacheRequests)
                        requestData = _requests.Dequeue();

                    Debug.Log("WebRequest: " + requestData.method + " request to " + requestData.url);

                    WWW request = null;

                    bool errorState = false;

                    string requestError;
                    string requestText;
                    byte[] requestBytes;

                    // REQUEST SET UP
                    if (requestData.formData == null)
                    {
                        if (requestData.method != RequestMethod.GET && requestData.data == null)
                        {
                            var d = new Dictionary<string, string>();
                            d.Add("foo", "bar");
                            requestData.data = d;
                        }

                        byte[] postData = null;
                        if (requestData.data != null)
                            postData = System.Text.Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(requestData.data));

                        var headers = requestData.headers;
                        if (headers == null)
                            headers = new Dictionary<string, string>();

                        if (!headers.ContainsKey("Content-Type"))
                            headers.Add("Content-Type", "application/json");

                        if (!headers.ContainsKey("X-HTTP-Method-Override"))
                            headers.Add("X-HTTP-Method-Override", requestData.method.ToString());

                        if (!headers.ContainsKey("Authentication"))
                        {
                            if (!string.IsNullOrEmpty(requestData.authentication))
                                headers.Add("Authorization", requestData.authentication);
                        }

                        request = new WWW(requestData.url, postData, headers);
                        while (!request.isDone)
                        {
                            if (requestData.onUpdate != null)
                                requestData.onUpdate(request.progress);

                            yield return null;
                        }

                        if (!string.IsNullOrEmpty(request.error))
                        {
                            errorState = true;
                            Debug.LogError("WebRequest: " + request.error);
                        }
                        else
                        {
                            if (cacheRequests)
                            {
                                Request thisReq = _requests.Dequeue();
                                DestroyCachedRequest(thisReq);
                            }
                        }

                        requestError = request.error;
                        requestText = request.text;
                        requestBytes = request.bytes;
                    }
                    else
                    {
                        WWWForm form = new WWWForm();
                        foreach (KeyValuePair<string, string> entry in requestData.formData)
                        {
                            form.AddField(entry.Key, entry.Value);
                        }

                        UnityWebRequest formRequest = UnityWebRequest.Post(requestData.url, form);

                        foreach (KeyValuePair<string, string> entry in requestData.headers)
                        {
                            formRequest.SetRequestHeader(entry.Key, entry.Value);
                        }

                        // Wait until the download is done
                        yield return formRequest.SendWebRequest();

                        if (formRequest.isNetworkError || formRequest.isHttpError)
                        {
                            errorState = true;
                            Debug.LogError("FormRequest: " + formRequest.error);
                        }
                        else
                        {
                            if (cacheRequests)
                            {
                                Request thisReq = _requests.Dequeue();
                                DestroyCachedRequest(thisReq);
                            }
                        }

                        requestError = formRequest.error;
                        requestText = formRequest.downloadHandler.text;
                        requestBytes = formRequest.downloadHandler.data;

                        formRequest.Dispose();
                    }

                    // RESPONSE PARSING
                    if (requestData.onComplete != null)
                    {
                        Response response = new Response();
                        response.request = requestData;
                        response.error = requestError;
                        response.text = requestText;
                        response.bytes = requestBytes;

                        if (request != null)
                        {
                            if (requestData.fetchType == FetchType.TEXTURE)
                            {
                                Texture2D t = new Texture2D(2, 2);
                                request.LoadImageIntoTexture(t);
                                response.texture = t;
                            }
                            else if (requestData.fetchType == FetchType.AUDIOCLIP)
                            {
                                response.audioClip = request.GetAudioClipCompressed();
                                yield return null;
                            }
                            else if (requestData.fetchType == FetchType.ASSETBUNDLE)
                            {
                                response.assetBundle = request.assetBundle;
                            }
                        }

                        requestData.onComplete(response);
                    }
                    if (request != null)
                    {
                        request.Dispose();
                    }

                    // rather than hammering the cms with the same failed request over and over...
                    if (errorState && cacheRequests)
                        yield return new WaitForSeconds(10f);
                }

                yield return null;
            }
        }
		
		void OnDestroy ()
		{
			_instance = null;
		}
	}
}