LangChaoMinIo.cs 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264
  1. using LitJson;
  2. using Minio;
  3. using Minio.DataModel.Args;
  4. using Minio.Exceptions;
  5. using System;
  6. using System.Collections;
  7. using System.Collections.Generic;
  8. using System.IO;
  9. using System.Threading;
  10. using System.Threading.Tasks;
  11. using UnityEngine;
  12. using UnityEngine.Networking;
  13. using XRTool.Util;
  14. public class LangChaoMinIo : MonoSingleton<LangChaoMinIo>
  15. {
  16. IMinioClient minio;
  17. string path;
  18. string bucket;
  19. string host;
  20. string tmpSecretId;
  21. string tmpSecretKey;
  22. string minioToken;
  23. int projectId;
  24. Thread thread;
  25. private void Start()
  26. {
  27. thread = new Thread(DoSomeWork);
  28. thread.Start();
  29. }
  30. bool isminioUpdate;
  31. bool isUpdate;
  32. void DoSomeWork()
  33. {
  34. while (true)
  35. {
  36. if (minio == null)
  37. {
  38. if (projectId != 0 && !isminioUpdate)
  39. {
  40. isminioUpdate = true;
  41. initMinIo((bool b) =>
  42. {
  43. isminioUpdate = false;
  44. });
  45. }
  46. }
  47. else
  48. {
  49. if (Nowfd != null && !isUpdate)
  50. {
  51. isUpdate = true;
  52. Run().Wait();
  53. }
  54. }
  55. Thread.Sleep(1000);
  56. }
  57. }
  58. void initMinIo(Action<bool> callBack)
  59. {
  60. JsonData data = new JsonData();
  61. data["inspectionId"] = projectId;
  62. GameStart.Instance.StartCoroutine(HttpTool.Instance.SendHttp(HttpActionLang.storage_inspectionCredential, data.ToJson(), async (string str) =>
  63. {
  64. try
  65. {
  66. JsonData d = JsonMapper.ToObject(str);
  67. minioToken = d["data"]["credentials"]["token"].ToString();
  68. tmpSecretId = d["data"]["credentials"]["tmpSecretId"].ToString();
  69. tmpSecretKey = d["data"]["credentials"]["tmpSecretKey"].ToString();
  70. host = d["data"]["host"].ToString();
  71. bucket = d["data"]["bucket"].ToString();
  72. path = d["data"]["path"].ToString();
  73. Debug.Log(str);
  74. bool isHttps = host.Contains("https");
  75. var endpoint = host.Split("//")[1];
  76. var accessKey = tmpSecretId;//"tr6Nh5D8bnlGaLJE6vb5";
  77. var secretKey = tmpSecretKey;// "aVOYdXLnX4MCiKbit8aomZNWvAx8YSpzhiwzFhrI";
  78. Debug.Log("endpoint===>" + endpoint + " isHttps==>" + isHttps);
  79. minio = new MinioClient()
  80. .WithEndpoint(endpoint)
  81. .WithCredentials(accessKey, secretKey)
  82. .WithSessionToken(minioToken)
  83. .WithSSL(isHttps)
  84. .Build();
  85. TimerMgr.Instance.CreateTimer(() =>
  86. {
  87. minio = null;
  88. }, 1200);
  89. callBack?.Invoke(true);
  90. }
  91. catch
  92. {
  93. callBack?.Invoke(false);
  94. }
  95. }));
  96. }
  97. Queue<FileData> fdQueue = new Queue<FileData>();
  98. void putFile(string filePath, string fileName, Action<bool> callBack)
  99. {
  100. FileData fd = new FileData();
  101. fd.filePath = filePath;
  102. fd.fileName = fileName;
  103. fd.callBack = callBack;
  104. fdQueue.Enqueue(fd);
  105. }
  106. string DicName = "XunJian";
  107. public void saveFile(Texture tex, int projectId, string Index, int imgIndex, Action<bool> callBack)
  108. {
  109. this.projectId = projectId;
  110. Texture2D texture2D = TextureToTexture2D(tex);
  111. byte[] bytes = texture2D.EncodeToPNG();
  112. if (!Directory.Exists(Application.persistentDataPath + "/" + DicName))
  113. Directory.CreateDirectory(Application.persistentDataPath + "/" + DicName);
  114. string fileName = DicName + "_" + projectId + "_" + Index + "_" + imgIndex + ".png";
  115. string filePathname = Application.persistentDataPath + "/" + DicName + "/" + fileName;
  116. if (File.Exists(filePathname))
  117. File.Delete(filePathname);
  118. File.WriteAllBytes(filePathname, bytes);
  119. PlayerPrefs.SetString(fileName, filePathname);
  120. putFile(filePathname, fileName, callBack);
  121. }
  122. /// <summary>
  123. /// 运行模式下Texture转换成Texture2D
  124. /// </summary>
  125. /// <param name="texture"></param>
  126. /// <returns></returns>
  127. private Texture2D TextureToTexture2D(Texture texture)
  128. {
  129. Texture2D texture2D = new Texture2D(texture.width, texture.height, TextureFormat.RGBA32, false);
  130. RenderTexture currentRT = RenderTexture.active;
  131. RenderTexture renderTexture = RenderTexture.GetTemporary(texture.width, texture.height, 32);
  132. Graphics.Blit(texture, renderTexture);
  133. RenderTexture.active = renderTexture;
  134. texture2D.ReadPixels(new Rect(0, 0, renderTexture.width, renderTexture.height), 0, 0);
  135. texture2D.Apply();
  136. RenderTexture.active = currentRT;
  137. RenderTexture.ReleaseTemporary(renderTexture);
  138. return texture2D;
  139. }
  140. /// <summary>
  141. /// 获取文件
  142. /// </summary>
  143. /// <param name="projectId">巡检ID</param>
  144. /// <param name="Index">步骤ID</param>
  145. /// <param name="imgIndex">步骤ID内图片ID</param>
  146. /// <param name="callBack"></param>
  147. public void getFile(int projectId, string Index, int imgIndex, Action<Texture2D> callBack)//, string path
  148. {
  149. this.projectId = projectId;
  150. string fileName = DicName + "_" + projectId + "_" + Index + "_" + imgIndex + ".png";
  151. string filePathname = PlayerPrefs.GetString(fileName);
  152. if (filePathname != "")
  153. {
  154. StartCoroutine(_GetTexture(filePathname, callBack));
  155. }
  156. else
  157. {
  158. callBack.Invoke(null);
  159. }
  160. }
  161. /// <summary>
  162. /// 请求图片
  163. /// </summary>
  164. /// <param name="url">图片地址,like 'http://www.my-server.com/image.png '</param>
  165. /// <param name="action">请求发起后处理回调结果的委托,处理请求结果的图片</param>
  166. /// <returns></returns>
  167. IEnumerator _GetTexture(string url, Action<Texture2D> actionResult)
  168. {
  169. UnityWebRequest uwr = new UnityWebRequest(url);
  170. DownloadHandlerTexture downloadTexture = new DownloadHandlerTexture(true);
  171. uwr.downloadHandler = downloadTexture;
  172. yield return uwr.SendWebRequest();
  173. Texture2D t = null;
  174. if (!(uwr.isNetworkError || uwr.isHttpError))
  175. {
  176. t = downloadTexture.texture;
  177. }
  178. else
  179. {
  180. Debug.Log("下载失败,请检查网络,或者下载地址是否正确: " + uwr.error);
  181. }
  182. if (actionResult != null)
  183. {
  184. actionResult(t);
  185. }
  186. }
  187. // File uploader task.
  188. private async Task Run()
  189. {
  190. try
  191. {
  192. var getListBucketsTask = await minio.ListBucketsAsync().ConfigureAwait(false);
  193. var bucketName = bucket;
  194. var objectName = path + "/" + Nowfd.fileName;
  195. var filePath = Nowfd.filePath;
  196. var contentType = "application/octet-stream";
  197. // Make a bucket on the server, if not already present.
  198. // Upload a file to bucket.
  199. var putObjectArgs = new PutObjectArgs()
  200. .WithBucket(bucketName)
  201. .WithObject(objectName)
  202. .WithFileName(filePath)
  203. .WithContentType(contentType);
  204. await minio.PutObjectAsync(putObjectArgs).ConfigureAwait(false);
  205. Debug.Log("33333333333333333");
  206. isUpdate = false;
  207. Nowfd = null;
  208. Nowfd.callBack?.Invoke(true);
  209. }
  210. catch
  211. {
  212. isUpdate = false;
  213. Nowfd = null;
  214. Nowfd.callBack?.Invoke(false);
  215. }
  216. }
  217. FileData Nowfd;
  218. private void Update()
  219. {
  220. if (fdQueue.Count > 0 && Nowfd == null)
  221. {
  222. Nowfd = fdQueue.Dequeue();
  223. }
  224. }
  225. public class FileData
  226. {
  227. public string filePath;
  228. public string fileName;
  229. public Action<bool> callBack;
  230. }
  231. public class GetFileData
  232. {
  233. }
  234. }