DownloadImageFromServer.cs 14 KB

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