123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278 |
- using System.Collections;
- using System.Collections.Generic;
- using UnityEngine;
- using COSXML;
- using COSXML.Auth;
- using COSXML.Model.Object;
- using COSXML.Model.Bucket;
- using COSXML.CosException;
- using System;
- using Newtonsoft.Json;
- using LitJson;
- using System.Threading.Tasks;
- using COSXML.Transfer;
- using System.IO;
- using COSXML.Model;
- using Newtonsoft.Json.Linq;
- public class COSDownLoad:MonoSingleton<COSDownLoad>
- {
- public SuccessCOS successCos;
- QCloudCredentialProvider cosCredentialProvider;
- CosXml cosXml;
- // Start is called before the first frame update
- public void Credential()
- {
- Credential credential = new Credential();
- credential.type = "material";
- string data = JsonConvert.SerializeObject(credential);
- Debug.Log(data);
- HttpTool.Instance.Post("/storage/credential/create", data, CredentialCallBack);
- }
- private void InitCos()
- {
- CosXmlConfig config = new CosXmlConfig.Builder()
- .IsHttps(true)
- .SetRegion(successCos.region)
- .SetDebugLog(true)
- .Build();
- cosCredentialProvider = new DefaultSessionQCloudCredentialProvider(
- successCos.credentials.tmpSecretId, successCos.credentials.tmpSecretKey, successCos.expiredTime, successCos.credentials.sessionToken);
- cosXml = new CosXmlServer(config, cosCredentialProvider);
- // StartCoroutine( MaterialManager.Instance.GetAllMaterials(UserInfo.Instance.Token));
- }
- private void CredentialCallBack( string msg)
- {
- Debug.Log(msg);
- JObject jObject = JObject.Parse(msg);
- if (jObject["code"].ToString() == "200")
- {
- successCos = JsonConvert.DeserializeObject<SuccessCOS>(jObject["data"].ToString());
- InitCos();
- }
- else
- {
- Debug.LogError(msg);
- }
-
- }
- /// <summary>
- /// 高级接口下载对象
- /// </summary>
- /// <param name="cosPath"> 下载地址 </param>
- /// <param name="localDir"> 本地保存文件夹</param>
- /// <param name="localFileName"> 本地保存文件名</param>
- /// <returns></returns>
- public async void TransferDownloadObject(DownLoadMaterial downloadMaterial, string localDir)
- {
- // 初始化 TransferConfig
- TransferConfig transferConfig = new TransferConfig();
- // 手动设置高级下载接口的分块阈值为 20MB(默认为20MB), 从5.4.26版本开始支持!
- //transferConfig.DivisionForDownload = 20 * 1024 * 1024;
- // 手动设置高级下载接口的分块大小为 10MB(默认为5MB),不建议此处设置过小的分块值,可能导致频繁重试或下载速度不合预期
- //transferConfig.SliceSizeForDownload = 10 * 1024 * 1024;
- // 初始化 TransferManager
- TransferManager transferManager = new TransferManager(cosXml, transferConfig);
- String bucket = successCos.bucket; //存储桶,格式:BucketName-APPID
- // String cosPath = "exampleobject"; //对象在存储桶中的位置标识符,即称对象键
- // string localDir = System.IO.Path.GetTempPath();//本地文件夹
- // string localFileName = "my-local-temp-file"; //指定本地保存的文件名
- string localFileName = Path.GetFileName(downloadMaterial.localLoadPath);
- // 下载对象
- COSXMLDownloadTask downloadTask = new COSXMLDownloadTask(bucket, downloadMaterial.downLoadPath,
- localDir, localFileName);
- // 手动设置高级下载接口的并发数 (默认为5), 从5.4.26版本开始支持!
- //downloadTask.SetMaxTasks(10);
- //downloadTask.progressCallback = delegate (long completed, long total)
- //{
- // Console.WriteLine(String.Format("progress = {0:##.##}%", completed * 100.0 / total));
- //};
- downloadTask.onState += OnState;
- try
- {
- COSXML.Transfer.COSXMLDownloadTask.DownloadTaskResult result = await
- transferManager.DownloadAsync(downloadTask);
- Console.WriteLine(result.GetResultInfo());
- string eTag = result.eTag;
- }
- catch (COSXML.CosException.CosClientException clientEx)
- {
- //请求失败
- Debug.LogError("CosClientException: " + clientEx);
- DownloadResManager.Instance.DownLoadFaild(downloadTask.localFileName);
- }
- catch (COSXML.CosException.CosServerException serverEx)
- {
- //请求失败
- Debug.LogError("CosServerException: " + serverEx.GetInfo());
- DownloadResManager.Instance.DownLoadFaild(downloadTask.localFileName);
- }
- listDownLoadTask.Add(downloadTask);
- }
- private List<COSXML.Transfer.COSXMLDownloadTask.DownloadTaskResult> listResult = new List<COSXMLDownloadTask.DownloadTaskResult>();
- private List<COSXMLDownloadTask> listDownLoadTask = new List<COSXMLDownloadTask>();
- /// <summary>
- /// 批量下载
- /// </summary>
- /// <param name="listDLMaterial">素材列表 </param>
- /// <param name="localDir"> 本地下载文件夹 </param>
- public async void TransferBatchDownloadObjects( List<DownLoadMaterial> listDLMaterial , string localDir)
- {
- if (listDLMaterial.Count == 0 || listDLMaterial == null)
- return;
- //.cssg-snippet-body-start:[transfer-batch-download-objects]
- TransferConfig transferConfig = new TransferConfig();
- // 初始化 TransferManager
- TransferManager transferManager = new TransferManager(cosXml, transferConfig);
- // 存储桶名称,此处填入格式必须为 bucketname-APPID, 其中 APPID 获取参考 https://console.cloud.tencent.com/developer
- string bucket = successCos.bucket;
- //string localDir = System.IO.Path.GetTempPath();//本地文件夹
- Debug.Log(listDLMaterial.Count);
- for (int i = 0; i < listDLMaterial.Count; i++)
- {
- string cosPath = listDLMaterial[i].downLoadPath;
- Debug.Log(cosPath);
- if(cosPath.IsNormalized()||cosPath=="")
- {
- DownloadResManager.Instance.DownLoadFaild(listDLMaterial[i].localLoadPath);
- continue;
- }
- string localFileName = Path.GetFileName(listDLMaterial[i].localLoadPath);
- COSXMLDownloadTask downloadTask = new COSXMLDownloadTask(bucket, cosPath,
- localDir, localFileName);
- downloadTask.failCallback = delegate (CosClientException clientException, CosServerException serverException)
- {
- Debug.LogError("clientException.errorCode : " + clientException.errorCode + " serverException.errorCode: " + serverException.errorCode +
- " serverException.errorMessage : " + serverException.errorMessage);
- };
- downloadTask.onState += OnState;
- try
- {
- await transferManager.DownloadAsync(downloadTask);
- }
- catch (COSXML.CosException.CosClientException clientEx)
- {
- //请求失败
- Debug.LogError("CosClientException: " + clientEx);
- DownloadResManager.Instance.DownLoadFaild(downloadTask.localFileName);
- }
- catch (COSXML.CosException.CosServerException serverEx)
- {
- //请求失败
- Debug.LogError("CosServerException: " + serverEx.GetInfo());
- DownloadResManager.Instance.DownLoadFaild(downloadTask.localFileName);
- }
-
- listDownLoadTask.Add(downloadTask);
- }
- }
- public string GetVideoUrl(DownloadManager downloadMaterial)
- {
- try
- {
- string requestURL = cosXml.GetObjectUrl(successCos.bucket, downloadMaterial.LocaDataPath);
- return requestURL;
- }
- catch (COSXML.CosException.CosClientException clientEx)
- {
- //请求失败
- return null;
- }
- catch (COSXML.CosException.CosServerException serverEx)
- {
- //请求失败
- return null;
- }
- }
- /// 下载时对单链接限速
- public async void DownloadObjectTrafficLimit(string cosPath, string localDir, string localFileName)
- {
- //.cssg-snippet-body-start:[download-object-traffic-limit]
- TransferConfig transferConfig = new TransferConfig();
- // 初始化 TransferManager
- TransferManager transferManager = new TransferManager(cosXml, transferConfig);
- String bucket = successCos.bucket; //存储桶,格式:BucketName-APPID
- // String cosPath = "exampleobject"; //对象在存储桶中的位置标识符,即称对象键
- // string localDir = System.IO.Path.GetTempPath();//本地文件夹
- // string localFileName = "my-local-temp-file"; //指定本地保存的文件名
- GetObjectRequest request = new GetObjectRequest(bucket,
- cosPath, localDir, localFileName);
- request.LimitTraffic(8 * 1000 * 1024); // 限制为1MB/s
- COSXMLDownloadTask downloadTask = new COSXMLDownloadTask(request);
- await transferManager.DownloadAsync(downloadTask);
- //.cssg-snippet-body-end
- }
- private void OnState(TaskState state)
- {
- Debug.Log(state);
- if (state == TaskState.Completed)
- for (int i = 0; i < listDownLoadTask.Count; i++)
- {
- Debug.Log(listDownLoadTask.Count + " "+listDownLoadTask[i].State());
- if (listDownLoadTask[i].State() == TaskState.Completed)
- {
- DownloadResManager.Instance.DownLoadCompleted(listDownLoadTask[i].localFileName);
- listDownLoadTask.RemoveAt(i);
- }
- }
- }
- }
- public class Credential
- {
- public string type { get; set; }
- }
- public class SuccessCOS
- {
- public CredentialsCos credentials { get; set; }
- public long startTime { get; set; }
- public long expiredTime { get; set; }
- public string bucket { get; set; }
- public string path { get; set; }
- public string region { get; set; }
- }
- public class CredentialsCos
- {
- public string tmpSecretId { get; set; }
- public string tmpSecretKey { get; set; }
- public string sessionToken { get; set; }
- }
|