123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452 |
- using System.Collections.Generic;
- using UnityEngine;
- using System.Collections;
- using System;
- using System.IO;
- using SimpleJSON;
- using UnityEngine.UI;
- /*[Serializable]
- public class VideoData
- {
- private string URLData;
- private float TimeSec;
- }*/
- public class DownloadImageFromServer : MonoBehaviour
- {
- #region Unity Singleton
- //private static DownloadImageFromServer _instance;
- public List<string> URLBannerAdList;
- public List<Texture2D> textureBunnerAd = new List<Texture2D>();
- public static RawImage CurTextureBackground;
- public static RawImage CurOldTextureBackground;
- public RawImage UiTextureAdTexture;
- public RawImage UiOldTextureAdTexture;
- 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 Texture PlaceholderImageNew { 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)
- {
- if (PlaceholderImage != null)
- {
- CurTextureBackground.texture = PlaceholderImageNew;
- }
- 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))
- {
- if (PlaceholderImage == null)
- {
- PlaceholderImage = www.texture;
- CurTextureBackground.texture = PlaceholderImage;
- PlaceholderImageNew = PlaceholderImage;
- }
- else
- {
- PlaceholderImageNew = www.texture;
- }
-
- parent.State = States.HasTexture;
- }
- }
- Loading = false;
- }
- private string ExtractFileName(string url)
- {
- var arr = url.ToLower().Replace("\\", "/").Split(new[] { '/' }, StringSplitOptions.RemoveEmptyEntries);
- return arr[arr.Length - 1];
- }
- public IEnumerator DownloadToList(DownloadImageFromServer parent)
- {
- if (PlaceholderImage != null)
- {
- CurTextureBackground.texture = PlaceholderImageNew;
- }
- 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))
- {
- var str = "https://game.gamatic.com/iCTS/BannerAD/";
- var conf = PlaceholderUrl.Substring(str.ToCharArray().Length);
- if (conf.Contains("OLD"))
- {
- DownloadImageFromServer.Instance.listOldTexturesBanner.Add(www.texture);
- }
- else
- {
- DownloadImageFromServer.Instance.listTexturesBanner.Add(www.texture);
- }
-
- parent.State = States.HasTexture;
- }
- }
- Loading = false;
- }
- }
- public bool Empty
- {
- get { return _configs.Count == 0; }
- }
- private readonly List<Texture> listTexturesBanner = new List<Texture>();
- private readonly List<Texture> listOldTexturesBanner = new List<Texture>();
- private void RequesNextAd()
- {
- if (Empty)
- {
- State = States.Empty;
- return;
- }
- if (!ConfigUnit.Loading)
- {
- currentAdBannerIndex++;
- if (currentAdBannerIndex >= _configs.Count)
- {
- currentAdBannerIndex = 0;
- }
- //Debug.Log(_configs[Adware.Instance.currentAdBannerIndex].PlaceholderUrl);
- StartCoroutine(_configs[currentAdBannerIndex].Download(this));
- //NGUIMenuScript.Instance._currentAdIndex = UnityEngine.Random.Range(0, _configs.Count);
- }
- }
- /// <summary>
- /// Path to server config
- /// </summary>
- public string ConfigURL;
- public static DownloadImageFromServer Instance { get; private set; }
- public void DownloadNextImage()
- {
- StartCoroutine(LoadConfig());
- }
- public States State;
- 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;
- AddAddToList();
- RequesNextAd();
- }
- else
- {
- Debug.LogError("Bunner:[" + www.error + "]");
- State = States.ConfigLoadFailed;
- }
- }
- private void AddAddToList()
- {
- for (int i = 0; i < _configs.Count; i++)
- {
- StartCoroutine(_configs[i].DownloadToList(this));
- }
- }
- private ConfigUnit Currnent
- {
- get { return _configs[currentAdBannerIndex]; }
- }
- void Start()
- {
- ConfigURL = GameConstants.BANNER_ADS;
- 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;
- }
- if (CurTextureBackground == null && UiTextureAdTexture != null)
- {
- CurTextureBackground = UiTextureAdTexture;
- }
- if (CurOldTextureBackground == null && UiOldTextureAdTexture != null)
- {
- CurOldTextureBackground = UiOldTextureAdTexture;
- }
- if (Instance)
- {
- Destroy(gameObject);
- }
- else
- {
- /*if (!Directory.Exists(Application.persistentDataPath + "/Data"))
- {
- Directory.CreateDirectory(Application.persistentDataPath + "/Data");
- }*/
- _configs = new List<ConfigUnit>();
- //NGUIMenuScript.Instance._currentAdIndex = -1;
- Instance = this;
- StartCoroutine(LoadConfig());
- //DontDestroyOnLoad(gameObject);
- }
- //DontDestroyOnLoad(gameObject);
- /*foreach (var banner in URLBannerAdList)
- {
- GetImage(banner, (b, d) => textureBunnerAd.Add(d));
- }*/
- //GetImage(URLBannerAdList[0], (b, d) => textureBunnerAd.Add(d));
- //GetImage(URLBannerAdList[0], (b, d) => textureBunnerAd.Add(d));
- }
- #endregion
- 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)
- {
- //Debug.Log("GetImage");
- if (textureName == null)
- {
- onComplete(false, null);
- //Debug.Log("GetImage2");
- return;
- }
- if (Instance._loadedImages.ContainsKey(textureName))
- {
- //Debug.Log("GetImage3");
- //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)))
- //{
- // //AVDebug.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);
- Debug.Log("GetImage4");
- Instance.StartCoroutine(Instance.DownloadImage(url, textureName, (success, downloadedTexture) =>
- {
- if (onComplete != null)
- {
- onComplete(success, downloadedTexture);
- }
- }));
- }
- }
- private int count;
- private int currentAdBannerIndex;
- private IEnumerator DownloadImage(string url, string textureName, Action<bool, Texture2D> onComplete)
- {
- WWW w = new WWW(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)
- {
- //Debug.Log("GetTexture");
- 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 void GetTexture()
- {
- //RequesNextAd();
- if(listTexturesBanner.Count>0)
- {
- currentAdBannerIndex = UnityEngine.Random.Range(0, listTexturesBanner.Count - 1);
- CurTextureBackground.texture = listTexturesBanner[currentAdBannerIndex];
- }
- }
- public Texture texture;
- public void GetTextureOldDurex()
- {
- CurOldTextureBackground.gameObject.SetActive(true);
- if (listOldTexturesBanner.Count > 0)
- {
- var rand = UnityEngine.Random.Range(0, listOldTexturesBanner.Count - 1);
- CurOldTextureBackground.texture = listOldTexturesBanner[rand];
- }
- for (int i = 0; i < _configs.Count; i++)
- {
- var str = "https://game.gamatic.com/iCTS/BannerAD/";
- var conf = _configs[i].PlaceholderUrl.Substring(str.ToCharArray().Length);
- if(conf.Contains("OLD"))
- {
- Debug.Log(conf);
- }
-
- }
- }
- }
|