COSDownLoad.cs 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. using COSXML;
  5. using COSXML.Auth;
  6. using COSXML.Model.Object;
  7. using COSXML.Model.Bucket;
  8. using COSXML.CosException;
  9. using System;
  10. using Newtonsoft.Json;
  11. using LitJson;
  12. using System.Threading.Tasks;
  13. using COSXML.Transfer;
  14. using System.IO;
  15. using COSXML.Model;
  16. using Newtonsoft.Json.Linq;
  17. public class COSDownLoad:MonoSingleton<COSDownLoad>
  18. {
  19. public SuccessCOS successCos;
  20. QCloudCredentialProvider cosCredentialProvider;
  21. CosXml cosXml;
  22. // Start is called before the first frame update
  23. public void Credential()
  24. {
  25. Credential credential = new Credential();
  26. credential.type = "material";
  27. string data = JsonConvert.SerializeObject(credential);
  28. Debug.Log(data);
  29. HttpTool.Instance.Post("/storage/credential/create", data, CredentialCallBack);
  30. }
  31. private void InitCos()
  32. {
  33. CosXmlConfig config = new CosXmlConfig.Builder()
  34. .IsHttps(true)
  35. .SetRegion(successCos.region)
  36. .SetDebugLog(true)
  37. .Build();
  38. cosCredentialProvider = new DefaultSessionQCloudCredentialProvider(
  39. successCos.credentials.tmpSecretId, successCos.credentials.tmpSecretKey, successCos.expiredTime, successCos.credentials.sessionToken);
  40. cosXml = new CosXmlServer(config, cosCredentialProvider);
  41. // StartCoroutine( MaterialManager.Instance.GetAllMaterials(UserInfo.Instance.Token));
  42. }
  43. private void CredentialCallBack( string msg)
  44. {
  45. Debug.Log(msg);
  46. JObject jObject = JObject.Parse(msg);
  47. if (jObject["code"].ToString() == "200")
  48. {
  49. successCos = JsonConvert.DeserializeObject<SuccessCOS>(jObject["data"].ToString());
  50. InitCos();
  51. }
  52. else
  53. {
  54. Debug.LogError(msg);
  55. }
  56. }
  57. /// <summary>
  58. /// 高级接口下载对象
  59. /// </summary>
  60. /// <param name="cosPath"> 下载地址 </param>
  61. /// <param name="localDir"> 本地保存文件夹</param>
  62. /// <param name="localFileName"> 本地保存文件名</param>
  63. /// <returns></returns>
  64. public async void TransferDownloadObject(DownLoadMaterial downloadMaterial, string localDir)
  65. {
  66. // 初始化 TransferConfig
  67. TransferConfig transferConfig = new TransferConfig();
  68. // 手动设置高级下载接口的分块阈值为 20MB(默认为20MB), 从5.4.26版本开始支持!
  69. //transferConfig.DivisionForDownload = 20 * 1024 * 1024;
  70. // 手动设置高级下载接口的分块大小为 10MB(默认为5MB),不建议此处设置过小的分块值,可能导致频繁重试或下载速度不合预期
  71. //transferConfig.SliceSizeForDownload = 10 * 1024 * 1024;
  72. // 初始化 TransferManager
  73. TransferManager transferManager = new TransferManager(cosXml, transferConfig);
  74. String bucket = successCos.bucket; //存储桶,格式:BucketName-APPID
  75. // String cosPath = "exampleobject"; //对象在存储桶中的位置标识符,即称对象键
  76. // string localDir = System.IO.Path.GetTempPath();//本地文件夹
  77. // string localFileName = "my-local-temp-file"; //指定本地保存的文件名
  78. string localFileName = Path.GetFileName(downloadMaterial.localLoadPath);
  79. // 下载对象
  80. COSXMLDownloadTask downloadTask = new COSXMLDownloadTask(bucket, downloadMaterial.downLoadPath,
  81. localDir, localFileName);
  82. // 手动设置高级下载接口的并发数 (默认为5), 从5.4.26版本开始支持!
  83. //downloadTask.SetMaxTasks(10);
  84. //downloadTask.progressCallback = delegate (long completed, long total)
  85. //{
  86. // Console.WriteLine(String.Format("progress = {0:##.##}%", completed * 100.0 / total));
  87. //};
  88. downloadTask.onState += OnState;
  89. try
  90. {
  91. COSXML.Transfer.COSXMLDownloadTask.DownloadTaskResult result = await
  92. transferManager.DownloadAsync(downloadTask);
  93. Console.WriteLine(result.GetResultInfo());
  94. string eTag = result.eTag;
  95. }
  96. catch (COSXML.CosException.CosClientException clientEx)
  97. {
  98. //请求失败
  99. Debug.LogError("CosClientException: " + clientEx);
  100. DownloadResManager.Instance.DownLoadFaild(downloadTask.localFileName);
  101. }
  102. catch (COSXML.CosException.CosServerException serverEx)
  103. {
  104. //请求失败
  105. Debug.LogError("CosServerException: " + serverEx.GetInfo());
  106. DownloadResManager.Instance.DownLoadFaild(downloadTask.localFileName);
  107. }
  108. listDownLoadTask.Add(downloadTask);
  109. }
  110. private List<COSXML.Transfer.COSXMLDownloadTask.DownloadTaskResult> listResult = new List<COSXMLDownloadTask.DownloadTaskResult>();
  111. private List<COSXMLDownloadTask> listDownLoadTask = new List<COSXMLDownloadTask>();
  112. /// <summary>
  113. /// 批量下载
  114. /// </summary>
  115. /// <param name="listDLMaterial">素材列表 </param>
  116. /// <param name="localDir"> 本地下载文件夹 </param>
  117. public async void TransferBatchDownloadObjects( List<DownLoadMaterial> listDLMaterial , string localDir)
  118. {
  119. if (listDLMaterial.Count == 0 || listDLMaterial == null)
  120. return;
  121. //.cssg-snippet-body-start:[transfer-batch-download-objects]
  122. TransferConfig transferConfig = new TransferConfig();
  123. // 初始化 TransferManager
  124. TransferManager transferManager = new TransferManager(cosXml, transferConfig);
  125. // 存储桶名称,此处填入格式必须为 bucketname-APPID, 其中 APPID 获取参考 https://console.cloud.tencent.com/developer
  126. string bucket = successCos.bucket;
  127. //string localDir = System.IO.Path.GetTempPath();//本地文件夹
  128. Debug.Log(listDLMaterial.Count);
  129. for (int i = 0; i < listDLMaterial.Count; i++)
  130. {
  131. string cosPath = listDLMaterial[i].downLoadPath;
  132. Debug.Log(cosPath);
  133. if(cosPath.IsNormalized()||cosPath=="")
  134. {
  135. DownloadResManager.Instance.DownLoadFaild(listDLMaterial[i].localLoadPath);
  136. continue;
  137. }
  138. string localFileName = Path.GetFileName(listDLMaterial[i].localLoadPath);
  139. COSXMLDownloadTask downloadTask = new COSXMLDownloadTask(bucket, cosPath,
  140. localDir, localFileName);
  141. downloadTask.failCallback = delegate (CosClientException clientException, CosServerException serverException)
  142. {
  143. Debug.LogError("clientException.errorCode : " + clientException.errorCode + " serverException.errorCode: " + serverException.errorCode +
  144. " serverException.errorMessage : " + serverException.errorMessage);
  145. };
  146. downloadTask.onState += OnState;
  147. try
  148. {
  149. await transferManager.DownloadAsync(downloadTask);
  150. }
  151. catch (COSXML.CosException.CosClientException clientEx)
  152. {
  153. //请求失败
  154. Debug.LogError("CosClientException: " + clientEx);
  155. DownloadResManager.Instance.DownLoadFaild(downloadTask.localFileName);
  156. }
  157. catch (COSXML.CosException.CosServerException serverEx)
  158. {
  159. //请求失败
  160. Debug.LogError("CosServerException: " + serverEx.GetInfo());
  161. DownloadResManager.Instance.DownLoadFaild(downloadTask.localFileName);
  162. }
  163. listDownLoadTask.Add(downloadTask);
  164. }
  165. }
  166. public string GetVideoUrl(DownloadManager downloadMaterial)
  167. {
  168. try
  169. {
  170. string requestURL = cosXml.GetObjectUrl(successCos.bucket, downloadMaterial.LocaDataPath);
  171. return requestURL;
  172. }
  173. catch (COSXML.CosException.CosClientException clientEx)
  174. {
  175. //请求失败
  176. return null;
  177. }
  178. catch (COSXML.CosException.CosServerException serverEx)
  179. {
  180. //请求失败
  181. return null;
  182. }
  183. }
  184. /// 下载时对单链接限速
  185. public async void DownloadObjectTrafficLimit(string cosPath, string localDir, string localFileName)
  186. {
  187. //.cssg-snippet-body-start:[download-object-traffic-limit]
  188. TransferConfig transferConfig = new TransferConfig();
  189. // 初始化 TransferManager
  190. TransferManager transferManager = new TransferManager(cosXml, transferConfig);
  191. String bucket = successCos.bucket; //存储桶,格式:BucketName-APPID
  192. // String cosPath = "exampleobject"; //对象在存储桶中的位置标识符,即称对象键
  193. // string localDir = System.IO.Path.GetTempPath();//本地文件夹
  194. // string localFileName = "my-local-temp-file"; //指定本地保存的文件名
  195. GetObjectRequest request = new GetObjectRequest(bucket,
  196. cosPath, localDir, localFileName);
  197. request.LimitTraffic(8 * 1000 * 1024); // 限制为1MB/s
  198. COSXMLDownloadTask downloadTask = new COSXMLDownloadTask(request);
  199. await transferManager.DownloadAsync(downloadTask);
  200. //.cssg-snippet-body-end
  201. }
  202. private void OnState(TaskState state)
  203. {
  204. Debug.Log(state);
  205. if (state == TaskState.Completed)
  206. for (int i = 0; i < listDownLoadTask.Count; i++)
  207. {
  208. Debug.Log(listDownLoadTask.Count + " "+listDownLoadTask[i].State());
  209. if (listDownLoadTask[i].State() == TaskState.Completed)
  210. {
  211. DownloadResManager.Instance.DownLoadCompleted(listDownLoadTask[i].localFileName);
  212. listDownLoadTask.RemoveAt(i);
  213. }
  214. }
  215. }
  216. }
  217. public class Credential
  218. {
  219. public string type { get; set; }
  220. }
  221. public class SuccessCOS
  222. {
  223. public CredentialsCos credentials { get; set; }
  224. public long startTime { get; set; }
  225. public long expiredTime { get; set; }
  226. public string bucket { get; set; }
  227. public string path { get; set; }
  228. public string region { get; set; }
  229. }
  230. public class CredentialsCos
  231. {
  232. public string tmpSecretId { get; set; }
  233. public string tmpSecretKey { get; set; }
  234. public string sessionToken { get; set; }
  235. }