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 URLBannerAdList; public List textureBunnerAd = new List(); public static UITexture CurTextureBackground; public UITexture UiTextureAdTexture; // public List URLBannerAdListLifja; //public List textureBunnerAdLifja = new List(); public enum States { Idle, LoadConfig, ConfigLoadDone, ConfigLoadFailed, Loading, LoadFailed, LoadDone, Empty, HasTexture, } private List _configs = new List(); 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 { } } /// /// Path to server config /// 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(); 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 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 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 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 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++; // } // } }