123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406 |
- using System.Collections.Generic;
- using UnityEngine;
- using System.Collections;
- using System;
- using System.IO;
- using SimpleJSON;
- public class DownloadImageFromServer : MonoBehaviour {
- #region Unity Singleton
- private string URL = "https://game.gamatic.com/app_condom_th/full_screen_ads/";
- private static DownloadImageFromServer _instance;
- public List<string> URLBannerAdList;
- public List<Texture2D> textureBunnerAd = new List<Texture2D>();
- public static UITexture CurTextureBackground;
- public UITexture UiTextureAdTexture;
- // public List<string> URLBannerAdListLifja;
- //public List<Texture2D> textureBunnerAdLifja = new List<Texture2D>();
- public enum States
- {
- Idle,
- LoadConfig,
- ConfigLoadDone,
- ConfigLoadFailed,
- Loading,
- LoadFailed,
- LoadDone,
- Empty,
- HasTexture,
- }
- private List<ConfigUnit> _configs = new List<ConfigUnit>();
- public class ConfigUnit
- {
- public static bool Loading { get; private set; }
- public string PlaceholderUrl { get; set; }
- public Texture PlaceholderImage { get; private set; }
- public bool IsLoaded { get; private set; }
- public bool Broken { get; private set; }
- public ConfigUnit(JSONNode source)
- {
- PlaceholderUrl = source["PlaceholderURL"];
- IsLoaded = false;
- }
- public IEnumerator Download(DownloadImageFromServer parent)
- {
- parent.State = States.Loading;
- Loading = true;
- var www = new WWW(PlaceholderUrl);
- yield return www;
- if (string.IsNullOrEmpty(www.error))
- {
- IsLoaded = true;
- www.Dispose();
- parent.State = States.LoadDone;
- }
- else
- {
- Debug.LogError("Banner:[" + www.error + "|" + www.url + "]");
- parent.State = States.LoadFailed;
- Broken = true;
- }
- if (!string.IsNullOrEmpty(PlaceholderUrl))
- {
- www = new WWW(PlaceholderUrl);
- yield return www;
- if (string.IsNullOrEmpty(www.error))
- {
- PlaceholderImage = www.texture;
- parent.State = States.HasTexture;
- CurTextureBackground.mainTexture = PlaceholderImage;
- }
- }
- Loading = false;
- }
- private string ExtractFileName(string url)
- {
- var arr = url.ToLower().Replace("\\", "/").Split(new[] { '/' }, StringSplitOptions.RemoveEmptyEntries);
- return arr[arr.Length - 1];
- }
- }
- public States State;
- public bool Empty
- {
- get { return _configs.Count == 0; }
- }
- private void RequesNextAd()
- {
- if (Empty)
- {
- State = States.Empty;
- return;
- }
- if (!ConfigUnit.Loading)
- {
- System.Random rand = new System.Random();
- Adware.Instance.currentAdBannerIndex = rand.Next(0, _configs.Count);
- if (Adware.Instance.currentAdBannerIndex >= _configs.Count)
- {
- Adware.Instance.currentAdBannerIndex = 0;
- }
- //Debug.Log(_configs[Adware.Instance.currentAdBannerIndex].PlaceholderUrl);
- StartCoroutine(_configs[Adware.Instance.currentAdBannerIndex].Download(this));
- //NGUIMenuScript.Instance._currentAdIndex = UnityEngine.Random.Range(0, _configs.Count);
- }
- else
- {
- }
- }
- /// <summary>
- /// Path to server config
- /// </summary>
- public string ConfigURL;
- public void DownloadNextImage()
- {
- StartCoroutine(LoadConfig());
- }
- public IEnumerator LoadConfig()
- {
- State = States.LoadConfig;
- var www = new WWW(ConfigURL);
- yield return www;
- if (string.IsNullOrEmpty(www.error))
- {
- var source = www.text;
- //Debug.Log(source);
- var json = SimpleJSON.JSON.Parse(www.text)["Config"].AsArray;
- foreach (JSONNode media in json)
- {
- _configs.Add(new ConfigUnit(media));
- }
- State = States.ConfigLoadDone;
- RequesNextAd();
- }
- else
- {
- Debug.LogError("Bunner:[" + www.error + "]");
- State = States.ConfigLoadFailed;
- }
- }
- private ConfigUnit Currnent
- {
- get { return _configs[Adware.Instance.currentAdBannerIndex]; }
- }
-
- public static int Counter2 = 0;
- public static DownloadImageFromServer Instance
- {
- get
- {
- if (_instance == null)
- {
- _instance = FindObjectOfType(typeof(DownloadImageFromServer)) as DownloadImageFromServer;
- if (_instance == null)
- {
- AVDebug.LogError(string.Format("No gameObject with {0} component exists. Make sure to create a gameObject with {0} component", new System.Diagnostics.StackFrame().GetMethod().DeclaringType));
- }
- }
- return _instance;
- }
- }
- void Awake()
- {
- if (_instance != null && _instance != this)
- {
- AVDebug.LogWarning(string.Format("{0} Instance already exists on another gameObject. Destroying this gameObject {1}", this.GetType().Name, gameObject.name));
- Destroy(gameObject);
- return;
- }
- _instance = this;
- DontDestroyOnLoad(gameObject);
- if (CurTextureBackground == null && UiTextureAdTexture != null)
- {
- CurTextureBackground = UiTextureAdTexture;
- }
- ConfigURL = GameConstants.BANNER_ADS;
-
- _configs = new List<ConfigUnit>();
- StartCoroutine(LoadConfig());
- }
- #endregion
- void GetImages()
- {
- switch (MenuManager._instance.CurStateGameState)
- {
- case MenuManager.StateGameProduction.DurexLifja:
-
- foreach (var banner in URLBannerAdList)
- {
- GetImage(banner, (b, d) => textureBunnerAd.Add(d));
- }
- //foreach (var banner in URLBannerAdListLifja)
- //{
- // GetImage(banner, (b, d) => textureBunnerAdLifja.Add(d));
- //}
- break;
- case MenuManager.StateGameProduction.None:
- break;
- }
- }
- private Hashtable _loadedImages = new Hashtable();
- public static void ClearImagesInMemory()
- {
- Instance._loadedImages = new Hashtable();
- }
- private IEnumerator LoadImageFromCache(string textureName, Action<Texture2D> onComplete)
- {
- string directoryPath = Application.persistentDataPath + "/imageCache";
- WWW w = new WWW("file://" + Path.GetFullPath(string.Format(@"{0}/{1}.png", directoryPath, textureName)));
- yield return w;
- onComplete(w.texture);
- }
- public static void GetImage(string url, Action<bool, Texture2D> onComplete)
- {
- string[] parsedTextureName = url.Split('/');
- string textureName = parsedTextureName[parsedTextureName.Length - 1].Split('.')[0];
- GetImage(url, textureName, onComplete);
- }
- public static void GetImage(string url, string textureName, Action<bool, Texture2D> onComplete)
- {
- if (textureName == null)
- {
- onComplete(false, null);
- return;
- }
- if (Instance._loadedImages.ContainsKey(textureName))
- {
- AVDebug.Log("Already got loaded image in memory: " + textureName);
- onComplete(true, (Texture2D)Instance._loadedImages[textureName]);
- }
- else
- //We cannot access files in WebPlayer
- /*#if !UNITY_WEBPLAYER && !UNITY_EDITOR
- if (File.Exists(string.Format("{0}/imageCache/{1}.png", Application.persistentDataPath, textureName)))
- {
- Debug.Log("Caching image from disk: " + textureName);
- if (onComplete != null)
- {
- Instance.StartCoroutine(Instance.LoadImageFromCache(textureName, (loadedTexture) =>
- {
- onComplete(true, loadedTexture);
- //There might have been dual asynch request to the same image. This avoids a crash
- if (!Instance._loadedImages.ContainsKey(textureName))
- {
- Instance._loadedImages.Add(textureName, loadedTexture);
- }
- }));
- }
- }
- else
- #endif*/
- {
- AVDebug.Log("Downloading image from url: " + url);
-
- Instance.StartCoroutine(Instance.DownloadImage(url, textureName, (success, downloadedTexture) =>
- {
-
- if (onComplete != null)
- {
- onComplete(success, downloadedTexture);
- }
- if (Counter2 == 0)
- {
- //DownloadImageFromServer.Instance. GetTexture();
- }
- Counter2++;
- }));
- }
- }
- private int count;
- private IEnumerator DownloadImage(string url, string textureName, Action<bool, Texture2D> onComplete)
- {
- var s = WWW.EscapeURL(url);
- WWW w = new WWW(URL + s);
- // Debug.Log(w.url);
- yield return w;
- if (w.texture != null/* && !w.texture.IsBogus()*/)
- {
-
- count++;
- //Debug.Log("Downloaded " + url);
- Instance.SaveImage(w.texture, textureName);
- if (onComplete != null)
- {
- onComplete(true, w.texture);
- }
- if (URLBannerAdList.Count >= 0)
- {
- //GetTexture();
- }
- }
- else
- {
- //Debug.Log("Download failed for " + url);
- if (onComplete != null)
- {
- onComplete(false, null);
- }
- }
- }
- private bool SaveImage(Texture2D texture, string textureName)
- {
- //There might have been dual asynch request to the same image. This avoids a crash
- if (Instance._loadedImages.ContainsKey(textureName))
- {
- //already saved
- return true;
- }
- Instance._loadedImages.Add(textureName, texture);
- //We cannot access files in WebPlayer
- #if !UNITY_WEBPLAYER && !UNITY_EDITOR
- string directoryPath = Application.persistentDataPath + "/imageCache";
- string fullPath = string.Format("{0}/{1}.png", directoryPath, textureName, ".png");
- if (File.Exists(fullPath))
- {
- return false;
- }
-
- if (!Directory.Exists(directoryPath))
- {
- Directory.CreateDirectory(directoryPath);
- }
- byte[] textureBytes = texture.EncodeToPNG();
- FileStream f = new FileStream(string.Format("{0}/{1}.png", directoryPath, textureName, ".png"), FileMode.Create, FileAccess.Write);
- f.Write(textureBytes, 0, textureBytes.Length);
- f.Flush();
- f.Close();
- #endif
- return true;
- }
- public IEnumerator GetTextureRoutine()
- {
- yield return new WaitForSeconds(1f);
- RequesNextAd();
- }
- public void GetTexture()
- {
- StartCoroutine(GetTextureRoutine());
-
- }
- private int counter = 0;
- //public void GetTexture()
- //{
- // switch (MenuManager._instance.CurStateGameState)
- // {
- // case MenuManager.StateGameProduction.DurexLifja:
- // if (counter%2 == 0 && textureBunnerAd.Count>0)
- // {
- // CurTextureBackground.mainTexture = textureBunnerAd[counter];
- // }
- // else
- // {
- // CurTextureBackground.mainTexture = textureBunnerAd[counter];
- // }
- // break;
- // case MenuManager.StateGameProduction.None:
- // //CurTextureBackground.mainTexture = textureBunnerAd[UnityEngine.Random.Range(0, textureBunnerAd.Count)];
- // break;
- // }
- // if(counter > 2)
- // {
- // counter = 0;
- // }
- // else
- // {
- // counter++;
- // }
- // }
- }
|