TestMinIO.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376
  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 TestMinIO : MonoSingleton<TestMinIO>
  15. {
  16. private IMinioClient minio;
  17. private string path;
  18. private string bucket;
  19. private string host;
  20. private string tmpSecretId;
  21. string tmpSecretKey;
  22. private string minioToken;
  23. private int projectId;
  24. private bool isminioUpdate;
  25. private bool isUpdate;
  26. private Thread thread;
  27. private void Start()
  28. {
  29. thread = new Thread(DoSomeWork);
  30. thread.Start();
  31. }
  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. using (UnityWebRequest request = new UnityWebRequest(url))
  207. {
  208. DownloadHandlerTexture downloadHandlerTexture = new DownloadHandlerTexture(true);
  209. request.downloadHandler = downloadHandlerTexture;
  210. yield return request.SendWebRequest();
  211. if (string.IsNullOrEmpty(request.error))
  212. {
  213. Texture2D localTexture = downloadHandlerTexture.texture;
  214. actionResult?.Invoke(localTexture);
  215. }
  216. else
  217. {
  218. actionResult?.Invoke(null);
  219. Debug.Log("_GetTexture:" + request.error);
  220. }
  221. }
  222. /*
  223. WWW www = new WWW(url);
  224. yield return www;
  225. Texture2D texture2D = new Texture2D(450, 300);
  226. if (www.isDone)
  227. {
  228. actionResult?.Invoke(texture2D);
  229. //texture2D.LoadImage(www.bytes);
  230. }
  231. */
  232. #else
  233. UnityWebRequest uwr = new UnityWebRequest(url);
  234. DownloadHandlerTexture downloadTexture = new DownloadHandlerTexture(true);
  235. uwr.downloadHandler = downloadTexture;
  236. yield return uwr.SendWebRequest();
  237. Texture2D t = null;
  238. if (!(uwr.isNetworkError || uwr.isHttpError))
  239. {
  240. t = downloadTexture.texture;
  241. }
  242. else
  243. {
  244. Debug.Log("下载失败,请检查网络,或者下载地址是否正确: " + uwr.error);
  245. }
  246. if (actionResult != null)
  247. {
  248. actionResult(t);
  249. }
  250. #endif
  251. }
  252. // File uploader task.
  253. private async Task Run()
  254. {
  255. try
  256. {
  257. var getListBucketsTask = await minio.ListBucketsAsync().ConfigureAwait(false);
  258. var bucketName = bucket;
  259. var objectName = path + "/" + Nowfd.fileName;
  260. var filePath = Nowfd.filePath;
  261. var contentType = "application/octet-stream";
  262. // Make a bucket on the server, if not already present.
  263. // Upload a file to bucket.
  264. var putObjectArgs = new PutObjectArgs()
  265. .WithBucket(bucketName)
  266. .WithObject(objectName)
  267. .WithFileName(filePath)
  268. .WithContentType(contentType);
  269. await minio.PutObjectAsync(putObjectArgs).ConfigureAwait(false);
  270. Debug.Log("33333333333333333");
  271. PlayerPrefs.SetString(Nowfd.fileName, Nowfd.filePath);
  272. isUpdate = false;
  273. Nowfd.callBack?.Invoke(Nowfd.fileName);
  274. Nowfd = null;
  275. }
  276. catch
  277. {
  278. Nowfd.callBack?.Invoke(null);
  279. isUpdate = false;
  280. Nowfd = null;
  281. }
  282. }
  283. bool isDownLoad;
  284. FileData Nowfd;
  285. private void Update()
  286. {
  287. if (fdQueue.Count > 0 && Nowfd == null)
  288. {
  289. Nowfd = fdQueue.Dequeue();
  290. }
  291. if (minio == null)
  292. {
  293. if (projectId != 0 && !isminioUpdate)
  294. {
  295. isminioUpdate = true;
  296. initMinIo((bool b) =>
  297. {
  298. isminioUpdate = false;
  299. });
  300. }
  301. }
  302. if (backQueue.Count > 0)
  303. {
  304. byte[] bytes = backQueue.Dequeue();
  305. if (bytes != null)
  306. {
  307. Debug.Log("444444444444");
  308. Texture2D t2d = new Texture2D(10, 10);
  309. t2d.LoadImage(bytes);
  310. t2d.Apply();
  311. nowgfd.callBack?.Invoke(t2d);
  312. }
  313. else
  314. {
  315. Debug.Log("55555555555555");
  316. nowgfd.callBack?.Invoke(null);
  317. }
  318. isDownLoad = false;
  319. nowgfd = null;
  320. }
  321. }
  322. public class FileData
  323. {
  324. public string filePath;
  325. public string fileName;
  326. public Action<string> callBack;
  327. }
  328. public class GetFileData
  329. {
  330. public string bucket;
  331. public string objectName;
  332. public Action<Texture2D> callBack;
  333. }
  334. }