DownLoadCOSXRItem.cs 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253
  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using System.IO;
  5. using System.Threading.Tasks;
  6. using COSXML;
  7. using COSXML.Auth;
  8. using COSXML.Model;
  9. using COSXML.Model.Object;
  10. using COSXML.Transfer;
  11. using LitJson;
  12. using Newtonsoft.Json;
  13. using Newtonsoft.Json.Linq;
  14. using UnityEngine;
  15. using UnityEngine.Networking;
  16. using XRTool.Util;
  17. using static DownLoadXRManager;
  18. public class DownLoadCOSXRItem : MonoBehaviour
  19. {
  20. public DownLoadConfig cosconifg;
  21. public PutFileData uploadconifg;
  22. public static CosXmlServer materialCosXml;
  23. public static Dictionary<string, List<DownLoadConfig>> downLoadingList = new Dictionary<string, List<DownLoadConfig>>();
  24. public void startDownload(DownLoadConfig conifg)
  25. {
  26. cosconifg = conifg;
  27. InitMaterialCos();
  28. StartCoroutine(ReadStreamingAssetsFile());
  29. }
  30. public void startUpLoad(PutFileData conifg)
  31. {
  32. uploadconifg = conifg;
  33. InitMaterialCos();
  34. StartCoroutine(ReadStreamingUpLoad());
  35. }
  36. private void InitMaterialCos()
  37. {
  38. CosXmlConfig config = new CosXmlConfig.Builder()
  39. .IsHttps(true)
  40. .SetRegion(cospingzheng.region)
  41. .SetDebugLog(true)
  42. .Build();
  43. Debug.Log("ReadStreamingAssetsFile==SetRegion=>" + cospingzheng.region);
  44. QCloudCredentialProvider cosCredentialProvider = new DefaultSessionQCloudCredentialProvider(
  45. cospingzheng.credentials.tmpSecretId, cospingzheng.credentials.tmpSecretKey, cospingzheng.expiredTime, cospingzheng.credentials.token);
  46. Debug.Log("ReadStreamingAssetsFile==tmpSecretId=>" + cospingzheng.credentials.tmpSecretId +
  47. " tmpSecretKey==>" + cospingzheng.credentials.tmpSecretKey +
  48. " expiredTime==>" + cospingzheng.expiredTime +
  49. " sessionToken==>" + cospingzheng.credentials.token);
  50. materialCosXml = new CosXmlServer(config, cosCredentialProvider);
  51. }
  52. IEnumerator ReadStreamingUpLoad()
  53. {
  54. if (!Directory.Exists(Application.persistentDataPath + "/DownLoadXR/"))
  55. {
  56. Directory.CreateDirectory(Application.persistentDataPath + "/DownLoadXR/");
  57. }
  58. //.cssg-snippet-body-start:[transfer-batch-download-objects]
  59. TransferConfig transferConfig = new TransferConfig();
  60. // 初始化 TransferManager
  61. TransferManager transferManager = new TransferManager(materialCosXml, transferConfig);
  62. // String cosPath = "exampleobject"; //对象在存储桶中的位置标识符,即称对象键
  63. // string localDir = System.IO.Path.GetTempPath();//本地文件夹
  64. // string localFileName = "my-local-temp-file"; //指定本地保存的文件名
  65. Debug.Log("ReadStreamingAssetsFile==cospingzheng.bucket=>" + cospingzheng.bucket+
  66. " uploadconifg.objectName==>" + uploadconifg.objectName +
  67. " uploadconifg.filePath==>" + uploadconifg.filePath) ;
  68. PutObjectRequest putrequest = new PutObjectRequest(cospingzheng.bucket, uploadconifg.objectName, uploadconifg.filePath);
  69. Dictionary<string, string> dicheaders = new Dictionary<string, string>();
  70. dicheaders.Add("X-Amz-Meta-Uuid", uploadconifg.uuid);
  71. putrequest.SetRequestHeaders(dicheaders);
  72. // 下载对象
  73. COSXMLUploadTask UpLoadTask = new COSXMLUploadTask(putrequest);
  74. UpLoadTask.SetSrcPath(uploadconifg.filePath);
  75. // 手动设置高级下载接口的并发数 (默认为5), 从5.4.26版本开始支持!
  76. //downloadTask.SetMaxTasks(10);
  77. UpLoadTask.progressCallback = delegate (long completed, long total)
  78. {
  79. // uploadconifg.presson?.Invoke(completed * 100.0f / total);
  80. Debug.Log(String.Format("Hjj UpLoad" + uploadconifg.filePath + "progress = {0:##.##}%", completed * 100.0 / total));
  81. //showDownLoadPre = completed * 100.0f / total;
  82. };
  83. // Debug.Log(downloadMaterial.downLoadPath + "||||||||| DGJ");
  84. UpLoadTask.onState += OnStateUpLoadTask;
  85. UpLoadTask.successCallback += SuccessCallback;
  86. // listDownLoadTask.Add(downloadTask);
  87. Task<COSXMLUploadTask.UploadTaskResult> task = null;
  88. try
  89. {
  90. task = transferManager.UploadAsync(UpLoadTask);
  91. }
  92. catch (COSXML.CosException.CosClientException clientEx)
  93. {
  94. Debug.Log("CosClientException===>" + clientEx);
  95. //请求失败
  96. }
  97. catch (COSXML.CosException.CosServerException serverEx)
  98. {
  99. Debug.Log("CosClientException===>" + serverEx);
  100. //请求失败
  101. }
  102. yield return task;
  103. while (!task.IsCompleted)
  104. {
  105. yield return null;
  106. }
  107. Debug.Log("ReadStreamingAssetsFile==IsCompleted=>" + task.IsCompleted);
  108. Debug.Log("ReadStreamingAssetsFile===>" + task.IsFaulted);
  109. Debug.Log("ReadStreamingAssetsFile===>" + task.IsCompletedSuccessfully);
  110. Debug.Log("ReadStreamingAssetsFile===>" + task.Status);
  111. Debug.Log("ReadStreamingAssetsFile===>" + task.Exception);
  112. Debug.Log("ReadStreamingAssetsFile===>" + task.Result.RawContentBodyString);
  113. // Destroy(this.gameObject);
  114. }
  115. public string localPath;
  116. IEnumerator ReadStreamingAssetsFile()
  117. {
  118. if(!Directory.Exists(Application.persistentDataPath + "/DownLoadXR/"))
  119. {
  120. Directory.CreateDirectory(Application.persistentDataPath + "/DownLoadXR/");
  121. }
  122. //.cssg-snippet-body-start:[transfer-batch-download-objects]
  123. TransferConfig transferConfig = new TransferConfig();
  124. // 初始化 TransferManager
  125. TransferManager transferManager = new TransferManager(materialCosXml, transferConfig);
  126. // String cosPath = "exampleobject"; //对象在存储桶中的位置标识符,即称对象键
  127. // string localDir = System.IO.Path.GetTempPath();//本地文件夹
  128. // string localFileName = "my-local-temp-file"; //指定本地保存的文件名
  129. localPath = Application.persistentDataPath + "/DownLoadXR/" + cosconifg.data.path.Split("/")[cosconifg.data.path.Split("/").Length - 1];
  130. string localFileName = Path.GetFileName(localPath);
  131. Debug.Log("ReadStreamingAssetsFile==cospingzheng.bucket=>" + cospingzheng.bucket +
  132. " cosconifg.data.path==>" + cosconifg.data.path +
  133. " localPathh==>" + localPath +
  134. " localFileName==>" + localFileName);
  135. // 下载对象
  136. COSXMLDownloadTask downloadTask = new COSXMLDownloadTask(cospingzheng.bucket, cosconifg.data.path,
  137. Application.persistentDataPath + "/DownLoadXR/", localFileName);
  138. // 手动设置高级下载接口的并发数 (默认为5), 从5.4.26版本开始支持!
  139. //downloadTask.SetMaxTasks(10);
  140. downloadTask.progressCallback = delegate (long completed, long total)
  141. {
  142. cosconifg.presson?.Invoke(completed * 100.0f / total);
  143. Debug.Log(String.Format("Hjj download"+ cosconifg.data.path + "progress = {0:##.##}%", completed * 100.0 / total));
  144. //showDownLoadPre = completed * 100.0f / total;
  145. };
  146. // Debug.Log(downloadMaterial.downLoadPath + "||||||||| DGJ");
  147. downloadTask.onState += OnState;
  148. downloadTask.successCallback += SuccessCallback;
  149. // listDownLoadTask.Add(downloadTask);
  150. Task<COSXMLDownloadTask.DownloadTaskResult> task = null;
  151. try
  152. {
  153. task = transferManager.DownloadAsync(downloadTask);
  154. }
  155. catch (COSXML.CosException.CosClientException clientEx)
  156. {
  157. Debug.Log("CosClientException===>" + clientEx);
  158. //请求失败
  159. }
  160. catch (COSXML.CosException.CosServerException serverEx)
  161. {
  162. Debug.Log("CosClientException===>" + serverEx);
  163. //请求失败
  164. }
  165. yield return task;
  166. while(!task.IsCompleted)
  167. {
  168. yield return null;
  169. }
  170. Debug.Log("ReadStreamingAssetsFile==IsCompleted=>" + task.IsCompleted);
  171. Debug.Log("ReadStreamingAssetsFile===>" + task.IsFaulted);
  172. Debug.Log("ReadStreamingAssetsFile===>" + task.IsCompletedSuccessfully);
  173. Debug.Log("ReadStreamingAssetsFile===>" + task.Status);
  174. Debug.Log("ReadStreamingAssetsFile===>" + task.Exception);
  175. Debug.Log("ReadStreamingAssetsFile===>" + task.Result.RawContentBodyString);
  176. // Destroy(this.gameObject);
  177. }
  178. private void OnStateUpLoadTask(TaskState taskState)
  179. {
  180. taskUploadQueue.Enqueue(taskState);
  181. }
  182. private void SuccessCallback(CosResult cosResult)
  183. {
  184. if(cosResult.IsSuccessful())
  185. {
  186. Debug.Log("SuccessCallback===>" + cosResult.httpMessage);
  187. Debug.Log("SuccessCallback===>" + cosResult.httpCode);
  188. Debug.Log("SuccessCallback===>" + cosResult.Key);
  189. }
  190. }
  191. public Queue<TaskState> taskQueue = new Queue<TaskState>();
  192. public Queue<TaskState> taskUploadQueue = new Queue<TaskState>();
  193. private void OnState(TaskState state)
  194. {
  195. taskQueue.Enqueue(state);
  196. }
  197. public byte[] readbytes(Stream stream)
  198. {
  199. using (Stream fs = stream)
  200. {
  201. byte[] bytes = new byte[fs.Length];
  202. fs.Read(bytes, 0, bytes.Length);
  203. fs.Close();
  204. return bytes;
  205. }
  206. }
  207. private void Update()
  208. {
  209. if (taskQueue.Count > 0)
  210. {
  211. var state = taskQueue.Dequeue();
  212. if (state == TaskState.Completed || state == TaskState.Failed)
  213. {
  214. if (state == TaskState.Completed)
  215. {
  216. FileInfo file = new FileInfo(localPath);
  217. cosconifg.bytes(readbytes(file.OpenRead()));
  218. }
  219. Debug.Log("Hjj download" + cosconifg.data.path + "TaskState.=>" + state);
  220. }
  221. }
  222. if (taskUploadQueue.Count > 0)
  223. {
  224. var state = taskUploadQueue.Dequeue();
  225. if (state == TaskState.Completed || state == TaskState.Failed)
  226. {
  227. uploadconifg.callBack?.Invoke(state.ToString());
  228. }
  229. }
  230. }
  231. }