DownloadImageFromServer.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406
  1. using System.Collections.Generic;
  2. using UnityEngine;
  3. using System.Collections;
  4. using System;
  5. using System.IO;
  6. using SimpleJSON;
  7. public class DownloadImageFromServer : MonoBehaviour {
  8. #region Unity Singleton
  9. private string URL = "https://game.gamatic.com/app_condom_th/full_screen_ads/";
  10. private static DownloadImageFromServer _instance;
  11. public List<string> URLBannerAdList;
  12. public List<Texture2D> textureBunnerAd = new List<Texture2D>();
  13. public static UITexture CurTextureBackground;
  14. public UITexture UiTextureAdTexture;
  15. // public List<string> URLBannerAdListLifja;
  16. //public List<Texture2D> textureBunnerAdLifja = new List<Texture2D>();
  17. public enum States
  18. {
  19. Idle,
  20. LoadConfig,
  21. ConfigLoadDone,
  22. ConfigLoadFailed,
  23. Loading,
  24. LoadFailed,
  25. LoadDone,
  26. Empty,
  27. HasTexture,
  28. }
  29. private List<ConfigUnit> _configs = new List<ConfigUnit>();
  30. public class ConfigUnit
  31. {
  32. public static bool Loading { get; private set; }
  33. public string PlaceholderUrl { get; set; }
  34. public Texture PlaceholderImage { get; private set; }
  35. public bool IsLoaded { get; private set; }
  36. public bool Broken { get; private set; }
  37. public ConfigUnit(JSONNode source)
  38. {
  39. PlaceholderUrl = source["PlaceholderURL"];
  40. IsLoaded = false;
  41. }
  42. public IEnumerator Download(DownloadImageFromServer parent)
  43. {
  44. parent.State = States.Loading;
  45. Loading = true;
  46. var www = new WWW(PlaceholderUrl);
  47. yield return www;
  48. if (string.IsNullOrEmpty(www.error))
  49. {
  50. IsLoaded = true;
  51. www.Dispose();
  52. parent.State = States.LoadDone;
  53. }
  54. else
  55. {
  56. Debug.LogError("Banner:[" + www.error + "|" + www.url + "]");
  57. parent.State = States.LoadFailed;
  58. Broken = true;
  59. }
  60. if (!string.IsNullOrEmpty(PlaceholderUrl))
  61. {
  62. www = new WWW(PlaceholderUrl);
  63. yield return www;
  64. if (string.IsNullOrEmpty(www.error))
  65. {
  66. PlaceholderImage = www.texture;
  67. parent.State = States.HasTexture;
  68. CurTextureBackground.mainTexture = PlaceholderImage;
  69. }
  70. }
  71. Loading = false;
  72. }
  73. private string ExtractFileName(string url)
  74. {
  75. var arr = url.ToLower().Replace("\\", "/").Split(new[] { '/' }, StringSplitOptions.RemoveEmptyEntries);
  76. return arr[arr.Length - 1];
  77. }
  78. }
  79. public States State;
  80. public bool Empty
  81. {
  82. get { return _configs.Count == 0; }
  83. }
  84. private void RequesNextAd()
  85. {
  86. if (Empty)
  87. {
  88. State = States.Empty;
  89. return;
  90. }
  91. if (!ConfigUnit.Loading)
  92. {
  93. System.Random rand = new System.Random();
  94. Adware.Instance.currentAdBannerIndex = rand.Next(0, _configs.Count);
  95. if (Adware.Instance.currentAdBannerIndex >= _configs.Count)
  96. {
  97. Adware.Instance.currentAdBannerIndex = 0;
  98. }
  99. //Debug.Log(_configs[Adware.Instance.currentAdBannerIndex].PlaceholderUrl);
  100. StartCoroutine(_configs[Adware.Instance.currentAdBannerIndex].Download(this));
  101. //NGUIMenuScript.Instance._currentAdIndex = UnityEngine.Random.Range(0, _configs.Count);
  102. }
  103. else
  104. {
  105. }
  106. }
  107. /// <summary>
  108. /// Path to server config
  109. /// </summary>
  110. public string ConfigURL;
  111. public void DownloadNextImage()
  112. {
  113. StartCoroutine(LoadConfig());
  114. }
  115. public IEnumerator LoadConfig()
  116. {
  117. State = States.LoadConfig;
  118. var www = new WWW(ConfigURL);
  119. yield return www;
  120. if (string.IsNullOrEmpty(www.error))
  121. {
  122. var source = www.text;
  123. //Debug.Log(source);
  124. var json = SimpleJSON.JSON.Parse(www.text)["Config"].AsArray;
  125. foreach (JSONNode media in json)
  126. {
  127. _configs.Add(new ConfigUnit(media));
  128. }
  129. State = States.ConfigLoadDone;
  130. RequesNextAd();
  131. }
  132. else
  133. {
  134. Debug.LogError("Bunner:[" + www.error + "]");
  135. State = States.ConfigLoadFailed;
  136. }
  137. }
  138. private ConfigUnit Currnent
  139. {
  140. get { return _configs[Adware.Instance.currentAdBannerIndex]; }
  141. }
  142. public static int Counter2 = 0;
  143. public static DownloadImageFromServer Instance
  144. {
  145. get
  146. {
  147. if (_instance == null)
  148. {
  149. _instance = FindObjectOfType(typeof(DownloadImageFromServer)) as DownloadImageFromServer;
  150. if (_instance == null)
  151. {
  152. 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));
  153. }
  154. }
  155. return _instance;
  156. }
  157. }
  158. void Awake()
  159. {
  160. if (_instance != null && _instance != this)
  161. {
  162. AVDebug.LogWarning(string.Format("{0} Instance already exists on another gameObject. Destroying this gameObject {1}", this.GetType().Name, gameObject.name));
  163. Destroy(gameObject);
  164. return;
  165. }
  166. _instance = this;
  167. DontDestroyOnLoad(gameObject);
  168. if (CurTextureBackground == null && UiTextureAdTexture != null)
  169. {
  170. CurTextureBackground = UiTextureAdTexture;
  171. }
  172. ConfigURL = GameConstants.BANNER_ADS;
  173. _configs = new List<ConfigUnit>();
  174. StartCoroutine(LoadConfig());
  175. }
  176. #endregion
  177. void GetImages()
  178. {
  179. switch (MenuManager._instance.CurStateGameState)
  180. {
  181. case MenuManager.StateGameProduction.DurexLifja:
  182. foreach (var banner in URLBannerAdList)
  183. {
  184. GetImage(banner, (b, d) => textureBunnerAd.Add(d));
  185. }
  186. //foreach (var banner in URLBannerAdListLifja)
  187. //{
  188. // GetImage(banner, (b, d) => textureBunnerAdLifja.Add(d));
  189. //}
  190. break;
  191. case MenuManager.StateGameProduction.None:
  192. break;
  193. }
  194. }
  195. private Hashtable _loadedImages = new Hashtable();
  196. public static void ClearImagesInMemory()
  197. {
  198. Instance._loadedImages = new Hashtable();
  199. }
  200. private IEnumerator LoadImageFromCache(string textureName, Action<Texture2D> onComplete)
  201. {
  202. string directoryPath = Application.persistentDataPath + "/imageCache";
  203. WWW w = new WWW("file://" + Path.GetFullPath(string.Format(@"{0}/{1}.png", directoryPath, textureName)));
  204. yield return w;
  205. onComplete(w.texture);
  206. }
  207. public static void GetImage(string url, Action<bool, Texture2D> onComplete)
  208. {
  209. string[] parsedTextureName = url.Split('/');
  210. string textureName = parsedTextureName[parsedTextureName.Length - 1].Split('.')[0];
  211. GetImage(url, textureName, onComplete);
  212. }
  213. public static void GetImage(string url, string textureName, Action<bool, Texture2D> onComplete)
  214. {
  215. if (textureName == null)
  216. {
  217. onComplete(false, null);
  218. return;
  219. }
  220. if (Instance._loadedImages.ContainsKey(textureName))
  221. {
  222. AVDebug.Log("Already got loaded image in memory: " + textureName);
  223. onComplete(true, (Texture2D)Instance._loadedImages[textureName]);
  224. }
  225. else
  226. //We cannot access files in WebPlayer
  227. /*#if !UNITY_WEBPLAYER && !UNITY_EDITOR
  228. if (File.Exists(string.Format("{0}/imageCache/{1}.png", Application.persistentDataPath, textureName)))
  229. {
  230. Debug.Log("Caching image from disk: " + textureName);
  231. if (onComplete != null)
  232. {
  233. Instance.StartCoroutine(Instance.LoadImageFromCache(textureName, (loadedTexture) =>
  234. {
  235. onComplete(true, loadedTexture);
  236. //There might have been dual asynch request to the same image. This avoids a crash
  237. if (!Instance._loadedImages.ContainsKey(textureName))
  238. {
  239. Instance._loadedImages.Add(textureName, loadedTexture);
  240. }
  241. }));
  242. }
  243. }
  244. else
  245. #endif*/
  246. {
  247. AVDebug.Log("Downloading image from url: " + url);
  248. Instance.StartCoroutine(Instance.DownloadImage(url, textureName, (success, downloadedTexture) =>
  249. {
  250. if (onComplete != null)
  251. {
  252. onComplete(success, downloadedTexture);
  253. }
  254. if (Counter2 == 0)
  255. {
  256. //DownloadImageFromServer.Instance. GetTexture();
  257. }
  258. Counter2++;
  259. }));
  260. }
  261. }
  262. private int count;
  263. private IEnumerator DownloadImage(string url, string textureName, Action<bool, Texture2D> onComplete)
  264. {
  265. var s = WWW.EscapeURL(url);
  266. WWW w = new WWW(URL + s);
  267. // Debug.Log(w.url);
  268. yield return w;
  269. if (w.texture != null/* && !w.texture.IsBogus()*/)
  270. {
  271. count++;
  272. //Debug.Log("Downloaded " + url);
  273. Instance.SaveImage(w.texture, textureName);
  274. if (onComplete != null)
  275. {
  276. onComplete(true, w.texture);
  277. }
  278. if (URLBannerAdList.Count >= 0)
  279. {
  280. //GetTexture();
  281. }
  282. }
  283. else
  284. {
  285. //Debug.Log("Download failed for " + url);
  286. if (onComplete != null)
  287. {
  288. onComplete(false, null);
  289. }
  290. }
  291. }
  292. private bool SaveImage(Texture2D texture, string textureName)
  293. {
  294. //There might have been dual asynch request to the same image. This avoids a crash
  295. if (Instance._loadedImages.ContainsKey(textureName))
  296. {
  297. //already saved
  298. return true;
  299. }
  300. Instance._loadedImages.Add(textureName, texture);
  301. //We cannot access files in WebPlayer
  302. #if !UNITY_WEBPLAYER && !UNITY_EDITOR
  303. string directoryPath = Application.persistentDataPath + "/imageCache";
  304. string fullPath = string.Format("{0}/{1}.png", directoryPath, textureName, ".png");
  305. if (File.Exists(fullPath))
  306. {
  307. return false;
  308. }
  309. if (!Directory.Exists(directoryPath))
  310. {
  311. Directory.CreateDirectory(directoryPath);
  312. }
  313. byte[] textureBytes = texture.EncodeToPNG();
  314. FileStream f = new FileStream(string.Format("{0}/{1}.png", directoryPath, textureName, ".png"), FileMode.Create, FileAccess.Write);
  315. f.Write(textureBytes, 0, textureBytes.Length);
  316. f.Flush();
  317. f.Close();
  318. #endif
  319. return true;
  320. }
  321. public IEnumerator GetTextureRoutine()
  322. {
  323. yield return new WaitForSeconds(1f);
  324. RequesNextAd();
  325. }
  326. public void GetTexture()
  327. {
  328. StartCoroutine(GetTextureRoutine());
  329. }
  330. private int counter = 0;
  331. //public void GetTexture()
  332. //{
  333. // switch (MenuManager._instance.CurStateGameState)
  334. // {
  335. // case MenuManager.StateGameProduction.DurexLifja:
  336. // if (counter%2 == 0 && textureBunnerAd.Count>0)
  337. // {
  338. // CurTextureBackground.mainTexture = textureBunnerAd[counter];
  339. // }
  340. // else
  341. // {
  342. // CurTextureBackground.mainTexture = textureBunnerAd[counter];
  343. // }
  344. // break;
  345. // case MenuManager.StateGameProduction.None:
  346. // //CurTextureBackground.mainTexture = textureBunnerAd[UnityEngine.Random.Range(0, textureBunnerAd.Count)];
  347. // break;
  348. // }
  349. // if(counter > 2)
  350. // {
  351. // counter = 0;
  352. // }
  353. // else
  354. // {
  355. // counter++;
  356. // }
  357. // }
  358. }