LangChaoMinIo.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354
  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. }
  39. else
  40. {
  41. if (Nowfd != null && !isUpdate)
  42. {
  43. isUpdate = true;
  44. Run().Wait();
  45. }
  46. if ( gfdQueue.Count > 0 && !isDownLoad)
  47. {
  48. isDownLoad = true;
  49. nowgfd = gfdQueue.Dequeue();
  50. RunFile().Wait();
  51. }
  52. }
  53. Thread.Sleep(1000);
  54. }
  55. }
  56. void initMinIo(Action<bool> callBack)
  57. {
  58. JsonData data = new JsonData();
  59. data["inspectionId"] = projectId;
  60. GameStart.Instance.StartCoroutine(HttpTool.Instance.SendHttp(HttpActionLang.storage_inspectionCredential, data.ToJson(), async (string str) =>
  61. {
  62. try
  63. {
  64. JsonData d = JsonMapper.ToObject(str);
  65. minioToken = d["data"]["credentials"]["token"].ToString();
  66. tmpSecretId = d["data"]["credentials"]["tmpSecretId"].ToString();
  67. tmpSecretKey = d["data"]["credentials"]["tmpSecretKey"].ToString();
  68. host = d["data"]["host"].ToString();
  69. bucket = d["data"]["bucket"].ToString();
  70. path = d["data"]["path"].ToString();
  71. Debug.Log(str);
  72. bool isHttps = host.Contains("https");
  73. var endpoint = host.Split("//")[1];
  74. var accessKey = tmpSecretId;//"tr6Nh5D8bnlGaLJE6vb5";
  75. var secretKey = tmpSecretKey;// "aVOYdXLnX4MCiKbit8aomZNWvAx8YSpzhiwzFhrI";
  76. Debug.Log("endpoint===>" + endpoint + " isHttps==>" + isHttps);
  77. minio = new MinioClient()
  78. .WithEndpoint(endpoint)
  79. .WithCredentials(accessKey, secretKey)
  80. .WithSessionToken(minioToken)
  81. .WithSSL(isHttps)
  82. .Build();
  83. TimerMgr.Instance.CreateTimer(() =>
  84. {
  85. minio = null;
  86. }, 1200);
  87. callBack?.Invoke(true);
  88. }
  89. catch
  90. {
  91. callBack?.Invoke(false);
  92. }
  93. }));
  94. }
  95. Queue<FileData> fdQueue = new Queue<FileData>();
  96. void putFile(string filePath, string fileName, Action<string> callBack)
  97. {
  98. FileData fd = new FileData();
  99. fd.filePath = filePath;
  100. fd.fileName = fileName;
  101. fd.callBack = callBack;
  102. fdQueue.Enqueue(fd);
  103. }
  104. string DicName = "XunJian";
  105. public void saveFile(byte[] bytes, int projectId, string Index, int imgIndex, Action<string> callBack)
  106. {
  107. this.projectId = projectId;
  108. if (!Directory.Exists(Application.persistentDataPath + "/" + DicName))
  109. Directory.CreateDirectory(Application.persistentDataPath + "/" + DicName);
  110. string fileName = DicName + "_" + projectId + "_" + Index + "_" + imgIndex + ".png";
  111. string filePathname = Application.persistentDataPath + "/" + DicName + "/" + fileName;
  112. // if (File.Exists(filePathname))
  113. // File.Delete(filePathname);
  114. File.WriteAllBytes(filePathname, bytes);
  115. // PlayerPrefs.SetString(fileName, filePathname);
  116. putFile(filePathname, fileName, callBack);
  117. }
  118. /// <summary>
  119. /// 运行模式下Texture转换成Texture2D
  120. /// </summary>
  121. /// <param name="texture"></param>
  122. /// <returns></returns>
  123. private Texture2D TextureToTexture2D(Texture texture)
  124. {
  125. Texture2D texture2D = new Texture2D(texture.width, texture.height, TextureFormat.RGBA32, false);
  126. RenderTexture currentRT = RenderTexture.active;
  127. RenderTexture renderTexture = RenderTexture.GetTemporary(texture.width, texture.height, 32);
  128. Graphics.Blit(texture, renderTexture);
  129. RenderTexture.active = renderTexture;
  130. texture2D.ReadPixels(new Rect(0, 0, renderTexture.width, renderTexture.height), 0, 0);
  131. texture2D.Apply();
  132. RenderTexture.active = currentRT;
  133. RenderTexture.ReleaseTemporary(renderTexture);
  134. return texture2D;
  135. }
  136. /// <summary>
  137. /// 获取文件
  138. /// </summary>
  139. /// <param name="projectId">巡检ID</param>
  140. /// <param name="Index">步骤ID</param>
  141. /// <param name="imgIndex">步骤ID内图片ID</param>
  142. /// <param name="callBack"></param>
  143. public void getFile(int projectId, string Index, int imgIndex, Action<Texture2D> callBack)//, string path
  144. {
  145. this.projectId = projectId;
  146. string fileName = DicName + "_" + projectId + "_" + Index + "_" + imgIndex + ".png";
  147. string filePathname = PlayerPrefs.GetString(fileName);
  148. if (filePathname != "")
  149. {
  150. StartCoroutine(_GetTexture(filePathname, callBack));
  151. }
  152. else
  153. {
  154. GetFileData gfd = new GetFileData();
  155. gfd.bucket = bucket;
  156. gfd.objectName = DicName + "_" + projectId + "_" + Index + "_" + imgIndex + ".png";
  157. gfd.callBack = callBack;
  158. gfdQueue.Enqueue(gfd);
  159. }
  160. }
  161. GetFileData nowgfd;
  162. Queue<byte[]> backQueue = new Queue<byte[]>();
  163. Queue<GetFileData> gfdQueue = new Queue<GetFileData>();
  164. // File uploader task.
  165. private async Task RunFile()
  166. {
  167. Debug.LogError(bucket);
  168. Debug.LogError(path + "/" + nowgfd.objectName);
  169. try
  170. {
  171. StatObjectArgs statObjectArgs = new StatObjectArgs()
  172. .WithBucket(bucket)
  173. .WithObject(path + "/" + nowgfd.objectName);
  174. await minio.StatObjectAsync(statObjectArgs);
  175. // Get input stream to have content of 'my-objectname' from 'my-bucketname'
  176. GetObjectArgs getObjectArgs = new GetObjectArgs()
  177. .WithBucket(bucket)
  178. .WithObject(path + "/" + nowgfd.objectName)
  179. .WithCallbackStream(async (stream) =>
  180. {
  181. backQueue.Enqueue(StreamToBytes(stream));
  182. });
  183. await minio.GetObjectAsync(getObjectArgs);
  184. }
  185. catch
  186. {
  187. backQueue.Enqueue(null);
  188. }
  189. }
  190. static byte[] StreamToBytes(Stream stream)
  191. {
  192. byte[] bytes = new byte[stream.Length];
  193. stream.Read(bytes, 0, bytes.Length);
  194. stream.Seek(0, SeekOrigin.Begin);
  195. return bytes;
  196. }
  197. /// <summary>
  198. /// 请求图片
  199. /// </summary>
  200. /// <param name="url">图片地址,like 'http://www.my-server.com/image.png '</param>
  201. /// <param name="action">请求发起后处理回调结果的委托,处理请求结果的图片</param>
  202. /// <returns></returns>
  203. IEnumerator _GetTexture(string url, Action<Texture2D> actionResult)
  204. {
  205. #if UNITY_ANDROID
  206. //Debug.LogError("请求图片:"+url);
  207. WWW w = new WWW("file://" + url);
  208. yield return w;
  209. if (w.isDone)
  210. actionResult?.Invoke(w.texture);
  211. #else
  212. UnityWebRequest uwr = new UnityWebRequest(url);
  213. DownloadHandlerTexture downloadTexture = new DownloadHandlerTexture(true);
  214. uwr.downloadHandler = downloadTexture;
  215. yield return uwr.SendWebRequest();
  216. Texture2D t = null;
  217. if (!(uwr.isNetworkError || uwr.isHttpError))
  218. {
  219. t = downloadTexture.texture;
  220. }
  221. else
  222. {
  223. Debug.Log("下载失败,请检查网络,或者下载地址是否正确: " + uwr.error);
  224. }
  225. if (actionResult != null)
  226. {
  227. actionResult(t);
  228. }
  229. #endif
  230. }
  231. // File uploader task.
  232. private async Task Run()
  233. {
  234. try
  235. {
  236. var getListBucketsTask = await minio.ListBucketsAsync().ConfigureAwait(false);
  237. var bucketName = bucket;
  238. var objectName = path + "/" + Nowfd.fileName;
  239. var filePath = Nowfd.filePath;
  240. var contentType = "application/octet-stream";
  241. // Make a bucket on the server, if not already present.
  242. // Upload a file to bucket.
  243. var putObjectArgs = new PutObjectArgs()
  244. .WithBucket(bucketName)
  245. .WithObject(objectName)
  246. .WithFileName(filePath)
  247. .WithContentType(contentType);
  248. await minio.PutObjectAsync(putObjectArgs).ConfigureAwait(false);
  249. Debug.Log("33333333333333333");
  250. PlayerPrefs.SetString(Nowfd.fileName, Nowfd.filePath);
  251. isUpdate = false;
  252. Nowfd.callBack?.Invoke(Nowfd.fileName);
  253. Nowfd = null;
  254. }
  255. catch
  256. {
  257. Nowfd.callBack?.Invoke(null);
  258. isUpdate = false;
  259. Nowfd = null;
  260. }
  261. }
  262. bool isDownLoad;
  263. FileData Nowfd;
  264. private void Update()
  265. {
  266. if (fdQueue.Count > 0 && Nowfd == null)
  267. {
  268. Nowfd = fdQueue.Dequeue();
  269. }
  270. if (minio == null)
  271. {
  272. if (projectId != 0 && !isminioUpdate)
  273. {
  274. isminioUpdate = true;
  275. initMinIo((bool b) =>
  276. {
  277. isminioUpdate = false;
  278. });
  279. }
  280. }
  281. if(backQueue.Count>0)
  282. {
  283. byte[] bytes = backQueue.Dequeue();
  284. if(bytes!=null)
  285. {
  286. Debug.Log("444444444444");
  287. Texture2D t2d = new Texture2D(10, 10);
  288. t2d.LoadImage(bytes);
  289. t2d.Apply();
  290. nowgfd.callBack?.Invoke(t2d);
  291. }else
  292. {
  293. Debug.Log("55555555555555");
  294. nowgfd.callBack?.Invoke(null);
  295. }
  296. isDownLoad = false;
  297. nowgfd = null;
  298. }
  299. }
  300. public class FileData
  301. {
  302. public string filePath;
  303. public string fileName;
  304. public Action<string> callBack;
  305. }
  306. public class GetFileData
  307. {
  308. public string bucket;
  309. public string objectName;
  310. public Action<Texture2D> callBack;
  311. }
  312. }