COSDownLoad.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447
  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. /*
  20. * 根据下载的类型 分为 -1 Scene Materail -2 vuforial
  21. *
  22. */
  23. public SuccessCOS materialSuccessCos;
  24. public SuccessCOS sceneSuccessCos;
  25. public SuccessCOS imageSuccessCos;
  26. public SuccessCOS publicSuccessCos;
  27. // QCloudCredentialProvider cosCredentialProvider;
  28. CosXml materialCosXml;
  29. CosXml sceneCosXml;
  30. CosXml imageCosXml;
  31. CosXml publicCosXml;
  32. // Start is called before the first frame update
  33. private void Start()
  34. {
  35. }
  36. public void Credential()
  37. {
  38. Credential credential = new Credential();
  39. credential.type = "material";
  40. string data = JsonConvert.SerializeObject(credential);
  41. //Debug.Log(data);
  42. HttpTool.Instance.Post("/storage/credential/create", data, CredentialMaterialCallBack);
  43. Credential credential2 = new Credential();
  44. credential2.type = "scene";
  45. string data2 = JsonConvert.SerializeObject(credential2);
  46. HttpTool.Instance.Post("/storage/credential/create", data2, CredentialSceneCallBack);
  47. Credential credential3 = new Credential();
  48. credential3.type = "image";
  49. string data3 = JsonConvert.SerializeObject(credential3);
  50. HttpTool.Instance.Post("/storage/credential/create", data3, CredentialImageCallBack);
  51. // publicSuccessCos = JsonConvert.DeserializeObject<SuccessCOS>("{'credentials':{'tmpSecretId':'AKIDLyyDWYsUvRDzn - HqetC4XZ9pNMhOjDEYuSKBvlWcep8iVS1dFa87FyVartAR1 - E_','tmpSecretKey':'rTXSx44gpPR / fgrUaT1zvK0xZQZe2SplrpTkoGEsgN4 = ','sessionToken':'3WfLBVhQ7lK1jNbOBMfcKC0BkZEamXYa9b61b73db72c57039c9cd0b65b4e19a7_9 - RKlXQeKHOCLXyEJscL705yLZxSuPrVLA1c - ZCA4TZmW8RA8dp1dJ7k4VZhRrNQhQ2zheytiN2wAqxKElmycMTnbk97t_FuAAqGPdO9IAnuYNbvOSgDXICIpxMsVPSqWS6cXrHeDhVCLkpZUaHiM2Exk - xbvlCflv4VPjsr6gFYQynEa3RBrvL4mWjg0xrSn0Lpz4h_VmEUW7cT3i07bnNqhA9nsdvCbyxf3JL3fwz92m8ltm - x0NK6fCsdIwaWnkHkWfWHBqwTqxMoID4vlGj84_FK4ZEc_HbXIqruZLikSM - 8u16ks78fODGILOt36EX_2_IRz5JGAX2kNj5BvkVUjIV - 6eB - qbJDkQce2sB_dDaA0cfNsrlfYFMQCWizcv5kDDbgkg4uengC0GbTZQUPm9Jyj9QuLsI9N2V7UuIUL41sN0LLWPSxrpZ4nUxjRJykleSnQ0_WnZaBIa2bFJAxdxOvJXuGIDqIhcTVsPmJkN_O7VUMFPousM9bAVQJjYeSh2a39eVcUJnvWIpiLSNtbgOZFOuXsofS4FYD8aNX3GWrzEyQXoAGBwasRFvjj7aiSgURVM7ue11i_Wz56RiFo2bNihu5cgGsx271ts'},'startTime':1694402249,'expiredTime':1694402549,'bucket':'fat - store - 10001 - 1317557471','path':' / personal / image / 156','region':'ap - shanghai'}");
  52. // CosXmlConfig config = new CosXmlConfig.Builder()
  53. // .IsHttps(true)
  54. // .SetRegion(publicSuccessCos.region)
  55. // .SetDebugLog(true)
  56. // .Build();
  57. // Debug.Log("" + publicSuccessCos.credentials);
  58. // QCloudCredentialProvider cosCredentialProvider = new DefaultSessionQCloudCredentialProvider(
  59. //publicSuccessCos.credentials.tmpSecretId, publicSuccessCos.credentials.tmpSecretKey, publicSuccessCos.expiredTime, publicSuccessCos.credentials.sessionToken);
  60. // publicCosXml = new CosXmlServer(config, cosCredentialProvider);
  61. // TestDownloadObject("default/c39352b7-0ecf-402b-8693-ca8dee01cc0e.dat", Application.persistentDataPath + "/");
  62. }
  63. private void InitMaterialCos()
  64. {
  65. CosXmlConfig config = new CosXmlConfig.Builder()
  66. .IsHttps(true)
  67. .SetRegion(materialSuccessCos.region)
  68. .SetDebugLog(true)
  69. .Build();
  70. QCloudCredentialProvider cosCredentialProvider = new DefaultSessionQCloudCredentialProvider(
  71. materialSuccessCos.credentials.tmpSecretId, materialSuccessCos.credentials.tmpSecretKey, materialSuccessCos.expiredTime, materialSuccessCos.credentials.sessionToken);
  72. materialCosXml = new CosXmlServer(config, cosCredentialProvider);
  73. }
  74. private void InitImageCos()
  75. {
  76. CosXmlConfig config = new CosXmlConfig.Builder()
  77. .IsHttps(true)
  78. .SetRegion(imageSuccessCos.region)
  79. .SetDebugLog(true)
  80. .Build();
  81. QCloudCredentialProvider cosCredentialProvider = new DefaultSessionQCloudCredentialProvider(
  82. imageSuccessCos.credentials.tmpSecretId, imageSuccessCos.credentials.tmpSecretKey, imageSuccessCos.expiredTime, imageSuccessCos.credentials.sessionToken);
  83. imageCosXml = new CosXmlServer(config, cosCredentialProvider);
  84. }
  85. private void InitSceneCos()
  86. {
  87. CosXmlConfig config = new CosXmlConfig.Builder()
  88. .IsHttps(true)
  89. .SetRegion(sceneSuccessCos.region)
  90. .SetDebugLog(true)
  91. .Build();
  92. QCloudCredentialProvider cosCredentialProvider = new DefaultSessionQCloudCredentialProvider(
  93. sceneSuccessCos.credentials.tmpSecretId, sceneSuccessCos.credentials.tmpSecretKey, sceneSuccessCos.expiredTime, sceneSuccessCos.credentials.sessionToken);
  94. sceneCosXml = new CosXmlServer(config, cosCredentialProvider);
  95. }
  96. private void CredentialMaterialCallBack( string msg)
  97. {
  98. Debug.Log(msg);
  99. JObject jObject = JObject.Parse(msg);
  100. if (jObject["code"].ToString() == "200")
  101. {
  102. materialSuccessCos = JsonConvert.DeserializeObject<SuccessCOS>(jObject["data"].ToString());
  103. InitMaterialCos();
  104. }
  105. else
  106. {
  107. Debug.LogError(msg);
  108. }
  109. }
  110. private void CredentialSceneCallBack(string msg)
  111. {
  112. Debug.Log(msg);
  113. JObject jObject = JObject.Parse(msg);
  114. if (jObject["code"].ToString() == "200")
  115. {
  116. sceneSuccessCos = JsonConvert.DeserializeObject<SuccessCOS>(jObject["data"].ToString());
  117. InitSceneCos();
  118. }
  119. else
  120. {
  121. Debug.LogError(msg);
  122. }
  123. }
  124. private void CredentialImageCallBack(string msg)
  125. {
  126. Debug.Log(msg);
  127. JObject jObject = JObject.Parse(msg);
  128. if (jObject["code"].ToString() == "200")
  129. {
  130. imageSuccessCos = JsonConvert.DeserializeObject<SuccessCOS>(jObject["data"].ToString());
  131. InitImageCos();
  132. }
  133. else
  134. {
  135. Debug.LogError(msg);
  136. }
  137. }
  138. public static int showDownLoadCount;
  139. public static int showDownEndLoadCount;
  140. public static float showDownLoadPre;
  141. public async void TestDownloadObject( string downloadPath,string localDir)
  142. {
  143. TransferConfig transferConfig = new TransferConfig();
  144. TransferManager transferManager; // 初始化 TransferManager
  145. String bucket; //存储桶,格式:BucketName-APPID
  146. transferManager = new TransferManager(publicCosXml, transferConfig);
  147. bucket = publicSuccessCos.bucket;
  148. string localFileName = Path.GetFileName(downloadPath);
  149. // localDir = downloadMaterial.localLoadPath.Substring(0, downloadMaterial.localLoadPath.Length - localFileName.Length);
  150. // 下载对象
  151. COSXMLDownloadTask downloadTask = new COSXMLDownloadTask(bucket, downloadPath,
  152. localDir, localFileName);
  153. // 手动设置高级下载接口的并发数 (默认为5), 从5.4.26版本开始支持!
  154. //downloadTask.SetMaxTasks(10);
  155. downloadTask.progressCallback = delegate (long completed, long total)
  156. {
  157. // Debug.Log(String.Format("Hjj download"+downloadMaterial.downLoadPath+"progress = {0:##.##}%", completed * 100.0 / total));
  158. // showDownLoadPre = completed * 100.0f / total;
  159. };
  160. Debug.Log(downloadPath + "||||||||| DGJ");
  161. // downloadTask.onState += OnState;
  162. // listDownLoadTask.Add(downloadTask);
  163. try
  164. {
  165. COSXML.Transfer.COSXMLDownloadTask.DownloadTaskResult result = await
  166. transferManager.DownloadAsync(downloadTask);
  167. Console.WriteLine(result.GetResultInfo());
  168. string eTag = result.eTag;
  169. }
  170. catch (COSXML.CosException.CosClientException clientEx)
  171. {
  172. //请求失败
  173. Debug.LogError(downloadPath + " CosClientException: " + clientEx);
  174. DownloadResManager.Instance.DownLoadFaild(downloadTask.localFileName);
  175. }
  176. catch (COSXML.CosException.CosServerException serverEx)
  177. {
  178. //请求失败
  179. Debug.LogError(downloadPath + " CosServerException: " + serverEx.GetInfo());
  180. DownloadResManager.Instance.DownLoadFaild(downloadTask.localFileName);
  181. }
  182. }
  183. /// <summary>
  184. /// 高级接口下载对象
  185. /// </summary>
  186. /// <param name="cosPath"> 下载地址 </param>
  187. /// <param name="localDir"> 本地保存文件夹</param>
  188. /// <param name="localFileName"> 本地保存文件名</param>
  189. /// <returns></returns>
  190. public async void TransferDownloadObject(DownLoadMaterial downloadMaterial, string localDir)
  191. {
  192. // 初始化 TransferConfig
  193. TransferConfig transferConfig = new TransferConfig();
  194. // 手动设置高级下载接口的分块阈值为 20MB(默认为20MB), 从5.4.26版本开始支持!
  195. //transferConfig.DivisionForDownload = 20 * 1024 * 1024;
  196. // 手动设置高级下载接口的分块大小为 10MB(默认为5MB),不建议此处设置过小的分块值,可能导致频繁重试或下载速度不合预期
  197. //transferConfig.SliceSizeForDownload = 10 * 1024 * 1024;
  198. TransferManager transferManager; // 初始化 TransferManager
  199. String bucket; //存储桶,格式:BucketName-APPID
  200. Debug.Log("Hjj TransferDownloadObject===>"+ downloadMaterial.type);
  201. switch (downloadMaterial.type)
  202. {
  203. case "-1":
  204. transferManager = new TransferManager(sceneCosXml, transferConfig);
  205. bucket = sceneSuccessCos.bucket;
  206. break;
  207. case "-2":
  208. transferManager = new TransferManager(imageCosXml, transferConfig);
  209. bucket = imageSuccessCos.bucket;
  210. break;
  211. default:
  212. transferManager = new TransferManager(materialCosXml, transferConfig);
  213. if(materialSuccessCos!=null)
  214. bucket = materialSuccessCos.bucket;
  215. else
  216. {
  217. showDownEndLoadCount++;
  218. return;
  219. }
  220. break;
  221. }
  222. /// if()
  223. // String cosPath = "exampleobject"; //对象在存储桶中的位置标识符,即称对象键
  224. // string localDir = System.IO.Path.GetTempPath();//本地文件夹
  225. // string localFileName = "my-local-temp-file"; //指定本地保存的文件名
  226. string localFileName = Path.GetFileName(downloadMaterial.localLoadPath);
  227. localDir = downloadMaterial.localLoadPath.Substring(0, downloadMaterial.localLoadPath.Length - localFileName.Length);
  228. // 下载对象
  229. COSXMLDownloadTask downloadTask = new COSXMLDownloadTask(bucket, downloadMaterial.downLoadPath,
  230. localDir, localFileName);
  231. // 手动设置高级下载接口的并发数 (默认为5), 从5.4.26版本开始支持!
  232. //downloadTask.SetMaxTasks(10);
  233. downloadTask.progressCallback = delegate (long completed, long total)
  234. {
  235. // Debug.Log(String.Format("Hjj download"+downloadMaterial.downLoadPath+"progress = {0:##.##}%", completed * 100.0 / total));
  236. showDownLoadPre = completed * 100.0f / total;
  237. };
  238. Debug.Log(downloadMaterial.downLoadPath +"||||||||| DGJ");
  239. downloadTask.onState += OnState;
  240. listDownLoadTask.Add(downloadTask);
  241. try
  242. {
  243. COSXML.Transfer.COSXMLDownloadTask.DownloadTaskResult result = await
  244. transferManager.DownloadAsync(downloadTask);
  245. Console.WriteLine(result.GetResultInfo());
  246. string eTag = result.eTag;
  247. }
  248. catch (COSXML.CosException.CosClientException clientEx)
  249. {
  250. //请求失败
  251. Debug.LogError(downloadMaterial.downLoadPath + " CosClientException: " + clientEx);
  252. DownloadResManager.Instance.DownLoadFaild(downloadTask.localFileName);
  253. listDownLoadTask.Remove(downloadTask);
  254. showDownEndLoadCount++;
  255. }
  256. catch (COSXML.CosException.CosServerException serverEx)
  257. {
  258. //请求失败
  259. Debug.LogError(downloadMaterial.downLoadPath+ " CosServerException: " + serverEx.GetInfo());
  260. DownloadResManager.Instance.DownLoadFaild(downloadTask.localFileName);
  261. listDownLoadTask.Remove(downloadTask);
  262. showDownEndLoadCount++;
  263. }
  264. }
  265. private List<COSXML.Transfer.COSXMLDownloadTask.DownloadTaskResult> listResult = new List<COSXMLDownloadTask.DownloadTaskResult>();
  266. private List<COSXMLDownloadTask> listDownLoadTask = new List<COSXMLDownloadTask>();
  267. /// <summary>
  268. /// 批量下载
  269. /// </summary>
  270. /// <param name="listDLMaterial">素材列表 </param>
  271. /// <param name="localDir"> 本地下载文件夹 </param>
  272. public async void TransferBatchDownloadObjects( List<DownLoadMaterial> listDLMaterial , string localDir)
  273. {
  274. if (listDLMaterial.Count == 0 || listDLMaterial == null)
  275. return;
  276. //.cssg-snippet-body-start:[transfer-batch-download-objects]
  277. TransferConfig transferConfig = new TransferConfig();
  278. // 初始化 TransferManager
  279. TransferManager transferManager = new TransferManager(materialCosXml, transferConfig);
  280. // 存储桶名称,此处填入格式必须为 bucketname-APPID, 其中 APPID 获取参考 https://console.cloud.tencent.com/developer
  281. string bucket = materialSuccessCos.bucket;
  282. //string localDir = System.IO.Path.GetTempPath();//本地文件夹
  283. Debug.Log(listDLMaterial.Count);
  284. for (int i = 0; i < listDLMaterial.Count; i++)
  285. {
  286. string cosPath = listDLMaterial[i].downLoadPath;
  287. Debug.Log(cosPath);
  288. if(cosPath==null||cosPath=="")
  289. {
  290. DownloadResManager.Instance.DownLoadFaild(listDLMaterial[i].localLoadPath);
  291. continue;
  292. }
  293. string localFileName = Path.GetFileName(listDLMaterial[i].localLoadPath);
  294. Debug.Log(cosPath + " " + localDir + localFileName);
  295. COSXMLDownloadTask downloadTask = new COSXMLDownloadTask(bucket, cosPath,
  296. localDir, localFileName);
  297. downloadTask.failCallback = delegate (CosClientException clientException, CosServerException serverException)
  298. {
  299. Debug.LogError("clientException.errorCode : " + clientException.errorCode + " serverException.errorCode: " + serverException.errorCode +
  300. " serverException.errorMessage : " + serverException.errorMessage);
  301. };
  302. downloadTask.onState += OnState;
  303. try
  304. {
  305. await transferManager.DownloadAsync(downloadTask);
  306. }
  307. catch (COSXML.CosException.CosClientException clientEx)
  308. {
  309. //请求失败
  310. Debug.LogError("CosClientException: " + clientEx);
  311. DownloadResManager.Instance.DownLoadFaild(downloadTask.localFileName);
  312. listDownLoadTask.RemoveAt(0);
  313. }
  314. catch (COSXML.CosException.CosServerException serverEx)
  315. {
  316. //请求失败
  317. Debug.LogError("CosServerException: " + serverEx.GetInfo());
  318. DownloadResManager.Instance.DownLoadFaild(downloadTask.localFileName);
  319. listDownLoadTask.RemoveAt(0);
  320. }
  321. listDownLoadTask.Add(downloadTask);
  322. }
  323. }
  324. public Queue<TaskState> taskQueue = new Queue<TaskState>();
  325. private void OnState(TaskState state)
  326. {
  327. taskQueue.Enqueue(state);
  328. }
  329. private void Update()
  330. {
  331. if(taskQueue.Count>0)
  332. {
  333. var state = taskQueue.Dequeue();
  334. if (state == TaskState.Completed || state == TaskState.Failed)
  335. {
  336. int ct = listDownLoadTask.Count - 1;
  337. for (int i = ct; i >= 0; i--)
  338. {
  339. if (listDownLoadTask[i].State() == TaskState.Completed)
  340. {
  341. showDownEndLoadCount++;
  342. Debug.Log(listDownLoadTask.Count + " " + listDownLoadTask[i].State() + " " + listDownLoadTask[i].localFileName);
  343. DownloadResManager.Instance.DownLoadCompleted(listDownLoadTask[i].localFileName);
  344. listDownLoadTask.RemoveAt(i);
  345. }else if (listDownLoadTask[i].State() == TaskState.Failed)
  346. {
  347. showDownEndLoadCount++;
  348. Debug.Log(listDownLoadTask.Count + " " + listDownLoadTask[i].State() + " " + listDownLoadTask[i].localFileName);
  349. DownloadResManager.Instance.DownLoadFaild(listDownLoadTask[i].localFileName);
  350. listDownLoadTask.RemoveAt(i);
  351. }
  352. }
  353. }
  354. }
  355. }
  356. }
  357. public class Credential
  358. {
  359. public string type { get; set; }
  360. }
  361. public class SuccessCOS
  362. {
  363. public CredentialsCos credentials { get; set; }
  364. public long startTime { get; set; }
  365. public long expiredTime { get; set; }
  366. public string bucket { get; set; }
  367. public string path { get; set; }
  368. public string region { get; set; }
  369. }
  370. public class CredentialsCos
  371. {
  372. public string tmpSecretId { get; set; }
  373. public string tmpSecretKey { get; set; }
  374. public string sessionToken { get; set; }
  375. }