From e83e589f29ed8a8e87501b994e553d9f5989b26a Mon Sep 17 00:00:00 2001 From: withsalt Date: Fri, 4 Mar 2022 22:57:15 +0800 Subject: [PATCH] =?UTF-8?q?=E4=BD=BF=E7=94=A8Qiniu=20nuget=E5=8C=85?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 51 + .../CacheProviders/RedisCacheProvider.cs | 3 - src/samples/Sample.AspNetCore.Mvc/Startup.cs | 5 +- .../OnceMi.AspNetCore.OSS.csproj | 1 + .../SDK/Qiniu/CDN/BandwidthInfo.cs | 77 - .../SDK/Qiniu/CDN/BandwidthRequest.cs | 68 - .../SDK/Qiniu/CDN/BandwidthResult.cs | 98 -- .../SDK/Qiniu/CDN/CdnManager.cs | 321 ---- .../SDK/Qiniu/CDN/FluxInfo.cs | 77 - .../SDK/Qiniu/CDN/FluxRequest.cs | 68 - .../SDK/Qiniu/CDN/FluxResult.cs | 97 -- .../SDK/Qiniu/CDN/LogListInfo.cs | 80 - .../SDK/Qiniu/CDN/LogListRequest.cs | 94 -- .../SDK/Qiniu/CDN/LogListResult.cs | 102 -- .../SDK/Qiniu/CDN/PrefetchInfo.cs | 62 - .../SDK/Qiniu/CDN/PrefetchRequest.cs | 73 - .../SDK/Qiniu/CDN/PrefetchResult.cs | 94 -- .../SDK/Qiniu/CDN/RefreshInfo.cs | 80 - .../SDK/Qiniu/CDN/RefreshRequest.cs | 106 -- .../SDK/Qiniu/CDN/RefreshResult.cs | 104 -- .../SDK/Qiniu/Http/ContentType.cs | 33 - .../SDK/Qiniu/Http/HttpCode.cs | 168 -- .../SDK/Qiniu/Http/HttpHelper.cs | 101 -- .../SDK/Qiniu/Http/HttpManager.cs | 1384 ----------------- .../SDK/Qiniu/Http/HttpResult.cs | 144 -- .../SDK/Qiniu/Http/UrlHelper.cs | 87 -- .../SDK/Qiniu/QiniuCSharpSDK.cs | 42 - .../SDK/Qiniu/Storage/BatchInfo.cs | 63 - .../SDK/Qiniu/Storage/BatchResult.cs | 106 -- .../SDK/Qiniu/Storage/BucketInfo.cs | 53 - .../SDK/Qiniu/Storage/BucketManager.cs | 802 ---------- .../SDK/Qiniu/Storage/BucketResult.cs | 79 - .../SDK/Qiniu/Storage/BucketsResult.cs | 77 - .../SDK/Qiniu/Storage/ChunkUnit.cs | 102 -- .../SDK/Qiniu/Storage/Config.cs | 136 -- .../SDK/Qiniu/Storage/DomainsResult.cs | 79 - .../SDK/Qiniu/Storage/DownloadManager.cs | 105 -- .../SDK/Qiniu/Storage/FetchInfo.cs | 33 - .../SDK/Qiniu/Storage/FetchResult.cs | 72 - .../SDK/Qiniu/Storage/FileInfo.cs | 40 - .../SDK/Qiniu/Storage/FormUploader.cs | 270 ---- .../SDK/Qiniu/Storage/ListInfo.cs | 50 - .../SDK/Qiniu/Storage/ListItem.cs | 52 - .../SDK/Qiniu/Storage/ListResult.cs | 96 -- .../SDK/Qiniu/Storage/OperationManager.cs | 281 ---- .../SDK/Qiniu/Storage/PfopInfo.cs | 98 -- .../SDK/Qiniu/Storage/PfopResult.cs | 78 - .../SDK/Qiniu/Storage/PrefopResult.cs | 73 - .../SDK/Qiniu/Storage/PutExtra.cs | 51 - .../SDK/Qiniu/Storage/PutPolicy.cs | 167 -- .../SDK/Qiniu/Storage/QiniuException.cs | 24 - .../SDK/Qiniu/Storage/ResumableUploader.cs | 849 ---------- .../SDK/Qiniu/Storage/ResumeBlocker.cs | 38 - .../SDK/Qiniu/Storage/ResumeContext.cs | 59 - .../SDK/Qiniu/Storage/ResumeHelper.cs | 74 - .../SDK/Qiniu/Storage/ResumeInfo.cs | 62 - .../SDK/Qiniu/Storage/StatResult.cs | 74 - .../SDK/Qiniu/Storage/UploadController.cs | 29 - .../SDK/Qiniu/Storage/UploadManager.cs | 94 -- .../Qiniu/Storage/UploadProgressHandler.cs | 9 - .../SDK/Qiniu/Storage/Zone.cs | 107 -- .../SDK/Qiniu/Storage/ZoneHelper.cs | 123 -- .../SDK/Qiniu/Storage/ZoneInfo.cs | 36 - .../SDK/Qiniu/Util/Auth.cs | 161 -- .../SDK/Qiniu/Util/Base64.cs | 67 - .../SDK/Qiniu/Util/CRC32.cs | 133 -- .../SDK/Qiniu/Util/ETag.cs | 73 - .../SDK/Qiniu/Util/Hashing.cs | 76 - .../SDK/Qiniu/Util/LabMD5.cs | 272 ---- .../SDK/Qiniu/Util/Mac.cs | 29 - .../SDK/Qiniu/Util/QETag.cs | 73 - .../SDK/Qiniu/Util/Signature.cs | 126 -- .../SDK/Qiniu/Util/StringHelper.cs | 42 - .../SDK/Qiniu/Util/UnixTimestamp.cs | 88 -- .../SDK/Qiniu/Util/UpToken.cs | 58 - .../SDK/Qiniu/Util/UrlHelper.cs | 110 -- .../SDK/Qiniu/Util/UserEnv.cs | 111 -- 77 files changed, 54 insertions(+), 9526 deletions(-) delete mode 100644 src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/CDN/BandwidthInfo.cs delete mode 100644 src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/CDN/BandwidthRequest.cs delete mode 100644 src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/CDN/BandwidthResult.cs delete mode 100644 src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/CDN/CdnManager.cs delete mode 100644 src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/CDN/FluxInfo.cs delete mode 100644 src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/CDN/FluxRequest.cs delete mode 100644 src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/CDN/FluxResult.cs delete mode 100644 src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/CDN/LogListInfo.cs delete mode 100644 src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/CDN/LogListRequest.cs delete mode 100644 src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/CDN/LogListResult.cs delete mode 100644 src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/CDN/PrefetchInfo.cs delete mode 100644 src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/CDN/PrefetchRequest.cs delete mode 100644 src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/CDN/PrefetchResult.cs delete mode 100644 src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/CDN/RefreshInfo.cs delete mode 100644 src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/CDN/RefreshRequest.cs delete mode 100644 src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/CDN/RefreshResult.cs delete mode 100644 src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/Http/ContentType.cs delete mode 100644 src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/Http/HttpCode.cs delete mode 100644 src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/Http/HttpHelper.cs delete mode 100644 src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/Http/HttpManager.cs delete mode 100644 src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/Http/HttpResult.cs delete mode 100644 src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/Http/UrlHelper.cs delete mode 100644 src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/QiniuCSharpSDK.cs delete mode 100644 src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/Storage/BatchInfo.cs delete mode 100644 src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/Storage/BatchResult.cs delete mode 100644 src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/Storage/BucketInfo.cs delete mode 100644 src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/Storage/BucketManager.cs delete mode 100644 src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/Storage/BucketResult.cs delete mode 100644 src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/Storage/BucketsResult.cs delete mode 100644 src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/Storage/ChunkUnit.cs delete mode 100644 src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/Storage/Config.cs delete mode 100644 src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/Storage/DomainsResult.cs delete mode 100644 src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/Storage/DownloadManager.cs delete mode 100644 src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/Storage/FetchInfo.cs delete mode 100644 src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/Storage/FetchResult.cs delete mode 100644 src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/Storage/FileInfo.cs delete mode 100644 src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/Storage/FormUploader.cs delete mode 100644 src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/Storage/ListInfo.cs delete mode 100644 src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/Storage/ListItem.cs delete mode 100644 src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/Storage/ListResult.cs delete mode 100644 src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/Storage/OperationManager.cs delete mode 100644 src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/Storage/PfopInfo.cs delete mode 100644 src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/Storage/PfopResult.cs delete mode 100644 src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/Storage/PrefopResult.cs delete mode 100644 src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/Storage/PutExtra.cs delete mode 100644 src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/Storage/PutPolicy.cs delete mode 100644 src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/Storage/QiniuException.cs delete mode 100644 src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/Storage/ResumableUploader.cs delete mode 100644 src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/Storage/ResumeBlocker.cs delete mode 100644 src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/Storage/ResumeContext.cs delete mode 100644 src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/Storage/ResumeHelper.cs delete mode 100644 src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/Storage/ResumeInfo.cs delete mode 100644 src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/Storage/StatResult.cs delete mode 100644 src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/Storage/UploadController.cs delete mode 100644 src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/Storage/UploadManager.cs delete mode 100644 src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/Storage/UploadProgressHandler.cs delete mode 100644 src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/Storage/Zone.cs delete mode 100644 src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/Storage/ZoneHelper.cs delete mode 100644 src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/Storage/ZoneInfo.cs delete mode 100644 src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/Util/Auth.cs delete mode 100644 src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/Util/Base64.cs delete mode 100644 src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/Util/CRC32.cs delete mode 100644 src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/Util/ETag.cs delete mode 100644 src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/Util/Hashing.cs delete mode 100644 src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/Util/LabMD5.cs delete mode 100644 src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/Util/Mac.cs delete mode 100644 src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/Util/QETag.cs delete mode 100644 src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/Util/Signature.cs delete mode 100644 src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/Util/StringHelper.cs delete mode 100644 src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/Util/UnixTimestamp.cs delete mode 100644 src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/Util/UpToken.cs delete mode 100644 src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/Util/UrlHelper.cs delete mode 100644 src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/Util/UserEnv.cs diff --git a/README.md b/README.md index b0221df..d1775e4 100644 --- a/README.md +++ b/README.md @@ -138,6 +138,7 @@ public async Task ListBuckets() | SessionToken | string | token | | 仅Minio中使用 | | IsEnableHttps | bool | 是否启用HTTPS | true | 建议启用 | | IsEnableCache | bool | 是否启用缓存 | true | 启用后将缓存签名URL,以减少请求次数 | +| UseCustumCacheProvider | bool | 是否使用自定义缓存提供器 | false | 将用自己实现的缓存提供器替代内部的MemoryCache,如使用Redis | ### API参考 @@ -328,12 +329,62 @@ Task GetObjectMetadataAsync(string bucketName 清除该对象的访问权限或将其恢复至继承权限。 注意:七牛云对象储存不支持此操作! +### 替换内部缓存提供器 + +如果启用了缓存来缓存签名URL,可以提高单个文件的签名URL请求效率。由于1.1.3之前版本使用的MemoryCache,有三个问题: +1、不支持分布式,只能单机缓存 +2、大量占用应用服务器内存 +3、应用重启之后,之前的缓存丢失 + +从1.1.3开始,提供了一个ICacheProvider接口。用户可以自己实现此接口,替换掉内部的MemoryCache,比如使用Redis。 +下面是代码: +```csharp +class RedisCacheProvider : ICacheProvider +{ + private readonly RedisClient _cache; + + public RedisCacheProvider(RedisClient cache) + { + this._cache = cache ?? throw new ArgumentNullException(nameof(cache)); + } + + public T Get(string key) where T : class + { + string val = _cache.Get(key); + if (string.IsNullOrEmpty(val)) + { + return default(T); + } + return JsonUtil.DeserializeStringToObject(val); + } + + public void Remove(string key) + { + _cache.Del(key); + } + + public void Set(string key, T value, TimeSpan ts) where T : class + { + string stringVal = JsonUtil.SerializeToString(value); + _cache.Set(key, stringVal, ts); + } +} + +//然后在ConfigureServices中注入 +var client = new RedisClient("127.0.0.1:6379,password=,ConnectTimeout=3000,defaultdatabase=0"); +services.TryAddSingleton(client); +services.TryAddSingleton(); +``` + ## Dependencies 1. Aliyun.OSS.SDK.NetCore 2. Microsoft.Extensions.Caching.Memory 3. Newtonsoft.Json 4. Tencent.QCloud.Cos.Sdk +5. Minio +6. Qiniu +7. https://github.com/huaweicloud/huaweicloud-sdk-dotnet-obs ## To do list 1. 修改签名URL过期策略为滑动过期策略 diff --git a/src/samples/Sample.AspNetCore.Mvc/CacheProviders/RedisCacheProvider.cs b/src/samples/Sample.AspNetCore.Mvc/CacheProviders/RedisCacheProvider.cs index bc4a956..364bcf0 100644 --- a/src/samples/Sample.AspNetCore.Mvc/CacheProviders/RedisCacheProvider.cs +++ b/src/samples/Sample.AspNetCore.Mvc/CacheProviders/RedisCacheProvider.cs @@ -1,10 +1,7 @@ using FreeRedis; -using Microsoft.Extensions.Caching.Memory; using OnceMi.AspNetCore.OSS; using OnceMi.Framework.Util.Json; using System; -using System.Collections.Generic; -using System.Text; namespace Sample.AspNetCore.Mvc.CacheProviders { diff --git a/src/samples/Sample.AspNetCore.Mvc/Startup.cs b/src/samples/Sample.AspNetCore.Mvc/Startup.cs index 4ca429e..9602413 100644 --- a/src/samples/Sample.AspNetCore.Mvc/Startup.cs +++ b/src/samples/Sample.AspNetCore.Mvc/Startup.cs @@ -43,9 +43,8 @@ public void ConfigureServices(IServiceCollection services) option.IsEnableHttps = true; option.IsEnableCache = true; - //ǷǷʹԶ建ṩ - //ôãʹԶĻṩ滻ĬϵMemoryCache - //ǰʾʵԼṩ + //ǷʹԶ建ṩ + //ôõǰʾʵԼṩ option.UseCustumCacheProvider = false; }); diff --git a/src/src/OnceMi.AspNetCore.OSS/OnceMi.AspNetCore.OSS.csproj b/src/src/OnceMi.AspNetCore.OSS/OnceMi.AspNetCore.OSS.csproj index b66b0e3..f397df6 100644 --- a/src/src/OnceMi.AspNetCore.OSS/OnceMi.AspNetCore.OSS.csproj +++ b/src/src/OnceMi.AspNetCore.OSS/OnceMi.AspNetCore.OSS.csproj @@ -20,6 +20,7 @@ + diff --git a/src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/CDN/BandwidthInfo.cs b/src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/CDN/BandwidthInfo.cs deleted file mode 100644 index c0bfa51..0000000 --- a/src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/CDN/BandwidthInfo.cs +++ /dev/null @@ -1,77 +0,0 @@ -using System.Collections.Generic; -using System; -namespace Qiniu.CDN -{ - /// - /// 带宽-消息内容结构 - /// 说明: - /// 1.返回的数据包含开始日期和结束日期 - /// 2.带宽的单位为 bps - /// 3.数据(data)只包含有流量的域名 - /// 以下是一个返回结果示例 - /// - /// 200 OK HTTP/1.1 - /// { - /// "code": 200, - /// "error": "", - /// "time": ["2016-07-01 00:00:00","2016-07-01 00:05:00", ...], - /// "data": { - /// "a.com": { - /// "china": [8888, 9999, 10000, ...], - /// "oversea": [3333, 4444, 5000, ...], - /// }, - /// "b.com": { - /// "china": [8888, 9999, 10000, ...], - /// "oversea": [3333, 4444, 5000, ...], - /// } - /// } - /// } - /// - /// 另请参阅 http://developer.qiniu.com/article/fusion/api/traffic-bandwidth.html#batch-bandwidth - /// - public class BandwidthInfo - { - /// - /// 代码 含义 说明 - /// 200 success 成功(OK) - /// 400032 invalid host 请求中存在无效的域名,请确保域名格式正确 - /// 400080 invalid start time 开始时间格式错误 - /// 400081 invalid end time 截止时间格式错误 - /// 400082 invalid time range 时间范围错误,请确保开始时间早于结束时间,且时间范围不超过 30 天 - /// 500000 internal error 服务端内部错误,请联系技术支持 - /// - public int Code { get; set; } - - /// - /// 错误消息(状态码非OK时) - /// - public string Error { get; set; } - - /// - /// 时间点列表 - /// - public List Time { get; set; } - - /// - /// 带宽数居(与时间点列表对应) - /// 数据内容请参见该类型说明 - /// - public Dictionary Data { get; set; } - } - - /// - /// 带宽-数据内容 - /// - public class BandWidthData - { - /// - /// 国内带宽数据 - /// - public List China { get; set; } - - /// - /// 海外带宽数据 - /// - public List Oversea { get; set; } - } -} diff --git a/src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/CDN/BandwidthRequest.cs b/src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/CDN/BandwidthRequest.cs deleted file mode 100644 index 16e210c..0000000 --- a/src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/CDN/BandwidthRequest.cs +++ /dev/null @@ -1,68 +0,0 @@ -using Newtonsoft.Json; -namespace Qiniu.CDN -{ - /// - /// 查询带宽-请求 - /// - public class BandwidthRequest - { - /// - /// 起始日期,例如2016-09-01 - /// - [JsonProperty("startDate")] - public string StartDate { get; set; } - - /// - /// 结束日期,例如2016-09-10 - /// - [JsonProperty("endDate")] - public string EndDate { get; set; } - - /// - /// 时间粒度((取值:5min / hour /day)) - /// - [JsonProperty("granularity")] - public string Granularity { get; set; } - - /// - /// 域名列表,以西文半角分号分割 - /// - [JsonProperty("domains")] - public string Domains { get; set; } - - /// - /// 初始化(所有成员为空,需要后续赋值) - /// - public BandwidthRequest() - { - StartDate = ""; - EndDate = ""; - Granularity = ""; - Domains = ""; - } - - /// - /// 初始化所有成员 - /// - /// 起始日期 - /// 结束日期 - /// 时间粒度 - /// 域名列表 - public BandwidthRequest(string startDate, string endDate, string granularity, string domains) - { - StartDate = startDate; - EndDate = endDate; - Granularity = granularity; - Domains = domains; - } - - /// - /// 转换到JSON字符串 - /// - /// 请求内容的JSON字符串 - public string ToJsonStr() - { - return JsonConvert.SerializeObject(this); - } - } -} diff --git a/src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/CDN/BandwidthResult.cs b/src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/CDN/BandwidthResult.cs deleted file mode 100644 index 1120b1a..0000000 --- a/src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/CDN/BandwidthResult.cs +++ /dev/null @@ -1,98 +0,0 @@ -using System.Text; -using Newtonsoft.Json; -using Qiniu.Http; - -namespace Qiniu.CDN -{ - /// - /// 查询带宽-结果 - /// - public class BandwidthResult : HttpResult - { - /// - /// 获取带宽信息 - /// - public BandwidthInfo Result - { - get - { - BandwidthInfo info = null; - if ((Code == (int)HttpCode.OK) && (!string.IsNullOrEmpty(Text))) - { - info = JsonConvert.DeserializeObject(Text); - } - return info; - } - } - - /// - /// 转换为易读字符串格式 - /// - /// 便于打印和阅读的字符串 - public override string ToString() - { - StringBuilder sb = new StringBuilder(); - - sb.AppendFormat("code:{0}\n", Code); - - sb.AppendLine(); - - if (Result != null) - { - sb.AppendLine("result:"); - sb.AppendFormat("code:{0}\n", Result.Code); - if (!string.IsNullOrEmpty(Result.Error)) - { - sb.AppendFormat("error:{0}\n", Result.Error); - } - if (Result.Time != null) - { - sb.Append("time:"); - foreach (var t in Result.Time) - { - sb.Append(t + " "); - } - sb.AppendLine(); - } - - if (Result.Data != null && Result.Data.Count > 0) - { - sb.Append("bandwidth:"); - foreach (var kvp in Result.Data) - { - sb.AppendFormat("{0}:\nChina: {1}, Oversea={2}\n", kvp.Key, kvp.Value.China, kvp.Value.Oversea); - } - sb.AppendLine(); - } - } - else - { - if (!string.IsNullOrEmpty(Text)) - { - sb.AppendLine("text:"); - sb.AppendLine(Text); - } - } - sb.AppendLine(); - - sb.AppendFormat("ref-code:{0}\n", RefCode); - - if (!string.IsNullOrEmpty(RefText)) - { - sb.AppendLine("ref-text:"); - sb.AppendLine(RefText); - } - - if (RefInfo != null) - { - sb.AppendFormat("ref-info:\n"); - foreach (var d in RefInfo) - { - sb.AppendLine(string.Format("{0}:{1}", d.Key, d.Value)); - } - } - - return sb.ToString(); - } - } -} diff --git a/src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/CDN/CdnManager.cs b/src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/CDN/CdnManager.cs deleted file mode 100644 index 0d7eeb6..0000000 --- a/src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/CDN/CdnManager.cs +++ /dev/null @@ -1,321 +0,0 @@ -using System; -using System.Text; -using Qiniu.Util; -using Qiniu.Http; - -namespace Qiniu.CDN -{ - - /// - /// 融合CDN加速-功能模块: 缓存刷新、文件预取、流量/带宽查询、日志查询、时间戳防盗链 - /// 另请参阅 http://developer.qiniu.com/article/index.html#fusion-api-handbook - /// 关于时间戳防盗链可参阅 https://support.qiniu.com/question/195128 - /// - public class CdnManager - { - private const string FUSION_API_HOST = "http://fusion.qiniuapi.com"; - private Auth auth; - private HttpManager httpManager; - - /// - /// 初始化 - /// - /// 账号(密钥) - public CdnManager(Mac mac) - { - auth = new Auth(mac); - httpManager = new HttpManager(); - } - - private string refreshEntry() - { - return string.Format("{0}/v2/tune/refresh", FUSION_API_HOST); - } - - private string prefetchEntry() - { - return string.Format("{0}/v2/tune/prefetch", FUSION_API_HOST); - } - - private string bandwidthEntry() - { - return string.Format("{0}/v2/tune/bandwidth", FUSION_API_HOST); - } - - private string fluxEntry() - { - return string.Format("{0}/v2/tune/flux", FUSION_API_HOST); - } - - private string logListEntry() - { - return string.Format("{0}/v2/tune/log/list", FUSION_API_HOST); - } - - - /// - /// 缓存刷新-刷新URL和URL目录 - /// - /// 要刷新的URL列表 - /// 要刷新的URL目录列表 - /// 缓存刷新的结果 - public RefreshResult RefreshUrlsAndDirs(string[] urls, string[] dirs) - { - RefreshRequest request = new RefreshRequest(urls, dirs); - RefreshResult result = new RefreshResult(); - - try - { - string url = refreshEntry(); - string body = request.ToJsonStr(); - string token = auth.CreateManageToken(url); - - HttpResult hr = httpManager.PostJson(url, body, token); - result.Shadow(hr); - } - catch (Exception ex) - { - StringBuilder sb = new StringBuilder(); - sb.AppendFormat("[{0}] [refresh] Error: ", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.ffff")); - Exception e = ex; - while (e != null) - { - sb.Append(e.Message + " "); - e = e.InnerException; - } - sb.AppendLine(); - - result.RefCode = (int)HttpCode.INVALID_ARGUMENT; - result.RefText += sb.ToString(); - } - - return result; - } - - /// - /// 缓存刷新-刷新URL - /// - /// 要刷新的URL列表 - /// 缓存刷新的结果 - public RefreshResult RefreshUrls(string[] urls) - { - return RefreshUrlsAndDirs(urls, null); - } - - /// - /// 缓存刷新-刷新URL目录 - /// - /// 要刷新的URL目录列表 - /// 缓存刷新的结果 - public RefreshResult RefreshDirs(string[] dirs) - { - return RefreshUrlsAndDirs(null, dirs); - } - - /// - /// 文件预取 - /// - /// 待预取的文件URL列表 - /// 文件预取的结果 - public PrefetchResult PrefetchUrls(string[] urls) - { - PrefetchRequest request = new PrefetchRequest(); - request.AddUrls(urls); - - PrefetchResult result = new PrefetchResult(); - - try - { - string url = prefetchEntry(); - string body = request.ToJsonStr(); - string token = auth.CreateManageToken(url); - - HttpResult hr = httpManager.PostJson(url, body, token); - result.Shadow(hr); - } - catch (Exception ex) - { - StringBuilder sb = new StringBuilder(); - sb.AppendFormat("[{0}] [prefetch] Error: ", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.ffff")); - Exception e = ex; - while (e != null) - { - sb.Append(e.Message + " "); - e = e.InnerException; - } - sb.AppendLine(); - - result.RefCode = (int)HttpCode.INVALID_ARGUMENT; - result.RefText += sb.ToString(); - } - - return result; - } - - - /// - /// 批量查询cdn带宽 - /// - /// 域名列表 - /// 起始日期,如2017-01-01 - /// 结束日期,如2017-01-02 - /// 时间粒度,如day - /// 带宽查询的结果 - public BandwidthResult GetBandwidthData(string[] domains, string startDate, string endDate, string granularity) - { - BandwidthRequest request = new BandwidthRequest(); - request.Domains = string.Join(";", domains); - request.StartDate = startDate; - request.EndDate = endDate; - request.Granularity = granularity; - - BandwidthResult result = new BandwidthResult(); - - try - { - string url = bandwidthEntry(); - string body = request.ToJsonStr(); - string token = auth.CreateManageToken(url); - - HttpResult hr = httpManager.PostJson(url, body, token); - result.Shadow(hr); - } - catch (Exception ex) - { - StringBuilder sb = new StringBuilder(); - sb.AppendFormat("[{0}] [bandwidth] Error: ", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.ffff")); - Exception e = ex; - while (e != null) - { - sb.Append(e.Message + " "); - e = e.InnerException; - } - sb.AppendLine(); - - result.RefCode = (int)HttpCode.INVALID_ARGUMENT; - result.RefText += sb.ToString(); - } - - return result; - } - - - /// - /// 批量查询cdn流量 - /// - /// 域名列表 - /// 起始日期,如2017-01-01 - /// 结束日期,如2017-01-02 - /// 时间粒度,如day - /// 流量查询的结果 - public FluxResult GetFluxData(string[] domains, string startDate, string endDate, string granularity) - { - FluxRequest request = new FluxRequest(); - request.Domains = string.Join(";", domains); - request.StartDate = startDate; - request.EndDate = endDate; - request.Granularity = granularity; - - FluxResult result = new FluxResult(); - - try - { - string url = fluxEntry(); - string body = request.ToJsonStr(); - string token = auth.CreateManageToken(url); - - HttpResult hr = httpManager.PostJson(url, body, token); - result.Shadow(hr); - } - catch (Exception ex) - { - StringBuilder sb = new StringBuilder(); - sb.AppendFormat("[{0}] [flux] Error: ", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.ffff")); - Exception e = ex; - while (e != null) - { - sb.Append(e.Message + " "); - e = e.InnerException; - } - sb.AppendLine(); - - result.RefCode = (int)HttpCode.INVALID_ARGUMENT; - result.RefText += sb.ToString(); - } - - return result; - } - - - /// - /// 查询日志列表,获取日志的下载外链 - /// - /// 域名列表 - /// 具体日期,例如2017-08-12 - /// 日志查询的结果 - public LogListResult GetCdnLogList(string[] domains, string day) - { - LogListRequest request = new LogListRequest(); - request.Domains = string.Join(";", domains); - request.Day = day; - LogListResult result = new LogListResult(); - - try - { - string url = logListEntry(); - string body = request.ToJsonStr(); - string token = auth.CreateManageToken(url); - - HttpResult hr = httpManager.PostJson(url, body, token); - result.Shadow(hr); - } - catch (Exception ex) - { - StringBuilder sb = new StringBuilder(); - sb.AppendFormat("[{0}] [loglist] Error: ", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.ffff")); - Exception e = ex; - while (e != null) - { - sb.Append(e.Message + " "); - e = e.InnerException; - } - sb.AppendLine(); - - result.RefCode = (int)HttpCode.INVALID_ARGUMENT; - result.RefText += sb.ToString(); - } - - return result; - } - - /// - /// 时间戳防盗链 - /// - /// 主机,如http://domain.com - /// 文件名,如 hello/world/test.jpg - /// 请求参数,如?v=1.1 - /// 后台提供的key - /// 链接有效时长 - /// 时间戳防盗链接 - public static string CreateTimestampAntiLeechUrl(string host, string fileName, string query, - string encryptKey, int expireInSeconds) - { - long expireAt = UnixTimestamp.GetUnixTimestamp(expireInSeconds); - string expireHex = expireAt.ToString("x"); - string path = string.Format("/{0}", Uri.EscapeUriString(fileName)); - string toSign = string.Format("{0}{1}{2}", encryptKey, path, expireHex); - string sign = Hashing.CalcMD5X(toSign); - string finalUrl = null; - if (!string.IsNullOrEmpty(query)) - { - finalUrl = string.Format("{0}{1}?{2}&sign={3}&t={4}", host, path, query, sign, expireHex); - } - else - { - finalUrl = string.Format("{0}{1}?sign={2}&t={3}", host, path, sign, expireHex); - } - return finalUrl; - } - - } -} diff --git a/src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/CDN/FluxInfo.cs b/src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/CDN/FluxInfo.cs deleted file mode 100644 index 7d9324a..0000000 --- a/src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/CDN/FluxInfo.cs +++ /dev/null @@ -1,77 +0,0 @@ -using System.Collections.Generic; -using System; -namespace Qiniu.CDN -{ - /// - /// 流量-消息内容结构 - /// 说明: - /// 1.返回的数据包含开始日期和结束日期 - /// 2.带宽的单位为 byte - /// 3.数据(data)只包含有流量的域名 - /// - /// 以下是一个返回结果示例 - /// - /// { - /// "code": 200, - /// "error": "", - /// "time": ["2016-07-01 00:00:00","2016-07-01 00:05:00", ...], - /// "data": { - /// "a.com": { - /// "china": [8888, 9999, 10000, ...], - /// "oversea": [3333, 4444, 5000, ...], - /// }, - /// "b.com": { - /// "china": [8888, 9999, 10000, ...], - /// "oversea": [3333, 4444, 5000, ...], - /// } - /// } - /// } - /// - /// 另请参阅 http://developer.qiniu.com/article/fusion/api/traffic-bandwidth.html#batch-flux - /// - public class FluxInfo - { - /// - /// 代码 含义 说明 - /// 200 success 成功(OK) - /// 400032 invalid host 请求中存在无效的域名,请确保域名格式正确 - /// 400080 invalid start time 开始时间格式错误 - /// 400081 invalid end time 截止时间格式错误 - /// 400082 invalid time range 时间范围错误,请确保开始时间早于结束时间,且时间范围不超过 30 天 - /// 500000 internal error 服务端内部错误,请联系技术支持 - /// - public int Code { get; set; } - - /// - /// 错误消息(状态码非OK时) - /// - public string Error { get; set; } - - /// - /// 时间点列表 - /// - public List Time { get; set; } - - /// - /// 流量数居(与时间点列表对应) - /// - public Dictionary Data { get; set; } - - /// - /// 流量-数据内容 - /// - public class FluxData - { - /// - /// 国内流量数据 - /// - public List China { get; set; } - - /// - /// 海外流量数据 - /// - public List Oversea { get; set; } - } - - } -} diff --git a/src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/CDN/FluxRequest.cs b/src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/CDN/FluxRequest.cs deleted file mode 100644 index 6a3cafe..0000000 --- a/src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/CDN/FluxRequest.cs +++ /dev/null @@ -1,68 +0,0 @@ -using Newtonsoft.Json; -namespace Qiniu.CDN -{ - /// - /// 查询流量-请求 - /// - public class FluxRequest - { - /// - /// 起始日期,例如2016-09-01 - /// - [JsonProperty("startDate")] - public string StartDate { get; set; } - - /// - /// 结束日期,例如2016-09-10 - /// - [JsonProperty("endDate")] - public string EndDate { get; set; } - - /// - /// 时间粒度((取值:5min / hour /day)) - /// - [JsonProperty("granularity")] - public string Granularity { get; set; } - - /// - /// 域名列表,以西文半角分号分割 - /// - [JsonProperty("domains")] - public string Domains { get; set; } - - /// - /// 初始化(所有成员为空,需要后续赋值) - /// - public FluxRequest() - { - StartDate = ""; - EndDate = ""; - Granularity = ""; - Domains = ""; - } - - /// - /// 初始化所有成员 - /// - /// 起始日期 - /// 结束日期 - /// 时间粒度 - /// 域名列表 - public FluxRequest(string startDate, string endDate, string granularity, string domains) - { - StartDate = startDate; - EndDate = endDate; - Granularity = granularity; - Domains = domains; - } - - /// - /// 转换到JSON字符串 - /// - /// 请求内容的JSON字符串 - public string ToJsonStr() - { - return JsonConvert.SerializeObject(this); - } - } -} diff --git a/src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/CDN/FluxResult.cs b/src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/CDN/FluxResult.cs deleted file mode 100644 index a512f3b..0000000 --- a/src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/CDN/FluxResult.cs +++ /dev/null @@ -1,97 +0,0 @@ -using System.Text; -using Newtonsoft.Json; -using Qiniu.Http; - -namespace Qiniu.CDN -{ - /// - /// 查询流量-结果 - /// - public class FluxResult : HttpResult - { - /// - /// 获取流量信息 - /// - public FluxInfo Result - { - get - { - FluxInfo info = null; - if ((Code == (int)HttpCode.OK) && (!string.IsNullOrEmpty(Text))) - { - info=JsonConvert.DeserializeObject(Text); - } - return info; - } - } - - /// - /// 转换为易读字符串格式 - /// - /// 便于打印和阅读的字符串 - public override string ToString() - { - StringBuilder sb = new StringBuilder(); - - sb.AppendFormat("code:{0}\n", Code); - sb.AppendLine(); - - if (Result != null) - { - sb.AppendLine("result:"); - sb.AppendFormat("code:{0}\n", Result.Code); - if (!string.IsNullOrEmpty(Result.Error)) - { - sb.AppendFormat("error:{0}\n", Result.Error); - } - if (Result.Time != null) - { - sb.Append("time:"); - foreach (var t in Result.Time) - { - sb.Append(t + " "); - } - sb.AppendLine(); - } - - if (Result.Data != null && Result.Data.Count > 0) - { - sb.Append("flux:"); - foreach (var kvp in Result.Data) - { - sb.AppendFormat("{0}:\nChina: {1}, Oversea={2}\n", kvp.Key, kvp.Value.China, kvp.Value.Oversea); - } - sb.AppendLine(); - } - } - else - { - if (!string.IsNullOrEmpty(Text)) - { - sb.AppendLine("text:"); - sb.AppendLine(Text); - } - } - sb.AppendLine(); - - sb.AppendFormat("ref-code:{0}\n", RefCode); - - if (!string.IsNullOrEmpty(RefText)) - { - sb.AppendLine("ref-text:"); - sb.AppendLine(RefText); - } - - if (RefInfo != null) - { - sb.AppendFormat("ref-info:\n"); - foreach (var d in RefInfo) - { - sb.AppendLine(string.Format("{0}:{1}", d.Key, d.Value)); - } - } - - return sb.ToString(); - } - } -} diff --git a/src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/CDN/LogListInfo.cs b/src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/CDN/LogListInfo.cs deleted file mode 100644 index 74c514c..0000000 --- a/src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/CDN/LogListInfo.cs +++ /dev/null @@ -1,80 +0,0 @@ -using System.Collections.Generic; - -namespace Qiniu.CDN -{ - /// - /// 日志-消息内容结构 - /// - /// 以下是一个返回结果示例 - /// - /// { - /// "data": { - /// "log-test1.SOME_TEST.com": [ - /// { - /// "name":"log-test1.SOME_TEST.com_2016-07-01-00_00.gz", - /// "size": 88490306, - /// "mtime": 1466274440, - /// "url": "http://FUSION_LOG_DOWNLOAD_URL1" - /// } - /// ], - /// "log-test2.SOME_TEST.com": [ - /// { - /// "name":"log-test2.SOME_TEST.com_2016-07-01-00_00.gz", - /// "size": 73280873, - /// "mtime": 1466273259, - /// "url": "http://FUSION_LOG_DOWNLOAD_URL2" - /// } - /// ] - /// } - /// } - /// - /// /// - public class LogListInfo - { - /// - /// 代码 含义 说明 - /// 200 success 成功(OK) - /// 400 invalid params 请求参数格式错误 - /// 401 bad token 认证授权失败(包括密钥信息不正确;数字签名错误;授权已超时) - /// 400032 invalid host 请求中存在无效的域名,请确保域名格式正确 - /// 500000 internal error 服务器内部错误 - /// - public int Code { get; set; } - - /// - /// 错误消息(状态码非OK时) - /// - public string Error { get; set; } - - /// - /// 日志信息(与域名列表对应) - /// - public Dictionary> Data { get; set; } - } - - /// - /// 日志信息内容 - /// - public class LogData - { - /// - /// 文件名 - /// - public string Name { get; set; } - - /// - /// 文件大小,单位为 Byte - /// - public long Size { get; set; } - - /// - /// 文件修改时间,Unix 时间戳 - /// - public long Mtime { get; set; } - - /// - /// 日志下载链接 - /// - public string Url { get; set; } - } -} diff --git a/src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/CDN/LogListRequest.cs b/src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/CDN/LogListRequest.cs deleted file mode 100644 index 97e7167..0000000 --- a/src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/CDN/LogListRequest.cs +++ /dev/null @@ -1,94 +0,0 @@ -using System.Text; -using System.Collections.Generic; -using Newtonsoft.Json; -namespace Qiniu.CDN -{ - /// - /// 查询日志-请求 - /// - public class LogListRequest - { - /// - /// 日期,例如 2016-09-01 - /// - [JsonProperty("day")] - public string Day { get; set; } - - /// - /// 域名列表,以西文半角分号分割 - /// - [JsonProperty("domains")] - public string Domains { get; set; } - - /// - /// 初始化(所有成员为空,需要后续赋值) - /// - public LogListRequest() - { - Day = ""; - Domains = ""; - } - - /// - /// 初始化所有成员 - /// - /// 日期 - /// 域名列表(多个域名以;分隔的字符串) - public LogListRequest(string day, string domains) - { - Day = day; - Domains = domains; - } - - /// - /// 初始化所有成员 - /// - /// 日期 - /// 域名列表 - public LogListRequest(string day, IList domains) - { - if (string.IsNullOrEmpty(day)) - { - Day = ""; - } - else - { - Day = day; - } - - if (domains == null) - { - Domains = ""; - } - else - { - List uniqueDomains = new List(); - foreach (string d in domains) - { - if (!uniqueDomains.Contains(d)) - { - uniqueDomains.Add(d); - } - } - - if (uniqueDomains.Count > 0) - { - Domains = string.Join(";", uniqueDomains); - } - else - { - Domains = ""; - } - } - } - - /// - /// 转换到JSON字符串 - /// - /// 请求内容的JSON字符串 - public string ToJsonStr() - { - return JsonConvert.SerializeObject(this); - } - } -} diff --git a/src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/CDN/LogListResult.cs b/src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/CDN/LogListResult.cs deleted file mode 100644 index db4614b..0000000 --- a/src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/CDN/LogListResult.cs +++ /dev/null @@ -1,102 +0,0 @@ -using System.Text; -using Newtonsoft.Json; -using Qiniu.Http; - -namespace Qiniu.CDN -{ - /// - /// 查询日志-结果 - /// - public class LogListResult : HttpResult - { - /// - /// 获取日志列表信息 - /// - public LogListInfo Result - { - get - { - LogListInfo info = null; - if ((Code == (int)HttpCode.OK) && (!string.IsNullOrEmpty(Text))) - { - info=JsonConvert.DeserializeObject(Text); - } - return info; - } - } - - /// - /// 转换为易读字符串格式 - /// - /// 便于打印和阅读的字符串 - public override string ToString() - { - StringBuilder sb = new StringBuilder(); - - sb.AppendFormat("code:{0}\n", Code); - sb.AppendLine(); - - if (Result != null) - { - sb.AppendLine("result:"); - sb.AppendFormat("code:{0}\n", Result.Code); - if (!string.IsNullOrEmpty(Result.Error)) - { - sb.AppendFormat("error:{0}\n", Result.Error); - } - if (Result.Data != null && Result.Data.Count > 0) - { - sb.AppendLine("log:"); - foreach (var key in Result.Data.Keys) - { - sb.AppendFormat("{0}:\n", key); - foreach (var d in Result.Data) - { - if (d.Value != null) - { - sb.AppendFormat("Domain:{0}\n", d.Key); - foreach (var s in d.Value) - { - if (s != null) - { - sb.AppendFormat("Name:{0}\nSize:{1}\nMtime:{2}\nUrl:{3}\n\n", s.Name, s.Size, s.Mtime, s.Url); - } - } - } - } - sb.AppendLine(); - } - } - } - else - { - if (!string.IsNullOrEmpty(Text)) - { - sb.AppendLine("text:"); - sb.AppendLine(Text); - } - } - sb.AppendLine(); - - sb.AppendFormat("ref-code:{0}\n", RefCode); - - if (!string.IsNullOrEmpty(RefText)) - { - sb.AppendLine("ref-text:"); - sb.AppendLine(RefText); - } - - if (RefInfo != null) - { - sb.AppendFormat("ref-info:\n"); - foreach (var d in RefInfo) - { - sb.AppendLine(string.Format("{0}:{1}", d.Key, d.Value)); - } - } - - return sb.ToString(); - } - } -} - diff --git a/src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/CDN/PrefetchInfo.cs b/src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/CDN/PrefetchInfo.cs deleted file mode 100644 index 4d4f0ac..0000000 --- a/src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/CDN/PrefetchInfo.cs +++ /dev/null @@ -1,62 +0,0 @@ -using System.Collections.Generic; - -namespace Qiniu.CDN -{ - /// - /// 文件预取-消息内容结构 - /// - /// 在请求成功时 code 为 200,requestId、quotaDay、surplusDay 才会有有效值,否则为空。 - /// 在请求失败时 code 为非 200,error 中包含描述信息。 - /// - /// 以下是一个返回结果示例 - /// - /// { - /// "code":200, - /// "error":"success", - /// "requestId":"577471ace3ab3a030c058972", - /// "invalidUrls":null, - /// "quotaDay":100, - /// "surplusDay":99 - /// } - /// - /// - public class PrefetchInfo - { - /// - /// 代码 含义 说明 - /// /// 200 success 成功(OK) - /// 400031 invalid url 请求中存在无效的 url,请确保提交的 url 格式正确 - /// 400032 invalid host 请求中存在无效的域名,请确保域名格式正确 - /// 400033 prefetch url limit error 请求次数超出当日预取限额 - /// 400036 invalid request id 无效的请求 id - /// 400037 url has existed url 正在预取中 - /// 500000 internal error 服务端内部错误,请联系技术支持 - /// - public int Code { get; set; } - - /// - /// 错误消息(状态码非OK时) - /// - public string Error { get; set; } - - /// - /// 请求ID(可用于反馈排查) - /// - public string RequestId { get; set; } - - /// - /// 非法URL - /// - public List InvalidUrls { get; set; } - - /// - /// 当日限额 - /// - public int QuotaDay { get; set; } - - /// - /// 当日剩余额度 - /// - public int SurplusDay { get; set; } - } -} diff --git a/src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/CDN/PrefetchRequest.cs b/src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/CDN/PrefetchRequest.cs deleted file mode 100644 index 5f7d89a..0000000 --- a/src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/CDN/PrefetchRequest.cs +++ /dev/null @@ -1,73 +0,0 @@ -using System.Collections.Generic; -using System.Text; -using Newtonsoft.Json; - -namespace Qiniu.CDN -{ - /// - /// 文件预取-请求 - /// - public class PrefetchRequest - { - /// - /// 要预取的单个url列表,总数不超过100条 - /// 单个url,即一个具体的url,例如:http://bar.foo.com/test.zip - /// 注意: - /// 请输入资源 url 完整的绝对路径,由 http:// 或 https:// 开始 - /// 资源 url 不支持通配符,例如:不支持 http://www.test.com/abc/*.* - /// - [JsonProperty("urls",NullValueHandling=NullValueHandling.Ignore)] - public List Urls { get; set; } - - /// - /// 初始化(URL列表为空,需要后续赋值) - /// - public PrefetchRequest() - { - Urls = new List(); - } - - /// - /// 初始化(URL列表) - /// - /// URL列表 - public PrefetchRequest(IList urls) - { - if (urls != null) - { - Urls = new List(urls); - } - else - { - Urls = new List(); - } - } - - /// - /// 添加要查询的URL - /// - /// URL列表 - public void AddUrls(IList urls) - { - if (urls != null) - { - foreach (string u in urls) - { - if(!Urls.Contains(u)) - { - Urls.Add(u); - } - } - } - } - - /// - /// 转换到JSON字符串 - /// - /// 请求内容的JSON字符串 - public string ToJsonStr() - { - return JsonConvert.SerializeObject(this); - } - } -} diff --git a/src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/CDN/PrefetchResult.cs b/src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/CDN/PrefetchResult.cs deleted file mode 100644 index 5a12fb9..0000000 --- a/src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/CDN/PrefetchResult.cs +++ /dev/null @@ -1,94 +0,0 @@ -using System.Text; -using Newtonsoft.Json; -using Qiniu.Http; - -namespace Qiniu.CDN -{ - /// - /// 文件预取-结果 - /// - public class PrefetchResult : HttpResult - { - /// - /// 获取文件预取信息 - /// - public PrefetchInfo Result - { - get - { - PrefetchInfo info = null; - if ((Code == (int)HttpCode.OK) && (!string.IsNullOrEmpty(Text))) - { - info=JsonConvert.DeserializeObject(Text); - } - return info; - } - } - - /// - /// 转换为易读字符串格式 - /// - /// 便于打印和阅读的字符串 - public override string ToString() - { - StringBuilder sb = new StringBuilder(); - - sb.AppendFormat("code:{0}\n", Code); - sb.AppendLine(); - - if (Result != null) - { - sb.AppendLine("result:"); - sb.AppendFormat("code:{0}\n", Result.Code); - if (!string.IsNullOrEmpty(Result.Error)) - { - sb.AppendFormat("error:{0}\n", Result.Error); - } - if (!string.IsNullOrEmpty(Result.RequestId)) - { - sb.AppendFormat("requestId:{0}\n", Result.RequestId); - } - if (Result.InvalidUrls != null && Result.InvalidUrls.Count > 0) - { - sb.Append("invalidUrls:"); - foreach (var s in Result.InvalidUrls) - { - sb.Append(s + " "); - } - } - sb.AppendLine(); - sb.AppendFormat("quotaDay:{0}\n", Result.QuotaDay); - sb.AppendFormat("surplusaDay:{0}\n", Result.SurplusDay); - } - else - { - if (!string.IsNullOrEmpty(Text)) - { - sb.AppendLine("text:"); - sb.AppendLine(Text); - } - } - sb.AppendLine(); - - sb.AppendFormat("ref-code:{0}\n", RefCode); - - if (!string.IsNullOrEmpty(RefText)) - { - sb.AppendLine("ref-text:"); - sb.AppendLine(RefText); - } - - if (RefInfo != null) - { - sb.AppendFormat("ref-info:\n"); - foreach (var d in RefInfo) - { - sb.AppendLine(string.Format("{0}:{1}", d.Key, d.Value)); - } - } - - return sb.ToString(); - } - } -} - diff --git a/src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/CDN/RefreshInfo.cs b/src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/CDN/RefreshInfo.cs deleted file mode 100644 index 8128e10..0000000 --- a/src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/CDN/RefreshInfo.cs +++ /dev/null @@ -1,80 +0,0 @@ -using System.Collections.Generic; - -namespace Qiniu.CDN -{ - /// - /// 缓存刷新-消息内容结构 - /// - /// 在请求成功时 code 为 200,requestId、urlQuotaDay、urlSurplusDay、dirQuotaDay、dirSurplusDay才会有有效值,否则为空。 - /// 在请求失败时 code 为非 200,error 中包含描述信息。 - /// - /// 以下是一个返回结果示例 - /// - /// { - /// "code":200, - /// "error":"success", - /// "requestId":"575d1930f9537d3f2600003d", - /// "invalidUrls":null, - /// "invalidDirs":null, - /// "urlQuotaDay":100, - /// "urlSurplusDay":99, - /// "dirQuotaDay":10, - /// "dirSurplusDay":10 - /// } - /// - /// - public class RefreshInfo - { - /// - /// 代码 含义 说明 - /// 200 success 成功(OK) - /// 400031 invalid url 请求中存在无效的 url,请确保 url 格式正确 - /// 400032 invalid host 请求中存在无效的域名,请确保域名格式正确 - /// 400034 refresh url limit error 请求次数超出当日刷新限额 - /// 400036 invalid request id 无效的请求 id - /// 400037 url has existed url 正在刷新中 - /// 500000 internal error 服务端内部错误,请联系技术支持 - /// - public int Code { get; set; } - - /// - /// 错误消息(状态码非OK时) - /// - public string Error { get; set; } - - /// - /// 请求ID(可用于反馈排查) - /// - public string RequestId { get; set; } - - /// - /// 非法URL - /// - public List InvalidUrls { get; set; } - - /// - /// 非法URL目录 - /// - public List InvalidDirs { get; set; } - - /// - /// 当日URL刷新限额 - /// - public int UrlQuotaDay { get; set; } - - /// - /// 当日剩余URL刷新额度 - /// - public int UrlSurplusDay { get; set; } - - /// - /// 当日URL目录刷新限额 - /// - public int DirQuotaDay { get; set; } - - /// - /// 当日剩余URL目录刷新额度 - /// - public int DirSurplusDay { get; set; } - } -} diff --git a/src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/CDN/RefreshRequest.cs b/src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/CDN/RefreshRequest.cs deleted file mode 100644 index 08ac813..0000000 --- a/src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/CDN/RefreshRequest.cs +++ /dev/null @@ -1,106 +0,0 @@ -using System.Collections.Generic; -using System.Text; -using Newtonsoft.Json; -namespace Qiniu.CDN -{ - /// - /// 缓存刷新-请求 - /// - public class RefreshRequest - { - /// - /// 要预取的单个url列表,总数不超过100条 - /// 单个url,即一个具体的url,例如:http://bar.foo.com/test.zip - /// 注意: - /// 请输入资源 url 完整的绝对路径,由 http:// 或 https:// 开始 - /// 资源 url 不支持通配符,例如:不支持 http://www.test.com/abc/*.* - /// 带参数的 url 刷新,根据其域名缓存配置是否忽略参数缓存决定刷新结果。 - /// 如果配置了时间戳防盗链的资源 url 提交时刷新需要去掉 e 和 token 参数 - /// - [JsonProperty("urls", NullValueHandling = NullValueHandling.Ignore)] - public List Urls { get; set; } - - /// - /// 要刷新的目录url列表,总数不超过10条;目录dir,即表示一个目录级的url,需要以 / 结尾 - /// 例如:http://bar.foo.com/dir/, - /// 也支持在尾部使用通配符,例如:http://bar.foo.com/dir/* - /// - [JsonProperty("dirs", NullValueHandling = NullValueHandling.Ignore)] - public List Dirs { get; set; } - - /// - /// 初始化(所有成员为空,需要后续赋值) - /// - public RefreshRequest() - { - this.Urls = new List(); - this.Dirs = new List(); - } - - /// - /// 初始化URL列表 - /// - /// URL列表 - /// URL目录列表 - public RefreshRequest(IList urls, IList dirs) - { - this.Urls = new List(); - this.Dirs = new List(); - - if (urls != null) - { - AddUrls(urls); - } - - if (dirs != null) - { - AddDirs(dirs); - } - } - - /// - /// 添加URL列表 - /// - /// URL列表 - public void AddUrls(IList urls) - { - if (urls != null) - { - foreach (var u in urls) - { - if (!this.Urls.Contains(u)) - { - this.Urls.Add(u); - } - } - } - } - - /// - /// 添加URL目录列表 - /// - /// URL目录列表 - public void AddDirs(IList dirs) - { - if (dirs != null) - { - foreach (var d in dirs) - { - if (!this.Dirs.Contains(d)) - { - this.Dirs.Add(d); - } - } - } - } - - /// - /// 转换到JSON字符串 - /// - /// 请求内容的JSON字符串 - public string ToJsonStr() - { - return JsonConvert.SerializeObject(this); - } - } -} diff --git a/src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/CDN/RefreshResult.cs b/src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/CDN/RefreshResult.cs deleted file mode 100644 index 00aa719..0000000 --- a/src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/CDN/RefreshResult.cs +++ /dev/null @@ -1,104 +0,0 @@ -using System.Text; -using Newtonsoft.Json; -using Qiniu.Http; - -namespace Qiniu.CDN -{ - /// - /// 缓存刷新-结果 - /// - public class RefreshResult : HttpResult - { - /// - /// 获取缓存刷新信息 - /// - public RefreshInfo Result - { - get - { - RefreshInfo info = null; - if ((Code == (int)HttpCode.OK) && (!string.IsNullOrEmpty(Text))) - { - info=JsonConvert.DeserializeObject(Text); - } - return info; - } - } - - /// - /// 转换为易读字符串格式 - /// - /// 便于打印和阅读的字符串 - public override string ToString() - { - StringBuilder sb = new StringBuilder(); - - sb.AppendFormat("code:{0}\n", Code); - sb.AppendLine(); - - if (Result != null) - { - sb.AppendLine("result:"); - sb.AppendFormat("code:{0}\n", Result.Code); - if (!string.IsNullOrEmpty(Result.Error)) - { - sb.AppendFormat("error:{0}\n", Result.Error); - } - if (!string.IsNullOrEmpty(Result.RequestId)) - { - sb.AppendFormat("requestId:{0}\n", Result.RequestId); - } - if (Result.InvalidDirs != null && Result.InvalidDirs.Count > 0) - { - sb.Append("invalidDirs:"); - foreach (var s in Result.InvalidDirs) - { - sb.Append(s + " "); - } - sb.AppendLine(); - } - if (Result.InvalidUrls != null && Result.InvalidUrls.Count > 0) - { - sb.Append("invalidUrls:"); - foreach (var s in Result.InvalidUrls) - { - sb.Append(s + " "); - } - sb.AppendLine(); - } - sb.AppendFormat("dirQuotaDay:{0}\n", Result.DirQuotaDay); - sb.AppendFormat("dirSurplusDay:{0}\n", Result.DirSurplusDay); - sb.AppendFormat("urlQuotaDay:{0}\n", Result.UrlQuotaDay); - sb.AppendFormat("urlSurplusDay:{0}\n", Result.UrlSurplusDay); - } - else - { - if (!string.IsNullOrEmpty(Text)) - { - sb.AppendLine("text:"); - sb.AppendLine(Text); - } - } - sb.AppendLine(); - - sb.AppendFormat("ref-code:{0}\n", RefCode); - - if (!string.IsNullOrEmpty(RefText)) - { - sb.AppendLine("ref-text:"); - sb.AppendLine(RefText); - } - - if (RefInfo != null) - { - sb.AppendFormat("ref-info:\n"); - foreach (var d in RefInfo) - { - sb.AppendLine(string.Format("{0}:{1}", d.Key, d.Value)); - } - } - - return sb.ToString(); - } - } -} \ No newline at end of file diff --git a/src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/Http/ContentType.cs b/src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/Http/ContentType.cs deleted file mode 100644 index 132a48e..0000000 --- a/src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/Http/ContentType.cs +++ /dev/null @@ -1,33 +0,0 @@ -namespace Qiniu.Http -{ - /// - /// HTTP 内容类型(Content-Type) - /// - public class ContentType - { - /// - /// 资源类型:普通文本 - /// - public static string TEXT_PLAIN = "text/plain"; - - /// - /// 资源类型:JSON字符串 - /// - public static string APPLICATION_JSON = "application/json"; - - /// - /// 资源类型:未知类型(数据流) - /// - public static string APPLICATION_OCTET_STREAM = "application/octet-stream"; - - /// - /// 资源类型:表单数据(键值对) - /// - public static string WWW_FORM_URLENC = "application/x-www-form-urlencoded"; - - /// - /// 资源类型:多分部数据 - /// - public static string MULTIPART_FORM_DATA = "multipart/form-data"; - } -} diff --git a/src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/Http/HttpCode.cs b/src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/Http/HttpCode.cs deleted file mode 100644 index eaf088c..0000000 --- a/src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/Http/HttpCode.cs +++ /dev/null @@ -1,168 +0,0 @@ -namespace Qiniu.Http -{ - /// - /// HTTP 状态码 - /// - public enum HttpCode - { - #region _PRE_ - - /// - /// 成功 - /// - OK = 200, - - /// - /// 部分OK - /// - PARTLY_OK = 298, - - /// - /// 请求错误 - /// - BAD_REQUEST = 400, - - /// - /// 认证授权失败 - /// - AUTHENTICATION_FAILED = 401, - - /// - /// 拒绝访问 - /// - ACCESS_DENIED = 403, - - /// - /// 资源不存在 - /// - OBJECT_NOT_FOUND = 404, - - /// - /// CRC32校验失败 - /// - CRC32_CHECK_FAILEd = 406, - - /// - /// 上传文件大小超限 - /// - FILE_SIZE_EXCEED = 413, - - /// - /// 镜像回源失败 - /// - PREFETCH_FAILED = 478, - - /// - /// 错误网关 - /// - BAD_GATEWAY = 502, - - /// - /// 服务端不可用 - /// - SERVER_UNAVAILABLE = 503, - - /// - /// 服务端操作超时 - /// - SERVER_TIME_EXCEED = 504, - - /// - /// 单个资源访问频率过高 - /// - TOO_FREQUENT_ACCESS = 573, - - /// - /// 回调失败 - /// - CALLBACK_FAILED = 579, - - /// - /// 服务端操作失败 - /// - SERVER_OPERATION_FAILED = 599, - - /// - /// 资源内容被修改 - /// - CONTENT_MODIFIED = 608, - - /// - /// 文件不存在 - /// - FILE_NOT_EXIST = 612, - - /// - /// 文件已存在 - /// - FILE_EXISTS = 614, - - /// - /// 空间数量已达上限 - /// - BUCKET_COUNT_LIMIT = 630, - - /// - /// 空间或者文件不存在 - /// - BUCKET_NOT_EXIST = 631, - - /// - /// 列举资源(list)使用了非法的marker - /// - INVALID_MARKER = 640, - - /// - /// 在断点续上传过程中,后续上传接收地址不正确或ctx信息已过期。 - /// - CONTEXT_EXPIRED = 701, - - #endregion _PRE_ - - #region _USR_ - - /// - /// 自定义HTTP状态码 (默认值) - /// - USER_UNDEF = 0, - - /// - /// 自定义HTTP状态码 (用户取消) - /// - USER_CANCELED = -2, - - /// - /// 自定义HTTP状态码 (用户暂停) - /// - USER_PAUSED = 1, - - /// - /// 自定义HTTP状态码 (用户继续) - /// - USER_RESUMED = 2, - - /// - /// 自定义HTTP状态码 (需要重试) - /// - USER_NEED_RETRY = 3, - - /// - /// 自定义HTTP状态码 (异常或错误) - /// - INVALID_ARGUMENT = -4, - - /// - /// 自定义HTTP状态码(文件不合法) - /// - INVALID_FILE = -3, - - /// - /// 自定义HTTP状态码(凭证不合法) - /// - INVALID_TOKEN = -5, - - #endregion _USR_ - - } - -} diff --git a/src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/Http/HttpHelper.cs b/src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/Http/HttpHelper.cs deleted file mode 100644 index bdd72d0..0000000 --- a/src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/Http/HttpHelper.cs +++ /dev/null @@ -1,101 +0,0 @@ -using System; -using Qiniu.Util; - -namespace Qiniu.Http -{ - /// - /// HTTP辅助工具:帮助生成UA,boundary等 - /// - public class HttpHelper - { - /// - /// 资源类型:普通文本 - /// - public static string CONTENT_TYPE_TEXT_PLAIN = "text/plain"; - - /// - /// 资源类型:JSON字符串 - /// - public static string CONTENT_TYPE_APP_JSON = "application/json"; - - /// - /// 资源类型:未知类型(数据流) - /// - public static string CONTENT_TYPE_APP_OCTET = "application/octet-stream"; - - /// - /// 资源类型:表单数据(键值对) - /// - public static string CONTENT_TYPE_WWW_FORM = "application/x-www-form-urlencoded"; - - /// - /// 资源类型:多分部数据 - /// - public static string CONTENT_TYPE_MULTIPART = "multipart/form-data"; - - /// - /// HTTP状态码200 (OK) - /// - public static int STATUS_CODE_OK = 200; - - /// - /// HTTP状态码298 (部分OK) - /// - public static int STATUS_CODE_PARTLY_OK = 298; - - /// - /// 自定义HTTP状态码 (默认值) - /// - public static int STATUS_CODE_UNDEF = -256; - - /// - /// 自定义HTTP状态码 (用户取消) - /// - public static int STATUS_CODE_USER_CANCELED = -255; - - /// - /// 自定义HTTP状态码 (用户暂停) - /// - public static int STATUS_CODE_USER_PAUSED = -254; - - /// - /// 自定义HTTP状态码 (用户继续) - /// - public static int STATUS_CODE_USER_RESUMED = -253; - - /// - /// 自定义HTTP状态码 (需要重试) - /// - public static int STATUS_CODE_NEED_RETRY= -252; - - /// - /// 自定义HTTP状态码 (异常或错误) - /// - public static int STATUS_CODE_EXCEPTION = -252; - - /// - /// 客户端标识 - /// - /// 客户端标识UA - public static string getUserAgent() - { -#if NetStandard - string sfx = Environment.MachineName; -#else - var osInfo = Environment.OSVersion; - string sfx = Environment.MachineName + "; " + osInfo.Platform + "; " + osInfo.Version; -#endif - return string.Format("{0}/{1} ({2})", QiniuCSharpSDK.ALIAS, QiniuCSharpSDK.VERSION, sfx); - } - - /// - /// 多部分表单数据(multi-part form-data)的分界(boundary)标识 - /// - /// 多部分表单数据的boundary - public static string createFormDataBoundary() - { - string now = DateTime.UtcNow.Ticks.ToString(); - return string.Format("-------{0}Boundary{1}", QiniuCSharpSDK.ALIAS, Hashing.CalcMD5(now)); - } - } -} diff --git a/src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/Http/HttpManager.cs b/src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/Http/HttpManager.cs deleted file mode 100644 index 803143b..0000000 --- a/src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/Http/HttpManager.cs +++ /dev/null @@ -1,1384 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Text; -using System.IO; -using System.Net; -using Qiniu.Util; - -namespace Qiniu.Http -{ - /// - /// HttpManager for .NET 2.0/3.0/3.5/4.0 - /// - public class HttpManager - { - private bool allowAutoRedirect; - private string userAgent; - - /// - /// 初始化 - /// - /// 是否允许HttpWebRequest的“重定向”,默认禁止 - public HttpManager(bool allowAutoRedirect = false) - { - this.allowAutoRedirect = allowAutoRedirect; - userAgent = GetUserAgent(); - } - - /// - /// 客户端标识(UserAgent),示例:"SepcifiedClient/1.1 (Universal)" - /// - /// 客户端标识UA - public static string GetUserAgent() - { - string osDesc = Environment.OSVersion.Platform + "; " + Environment.OSVersion.Version; - return string.Format("{0}/{1} ({2}; {3})", QiniuCSharpSDK.ALIAS, QiniuCSharpSDK.VERSION, QiniuCSharpSDK.RTFX, osDesc); - } - - /// - /// 设置自定义的客户端标识(UserAgent),示例:"SepcifiedClient/1.1 (Universal)" - /// 如果设置为空白或者不设置,SDK会自动使用默认的UserAgent - /// - /// 用户自定义的UserAgent - /// 客户端标识UA - public void SetUserAgent(string userAgent) - { - if(!string.IsNullOrEmpty(userAgent)) - { - this.userAgent = userAgent; - } - } - - /// - /// 多部分表单数据(multi-part form-data)的分界(boundary)标识 - /// - /// 分界(boundary)标识字符串 - public static string CreateFormDataBoundary() - { - string now = DateTime.UtcNow.Ticks.ToString(); - return string.Format("-------{0}Boundary{1}", QiniuCSharpSDK.ALIAS, Hashing.CalcMD5X(now)); - } - - /// - /// HTTP-GET方法 - /// - /// 请求目标URL - /// 令牌(凭证)[可选->设置为null] - /// 是否以二进制模式读取响应内容(默认:否,即表示以文本方式读取) - /// HTTP-GET的响应结果 - public HttpResult Get(string url, string token, bool binaryMode = false) - { - HttpResult result = new HttpResult(); - - HttpWebRequest wReq = null; - - try - { - wReq = WebRequest.Create(url) as HttpWebRequest; - wReq.Method = "GET"; - if (!string.IsNullOrEmpty(token)) - { - wReq.Headers.Add("Authorization", token); - } - wReq.UserAgent = userAgent; - wReq.AllowAutoRedirect = allowAutoRedirect; - wReq.ServicePoint.Expect100Continue = false; - - HttpWebResponse wResp = wReq.GetResponse() as HttpWebResponse; - - if (wResp != null) - { - result.Code = (int)wResp.StatusCode; - result.RefCode = (int)wResp.StatusCode; - - getHeaders(ref result, wResp); - - if (binaryMode) - { - int len = (int)wResp.ContentLength; - result.Data = new byte[len]; - int bytesLeft = len; - int bytesRead = 0; - - using (BinaryReader br = new BinaryReader(wResp.GetResponseStream())) - { - while (bytesLeft > 0) - { - bytesRead = br.Read(result.Data, len - bytesLeft, bytesLeft); - bytesLeft -= bytesRead; - } - } - } - else - { - using (StreamReader sr = new StreamReader(wResp.GetResponseStream())) - { - result.Text = sr.ReadToEnd(); - } - } - - wResp.Close(); - } - } - catch (WebException wex) - { - HttpWebResponse xResp = wex.Response as HttpWebResponse; - if (xResp != null) - { - result.Code = (int)xResp.StatusCode; - result.RefCode = (int)xResp.StatusCode; - - getHeaders(ref result, xResp); - - using (StreamReader sr = new StreamReader(xResp.GetResponseStream())) - { - result.Text = sr.ReadToEnd(); - } - - xResp.Close(); - } - } - catch (Exception ex) - { - StringBuilder sb = new StringBuilder(); - sb.AppendFormat("[{0}] [{1}] [HTTP-GET] Error: ", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.ffff"),userAgent); - Exception e = ex; - while (e != null) - { - sb.Append(e.Message + " "); - e = e.InnerException; - } - sb.AppendLine(); - - result.RefCode = (int)HttpCode.USER_UNDEF; - result.RefText += sb.ToString(); - } - finally - { - if (wReq != null) - { - wReq.Abort(); - } - } - - return result; - } - - /// - /// HTTP-POST方法(不包含body数据) - /// - /// 请求目标URL - /// 令牌(凭证)[可选] - /// 是否以二进制模式读取响应内容(默认:否,即表示以文本方式读取) - /// HTTP-POST的响应结果 - public HttpResult Post(string url, string token, bool binaryMode = false) - { - HttpResult result = new HttpResult(); - - HttpWebRequest wReq = null; - - try - { - wReq = WebRequest.Create(url) as HttpWebRequest; - wReq.Method = "POST"; - if (!string.IsNullOrEmpty(token)) - { - wReq.Headers.Add("Authorization", token); - } - wReq.UserAgent = userAgent; - wReq.AllowAutoRedirect = allowAutoRedirect; - wReq.ServicePoint.Expect100Continue = false; - - HttpWebResponse wResp = wReq.GetResponse() as HttpWebResponse; - - if (wResp != null) - { - result.Code = (int)wResp.StatusCode; - result.RefCode = (int)wResp.StatusCode; - - getHeaders(ref result, wResp); - - if (binaryMode) - { - int len = (int)wResp.ContentLength; - result.Data = new byte[len]; - int bytesLeft = len; - int bytesRead = 0; - - using (BinaryReader br = new BinaryReader(wResp.GetResponseStream())) - { - while (bytesLeft > 0) - { - bytesRead = br.Read(result.Data, len - bytesLeft, bytesLeft); - bytesLeft -= bytesRead; - } - } - } - else - { - using (StreamReader sr = new StreamReader(wResp.GetResponseStream())) - { - result.Text = sr.ReadToEnd(); - } - } - - wResp.Close(); - } - } - catch (WebException wex) - { - HttpWebResponse xResp = wex.Response as HttpWebResponse; - if (xResp != null) - { - result.Code = (int)xResp.StatusCode; - result.RefCode = (int)xResp.StatusCode; - - getHeaders(ref result, xResp); - - using (StreamReader sr = new StreamReader(xResp.GetResponseStream())) - { - result.Text = sr.ReadToEnd(); - } - - xResp.Close(); - } - } - catch (Exception ex) - { - StringBuilder sb = new StringBuilder(); - sb.AppendFormat("[{0}] [{1}] [HTTP-POST] Error: ", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.ffff"),userAgent); - Exception e = ex; - while (e != null) - { - sb.Append(e.Message + " "); - e = e.InnerException; - } - sb.AppendLine(); - - result.RefCode = (int)HttpCode.USER_UNDEF; - result.RefText += sb.ToString(); - } - finally - { - if (wReq != null) - { - wReq.Abort(); - } - } - - return result; - } - - /// - /// HTTP-POST方法(包含body数据) - /// - /// 请求目标URL - /// 主体数据(字节数据) - /// 令牌(凭证)[可选->设置为null] - /// 是否以二进制模式读取响应内容(默认:否,即表示以文本方式读取) - /// HTTP-POST的响应结果 - public HttpResult PostData(string url, byte[] data, string token, bool binaryMode = false) - { - HttpResult result = new HttpResult(); - - HttpWebRequest wReq = null; - - try - { - wReq = WebRequest.Create(url) as HttpWebRequest; - wReq.Method = "POST"; - if (!string.IsNullOrEmpty(token)) - { - wReq.Headers.Add("Authorization", token); - } - wReq.ContentType = ContentType.APPLICATION_OCTET_STREAM; - wReq.UserAgent = userAgent; - wReq.AllowAutoRedirect = allowAutoRedirect; - wReq.ServicePoint.Expect100Continue = false; - - if (data != null) - { - wReq.AllowWriteStreamBuffering = true; - using (Stream sReq = wReq.GetRequestStream()) - { - sReq.Write(data, 0, data.Length); - sReq.Flush(); - } - } - - HttpWebResponse wResp = wReq.GetResponse() as HttpWebResponse; - - if (wResp != null) - { - result.Code = (int)wResp.StatusCode; - result.RefCode = (int)wResp.StatusCode; - - getHeaders(ref result, wResp); - - if (binaryMode) - { - int len = (int)wResp.ContentLength; - result.Data = new byte[len]; - int bytesLeft = len; - int bytesRead = 0; - - using (BinaryReader br = new BinaryReader(wResp.GetResponseStream())) - { - while (bytesLeft > 0) - { - bytesRead = br.Read(result.Data, len - bytesLeft, bytesLeft); - bytesLeft -= bytesRead; - } - } - } - else - { - using (StreamReader sr = new StreamReader(wResp.GetResponseStream())) - { - result.Text = sr.ReadToEnd(); - } - } - - wResp.Close(); - } - } - catch (WebException wex) - { - HttpWebResponse xResp = wex.Response as HttpWebResponse; - if (xResp != null) - { - result.Code = (int)xResp.StatusCode; - result.RefCode = (int)xResp.StatusCode; - - getHeaders(ref result, xResp); - - using (StreamReader sr = new StreamReader(xResp.GetResponseStream())) - { - result.Text = sr.ReadToEnd(); - } - - xResp.Close(); - } - } - catch (Exception ex) - { - StringBuilder sb = new StringBuilder(); - sb.AppendFormat("[{0}] [{1}] [HTTP-POST-BIN] Error: ", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.ffff"),userAgent); - Exception e = ex; - while (e != null) - { - sb.Append(e.Message + " "); - e = e.InnerException; - } - sb.AppendLine(); - - result.RefCode = (int)HttpCode.USER_UNDEF; - result.RefText += sb.ToString(); - } - finally - { - if (wReq != null) - { - wReq.Abort(); - } - } - - return result; - } - - /// - /// HTTP-POST方法(包含body数据) - /// - /// 请求目标URL - /// 主体数据(字节数据) - /// 主体数据内容类型 - /// 令牌(凭证)[可选] - /// 是否以二进制模式读取响应内容(默认:否,即表示以文本方式读取) - /// HTTP-POST的响应结果 - public HttpResult PostData(string url, byte[] data, string mimeType, string token, bool binaryMode = false) - { - HttpResult result = new HttpResult(); - - HttpWebRequest wReq = null; - - try - { - wReq = WebRequest.Create(url) as HttpWebRequest; - wReq.Method = "POST"; - if (!string.IsNullOrEmpty(token)) - { - wReq.Headers.Add("Authorization", token); - } - wReq.ContentType = mimeType; - wReq.UserAgent = userAgent; - wReq.AllowAutoRedirect = allowAutoRedirect; - wReq.ServicePoint.Expect100Continue = false; - - if (data != null) - { - wReq.AllowWriteStreamBuffering = true; - using (Stream sReq = wReq.GetRequestStream()) - { - sReq.Write(data, 0, data.Length); - sReq.Flush(); - } - } - - HttpWebResponse wResp = wReq.GetResponse() as HttpWebResponse; - - if (wResp != null) - { - result.Code = (int)wResp.StatusCode; - result.RefCode = (int)wResp.StatusCode; - - getHeaders(ref result, wResp); - - if (binaryMode) - { - int len = (int)wResp.ContentLength; - result.Data = new byte[len]; - int bytesLeft = len; - int bytesRead = 0; - - using (BinaryReader br = new BinaryReader(wResp.GetResponseStream())) - { - while (bytesLeft > 0) - { - bytesRead = br.Read(result.Data, len - bytesLeft, bytesLeft); - bytesLeft -= bytesRead; - } - } - } - else - { - using (StreamReader sr = new StreamReader(wResp.GetResponseStream())) - { - result.Text = sr.ReadToEnd(); - } - } - - wResp.Close(); - } - } - catch (WebException wex) - { - HttpWebResponse xResp = wex.Response as HttpWebResponse; - if (xResp != null) - { - result.Code = (int)xResp.StatusCode; - result.RefCode = (int)xResp.StatusCode; - - getHeaders(ref result, xResp); - - using (StreamReader sr = new StreamReader(xResp.GetResponseStream())) - { - result.Text = sr.ReadToEnd(); - } - - xResp.Close(); - } - } - catch (Exception ex) - { - StringBuilder sb = new StringBuilder(); - sb.AppendFormat("[{0}] [{1}] [HTTP-POST-BIN] Error: ", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.ffff"),userAgent); - Exception e = ex; - while (e != null) - { - sb.Append(e.Message + " "); - e = e.InnerException; - } - sb.AppendLine(); - - result.RefCode = (int)HttpCode.USER_UNDEF; - result.RefText += sb.ToString(); - } - finally - { - if (wReq != null) - { - wReq.Abort(); - } - } - - return result; - } - - /// - /// HTTP-POST方法(包含JSON文本的body数据) - /// - /// 请求目标URL - /// 主体数据(JSON文本) - /// 令牌(凭证)[可选] - /// 是否以二进制模式读取响应内容(默认:否,即表示以文本方式读取) - /// HTTP-POST的响应结果 - public HttpResult PostJson(string url, string data, string token, bool binaryMode = false) - { - HttpResult result = new HttpResult(); - - HttpWebRequest wReq = null; - - try - { - wReq = WebRequest.Create(url) as HttpWebRequest; - wReq.Method = "POST"; - if (!string.IsNullOrEmpty(token)) - { - wReq.Headers.Add("Authorization", token); - } - wReq.ContentType = ContentType.APPLICATION_JSON; - wReq.UserAgent = userAgent; - wReq.AllowAutoRedirect = allowAutoRedirect; - wReq.ServicePoint.Expect100Continue = false; - - if (data != null) - { - wReq.AllowWriteStreamBuffering = true; - using (Stream sReq = wReq.GetRequestStream()) - { - sReq.Write(Encoding.UTF8.GetBytes(data), 0, data.Length); - sReq.Flush(); - } - } - - HttpWebResponse wResp = wReq.GetResponse() as HttpWebResponse; - - if (wResp != null) - { - result.Code = (int)wResp.StatusCode; - result.RefCode = (int)wResp.StatusCode; - - getHeaders(ref result, wResp); - - if (binaryMode) - { - int len = (int)wResp.ContentLength; - result.Data = new byte[len]; - int bytesLeft = len; - int bytesRead = 0; - - using (BinaryReader br = new BinaryReader(wResp.GetResponseStream())) - { - while (bytesLeft > 0) - { - bytesRead = br.Read(result.Data, len - bytesLeft, bytesLeft); - bytesLeft -= bytesRead; - } - } - } - else - { - using (StreamReader sr = new StreamReader(wResp.GetResponseStream())) - { - result.Text = sr.ReadToEnd(); - } - } - - wResp.Close(); - } - } - catch (WebException wex) - { - HttpWebResponse xResp = wex.Response as HttpWebResponse; - if (xResp != null) - { - result.Code = (int)xResp.StatusCode; - result.RefCode = (int)xResp.StatusCode; - - getHeaders(ref result, xResp); - - using (StreamReader sr = new StreamReader(xResp.GetResponseStream())) - { - result.Text = sr.ReadToEnd(); - } - - xResp.Close(); - } - } - catch (Exception ex) - { - StringBuilder sb = new StringBuilder(); - sb.AppendFormat("[{0}] [{1}] [HTTP-POST-JSON] Error: ", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.ffff"),userAgent); - Exception e = ex; - while (e != null) - { - sb.Append(e.Message + " "); - e = e.InnerException; - } - sb.AppendLine(); - - result.RefCode = (int)HttpCode.USER_UNDEF; - result.RefText += sb.ToString(); - } - finally - { - if (wReq != null) - { - wReq.Abort(); - } - } - - return result; - } - - /// - /// HTTP-POST方法(包含普通文本的body数据) - /// - /// 请求目标URL - /// 主体数据(普通文本) - /// 令牌(凭证)[可选->设置为null] - /// 是否以二进制模式读取响应内容(默认:否,即表示以文本方式读取) - /// HTTP-POST的响应结果 - public HttpResult PostText(string url, string data, string token, bool binaryMode = false) - { - HttpResult result = new HttpResult(); - - HttpWebRequest wReq = null; - - try - { - wReq = WebRequest.Create(url) as HttpWebRequest; - wReq.Method = "POST"; - if (!string.IsNullOrEmpty(token)) - { - wReq.Headers.Add("Authorization", token); - } - wReq.ContentType = ContentType.TEXT_PLAIN; - wReq.UserAgent = userAgent; - wReq.AllowAutoRedirect = allowAutoRedirect; - wReq.ServicePoint.Expect100Continue = false; - - if (data != null) - { - wReq.AllowWriteStreamBuffering = true; - using (Stream sReq = wReq.GetRequestStream()) - { - sReq.Write(Encoding.UTF8.GetBytes(data), 0, data.Length); - sReq.Flush(); - } - } - - HttpWebResponse wResp = wReq.GetResponse() as HttpWebResponse; - - if (wResp != null) - { - result.Code = (int)wResp.StatusCode; - result.RefCode = (int)wResp.StatusCode; - - getHeaders(ref result, wResp); - - if (binaryMode) - { - int len = (int)wResp.ContentLength; - result.Data = new byte[len]; - int bytesLeft = len; - int bytesRead = 0; - - using (BinaryReader br = new BinaryReader(wResp.GetResponseStream())) - { - while (bytesLeft > 0) - { - bytesRead = br.Read(result.Data, len - bytesLeft, bytesLeft); - bytesLeft -= bytesRead; - } - } - } - else - { - using (StreamReader sr = new StreamReader(wResp.GetResponseStream())) - { - result.Text = sr.ReadToEnd(); - } - } - - wResp.Close(); - } - } - catch (WebException wex) - { - HttpWebResponse xResp = wex.Response as HttpWebResponse; - if (xResp != null) - { - result.Code = (int)xResp.StatusCode; - result.RefCode = (int)xResp.StatusCode; - - getHeaders(ref result, xResp); - - using (StreamReader sr = new StreamReader(xResp.GetResponseStream())) - { - result.Text = sr.ReadToEnd(); - } - - xResp.Close(); - } - } - catch (Exception ex) - { - StringBuilder sb = new StringBuilder(); - sb.AppendFormat("[{0}] [{1}] [HTTP-POST-TEXT] Error: ", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.ffff"),userAgent); - Exception e = ex; - while (e != null) - { - sb.Append(e.Message + " "); - e = e.InnerException; - } - sb.AppendLine(); - - result.RefCode = (int)HttpCode.USER_UNDEF; - result.RefText += sb.ToString(); - } - finally - { - if (wReq != null) - { - wReq.Abort(); - } - } - - return result; - } - - /// - /// HTTP-POST方法(包含表单数据) - /// - /// 请求目标URL - /// 键值对数据 - /// 令牌(凭证)[可选->设置为null] - /// 是否以二进制模式读取响应内容(默认:否,即表示以文本方式读取) - /// HTTP-POST的响应结果 - public HttpResult PostForm(string url, Dictionary kvData, string token, bool binaryMode = false) - { - HttpResult result = new HttpResult(); - - HttpWebRequest wReq = null; - - try - { - wReq = WebRequest.Create(url) as HttpWebRequest; - wReq.Method = "POST"; - if (!string.IsNullOrEmpty(token)) - { - wReq.Headers.Add("Authorization", token); - } - wReq.ContentType = ContentType.WWW_FORM_URLENC; - wReq.UserAgent = userAgent; - wReq.AllowAutoRedirect = allowAutoRedirect; - wReq.ServicePoint.Expect100Continue = false; - - if (kvData != null) - { - StringBuilder sbb = new StringBuilder(); - foreach (var kv in kvData) - { - sbb.AppendFormat("{0}={1}&", Uri.EscapeDataString(kv.Key), Uri.EscapeDataString(kv.Value)); - } - - wReq.AllowWriteStreamBuffering = true; - using (Stream sReq = wReq.GetRequestStream()) - { - sReq.Write(Encoding.UTF8.GetBytes(sbb.ToString()), 0, sbb.Length - 1); - sReq.Flush(); - } - } - - HttpWebResponse wResp = wReq.GetResponse() as HttpWebResponse; - - if (wResp != null) - { - result.Code = (int)wResp.StatusCode; - result.RefCode = (int)wResp.StatusCode; - - getHeaders(ref result, wResp); - - if (binaryMode) - { - int len = (int)wResp.ContentLength; - result.Data = new byte[len]; - int bytesLeft = len; - int bytesRead = 0; - - using (BinaryReader br = new BinaryReader(wResp.GetResponseStream())) - { - while (bytesLeft > 0) - { - bytesRead = br.Read(result.Data, len - bytesLeft, bytesLeft); - bytesLeft -= bytesRead; - } - } - } - else - { - using (StreamReader sr = new StreamReader(wResp.GetResponseStream())) - { - result.Text = sr.ReadToEnd(); - } - } - - wResp.Close(); - } - } - catch (WebException wex) - { - HttpWebResponse xResp = wex.Response as HttpWebResponse; - if (xResp != null) - { - result.Code = (int)xResp.StatusCode; - result.RefCode = (int)xResp.StatusCode; - - getHeaders(ref result, xResp); - - using (StreamReader sr = new StreamReader(xResp.GetResponseStream())) - { - result.Text = sr.ReadToEnd(); - } - - xResp.Close(); - } - } - catch (Exception ex) - { - StringBuilder sb = new StringBuilder(); - sb.AppendFormat("[{0}] [{1}] [HTTP-POST-FORM] Error: ", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.ffff"),userAgent); - Exception e = ex; - while (e != null) - { - sb.Append(e.Message + " "); - e = e.InnerException; - } - sb.AppendLine(); - - result.RefCode = (int)HttpCode.USER_UNDEF; - result.RefText += sb.ToString(); - } - finally - { - if (wReq != null) - { - wReq.Abort(); - } - } - - return result; - } - - /// - /// HTTP-POST方法(包含表单数据) - /// - /// 请求目标URL - /// 表单数据 - /// 令牌(凭证)[可选->设置为null] - /// 是否以二进制模式读取响应内容(默认:否,即表示以文本方式读取) - /// HTTP-POST的响应结果 - public HttpResult PostForm(string url, string data, string token, bool binaryMode = false) - { - HttpResult result = new HttpResult(); - - HttpWebRequest wReq = null; - - try - { - wReq = WebRequest.Create(url) as HttpWebRequest; - wReq.Method = "POST"; - if (!string.IsNullOrEmpty(token)) - { - wReq.Headers.Add("Authorization", token); - } - wReq.ContentType = ContentType.WWW_FORM_URLENC; - wReq.UserAgent = userAgent; - wReq.AllowAutoRedirect = allowAutoRedirect; - wReq.ServicePoint.Expect100Continue = false; - - if (!string.IsNullOrEmpty(data)) - { - wReq.AllowWriteStreamBuffering = true; - using (Stream sReq = wReq.GetRequestStream()) - { - sReq.Write(Encoding.UTF8.GetBytes(data), 0, data.Length); - sReq.Flush(); - } - } - - HttpWebResponse wResp = wReq.GetResponse() as HttpWebResponse; - - if (wResp != null) - { - result.Code = (int)wResp.StatusCode; - result.RefCode = (int)wResp.StatusCode; - - getHeaders(ref result, wResp); - - if (binaryMode) - { - int len = (int)wResp.ContentLength; - result.Data = new byte[len]; - int bytesLeft = len; - int bytesRead = 0; - - using (BinaryReader br = new BinaryReader(wResp.GetResponseStream())) - { - while (bytesLeft > 0) - { - bytesRead = br.Read(result.Data, len - bytesLeft, bytesLeft); - bytesLeft -= bytesRead; - } - } - } - else - { - using (StreamReader sr = new StreamReader(wResp.GetResponseStream())) - { - result.Text = sr.ReadToEnd(); - } - } - - wResp.Close(); - } - } - catch (WebException wex) - { - HttpWebResponse xResp = wex.Response as HttpWebResponse; - if (xResp != null) - { - result.Code = (int)xResp.StatusCode; - result.RefCode = (int)xResp.StatusCode; - - getHeaders(ref result, xResp); - - using (StreamReader sr = new StreamReader(xResp.GetResponseStream())) - { - result.Text = sr.ReadToEnd(); - } - - xResp.Close(); - } - } - catch (Exception ex) - { - StringBuilder sb = new StringBuilder(); - sb.AppendFormat("[{0}] [{1}] [HTTP-POST-FORM] Error: ", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.ffff"),userAgent); - Exception e = ex; - while (e != null) - { - sb.Append(e.Message + " "); - e = e.InnerException; - } - sb.AppendLine(); - - result.RefCode = (int)HttpCode.USER_UNDEF; - result.RefText += sb.ToString(); - } - finally - { - if (wReq != null) - { - wReq.Abort(); - } - } - - return result; - } - - /// - /// HTTP-POST方法(包含表单数据) - /// - /// 请求目标URL - /// 表单数据 - /// 令牌(凭证)[可选->设置为null] - /// 是否以二进制模式读取响应内容(默认:否,即表示以文本方式读取) - /// HTTP-POST的响应结果 - public HttpResult PostForm(string url, byte[] data, string token, bool binaryMode = false) - { - HttpResult result = new HttpResult(); - - HttpWebRequest wReq = null; - - try - { - wReq = WebRequest.Create(url) as HttpWebRequest; - wReq.Method = "POST"; - if (!string.IsNullOrEmpty(token)) - { - wReq.Headers.Add("Authorization", token); - } - wReq.ContentType = ContentType.WWW_FORM_URLENC; - wReq.UserAgent = userAgent; - wReq.AllowAutoRedirect = allowAutoRedirect; - wReq.ServicePoint.Expect100Continue = false; - - if (data != null) - { - wReq.AllowWriteStreamBuffering = true; - using (Stream sReq = wReq.GetRequestStream()) - { - sReq.Write(data, 0, data.Length); - sReq.Flush(); - } - } - - HttpWebResponse wResp = wReq.GetResponse() as HttpWebResponse; - - if (wResp != null) - { - result.Code = (int)wResp.StatusCode; - result.RefCode = (int)wResp.StatusCode; - - getHeaders(ref result, wResp); - - if (binaryMode) - { - int len = (int)wResp.ContentLength; - result.Data = new byte[len]; - int bytesLeft = len; - int bytesRead = 0; - - using (BinaryReader br = new BinaryReader(wResp.GetResponseStream())) - { - while (bytesLeft > 0) - { - bytesRead = br.Read(result.Data, len - bytesLeft, bytesLeft); - bytesLeft -= bytesRead; - } - } - } - else - { - using (StreamReader sr = new StreamReader(wResp.GetResponseStream())) - { - result.Text = sr.ReadToEnd(); - } - } - - wResp.Close(); - } - } - catch (WebException wex) - { - HttpWebResponse xResp = wex.Response as HttpWebResponse; - if (xResp != null) - { - result.Code = (int)xResp.StatusCode; - result.RefCode = (int)xResp.StatusCode; - - getHeaders(ref result, xResp); - - using (StreamReader sr = new StreamReader(xResp.GetResponseStream())) - { - result.Text = sr.ReadToEnd(); - } - - xResp.Close(); - } - } - catch (Exception ex) - { - StringBuilder sb = new StringBuilder(); - sb.AppendFormat("[{0}] [{1}] [HTTP-POST-FORM] Error: ", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.ffff"),userAgent); - Exception e = ex; - while (e != null) - { - sb.Append(e.Message + " "); - e = e.InnerException; - } - sb.AppendLine(); - - result.RefCode = (int)HttpCode.USER_UNDEF; - result.RefText += sb.ToString(); - } - finally - { - if (wReq != null) - { - wReq.Abort(); - } - } - - return result; - } - - /// - /// HTTP-POST方法(包含多分部数据,multipart/form-data) - /// - /// 请求目标URL - /// 主体数据 - /// 分界标志 - /// 令牌(凭证)[可选->设置为null] - /// 是否以二进制模式读取响应内容(默认:否,即表示以文本方式读取) - /// HTTP-POST的响应结果 - public HttpResult PostMultipart(string url, byte[] data, string boundary, string token, bool binaryMode = false) - { - HttpResult result = new HttpResult(); - - HttpWebRequest wReq = null; - - try - { - wReq = WebRequest.Create(url) as HttpWebRequest; - wReq.Method = "POST"; - if (!string.IsNullOrEmpty(token)) - { - wReq.Headers.Add("Authorization", token); - } - wReq.ContentType = string.Format("{0}; boundary={1}", ContentType.MULTIPART_FORM_DATA, boundary); - wReq.UserAgent = userAgent; - wReq.AllowAutoRedirect = allowAutoRedirect; - wReq.ServicePoint.Expect100Continue = false; - - wReq.AllowWriteStreamBuffering = true; - using (Stream sReq = wReq.GetRequestStream()) - { - sReq.Write(data, 0, data.Length); - sReq.Flush(); - } - - HttpWebResponse wResp = wReq.GetResponse() as HttpWebResponse; - - if (wResp != null) - { - result.Code = (int)wResp.StatusCode; - result.RefCode = (int)wResp.StatusCode; - - getHeaders(ref result, wResp); - - if (binaryMode) - { - int len = (int)wResp.ContentLength; - result.Data = new byte[len]; - int bytesLeft = len; - int bytesRead = 0; - - using (BinaryReader br = new BinaryReader(wResp.GetResponseStream())) - { - while (bytesLeft > 0) - { - bytesRead = br.Read(result.Data, len - bytesLeft, bytesLeft); - bytesLeft -= bytesRead; - } - } - } - else - { - using (StreamReader sr = new StreamReader(wResp.GetResponseStream())) - { - result.Text = sr.ReadToEnd(); - } - } - - wResp.Close(); - } - } - catch (WebException wex) - { - HttpWebResponse xResp = wex.Response as HttpWebResponse; - if (xResp != null) - { - result.Code = (int)xResp.StatusCode; - result.RefCode = (int)xResp.StatusCode; - - getHeaders(ref result, xResp); - - using (StreamReader sr = new StreamReader(xResp.GetResponseStream())) - { - result.Text = sr.ReadToEnd(); - } - - xResp.Close(); - } - } - catch (Exception ex) - { - StringBuilder sb = new StringBuilder(); - sb.AppendFormat("[{0}] [{1}] [HTTP-POST-MPART] Error: ", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.ffff"), userAgent); - Exception e = ex; - while (e != null) - { - sb.Append(e.Message + " "); - e = e.InnerException; - } - sb.AppendLine(); - - result.RefCode = (int)HttpCode.USER_UNDEF; - result.RefText += sb.ToString(); - } - finally - { - if (wReq != null) - { - wReq.Abort(); - } - } - - return result; - } - - /// - /// HTTP-PUT方法(包含body数据, headers) - /// - /// 请求目标URL - /// 主体数据(字节数据) - /// 上传设置的headers - /// 令牌(凭证)[可选->设置为null] - /// 是否以二进制模式读取响应内容(默认:否,即表示以文本方式读取) - /// HTTP-PUT的响应结果 - public HttpResult PutDataWithHeaders(string url, byte[] data, Dictionary headers, bool binaryMode = false) - { - HttpResult result = new HttpResult(); - - HttpWebRequest wReq = null; - - try - { - wReq = WebRequest.Create(url) as HttpWebRequest; - wReq.Method = "PUT"; - wReq.ContentType = ContentType.APPLICATION_OCTET_STREAM; - wReq.UserAgent = userAgent; - wReq.AllowAutoRedirect = allowAutoRedirect; - wReq.ServicePoint.Expect100Continue = false; - - foreach(KeyValuePair header in headers) - { - if (!string.IsNullOrEmpty(header.Value)) - { - wReq.Headers.Add(header.Key, header.Value); - } - } - - if (data != null) - { - wReq.AllowWriteStreamBuffering = true; - using (Stream sReq = wReq.GetRequestStream()) - { - sReq.Write(data, 0, data.Length); - sReq.Flush(); - } - } - - HttpWebResponse wResp = wReq.GetResponse() as HttpWebResponse; - - if (wResp != null) - { - result.Code = (int)wResp.StatusCode; - result.RefCode = (int)wResp.StatusCode; - - getHeaders(ref result, wResp); - - if (binaryMode) - { - int len = (int)wResp.ContentLength; - result.Data = new byte[len]; - int bytesLeft = len; - int bytesRead = 0; - - using (BinaryReader br = new BinaryReader(wResp.GetResponseStream())) - { - while (bytesLeft > 0) - { - bytesRead = br.Read(result.Data, len - bytesLeft, bytesLeft); - bytesLeft -= bytesRead; - } - } - } - else - { - using (StreamReader sr = new StreamReader(wResp.GetResponseStream())) - { - result.Text = sr.ReadToEnd(); - } - } - - wResp.Close(); - } - } - catch (WebException wex) - { - HttpWebResponse xResp = wex.Response as HttpWebResponse; - if (xResp != null) - { - result.Code = (int)xResp.StatusCode; - result.RefCode = (int)xResp.StatusCode; - - getHeaders(ref result, xResp); - - using (StreamReader sr = new StreamReader(xResp.GetResponseStream())) - { - result.Text = sr.ReadToEnd(); - } - - xResp.Close(); - } - } - catch (Exception ex) - { - StringBuilder sb = new StringBuilder(); - sb.AppendFormat("[{0}] [{1}] [HTTP-PUT-BIN] Error: ", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.ffff"),userAgent); - Exception e = ex; - while (e != null) - { - sb.Append(e.Message + " "); - e = e.InnerException; - } - sb.AppendLine(); - - result.RefCode = (int)HttpCode.USER_UNDEF; - result.RefText += sb.ToString(); - } - finally - { - if (wReq != null) - { - wReq.Abort(); - } - } - - return result; - } - - /// - /// 获取返回信息头 - /// - /// 即将被HTTP请求封装函数返回的HttpResult变量 - /// 正在被读取的HTTP响应 - private void getHeaders(ref HttpResult hr, HttpWebResponse resp) - { - if (resp != null) - { - if (hr.RefInfo == null) - { - hr.RefInfo = new Dictionary(); - } - - hr.RefInfo.Add("ProtocolVersion", resp.ProtocolVersion.ToString()); - - if (!string.IsNullOrEmpty(resp.CharacterSet)) - { - hr.RefInfo.Add("Characterset", resp.CharacterSet); - } - - if (!string.IsNullOrEmpty(resp.ContentEncoding)) - { - hr.RefInfo.Add("ContentEncoding", resp.ContentEncoding); - } - - if (!string.IsNullOrEmpty(resp.ContentType)) - { - hr.RefInfo.Add("ContentType", resp.ContentType); - } - - hr.RefInfo.Add("ContentLength", resp.ContentLength.ToString()); - - var headers = resp.Headers; - if (headers != null && headers.Count > 0) - { - if (hr.RefInfo == null) - { - hr.RefInfo = new Dictionary(); - } - foreach (var key in headers.AllKeys) - { - hr.RefInfo.Add(key, headers[key]); - } - } - } - } - - } -} \ No newline at end of file diff --git a/src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/Http/HttpResult.cs b/src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/Http/HttpResult.cs deleted file mode 100644 index 1c93db5..0000000 --- a/src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/Http/HttpResult.cs +++ /dev/null @@ -1,144 +0,0 @@ -using System.Collections.Generic; -using System.Text; - -namespace Qiniu.Http -{ - /// - /// HTTP请求(GET,POST等)的返回消息 - /// - public class HttpResult - { - /// - /// 状态码 (200表示OK) - /// - public int Code { get; set; } - - /// - /// 消息或错误文本 - /// - public string Text { get; set; } - - /// - /// 消息或错误(二进制格式) - /// - public byte[] Data { get; set; } - - /// - /// 参考代码(用户自定义) - /// - public int RefCode { get; set; } - - /// - /// 附加信息(用户自定义,如Exception内容) - /// - public string RefText { get; set; } - - /// - /// 参考信息(从返回消息WebResponse的头部获取) - /// - public Dictionary RefInfo { get; set; } - - /// - /// 初始化(所有成员默认值,需要后续赋值) - /// - public HttpResult() - { - Code = (int)HttpCode.USER_UNDEF; - Text = null; - Data = null; - - RefCode = (int)HttpCode.USER_UNDEF; - RefInfo = null; - } - - /// - /// 对象复制 - /// - /// 要复制其内容的来源 - public void Shadow(HttpResult hr) - { - this.Code = hr.Code; - this.Text = hr.Text; - this.Data = hr.Data; - this.RefCode = hr.RefCode; - this.RefText += hr.RefText; - this.RefInfo = hr.RefInfo; - } - - /// - /// 转换为易读或便于打印的字符串格式 - /// - /// 便于打印和阅读的字符串 - public override string ToString() - { - StringBuilder sb = new StringBuilder(); - - sb.AppendFormat("code:{0}", Code); - sb.AppendLine(); - - if (!string.IsNullOrEmpty(Text)) - { - sb.AppendLine("text:"); - sb.AppendLine(Text); - } - - if (Data != null) - { - sb.AppendLine("data:"); - int n = 1024; - if (Data.Length <= n) - { - sb.AppendLine(Encoding.UTF8.GetString(Data)); - } - else - { - - sb.AppendLine(Encoding.UTF8.GetString(Data, 0, n)); - sb.AppendFormat("<--- TOO-LARGE-TO-DISPLAY --- TOTAL {0} BYTES --->", Data.Length); - sb.AppendLine(); - } - } - - sb.AppendLine(); - - sb.AppendFormat("ref-code:{0}", RefCode); - sb.AppendLine(); - - if(!string.IsNullOrEmpty(RefText)) - { - sb.AppendLine("ref-text:"); - sb.AppendLine(RefText); - } - - if (RefInfo != null) - { - sb.AppendLine("ref-info:"); - foreach (var d in RefInfo) - { - sb.AppendLine(string.Format("{0}:{1}", d.Key, d.Value)); - } - } - - sb.AppendLine(); - - return sb.ToString(); - } - - /// - /// 非法上传凭证错误 - /// - public static HttpResult InvalidToken = new HttpResult { - Code=(int)HttpCode.INVALID_TOKEN, - Text="invalid uptoken" - }; - - /// - /// 非法文件错误 - /// - public static HttpResult InvalidFile = new HttpResult - { - Code = (int)HttpCode.INVALID_FILE, - Text = "invalid file" - }; - } -} diff --git a/src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/Http/UrlHelper.cs b/src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/Http/UrlHelper.cs deleted file mode 100644 index 90f2b95..0000000 --- a/src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/Http/UrlHelper.cs +++ /dev/null @@ -1,87 +0,0 @@ -using System.Text.RegularExpressions; - -namespace Qiniu.Http -{ - /// - /// URL辅助工具(RegExp) - /// - public class UrlHelper - { - private static Regex regx = new Regex(@"(http|https):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?^=%&:/~\+#]*[\w\-\@?^=%&/~\+#])?"); - - private static Regex regu = new Regex(@"(http|https):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\.,/~\+#]*)?"); - - private static Regex regd = new Regex(@"(http|https):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\.,/~\+#]*)?/"); - - /// - /// 是否合法URL - /// - /// 待判断的url - /// - public static bool isValidUrl(string _url) - { - return regx.IsMatch(_url); - } - - /// - /// 是否一般URL(不包含?等后缀参数) - /// - /// 待判断的url - /// - public static bool isNormalUrl(string _url) - { - return regu.IsMatch(_url); - } - - /// - /// 是否合法URL目录 - /// - /// 待判断的url目录 - /// - public static bool isValidDir(string _dir) - { - return regd.IsMatch(_dir); - } - - /// - /// 从原始URL转换为一般URL(根据需要截断) - /// - /// 待转换的url - /// - public static string getNormalUrl(string _url) - { - var m = regu.Match(_url); - return m.Value; - } - - /// - /// URL分析,拆分出Host,Path,File,Query各个部分 - /// - /// 原始URL - /// host部分 - /// path部分 - /// 文件名 - /// 参数 - public static void urlSplit(string url, out string host, out string path, out string file, out string query) - { - int start = 0; - - Regex regHost = new Regex(@"(http|https):\/\/[\w\-_]+(\.[\w\-_]+)+"); - host = regHost.Match(url, start).Value; - start += host.Length; - - Regex regPath = new Regex(@"(/(\w|\-)*)+/"); - path = regPath.Match(url, start).Value; - if (string.IsNullOrEmpty(path)) - { - path = "/"; - } - start += path.Length; - - int index = url.IndexOf('?', start); - file = url.Substring(start, index - start); - - query = url.Substring(index); - } - } -} diff --git a/src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/QiniuCSharpSDK.cs b/src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/QiniuCSharpSDK.cs deleted file mode 100644 index 5d5e4e6..0000000 --- a/src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/QiniuCSharpSDK.cs +++ /dev/null @@ -1,42 +0,0 @@ -/// -/// Qiniu (Cloud) C# SDK for .NET Framework 2.0+/Core/UWP -/// Modules in this SDK: -/// "Storage" 存储相关功能,上传,下载,数据处理,资源管理 -/// "CDN", Fusion CDN, 融合CDN加速; -/// "Util", Utilities such as MD5 hashing, 实用工具(如MD5哈希计算等); -/// "Http", HTTP Request Manager, HTTP请求管理器 -/// -public class QiniuCSharpSDK -{ - /// - /// SDK名称 - /// - public const string ALIAS = "QiniuCSharpSDK"; - - /// - /// 目标框架 - /// -#if Net20 - public const string RTFX = "NET20"; -#elif Net35 - public const string RTFX = "NET35"; -#elif Net40 - public const string RTFX = "NET40"; -#elif Net45 - public const string RTFX = "NET45"; -#elif Net46 - public const string RTFX = "NET46"; -#elif NetCore - public const string RTFX = "NETCore"; -#elif WINDOWS_UWP - public const string RTFX = "UWP"; -#else - public const string RTFX = "UNKNOWN"; -#endif - - /// - /// SDK版本号 - /// - public const string VERSION = "7.3.0"; - -} diff --git a/src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/Storage/BatchInfo.cs b/src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/Storage/BatchInfo.cs deleted file mode 100644 index 001c67e..0000000 --- a/src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/Storage/BatchInfo.cs +++ /dev/null @@ -1,63 +0,0 @@ -using Newtonsoft.Json; -namespace Qiniu.Storage -{ - /// - /// 批量处理返回的信息 - /// - public class BatchInfo - { - /// - /// 状态码 - /// - [JsonProperty("code",NullValueHandling=NullValueHandling.Ignore)] - public int Code { get; set; } - - /// - /// 消息 - /// - [JsonProperty("data",NullValueHandling=NullValueHandling.Ignore)] - public BatchData Data { get; set; } - } - - /// - /// 批量处理的结果内容 - /// - public class BatchData - { - /// - /// 处理遇到的错误信息 - /// - [JsonProperty("error", NullValueHandling = NullValueHandling.Ignore)] - public string Error { get; set; } - - /// - /// 文件hash(ETAG) - /// - [JsonProperty("hash", NullValueHandling = NullValueHandling.Ignore)] - public string Hash { get; set; } - - /// - /// 文件大小(字节) - /// - [JsonProperty("fsize", NullValueHandling = NullValueHandling.Ignore)] - public long Fsize { get; set; } - - /// - /// 文件MIME类型 - /// - [JsonProperty("mimeType", NullValueHandling = NullValueHandling.Ignore)] - public string MimeType { get; set; } - - /// - /// 上传时间 - /// - [JsonProperty("putTime", NullValueHandling = NullValueHandling.Ignore)] - public long PutTime { get; set; } - - /// - /// 文件存储类型 - /// - [JsonProperty("type", NullValueHandling = NullValueHandling.Ignore)] - public int FileType { get; set; } - } -} diff --git a/src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/Storage/BatchResult.cs b/src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/Storage/BatchResult.cs deleted file mode 100644 index 678b9b4..0000000 --- a/src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/Storage/BatchResult.cs +++ /dev/null @@ -1,106 +0,0 @@ -using System.Text; -using System.Collections.Generic; -using Newtonsoft.Json; -using Qiniu.Http; - -namespace Qiniu.Storage -{ - /// - /// 批量处理结果 - /// - public class BatchResult : HttpResult - { - /// - /// 错误消息 - /// - public string Error - { - get - { - string ex = null; - if (Code != (int)HttpCode.OK && Code != (int)HttpCode.PARTLY_OK) - { - - Dictionary ret = JsonConvert.DeserializeObject>(Text); - if (ret.ContainsKey("error")) - { - ex = ret["error"]; - } - } - return ex; - } - } - - /// - /// 获取批量处理结果 - /// - public List Result - { - get - { - List info = null; - if ((Code == (int)HttpCode.OK || Code == (int)HttpCode.PARTLY_OK) && - (!string.IsNullOrEmpty(Text))) - { - info = JsonConvert.DeserializeObject>(Text); - } - return info; - } - } - - /// - /// 转换为易读字符串格式 - /// - /// 便于打印和阅读的字符串> - public override string ToString() - { - StringBuilder sb = new StringBuilder(); - - sb.AppendFormat("code: {0}\n", Code); - - if (Result != null) - { - sb.AppendLine("result:"); - int i = 0, n = Result.Count; - foreach (var v in Result) - { - sb.AppendFormat("#{0}/{1}\n", ++i, n); - sb.AppendFormat("code: {0}\n", v.Code); - sb.AppendFormat("data:\n{0}\n\n", v.Data); - } - } - else - { - if (!string.IsNullOrEmpty(Error)) - { - sb.AppendFormat("Error: {0}\n", Error); - } - else if (!string.IsNullOrEmpty(Text)) - { - sb.AppendLine("text:"); - sb.AppendLine(Text); - } - } - sb.AppendLine(); - - sb.AppendFormat("ref-code: {0}\n", RefCode); - - if (!string.IsNullOrEmpty(RefText)) - { - sb.AppendLine("ref-text:"); - sb.AppendLine(RefText); - } - - if (RefInfo != null) - { - sb.AppendFormat("ref-info:\n"); - foreach (var d in RefInfo) - { - sb.AppendLine(string.Format("{0}: {1}", d.Key, d.Value)); - } - } - - return sb.ToString(); - } - } -} diff --git a/src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/Storage/BucketInfo.cs b/src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/Storage/BucketInfo.cs deleted file mode 100644 index 63c2265..0000000 --- a/src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/Storage/BucketInfo.cs +++ /dev/null @@ -1,53 +0,0 @@ -namespace Qiniu.Storage -{ - /// - /// bucket info - /// - public class BucketInfo - { - /// - /// bucket name - /// - public string tbl { get; set; } - - /// - /// itbl - /// - public long itbl { get; set; } - - /// - /// deprecated - /// - public string phy {get;set;} - - /// - /// id - /// - public long uid { get; set; } - - /// - /// zone - /// - public string zone { get; set; } - - /// - /// region - /// - public string region { get; set; } - - /// - /// isGlobal - /// - public bool global { get; set; } - - /// - /// isLineStorage - /// - public bool line { get; set; } - - /// - /// creationTime - /// - public long ctime { get; set; } - } -} diff --git a/src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/Storage/BucketManager.cs b/src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/Storage/BucketManager.cs deleted file mode 100644 index 9565ee7..0000000 --- a/src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/Storage/BucketManager.cs +++ /dev/null @@ -1,802 +0,0 @@ -using System; -using System.Text; -using Qiniu.Http; -using Qiniu.Util; -using System.Collections.Generic; -namespace Qiniu.Storage -{ - /// - /// 空间(资源)管理/操作 - /// - public class BucketManager - { - private Mac mac; - private Auth auth; - private HttpManager httpManager; - private Config config; - - /// - /// - /// - /// - /// - public BucketManager(Mac mac, Config config) - { - this.mac = mac; - this.auth = new Auth(mac); - this.httpManager = new HttpManager(); - this.config = config; - } - - - /// - /// 获取空间文件信息 - /// - /// 空间名称 - /// 文件key - /// 文件信息获取结果 - public StatResult Stat(string bucket, string key) - { - StatResult result = new StatResult(); - - try - { - string statUrl = string.Format("{0}{1}", this.config.RsHost(this.mac.AccessKey, bucket), - StatOp(bucket, key)); - string token = auth.CreateManageToken(statUrl); - - HttpResult hr = httpManager.Get(statUrl, token); - result.Shadow(hr); - } - catch (QiniuException ex) - { - StringBuilder sb = new StringBuilder(); - sb.AppendFormat("[{0}] [stat] Error: ", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.ffff")); - Exception e = ex; - while (e != null) - { - sb.Append(e.Message + " "); - e = e.InnerException; - } - sb.AppendLine(); - - result.Code = ex.HttpResult.Code; - result.RefCode = ex.HttpResult.Code; - result.Text = ex.HttpResult.Text; - result.RefText += sb.ToString(); - } - - return result; - } - - /// - /// 获取空间(bucket)列表 - /// - /// 是否列出被授权访问的空间 - /// 空间列表获取结果 - public BucketsResult Buckets(bool shared) - { - BucketsResult result = new BucketsResult(); - - try - { - string scheme = this.config.UseHttps ? "https://" : "http://"; - string rsHost = string.Format("{0}{1}", scheme, Config.DefaultRsHost); - string sharedStr = "false"; - if (shared) - { - sharedStr = "true"; - } - string bucketsUrl = string.Format("{0}/buckets?shared={1}", rsHost, sharedStr); - string token = auth.CreateManageToken(bucketsUrl); - - HttpResult hr = httpManager.Get(bucketsUrl, token); - result.Shadow(hr); - } - catch (QiniuException ex) - { - StringBuilder sb = new StringBuilder(); - sb.AppendFormat("[{0}] [buckets] Error: ", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.ffff")); - Exception e = ex; - while (e != null) - { - sb.Append(e.Message + " "); - e = e.InnerException; - } - sb.AppendLine(); - - result.Code = ex.HttpResult.Code; - result.RefCode = ex.HttpResult.Code; - result.Text = ex.HttpResult.Text; - result.RefText += sb.ToString(); - } - - return result; - } - - - /// - /// 删除文件 - /// - /// 空间名称 - /// 文件key - /// 状态码为200时表示OK - public HttpResult Delete(string bucket, string key) - { - HttpResult result = new HttpResult(); - - try - { - string deleteUrl = string.Format("{0}{1}", this.config.RsHost(this.mac.AccessKey, bucket), - DeleteOp(bucket, key)); - string token = auth.CreateManageToken(deleteUrl); - - result = httpManager.Post(deleteUrl, token); - } - catch (QiniuException ex) - { - StringBuilder sb = new StringBuilder(); - sb.AppendFormat("[{0}] [delete] Error: ", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.ffff")); - Exception e = ex; - while (e != null) - { - sb.Append(e.Message + " "); - e = e.InnerException; - } - sb.AppendLine(); - - result.Code = ex.HttpResult.Code; - result.RefCode = ex.HttpResult.Code; - result.Text = ex.HttpResult.Text; - result.RefText += sb.ToString(); - } - - return result; - } - - /// - /// 复制文件 - /// - /// 源空间 - /// 源文件key - /// 目标空间 - /// 目标key - /// 状态码为200时表示OK - public HttpResult Copy(string srcBucket, string srcKey, string dstBucket, string dstKey) - { - return Copy(srcBucket, srcKey, dstBucket, dstKey, false); - } - - /// - /// 复制文件 (with 'force' param) - /// - /// 源空间 - /// 源文件key - /// 目标空间 - /// 目标key - /// force标志,true/false - /// 状态码为200时表示OK - public HttpResult Copy(string srcBucket, string srcKey, string dstBucket, string dstKey, bool force) - { - HttpResult result = new HttpResult(); - - try - { - string copyUrl = string.Format("{0}{1}", this.config.RsHost(this.mac.AccessKey, srcBucket), - CopyOp(srcBucket, srcKey, dstBucket, dstKey, force)); - string token = auth.CreateManageToken(copyUrl); - - result = httpManager.Post(copyUrl, token); - } - catch (QiniuException ex) - { - StringBuilder sb = new StringBuilder(); - sb.AppendFormat("[{0}] [copy] Error: ", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.ffff")); - Exception e = ex; - while (e != null) - { - sb.Append(e.Message + " "); - e = e.InnerException; - } - sb.AppendLine(); - - result.Code = ex.HttpResult.Code; - result.RefCode = ex.HttpResult.Code; - result.Text = ex.HttpResult.Text; - result.RefText += sb.ToString(); - } - - return result; - } - - /// - /// 移动文件 - /// - /// 源空间 - /// 源文件key - /// 目标空间 - /// 目标key - /// 状态码为200时表示OK - public HttpResult Move(string srcBucket, string srcKey, string dstBucket, string dstKey) - { - return Move(srcBucket, srcKey, dstBucket, dstKey, false); - } - - /// - /// 移动文件 (with 'force' param) - /// - /// 源空间 - /// 源文件key - /// 目标空间 - /// 目标key - /// force标志,true/false - /// 状态码为200时表示OK - public HttpResult Move(string srcBucket, string srcKey, string dstBucket, string dstKey, bool force) - { - HttpResult result = new HttpResult(); - - try - { - string moveUrl = string.Format("{0}{1}", this.config.RsHost(this.mac.AccessKey, srcBucket), - MoveOp(srcBucket, srcKey, dstBucket, dstKey, force)); - string token = auth.CreateManageToken(moveUrl); - - result = httpManager.Post(moveUrl, token); - } - catch (QiniuException ex) - { - StringBuilder sb = new StringBuilder(); - sb.AppendFormat("[{0}] [move] Error: ", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.ffff")); - Exception e = ex; - while (e != null) - { - sb.Append(e.Message + " "); - e = e.InnerException; - } - sb.AppendLine(); - - result.Code = ex.HttpResult.Code; - result.RefCode = ex.HttpResult.Code; - result.Text = ex.HttpResult.Text; - result.RefText += sb.ToString(); - } - - return result; - } - - /// - /// 修改文件MimeType - /// - /// 空间名称 - /// 文件key - /// 修改后的MIME Type - /// 状态码为200时表示OK - public HttpResult ChangeMime(string bucket, string key, string mimeType) - { - HttpResult result = new HttpResult(); - - try - { - string chgmUrl = string.Format("{0}{1}", this.config.RsHost(this.mac.AccessKey, bucket), - ChangeMimeOp(bucket, key, mimeType)); - string token = auth.CreateManageToken(chgmUrl); - result = httpManager.Post(chgmUrl, token); - } - catch (QiniuException ex) - { - StringBuilder sb = new StringBuilder(); - sb.AppendFormat("[{0}] [chgm] Error: ", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.ffff")); - Exception e = ex; - while (e != null) - { - sb.Append(e.Message + " "); - e = e.InnerException; - } - sb.AppendLine(); - - result.Code = ex.HttpResult.Code; - result.RefCode = ex.HttpResult.Code; - result.Text = ex.HttpResult.Text; - result.RefText += sb.ToString(); - } - - return result; - } - - /// - /// 修改文件存储类型 - /// - /// 空间名称 - /// 文件key - /// 修改后的文件存储类型,0表示普通存储,1表示低频存储 - /// 状态码为200时表示OK - public HttpResult ChangeType(string bucket, string key, int fileType) - { - HttpResult result = new HttpResult(); - - try - { - string chtypeUrl = string.Format("{0}{1}", this.config.RsHost(this.mac.AccessKey, bucket), - ChangeTypeOp(bucket, key, fileType)); - string token = auth.CreateManageToken(chtypeUrl); - result = httpManager.Post(chtypeUrl, token); - } - catch (QiniuException ex) - { - StringBuilder sb = new StringBuilder(); - sb.AppendFormat("[{0}] [chtype] Error: ", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.ffff")); - Exception e = ex; - while (e != null) - { - sb.Append(e.Message + " "); - e = e.InnerException; - } - sb.AppendLine(); - - result.Code = ex.HttpResult.Code; - result.RefCode = ex.HttpResult.Code; - result.Text = ex.HttpResult.Text; - result.RefText += sb.ToString(); - } - - return result; - } - - /// - /// 批处理 - /// - /// 批量操作的操作字符串 - /// 状态码为200时表示OK - private BatchResult Batch(string batchOps) - { - BatchResult result = new BatchResult(); - - try - { - string scheme = this.config.UseHttps ? "https://" : "http://"; - string rsHost = string.Format("{0}{1}", scheme, Config.DefaultRsHost); - string batchUrl = rsHost + "/batch"; - byte[] data = Encoding.UTF8.GetBytes(batchOps); - string token = auth.CreateManageToken(batchUrl, data); - - HttpResult hr = httpManager.PostForm(batchUrl, data, token); - result.Shadow(hr); - } - catch (QiniuException ex) - { - StringBuilder sb = new StringBuilder(); - sb.AppendFormat("[{0}] [batch] Error: ", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.ffff")); - Exception e = ex; - while (e != null) - { - sb.Append(e.Message + " "); - e = e.InnerException; - } - sb.AppendLine(); - - result.Code = ex.HttpResult.Code; - result.RefCode = ex.HttpResult.Code; - result.Text = ex.HttpResult.Text; - result.RefText += sb.ToString(); - } - - return result; - } - - /// - /// 批处理,字符串数组拼接后与另一形式等价 - /// - /// 批量操作的操作字符串数组 - /// 状态码为200时表示OK - public BatchResult Batch(IList ops) - { - StringBuilder opsb = new StringBuilder(); - opsb.AppendFormat("op={0}", ops[0]); - for (int i = 1; i < ops.Count; ++i) - { - opsb.AppendFormat("&op={0}", ops[i]); - } - - return Batch(opsb.ToString()); - } - - /// - /// 抓取文件 - /// - /// 资源URL - /// 空间名称 - /// 文件key - /// 状态码为200时表示OK - public FetchResult Fetch(string resUrl, string bucket, string key) - { - FetchResult result = new FetchResult(); - - try - { - string fetchUrl = string.Format("{0}{1}", this.config.IovipHost(this.mac.AccessKey, bucket), - FetchOp(resUrl, bucket, key)); - string token = auth.CreateManageToken(fetchUrl); - - HttpResult httpResult = httpManager.Post(fetchUrl, token); - result.Shadow(httpResult); - } - catch (QiniuException ex) - { - StringBuilder sb = new StringBuilder(); - sb.AppendFormat("[{0}] [fetch] Error: ", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.ffff")); - Exception e = ex; - while (e != null) - { - sb.Append(e.Message + " "); - e = e.InnerException; - } - sb.AppendLine(); - - result.Code = ex.HttpResult.Code; - result.RefCode = ex.HttpResult.Code; - result.Text = ex.HttpResult.Text; - result.RefText += sb.ToString(); - } - - return result; - } - - /// - /// 更新文件,适用于"镜像源站"设置的空间 - /// - /// 空间名称 - /// 文件key - /// 状态码为200时表示OK - public HttpResult Prefetch(string bucket, string key) - { - HttpResult result = new HttpResult(); - - try - { - string prefetchUrl = this.config.IovipHost(this.mac.AccessKey, bucket) + PrefetchOp(bucket, key); - string token = auth.CreateManageToken(prefetchUrl); - - result = httpManager.Post(prefetchUrl, token); - } - catch (QiniuException ex) - { - StringBuilder sb = new StringBuilder(); - sb.AppendFormat("[{0}] [prefetch] Error: ", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.ffff")); - Exception e = ex; - while (e != null) - { - sb.Append(e.Message + " "); - e = e.InnerException; - } - sb.AppendLine(); - - result.Code = ex.HttpResult.Code; - result.RefCode = ex.HttpResult.Code; - result.Text = ex.HttpResult.Text; - result.RefText += sb.ToString(); - } - - return result; - } - - /// - /// 获取空间的域名 - /// - /// 空间名称 - /// 空间对应的域名 - public DomainsResult Domains(string bucket) - { - DomainsResult result = new DomainsResult(); - - try - { - string scheme = this.config.UseHttps ? "https://" : "http://"; - string rsHost = string.Format("{0}{1}", scheme, Config.DefaultApiHost); - string domainsUrl = string.Format("{0}{1}", rsHost, "/v6/domain/list"); - string body = string.Format("tbl={0}", bucket); - byte[] data = Encoding.UTF8.GetBytes(body); - string token = auth.CreateManageToken(domainsUrl, data); - - HttpResult hr = httpManager.PostForm(domainsUrl, data, token); - result.Shadow(hr); - } - catch (QiniuException ex) - { - StringBuilder sb = new StringBuilder(); - sb.AppendFormat("[{0}] [domains] Error: ", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.ffff")); - Exception e = ex; - while (e != null) - { - sb.Append(e.Message + " "); - e = e.InnerException; - } - sb.AppendLine(); - - result.Code = ex.HttpResult.Code; - result.RefCode = ex.HttpResult.Code; - result.Text = ex.HttpResult.Text; - result.RefText += sb.ToString(); - } - - return result; - } - - /// - /// - /// 获取空间文件列表 - /// listFiles(bucket, prefix, marker, limit, delimiter) - /// - /// bucket: 目标空间名称 - /// - /// prefix: 返回指定文件名前缀的文件列表(prefix可设为null) - /// - /// marker: 考虑到设置limit后返回的文件列表可能不全(需要重复执行listFiles操作) - /// 执行listFiles操作时使用marker标记来追加新的结果 - /// 特别注意首次执行listFiles操作时marker为null - /// - /// limit: 每次返回结果所包含的文件总数限制(limit最大值1000,建议值100) - /// - /// delimiter: 分隔符,比如-或者/等等,可以模拟作为目录结构(参考下述示例) - /// 假设指定空间中有2个文件 fakepath/1.txt fakepath/2.txt - /// 现设置分隔符delimiter = / 得到返回结果items =[],commonPrefixes = [fakepath/] - /// 然后调整prefix = fakepath/ delimiter = null 得到所需结果items = [1.txt,2.txt] - /// 于是可以在本地先创建一个目录fakepath,然后在该目录下写入items中的文件 - /// - /// - /// 空间名称 - /// 前缀 - /// 标记 - /// 数量限制 - /// 分隔符 - /// 文件列表获取结果 - public ListResult ListFiles(string bucket, string prefix, string marker, int limit, string delimiter) - { - ListResult result = new ListResult(); - - try - { - StringBuilder sb = new StringBuilder("/list?bucket=" + bucket); - - if (!string.IsNullOrEmpty(marker)) - { - sb.Append("&marker=" + marker); - } - - if (!string.IsNullOrEmpty(prefix)) - { - sb.Append("&prefix=" + prefix); - } - - if (!string.IsNullOrEmpty(delimiter)) - { - sb.Append("&delimiter=" + delimiter); - } - - if (limit > 1000 || limit < 1) - { - sb.Append("&limit=1000"); - } - else - { - sb.Append("&limit=" + limit); - } - - string listUrl = string.Format("{0}{1}", this.config.RsfHost(this.mac.AccessKey, bucket), sb.ToString()); - string token = auth.CreateManageToken(listUrl); - - HttpResult hr = httpManager.Post(listUrl, token); - result.Shadow(hr); - } - catch (QiniuException ex) - { - StringBuilder sb = new StringBuilder(); - sb.AppendFormat("[{0}] [listFiles] Error: ", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.ffff")); - Exception e = ex; - while (e != null) - { - sb.Append(e.Message + " "); - e = e.InnerException; - } - sb.AppendLine(); - - result.Code = ex.HttpResult.Code; - result.RefCode = ex.HttpResult.Code; - result.Text = ex.HttpResult.Text; - result.RefText += sb.ToString(); - } - - return result; - } - - /// - /// 更新文件生命周期 - /// - /// 空间名称 - /// 文件key - /// 多少天后删除 - /// 状态码为200时表示OK - public HttpResult DeleteAfterDays(string bucket, string key, int deleteAfterDays) - { - HttpResult result = new HttpResult(); - - try - { - string updateUrl = string.Format("{0}{1}", this.config.RsHost(this.mac.AccessKey, bucket), - DeleteAfterDaysOp(bucket, key, deleteAfterDays)); - string token = auth.CreateManageToken(updateUrl); - result = httpManager.Post(updateUrl, token); - } - catch (QiniuException ex) - { - StringBuilder sb = new StringBuilder(); - sb.AppendFormat("[{0}] [deleteAfterDays] Error: ", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.ffff")); - Exception e = ex; - while (e != null) - { - sb.Append(e.Message + " "); - e = e.InnerException; - } - sb.AppendLine(); - - result.Code = ex.HttpResult.Code; - result.RefCode = ex.HttpResult.Code; - result.Text = ex.HttpResult.Text; - result.RefText += sb.ToString(); - } - - return result; - } - - /// - /// 生成stat操作字符串 - /// - /// 空间名称 - /// 文件key - /// stat操作字符串 - public string StatOp(string bucket, string key) - { - return string.Format("/stat/{0}", Base64.UrlSafeBase64Encode(bucket, key)); - } - - /// - /// 生成delete操作字符串 - /// - /// 空间名称 - /// 文件key - /// delete操作字符串 - public string DeleteOp(string bucket, string key) - { - return string.Format("/delete/{0}", Base64.UrlSafeBase64Encode(bucket, key)); - } - - /// - /// 生成copy操作字符串 - /// - /// 源空间 - /// 源文件key - /// 目标空间 - /// 目标文件key - /// copy操作字符串 - public string CopyOp(string srcBucket, string srcKey, string dstBucket, string dstKey) - { - return CopyOp(srcBucket, srcKey, dstBucket, dstKey, false); - } - - /// - /// 生成copy(with 'force' param)操作字符串 - /// - /// 源空间 - /// 源文件key - /// 目标空间 - /// 目标文件key - /// force标志,true/false - /// copy操作字符串 - public string CopyOp(string srcBucket, string srcKey, string dstBucket, string dstKey, bool force) - { - string fx = force ? "force/true" : "force/false"; - return string.Format("/copy/{0}/{1}/{2}", Base64.UrlSafeBase64Encode(srcBucket, srcKey), - Base64.UrlSafeBase64Encode(dstBucket, dstKey), fx); - } - - /// - /// 生成move操作字符串 - /// - /// 源空间 - /// 源文件key - /// 目标空间 - /// 目标文件key - /// move操作字符串 - public string MoveOp(string srcBucket, string srcKey, string dstBucket, string dstKey) - { - return MoveOp(srcBucket, srcKey, dstBucket, dstKey, false); - } - - /// - /// 生成copy(with 'force' param)操作字符串 - /// - /// 源空间 - /// 源文件key - /// 目标空间 - /// 目标文件key - /// force标志,true/false - /// move操作字符串 - public string MoveOp(string srcBucket, string srcKey, string dstBucket, string dstKey, bool force) - { - string fx = force ? "force/true" : "force/false"; - return string.Format("/move/{0}/{1}/{2}", Base64.UrlSafeBase64Encode(srcBucket, srcKey), - Base64.UrlSafeBase64Encode(dstBucket, dstKey), fx); - } - - /// - /// 生成chgm操作字符串 - /// - /// 空间名称 - /// 文件key - /// 修改后MIME Type - /// chgm操作字符串 - public string ChangeMimeOp(string bucket, string key, string mimeType) - { - return string.Format("/chgm/{0}/mime/{1}", Base64.UrlSafeBase64Encode(bucket, key), - Base64.UrlSafeBase64Encode(mimeType)); - } - - /// - /// 生成chtype操作字符串 - /// - /// 空间名称 - /// 文件key - /// 修改后文件类型 - /// chtype操作字符串 - public string ChangeTypeOp(string bucket, string key, int fileType) - { - return string.Format("/chtype/{0}/type/{1}", Base64.UrlSafeBase64Encode(bucket, key), - fileType); - } - - /// - /// 生成fetch操作字符串 - /// - /// 资源URL - /// 空间名称 - /// 文件key - /// fetch操作字符串 - public string FetchOp(string url, string bucket, string key) - { - string entry = null; - if (key == null) - { - entry = Base64.UrlSafeBase64Encode(bucket); - } - else - { - entry = Base64.UrlSafeBase64Encode(bucket, key); - } - return string.Format("/fetch/{0}/to/{1}", Base64.UrlSafeBase64Encode(url), entry); - } - - /// - /// 生成prefetch操作字符串 - /// - /// 空间名称 - /// 文件key - /// prefetch操作字符串 - public string PrefetchOp(string bucket, string key) - { - return string.Format("/prefetch/{0}", Base64.UrlSafeBase64Encode(bucket, key)); - } - - /// - /// 生成updateLifecycle操作字符串 - /// - /// 空间名称 - /// 文件key - /// 多少天后删除(设为0表示取消) - /// updateLifecycle操作字符串 - public string DeleteAfterDaysOp(string bucket, string key, int deleteAfterDays) - { - return string.Format("/deleteAfterDays/{0}/{1}", - Base64.UrlSafeBase64Encode(bucket, key), deleteAfterDays); - } - - } -} diff --git a/src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/Storage/BucketResult.cs b/src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/Storage/BucketResult.cs deleted file mode 100644 index 0fb4aaf..0000000 --- a/src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/Storage/BucketResult.cs +++ /dev/null @@ -1,79 +0,0 @@ -using System.Text; -using Newtonsoft.Json; -using Qiniu.Http; - -namespace Qiniu.Storage -{ - /// - /// 获取bucket信息-结果 - /// - public class BucketResult : HttpResult - { - /// - /// bucket信息 - /// - public BucketInfo Result - { - get - { - BucketInfo info = null; - - if (Code == (int)HttpCode.OK && !string.IsNullOrEmpty(Text)) - { - info= JsonConvert.DeserializeObject(Text); - } - - return info; - } - } - - /// - /// 转换为易读字符串格式 - /// - /// 便于打印和阅读的字符串 - public override string ToString() - { - StringBuilder sb = new StringBuilder(); - - sb.AppendFormat("code: {0}\n", Code); - - if (Result != null) - { - sb.AppendLine("bucket-info:"); - sb.AppendFormat("tbl={0}\n", Result.tbl); - sb.AppendFormat("zone={0}\n", Result.zone); - sb.AppendFormat("region={0}\n", Result.region); - sb.AppendFormat("isGlobal={0}\n", Result.global); - sb.AppendFormat("isLine={0}\n", Result.line); - } - else - { - if (!string.IsNullOrEmpty(Text)) - { - sb.AppendLine("text:"); - sb.AppendLine(Text); - } - } - sb.AppendLine(); - - sb.AppendFormat("ref-code: {0}\n", RefCode); - - if (!string.IsNullOrEmpty(RefText)) - { - sb.AppendLine("ref-text:"); - sb.AppendLine(RefText); - } - - if (RefInfo != null) - { - sb.AppendFormat("ref-info:\n"); - foreach (var d in RefInfo) - { - sb.AppendLine(string.Format("{0}: {1}", d.Key, d.Value)); - } - } - - return sb.ToString(); - } - } -} diff --git a/src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/Storage/BucketsResult.cs b/src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/Storage/BucketsResult.cs deleted file mode 100644 index 61a61ef..0000000 --- a/src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/Storage/BucketsResult.cs +++ /dev/null @@ -1,77 +0,0 @@ -using System.Text; -using System.Collections.Generic; -using Newtonsoft.Json; -using Qiniu.Http; - -namespace Qiniu.Storage -{ - /// - /// 获取空间列表-结果 - /// - public class BucketsResult:HttpResult - { - /// - /// 空间列表 - /// - public List Result - { - get - { - List buckets = null; - if ((Code == (int)HttpCode.OK) && (!string.IsNullOrEmpty(Text))) - { - buckets = JsonConvert.DeserializeObject>(Text); - } - return buckets; - } - } - - /// - /// 转换为易读字符串格式 - /// - /// 便于打印和阅读的字符串 - public override string ToString() - { - StringBuilder sb = new StringBuilder(); - - sb.AppendFormat("code: {0}\n", Code); - - if (Result != null) - { - sb.AppendLine("bucket(s):"); - foreach(var b in Result) - { - sb.AppendLine(b); - } - } - else - { - if (!string.IsNullOrEmpty(Text)) - { - sb.AppendLine("text:"); - sb.AppendLine(Text); - } - } - sb.AppendLine(); - - sb.AppendFormat("ref-code: {0}\n", RefCode); - - if (!string.IsNullOrEmpty(RefText)) - { - sb.AppendLine("ref-text:"); - sb.AppendLine(RefText); - } - - if (RefInfo != null) - { - sb.AppendFormat("ref-info:\n"); - foreach (var d in RefInfo) - { - sb.AppendLine(string.Format("{0}: {1}", d.Key, d.Value)); - } - } - - return sb.ToString(); - } - } -} diff --git a/src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/Storage/ChunkUnit.cs b/src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/Storage/ChunkUnit.cs deleted file mode 100644 index b586b7f..0000000 --- a/src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/Storage/ChunkUnit.cs +++ /dev/null @@ -1,102 +0,0 @@ -namespace Qiniu.Storage -{ - /// - /// 分片大小 - /// - public enum ChunkUnit - { - /// - /// 128KB - /// - U128K = 1, - - /// - /// 256KB - /// - U256K = 2, - - /// - /// 512KB - /// - U512K = 4, - - /// - /// 1MB - /// - U1024K = 8, - - /// - /// 2MB - /// - U2048K = 16, - - /// - /// 4MB - /// - U4096K = 32 - }; - - /// - /// ChunkSize转换 - /// - public class ResumeChunk - { - private static int N = 128 * 1024; - - /// - /// 计算ChunkSize - /// - /// - /// - public static int GetChunkSize(ChunkUnit cu) - { - int c = (int)cu; - return c * N; - } - - /// - /// 计算ChunkUnit - /// - /// - /// - public static ChunkUnit GetChunkUnit(int chunkSize) - { - if (chunkSize < 128 * 1024 || chunkSize > 4 * 1024 * 1024) - { - return ChunkUnit.U2048K; - } - else - { - int u = chunkSize / N; - int cu; - - if (u == 1) - { - cu = 1; - } - else if (u < 4) - { - cu = 2; - } - else if (u < 8) - { - cu = 4; - } - else if (u < 16) - { - cu = 8; - } - else if (u < 32) - { - cu = 16; - } - else - { - cu = 32; - } - - return (ChunkUnit)cu; - } - } - } -} diff --git a/src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/Storage/Config.cs b/src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/Storage/Config.cs deleted file mode 100644 index 839ec5f..0000000 --- a/src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/Storage/Config.cs +++ /dev/null @@ -1,136 +0,0 @@ - -namespace Qiniu.Storage -{ - /// - /// 配置信息,主要包括Zone配置(另请参阅Zone模块) - /// 目前已支持的机房包括: - /// 华东(CN_East), 华北(CN_North), 华南(CN_South), 北美(US_North), 新加坡(AS_Singapore) - /// 默认设置为华东机房(CN_East) - /// - public class Config - { - /// - /// 默认高级资源管理域名 - /// - public static string DefaultRsHost = "rs.qiniu.com"; - /// - /// 默认数据处理域名 - /// - public static string DefaultApiHost = "api.qiniu.com"; - /// - /// 空间所在的区域(Zone) - /// - public Zone Zone = null; - /// - /// 是否采用https域名 - /// - public bool UseHttps = false; - /// - /// 是否采用CDN加速域名,对上传有效 - /// - public bool UseCdnDomains = false; - /// - /// 分片上传时,片的大小,默认为4MB,以提高上传效率 - /// - public ChunkUnit ChunkSize = ChunkUnit.U4096K; - /// - /// 分片上传的阈值,超过该大小采用分片上传的方式 - /// - public int PutThreshold =ResumeChunk.GetChunkSize(ChunkUnit.U1024K) * 10; - /// - /// 重试请求次数 - /// - public int MaxRetryTimes = 3; - - /// - /// 获取资源管理域名 - /// - /// - /// - /// - public string RsHost(string ak, string bucket) - { - string scheme = UseHttps ? "https://" : "http://"; - Zone z = this.Zone; - if (z == null) - { - z = ZoneHelper.QueryZone(ak, bucket); - } - return string.Format("{0}{1}", scheme, z.RsHost); - } - - /// - /// 获取资源列表域名 - /// - /// - /// - /// - public string RsfHost(string ak, string bucket) - { - string scheme = UseHttps ? "https://" : "http://"; - Zone z = this.Zone; - if (z == null) - { - z = ZoneHelper.QueryZone(ak, bucket); - } - return string.Format("{0}{1}", scheme, z.RsfHost); - } - - /// - /// 获取数据处理域名 - /// - /// - /// - /// - public string ApiHost(string ak, string bucket) - { - string scheme = UseHttps ? "https://" : "http://"; - Zone z = this.Zone; - if (z == null) - { - z = ZoneHelper.QueryZone(ak, bucket); - } - return string.Format("{0}{1}", scheme, z.ApiHost); - } - - /// - /// 获取资源抓取更新域名 - /// - /// - /// - /// - public string IovipHost(string ak, string bucket) - { - string scheme = UseHttps ? "https://" : "http://"; - Zone z = this.Zone; - if (z == null) - { - z = ZoneHelper.QueryZone(ak, bucket); - } - return string.Format("{0}{1}", scheme, z.IovipHost); - } - - /// - /// 获取文件上传域名 - /// - /// - /// - /// - public string UpHost(string ak, string bucket) - { - string scheme = UseHttps ? "https://" : "http://"; - Zone z = this.Zone; - if (z == null) - { - z = ZoneHelper.QueryZone(ak, bucket); - } - string upHost = z.SrcUpHosts[0]; - if (this.UseCdnDomains) - { - upHost = z.CdnUpHosts[0]; - } - - return string.Format("{0}{1}", scheme, upHost); - } - } -} diff --git a/src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/Storage/DomainsResult.cs b/src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/Storage/DomainsResult.cs deleted file mode 100644 index 1ccb721..0000000 --- a/src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/Storage/DomainsResult.cs +++ /dev/null @@ -1,79 +0,0 @@ -using System.Text; -using System.Collections.Generic; -using Newtonsoft.Json; -using Qiniu.Http; - -namespace Qiniu.Storage -{ - /// - /// 获取空间域名(domains操作)的返回消息 - /// - public class DomainsResult:HttpResult - { - /// - /// 域名(列表) - /// - public List Result - { - get - { - List domains = null; - if ((Code == (int)HttpCode.OK) && (!string.IsNullOrEmpty(Text))) - { - domains=JsonConvert.DeserializeObject>(Text); - } - return domains; - } - } - - /// - /// 转换为易读字符串格式 - /// - /// 便于打印和阅读的字符串 - public override string ToString() - { - StringBuilder sb = new StringBuilder(); - - sb.AppendFormat("code: {0}\n", Code); - - sb.AppendLine(); - - if (Result != null) - { - sb.AppendLine("domain(s):"); - foreach (var d in Result) - { - sb.AppendLine(d); - } - } - else - { - if (!string.IsNullOrEmpty(Text)) - { - sb.AppendLine("text:"); - sb.AppendLine(Text); - } - } - sb.AppendLine(); - - sb.AppendFormat("ref-code: {0}\n", RefCode); - - if (!string.IsNullOrEmpty(RefText)) - { - sb.AppendLine("ref-text:"); - sb.AppendLine(RefText); - } - - if (RefInfo != null) - { - sb.AppendFormat("ref-info:\n"); - foreach (var d in RefInfo) - { - sb.AppendLine(string.Format("{0}: {1}", d.Key, d.Value)); - } - } - - return sb.ToString(); - } - } -} diff --git a/src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/Storage/DownloadManager.cs b/src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/Storage/DownloadManager.cs deleted file mode 100644 index d036aba..0000000 --- a/src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/Storage/DownloadManager.cs +++ /dev/null @@ -1,105 +0,0 @@ -using System; -using System.IO; -using System.Text; -using Qiniu.Util; -using Qiniu.Http; - -namespace Qiniu.Storage -{ - /// - /// 空间文件下载,只提供简单下载逻辑 - /// 对于大文件下载、断点续下载等需求,可以根据实际情况自行实现 - /// - public class DownloadManager - { - /// - /// 生成授权的下载链接(访问私有空间中的文件时需要使用这种链接) - /// - /// 账号(密钥) - /// (私有)空间文件的下载域名 - /// (私有)空间文件名 - /// 从生成此链接的时刻算起,该链接有效时间(单位:秒) - /// 已授权的下载链接 - public static string CreatePrivateUrl(Mac mac, string domain, string fileName, int expireInSeconds = 3600) - { - long deadline = UnixTimestamp.GetUnixTimestamp(expireInSeconds); - string publicUrl = CreatePublishUrl(domain, fileName); - StringBuilder sb = new StringBuilder(publicUrl); - if (publicUrl.Contains("?")) - { - sb.AppendFormat("&e={0}", deadline); - } - else - { - sb.AppendFormat("?e={0}", deadline); - } - - string token = Auth.CreateDownloadToken(mac, sb.ToString()); - sb.AppendFormat("&token={0}", token); - - return sb.ToString(); - } - - /// - /// 生成公开空间的下载链接 - /// - /// 公开空间的文件下载域名 - /// 公开空间文件名 - /// 公开空间文件下载链接 - public static string CreatePublishUrl(string domain, string fileName) - { - return string.Format("{0}/{1}", domain, Uri.EscapeUriString(fileName)); - } - - /// - /// 下载文件到本地 - /// - /// (可访问的或者已授权的)链接 - /// (另存为)本地文件名 - /// 下载资源的结果 - public static HttpResult Download(string url, string saveasFile) - { - HttpResult result = new HttpResult(); - - try - { - HttpManager httpManager = new HttpManager(); - - result = httpManager.Get(url, null, true); - if (result.Code == (int)HttpCode.OK) - { - using (FileStream fs = File.Create(saveasFile, result.Data.Length)) - { - fs.Write(result.Data, 0, result.Data.Length); - fs.Flush(); - } - result.RefText += string.Format("[{0}] [Download] Success: (Remote file) ==> \"{1}\"\n", - DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.ffff"), saveasFile); - } - else - { - result.RefText += string.Format("[{0}] [Download] Error: code = {1}\n", - DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.ffff"), result.Code); - } - } - catch (Exception ex) - { - StringBuilder sb = new StringBuilder(); - sb.AppendFormat("[{0}] [Download] Error: ", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.ffff")); - Exception e = ex; - while (e != null) - { - sb.Append(e.Message + " "); - e = e.InnerException; - } - sb.AppendLine(); - - result.RefCode = (int)HttpCode.USER_UNDEF; - result.RefText += sb.ToString(); - } - - return result; - } - - } -} diff --git a/src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/Storage/FetchInfo.cs b/src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/Storage/FetchInfo.cs deleted file mode 100644 index 2467365..0000000 --- a/src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/Storage/FetchInfo.cs +++ /dev/null @@ -1,33 +0,0 @@ -using Newtonsoft.Json; -namespace Qiniu.Storage -{ - /// - /// 资源抓取返回的内容 - /// - public class FetchInfo - { - /// - /// 文件名 - /// - [JsonProperty("key")] - public string Key { set; get; } - - /// - /// 文件大小(字节) - /// - [JsonProperty("fsize")] - public long Fsize { set; get; } - - /// - /// 文件hash(ETAG) - /// - [JsonProperty("hash")] - public string Hash { set; get; } - - /// - /// 文件MIME类型 - /// - [JsonProperty("mimeType")] - public string MimeType { set; get; } - } -} diff --git a/src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/Storage/FetchResult.cs b/src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/Storage/FetchResult.cs deleted file mode 100644 index f7d0dc6..0000000 --- a/src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/Storage/FetchResult.cs +++ /dev/null @@ -1,72 +0,0 @@ -using Qiniu.Http; -using Newtonsoft.Json; -using System.Text; -namespace Qiniu.Storage -{ - /// - /// 文件抓取返回的消息 - /// - public class FetchResult : HttpResult - { - /// - /// Fetch信息列表 - /// - public FetchInfo Result - { - get - { - FetchInfo info = null; - if ((Code == (int)HttpCode.OK) && (!string.IsNullOrEmpty(Text))) - { - info = JsonConvert.DeserializeObject(Text); - } - return info; - } - } - - /// - /// 转换为易读字符串格式 - /// - /// 便于打印和阅读的字符串 - public override string ToString() - { - StringBuilder sb = new StringBuilder(); - - sb.AppendFormat("code: {0}\n", Code); - - if (Result != null) - { - sb.AppendFormat("Key={0}, Size={1}, Type={2}, Hash={3}\n", - Result.Key, Result.Fsize, Result.MimeType, Result.Hash); - } - else - { - if (!string.IsNullOrEmpty(Text)) - { - sb.AppendLine("text:"); - sb.AppendLine(Text); - } - } - sb.AppendLine(); - - sb.AppendFormat("ref-code: {0}\n", RefCode); - - if (!string.IsNullOrEmpty(RefText)) - { - sb.AppendLine("ref-text:"); - sb.AppendLine(RefText); - } - - if (RefInfo != null) - { - sb.AppendFormat("ref-info:\n"); - foreach (var d in RefInfo) - { - sb.AppendLine(string.Format("{0}: {1}", d.Key, d.Value)); - } - } - - return sb.ToString(); - } - } -} diff --git a/src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/Storage/FileInfo.cs b/src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/Storage/FileInfo.cs deleted file mode 100644 index 3ab21ee..0000000 --- a/src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/Storage/FileInfo.cs +++ /dev/null @@ -1,40 +0,0 @@ -using Newtonsoft.Json; -namespace Qiniu.Storage -{ - /// - /// 获取空间文件信息(stat操作)的有效内容 - /// - public class FileInfo - { - /// - /// 文件大小(字节) - /// - [JsonProperty("fsize")] - public long Fsize { set; get; } - - /// - /// 文件hash(ETAG) - /// - [JsonProperty("hash")] - public string Hash { set; get; } - - /// - /// 文件MIME类型 - /// - [JsonProperty("mimeType")] - public string MimeType { set; get; } - - /// - /// 文件上传时间 - /// - [JsonProperty("putTime")] - public long PutTime { set; get; } - - /// - /// 文件存储类型 - /// - [JsonProperty("type")] - public int FileType { get; set; } - - } -} diff --git a/src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/Storage/FormUploader.cs b/src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/Storage/FormUploader.cs deleted file mode 100644 index abe6560..0000000 --- a/src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/Storage/FormUploader.cs +++ /dev/null @@ -1,270 +0,0 @@ -using System; -using System.IO; -using System.Text; -using Qiniu.Http; -using Qiniu.Util; - -namespace Qiniu.Storage -{ - /// - /// 简单上传,适合于以下"情形1": - /// (1)网络较好并且待上传的文件体积较小时(比如100MB或更小一点)使用简单上传; - /// (2)文件较大或者网络状况不理想时请使用分片上传; - /// (3)文件较大并且需要支持断点续上传,请使用分片上传(断点续上传) - /// 上传时需要提供正确的上传凭证(由对应的上传策略生成) - /// 上传策略 http://developer.qiniu.com/article/developer/security/upload-token.html - /// 上传凭证 http://developer.qiniu.com/article/developer/security/put-policy.html - /// - public class FormUploader - { - private Config config; - private HttpManager httpManager; - - /// - /// 初始化 - /// - /// 表单上传的配置信息 - public FormUploader(Config config) - { - this.config = config; - this.httpManager = new HttpManager(); - } - - /// - /// 上传文件 - 可附加自定义参数 - /// - /// 待上传的本地文件 - /// 要保存的目标文件名称 - /// 上传凭证 - /// 上传可选设置 - /// 上传文件后的返回结果 - public HttpResult UploadFile(string localFile, string key, string token, PutExtra extra) - { - try - { - FileStream fs = new FileStream(localFile, FileMode.Open); - return this.UploadStream(fs, key, token, extra); - } - catch (Exception ex) - { - HttpResult ret = HttpResult.InvalidFile; - ret.RefText = ex.Message; - return ret; - } - } - - - /// - /// 上传数据 - /// - /// 待上传的数据 - /// 要保存的key - /// 上传凭证 - /// 上传可选设置 - /// 上传数据后的返回结果 - public HttpResult UploadData(byte[] data, string key, string token, PutExtra extra) - { - MemoryStream stream = new MemoryStream(data); - return this.UploadStream(stream, key, token, extra); - } - - /// - /// 上传数据流 - /// - /// (确定长度的)数据流 - /// 要保存的key - /// 上传凭证 - /// 上传可选设置 - /// 上传数据流后的返回结果 - public HttpResult UploadStream(Stream stream, string key, string token, PutExtra putExtra) - { - if (putExtra == null) - { - putExtra = new PutExtra(); - } - if (string.IsNullOrEmpty(putExtra.MimeType )) { - putExtra.MimeType = "application/octet-stream"; - } - if (putExtra.ProgressHandler == null) - { - putExtra.ProgressHandler = DefaultUploadProgressHandler; - } - if (putExtra.UploadController == null) - { - putExtra.UploadController = DefaultUploadController; - } - string fname = key; - if (string.IsNullOrEmpty(key)) - { - fname = "fname_temp"; - } - - HttpResult result = new HttpResult(); - - using (stream) - { - try - { - string boundary = HttpManager.CreateFormDataBoundary(); - StringBuilder bodyBuilder = new StringBuilder(); - bodyBuilder.AppendLine("--" + boundary); - - if (key != null) - { - //write key when it is not null - bodyBuilder.AppendLine("Content-Disposition: form-data; name=\"key\""); - bodyBuilder.AppendLine(); - bodyBuilder.AppendLine(key); - bodyBuilder.AppendLine("--" + boundary); - } - - //write token - bodyBuilder.AppendLine("Content-Disposition: form-data; name=\"token\""); - bodyBuilder.AppendLine(); - bodyBuilder.AppendLine(token); - bodyBuilder.AppendLine("--" + boundary); - - //write extra params - if (putExtra.Params != null && putExtra.Params.Count > 0) - { - foreach (var p in putExtra.Params) - { - if (p.Key.StartsWith("x:")) - { - bodyBuilder.AppendFormat("Content-Disposition: form-data; name=\"{0}\"", p.Key); - bodyBuilder.AppendLine(); - bodyBuilder.AppendLine(); - bodyBuilder.AppendLine(p.Value); - bodyBuilder.AppendLine("--" + boundary); - } - } - } - - //prepare data buffer - int bufferSize = 1024 * 1024; - byte[] buffer = new byte[bufferSize]; - int bytesRead = 0; - putExtra.ProgressHandler(0, stream.Length); - MemoryStream dataMS = new MemoryStream(); - while ((bytesRead = stream.Read(buffer, 0, bufferSize)) != 0) - { - dataMS.Write(buffer, 0, bytesRead); - } - - //write crc32 - uint crc32 = CRC32.CheckSumBytes(dataMS.ToArray()); - //write key when it is not null - bodyBuilder.AppendLine("Content-Disposition: form-data; name=\"crc32\""); - bodyBuilder.AppendLine(); - bodyBuilder.AppendLine(crc32.ToString()); - bodyBuilder.AppendLine("--" + boundary); - - //write fname - bodyBuilder.AppendFormat("Content-Disposition: form-data; name=\"file\"; filename=\"{0}\"", fname); - bodyBuilder.AppendLine(); - - //write mime type - bodyBuilder.AppendFormat("Content-Type: {0}", putExtra.MimeType); - bodyBuilder.AppendLine(); - bodyBuilder.AppendLine(); - - //write file data - StringBuilder bodyEnd = new StringBuilder(); - bodyEnd.AppendLine(); - bodyEnd.AppendLine("--" + boundary + "--"); - - byte[] partData1 = Encoding.UTF8.GetBytes(bodyBuilder.ToString()); - byte[] partData2 = dataMS.ToArray(); - byte[] partData3 = Encoding.UTF8.GetBytes(bodyEnd.ToString()); - - MemoryStream ms = new MemoryStream(); - ms.Write(partData1, 0, partData1.Length); - ms.Write(partData2, 0, partData2.Length); - ms.Write(partData3, 0, partData3.Length); - - //get upload host - string ak = UpToken.GetAccessKeyFromUpToken(token); - string bucket = UpToken.GetBucketFromUpToken(token); - if (ak == null || bucket == null) - { - return HttpResult.InvalidToken; - } - - string uploadHost = this.config.UpHost(ak, bucket); - putExtra.ProgressHandler(stream.Length / 5, stream.Length); - result = httpManager.PostMultipart(uploadHost, ms.ToArray(), boundary, null); - putExtra.ProgressHandler(stream.Length, stream.Length); - if (result.Code == (int)HttpCode.OK) - { - result.RefText += string.Format("[{0}] [FormUpload] Uploaded: #STREAM# ==> \"{1}\"\n", - DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.ffff"), key); - } - else - { - result.RefText += string.Format("[{0}] [FormUpload] Failed: code = {1}, text = {2}\n", - DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.ffff"), result.Code, result.Text); - } - - //close memory stream - ms.Close(); - dataMS.Close(); - } - catch (Exception ex) - { - StringBuilder sb = new StringBuilder(); - sb.AppendFormat("[{0}] [FormUpload] Error: ", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.ffff")); - Exception e = ex; - while (e != null) - { - sb.Append(e.Message + " "); - e = e.InnerException; - } - sb.AppendLine(); - - if (ex is QiniuException) - { - QiniuException qex = (QiniuException)ex; - result.Code = qex.HttpResult.Code; - result.RefCode = qex.HttpResult.Code; - result.Text = qex.HttpResult.Text; - result.RefText += sb.ToString(); - } - else - { - result.RefCode = (int)HttpCode.USER_UNDEF; - result.RefText += sb.ToString(); - } - } - } - - return result; - } - - /// - /// 默认的进度处理函数-上传文件 - /// - /// 已上传的字节数 - /// 文件总字节数 - public static void DefaultUploadProgressHandler(long uploadedBytes, long totalBytes) - { - if (uploadedBytes < totalBytes) - { - Console.WriteLine("[{0}] [FormUpload] Progress: {1,7:0.000}%", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.ffff"), 100.0 * uploadedBytes / totalBytes); - } - else - { - Console.WriteLine("[{0}] [FormUpload] Progress: {1,7:0.000}%\n", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.ffff"), 100.0); - } - } - - /// - /// 默认的上传控制函数,默认不执行任何控制 - /// - /// 控制状态 - public static UploadControllerAction DefaultUploadController() - { - return UploadControllerAction.Activated; - } - } - -} diff --git a/src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/Storage/ListInfo.cs b/src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/Storage/ListInfo.cs deleted file mode 100644 index b008b68..0000000 --- a/src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/Storage/ListInfo.cs +++ /dev/null @@ -1,50 +0,0 @@ -using System.Collections.Generic; -using Newtonsoft.Json; -namespace Qiniu.Storage -{ - /// - /// 获取空间文件(list操作) - /// - /// 返回JSON字符串 - /// - /// { - /// "marker":"MARKER", - /// "items": - /// [ - /// { - /// "key":"KEY", - /// "hash":"HASH", - /// "fsize":FSIZE, - /// "mimeType":"MIME_TYPE", - /// "putTime":PUT_TIME, - /// "type":FILE_TYPE - /// }, - /// { - /// ... - /// } - /// ], - /// "CmmonPrefixes":"COMMON_PREFIXES" - /// } - /// - /// - public class ListInfo - { - /// - /// marker标记 - /// - [JsonProperty("marker", NullValueHandling = NullValueHandling.Ignore)] - public string Marker { get; set; } - - /// - /// 文件列表 - /// - [JsonProperty("items", NullValueHandling = NullValueHandling.Ignore)] - public List Items { get; set; } - - /// - /// 公共前缀 - /// - [JsonProperty("commonPrefixes", NullValueHandling = NullValueHandling.Ignore)] - public List CommonPrefixes { get; set; } - } -} diff --git a/src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/Storage/ListItem.cs b/src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/Storage/ListItem.cs deleted file mode 100644 index 28e1346..0000000 --- a/src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/Storage/ListItem.cs +++ /dev/null @@ -1,52 +0,0 @@ -using Newtonsoft.Json; -namespace Qiniu.Storage -{ - /// - /// 文件描述(stat操作返回消息中包含的有效内容) - /// 与StatInfo一致 - /// - public class ListItem - { - /// - /// 文件名 - /// - [JsonProperty("key")] - public string Key { get; set; } - - /// - /// 文件hash(ETAG) - /// - [JsonProperty("hash")] - public string Hash { get; set; } - - /// - /// 文件大小(字节) - /// - [JsonProperty("fsize")] - public long Fsize { get; set; } - - /// - /// 文件MIME类型 - /// - [JsonProperty("mimeType")] - public string MimeType { get; set; } - - /// - /// 上传时间 - /// - [JsonProperty("putTime")] - public long PutTime { get; set; } - - /// - /// 文件存储类型 - /// - [JsonProperty("type")] - public int FileType { get; set; } - - /// - /// EndUser字段 - /// - [JsonProperty("endUser")] - public string EndUser { get; set; } - } -} diff --git a/src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/Storage/ListResult.cs b/src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/Storage/ListResult.cs deleted file mode 100644 index eb4f9aa..0000000 --- a/src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/Storage/ListResult.cs +++ /dev/null @@ -1,96 +0,0 @@ -using System.Text; -using Newtonsoft.Json; -using Qiniu.Http; - -namespace Qiniu.Storage -{ - /// - /// 获取空间文件列表(list操作)的返回消息 - /// - public class ListResult:HttpResult - { - /// - /// 文件列表信息 - /// - public ListInfo Result - { - get - { - ListInfo info = null; - if ((Code == (int)HttpCode.OK) && (!string.IsNullOrEmpty(Text))) - { - info= JsonConvert.DeserializeObject(Text); - } - return info; - } - } - - /// - /// 转换为易读字符串格式 - /// - /// 便于打印和阅读的字符串> - public override string ToString() - { - StringBuilder sb = new StringBuilder(); - - sb.AppendFormat("code: {0}\n", Code); - - if (Result != null) - { - if (Result.CommonPrefixes != null) - { - sb.Append("commonPrefixes:"); - foreach(var p in Result.CommonPrefixes) - { - sb.AppendFormat("{0} ", p); - } - sb.AppendLine(); - } - - if (!string.IsNullOrEmpty(Result.Marker)) - { - sb.AppendFormat("marker: {0}\n", Result.Marker); - } - - if (Result.Items != null) - { - sb.AppendLine("items:"); - int i = 0, n = Result.Items.Count; - foreach (var item in Result.Items) - { - sb.AppendFormat("#{0}/{1}:Key={2}, Size={3}, Mime={4}, Hash={5}, Time={6}, Type={7}\n", - ++i, n, item.Key, item.Fsize, item.MimeType, item.Hash, item.PutTime, item.FileType); - } - } - } - else - { - if (!string.IsNullOrEmpty(Text)) - { - sb.AppendLine("text:"); - sb.AppendLine(Text); - } - } - sb.AppendLine(); - - sb.AppendFormat("ref-code: {0}\n", RefCode); - - if (!string.IsNullOrEmpty(RefText)) - { - sb.AppendLine("ref-text:"); - sb.AppendLine(RefText); - } - - if (RefInfo != null) - { - sb.AppendFormat("ref-info:\n"); - foreach (var d in RefInfo) - { - sb.AppendLine(string.Format("{0}: {1}", d.Key, d.Value)); - } - } - - return sb.ToString(); - } - } -} diff --git a/src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/Storage/OperationManager.cs b/src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/Storage/OperationManager.cs deleted file mode 100644 index 8a3b8dd..0000000 --- a/src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/Storage/OperationManager.cs +++ /dev/null @@ -1,281 +0,0 @@ -using System; -using System.IO; -using System.Text; -using Qiniu.Util; -using Qiniu.Http; -using UrlHelper = Qiniu.Util.UrlHelper; - -namespace Qiniu.Storage -{ - /// - /// 数据处理 - /// - public class OperationManager - { - private Auth auth; - private Mac mac; - private Config config; - private HttpManager httpManager; - - /// - /// 构建新的数据处理对象 - /// - /// - /// - public OperationManager(Mac mac, Config config) - { - this.mac = mac; - this.auth = new Auth(mac); - this.config = config; - this.httpManager = new HttpManager(); - } - - - - /// - /// 数据处理 - /// - /// 空间 - /// 空间文件的key - /// 操作(命令参数) - /// 私有队列 - /// 通知url - /// forece参数 - /// pfop操作返回结果,正确返回结果包含persistentId - public PfopResult Pfop(string bucket, string key, string fops, string pipeline, string notifyUrl, bool force) - { - PfopResult result = new PfopResult(); - - try - { - string pfopUrl = string.Format("{0}/pfop/", this.config.ApiHost(this.mac.AccessKey, bucket)); - - StringBuilder sb = new StringBuilder(); - sb.AppendFormat("bucket={0}&key={1}&fops={2}", StringHelper.UrlEncode(bucket), StringHelper.UrlEncode(key), - StringHelper.UrlEncode(fops)); - if (!string.IsNullOrEmpty(notifyUrl)) - { - sb.AppendFormat("¬ifyURL={0}", StringHelper.UrlEncode(notifyUrl)); - } - if (force) - { - sb.Append("&force=1"); - } - if (!string.IsNullOrEmpty(pipeline)) - { - sb.AppendFormat("&pipeline={0}", pipeline); - } - byte[] data = Encoding.UTF8.GetBytes(sb.ToString()); - string token = auth.CreateManageToken(pfopUrl, data); - - HttpResult hr = httpManager.PostForm(pfopUrl, data, token); - result.Shadow(hr); - } - catch (QiniuException ex) - { - StringBuilder sb = new StringBuilder(); - sb.AppendFormat("[{0}] [pfop] Error: ", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.ffff")); - Exception e = ex; - while (e != null) - { - sb.Append(e.Message + " "); - e = e.InnerException; - } - sb.AppendLine(); - - result.Code = ex.HttpResult.Code; - result.RefCode = ex.HttpResult.Code; - result.Text = ex.HttpResult.Text; - result.RefText += sb.ToString(); - } - - return result; - } - - /// - /// 数据处理,操作字符串拼接后与另一种形式等价 - /// - /// 空间 - /// 空间文件的key - /// 操作(命令参数)列表 - /// 私有队列 - /// 通知url - /// forece参数 - /// 操作返回结果,正确返回结果包含persistentId - public PfopResult Pfop(string bucket, string key, string[] fops, string pipeline, string notifyUrl, bool force) - { - string ops = string.Join(";", fops); - return Pfop(bucket, key, ops, pipeline, notifyUrl, force); - } - - /// - /// 查询pfop操作处理结果(或状态) - /// - /// 持久化ID - /// 操作结果 - public PrefopResult Prefop(string persistentId) - { - PrefopResult result = new PrefopResult(); - - string scheme = this.config.UseHttps ? "https://" : "http://"; - string prefopUrl = string.Format("{0}{1}/status/get/prefop?id={2}", scheme, Config.DefaultApiHost, persistentId); - - HttpManager httpMgr = new HttpManager(); - HttpResult httpResult = httpMgr.Get(prefopUrl, null); - result.Shadow(httpResult); - - return result; - } - - /// - /// 根据uri的类型(网络url或者本地文件路径)自动选择dfop_url或者dfop_data - /// - /// 文件处理命令 - /// 资源/文件URI - /// 操作结果/返回数据 - public HttpResult Dfop(string fop, string uri) - { - if (UrlHelper.IsValidUrl(uri)) - { - return DfopUrl(fop, uri); - } - else - { - return DfopData(fop, uri); - } - } - - /// - /// 文本处理(直接传入文本内容) - /// - /// 文本处理命令 - /// 文本内容 - /// - public HttpResult DfopText(string fop, string text) - { - HttpResult result = new HttpResult(); - - string scheme = this.config.UseHttps ? "https://" : "http://"; - string dfopUrl = string.Format("{0}{1}/dfop?fop={2}", scheme, Config.DefaultApiHost, fop); - string token = auth.CreateManageToken(dfopUrl); - string boundary = HttpManager.CreateFormDataBoundary(); - string sep = "--" + boundary; - StringBuilder sb = new StringBuilder(); - sb.AppendLine(sep); - sb.AppendFormat("Content-Type: {0}", ContentType.TEXT_PLAIN); - sb.AppendLine(); - sb.AppendLine("Content-Disposition: form-data; name=data; filename=text"); - sb.AppendLine(); - sb.AppendLine(text); - sb.AppendLine(sep + "--"); - byte[] data = Encoding.UTF8.GetBytes(sb.ToString()); - - result = httpManager.PostMultipart(dfopUrl, data, boundary, token, true); - - - return result; - } - - /// - /// 文本处理(从文件读取文本) - /// - /// 文本处理命令 - /// 文本文件 - /// - public HttpResult DfopTextFile(string fop, string textFile) - { - HttpResult result = new HttpResult(); - - if (File.Exists(textFile)) - { - result = DfopText(fop, File.ReadAllText(textFile)); - } - else - { - result.RefCode = (int)HttpCode.INVALID_FILE; - result.RefText = "[dfop-error] File not found: " + textFile; - } - - return result; - } - - /// - /// 如果uri是网络url则使用此方法 - /// - /// 文件处理命令 - /// 资源URL - /// 处理结果 - public HttpResult DfopUrl(string fop, string url) - { - HttpResult result = new HttpResult(); - string scheme = this.config.UseHttps ? "https://" : "http://"; - string encodedUrl = StringHelper.UrlEncode(url); - string dfopUrl = string.Format("{0}{1}/dfop?fop={2}&url={3}", scheme, Config.DefaultApiHost, fop, encodedUrl); - string token = auth.CreateManageToken(dfopUrl); - - result = httpManager.Post(dfopUrl, token, true); - return result; - } - - /// - /// 如果uri是本地文件路径则使用此方法 - /// - /// 文件处理命令 - /// 文件名 - /// 处理结果 - public HttpResult DfopData(string fop, string localFile) - { - HttpResult result = new HttpResult(); - - try - { - string scheme = this.config.UseHttps ? "https://" : "http://"; - string dfopUrl = string.Format("{0}{1}/dfop?fop={2}", scheme, Config.DefaultApiHost, fop); - string token = auth.CreateManageToken(dfopUrl); - string boundary = HttpManager.CreateFormDataBoundary(); - string sep = "--" + boundary; - - StringBuilder sbp1 = new StringBuilder(); - sbp1.AppendLine(sep); - string filename = Path.GetFileName(localFile); - sbp1.AppendFormat("Content-Type: {0}", ContentType.APPLICATION_OCTET_STREAM); - sbp1.AppendLine(); - sbp1.AppendFormat("Content-Disposition: form-data; name=\"data\"; filename={0}", filename); - sbp1.AppendLine(); - sbp1.AppendLine(); - - StringBuilder sbp3 = new StringBuilder(); - sbp3.AppendLine(); - sbp3.AppendLine(sep + "--"); - - byte[] partData1 = Encoding.UTF8.GetBytes(sbp1.ToString()); - byte[] partData2 = File.ReadAllBytes(localFile); - byte[] partData3 = Encoding.UTF8.GetBytes(sbp3.ToString()); - - MemoryStream ms = new MemoryStream(); - ms.Write(partData1, 0, partData1.Length); - ms.Write(partData2, 0, partData2.Length); - ms.Write(partData3, 0, partData3.Length); - - result = httpManager.PostMultipart(dfopUrl, ms.ToArray(), boundary, token, true); - } - catch (Exception ex) - { - StringBuilder sb = new StringBuilder(); - sb.AppendFormat("[{0}] [dfop] Error: ", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.ffff")); - Exception e = ex; - while (e != null) - { - sb.Append(e.Message + " "); - e = e.InnerException; - } - sb.AppendLine(); - - result.RefCode = (int)HttpCode.USER_UNDEF; - result.RefText += sb.ToString(); - } - - return result; - } - } -} diff --git a/src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/Storage/PfopInfo.cs b/src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/Storage/PfopInfo.cs deleted file mode 100644 index f3a95e3..0000000 --- a/src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/Storage/PfopInfo.cs +++ /dev/null @@ -1,98 +0,0 @@ -using Newtonsoft.Json; - -namespace Qiniu.Storage -{ - /// - /// 持久化请求的回复 - /// - public class PfopInfo - { - /// - /// 任务ID - /// - [JsonProperty("id")] - public string Id; - /// - /// 任务结果状态码 - /// - [JsonProperty("code")] - public int Code; - /// - /// 任务结果状态描述 - /// - [JsonProperty("desc")] - public string Desc; - /// - /// 待处理的数据文件 - /// - [JsonProperty("inputKey")] - public string InputKey; - /// - /// 待处理文件所在空间 - /// - [JsonProperty("inputBucket")] - public string InputBucket; - /// - /// 数据处理队列 - /// - [JsonProperty("pipeline")] - public string Pipeline; - /// - /// 任务的Reqid - /// - [JsonProperty("reqid")] - public string Reqid; - /// - /// 数据处理的命令集合 - /// - [JsonProperty("items")] - public PfopItems[] Items; - } - - /// - /// 持久化处理命令 - /// - public class PfopItems - { - /// - /// 命令 - /// - [JsonProperty("cmd")] - public string Cmd; - /// - /// 命令执行结果状态码 - /// - [JsonProperty("code")] - public string Code; - /// - /// 命令执行结果描述 - /// - [JsonProperty("desc")] - public string Desc; - /// - /// 命令执行错误 - /// - [JsonProperty("Error", NullValueHandling = NullValueHandling.Ignore)] - public string Error; - /// - /// VSample命令的生成文件名列表 - /// - [JsonProperty("keys", NullValueHandling = NullValueHandling.Ignore)] - public string[] Keys; - /// - /// 命令生成的文件名 - /// - [JsonProperty("key", NullValueHandling = NullValueHandling.Ignore)] - public string Key; - /// - /// 命令生成的文件内容hash - /// - [JsonProperty("hash", NullValueHandling = NullValueHandling.Ignore)] - public string Hash; - /// - /// 该命令是否返回了上一次相同命令生成的结果 - /// - [JsonProperty("returnOld", NullValueHandling = NullValueHandling.Ignore)] - public int? ReturnOld; - } -} diff --git a/src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/Storage/PfopResult.cs b/src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/Storage/PfopResult.cs deleted file mode 100644 index 34d48eb..0000000 --- a/src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/Storage/PfopResult.cs +++ /dev/null @@ -1,78 +0,0 @@ -using System.Text; -using System.Collections.Generic; -using Newtonsoft.Json; -using Qiniu.Http; - -namespace Qiniu.Storage -{ - /// - /// 持久化 - /// - public class PfopResult : HttpResult - { - /// - /// 此ID可用于查询持久化进度 - /// - public string PersistentId - { - get - { - string pid = null; - - if ((Code == (int)HttpCode.OK) && (!string.IsNullOrEmpty(Text))) - { - Dictionary ret= JsonConvert.DeserializeObject>(Text); - if (ret.ContainsKey("persistentId")) - { - pid = ret["persistentId"]; - } - } - return pid; - } - } - - /// - /// 转换为易读字符串格式 - /// - /// 便于打印和阅读的字符串 - public override string ToString() - { - StringBuilder sb = new StringBuilder(); - - sb.AppendFormat("code: {0}\n", Code); - - if (!string.IsNullOrEmpty(PersistentId)) - { - sb.AppendFormat("PersistentId: {0}\n", PersistentId); - } - else - { - if (!string.IsNullOrEmpty(Text)) - { - sb.AppendLine("text:"); - sb.AppendLine(Text); - } - } - sb.AppendLine(); - - sb.AppendFormat("ref-code:{0}\n", RefCode); - - if (!string.IsNullOrEmpty(RefText)) - { - sb.AppendLine("ref-text:"); - sb.AppendLine(RefText); - } - - if (RefInfo != null) - { - sb.AppendFormat("ref-info:\n"); - foreach (var d in RefInfo) - { - sb.AppendLine(string.Format("{0}:{1}", d.Key, d.Value)); - } - } - - return sb.ToString(); - } - } -} diff --git a/src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/Storage/PrefopResult.cs b/src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/Storage/PrefopResult.cs deleted file mode 100644 index bd248bd..0000000 --- a/src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/Storage/PrefopResult.cs +++ /dev/null @@ -1,73 +0,0 @@ -using Newtonsoft.Json; -using Qiniu.Http; -using System.Text; -namespace Qiniu.Storage -{ - /// - /// 查询数据处理状态的返回值 - /// - public class PrefopResult:HttpResult - { - /// - /// 持久化任务的状态 - /// - public PfopInfo Result - { - get - { - PfopInfo info = null; - - if ((Code == (int)HttpCode.OK) && (!string.IsNullOrEmpty(Text))) - { - info= JsonConvert.DeserializeObject(Text); - } - return info; - } - } - - /// - /// 转换为易读字符串格式 - /// - /// 便于打印和阅读的字符串 - public override string ToString() - { - StringBuilder sb = new StringBuilder(); - - sb.AppendFormat("code: {0}\n", Code); - - if (this.Result!=null) - { - sb.AppendFormat("result: {0}\n", JsonConvert.SerializeObject(this.Result)); - } - else - { - if (!string.IsNullOrEmpty(Text)) - { - sb.AppendLine("text:"); - sb.AppendLine(Text); - } - } - sb.AppendLine(); - - sb.AppendFormat("ref-code:{0}\n", RefCode); - - if (!string.IsNullOrEmpty(RefText)) - { - sb.AppendLine("ref-text:"); - sb.AppendLine(RefText); - } - - if (RefInfo != null) - { - sb.AppendFormat("ref-info:\n"); - foreach (var d in RefInfo) - { - sb.AppendLine(string.Format("{0}:{1}", d.Key, d.Value)); - } - } - - return sb.ToString(); - } - } - -} diff --git a/src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/Storage/PutExtra.cs b/src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/Storage/PutExtra.cs deleted file mode 100644 index e4c1e97..0000000 --- a/src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/Storage/PutExtra.cs +++ /dev/null @@ -1,51 +0,0 @@ -using System.Collections.Generic; - -namespace Qiniu.Storage -{ - /// - /// 文件上传的额外可选设置 - /// - public class PutExtra - { - /// - /// 设置文件断点续传进度记录文件 - /// - public string ResumeRecordFile { set; get; } - /// - /// 上传可选参数字典,参数名次以 x: 开头 - /// - public Dictionary Params; - /// - /// 指定文件的MimeType - /// - public string MimeType { set; get; } - /// - /// 设置文件上传进度处理器 - /// - public UploadProgressHandler ProgressHandler { set; get; } - /// - /// 设置文件上传的状态控制器 - /// - public UploadController UploadController { set; get; } - - /// - /// 最大重试次数 - /// - public int MaxRetryTimes { set; get; } - - /// - /// 块并发上传的线程数量 - /// - public int BlockUploadThreads { set; get; } - - /// - /// 分片上传版本 目前支持v1/v2版本 默认v1 - /// - public string Version = "v1"; - - /// - /// 分片上传v2字段 默认大小为4MB 分片大小范围为1 MB - 1 GB - /// - public int PartSize = 4 * 1024 * 1024; -} -} \ No newline at end of file diff --git a/src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/Storage/PutPolicy.cs b/src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/Storage/PutPolicy.cs deleted file mode 100644 index 0c80616..0000000 --- a/src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/Storage/PutPolicy.cs +++ /dev/null @@ -1,167 +0,0 @@ -using Newtonsoft.Json; - -namespace Qiniu.Storage -{ - /// - /// 上传策略 - /// 参考文档:https://developer.qiniu.com/kodo/manual/1206/put-policy - /// - public class PutPolicy - { - /// - /// [必需]bucket或者bucket:key - /// - [JsonProperty("scope")] - public string Scope { get; set; } - - /// - /// [可选]若为 1,表示允许用户上传以 scope 的 keyPrefix 为前缀的文件。 - /// - [JsonProperty("isPrefixalScope", NullValueHandling = NullValueHandling.Ignore)] - public int? isPrefixalScope { get; set; } - - /// - /// [必需]上传策略失效时刻,请使用SetExpire来设置它 - /// - [JsonProperty("deadline")] - public int Deadline { get; private set; } - - /// - /// [可选]"仅新增"模式 - /// - [JsonProperty("insertOnly", NullValueHandling = NullValueHandling.Ignore)] - public int? InsertOnly { get; set; } - - /// - /// [可选]保存文件的key - /// - [JsonProperty("saveKey", NullValueHandling = NullValueHandling.Ignore)] - public string SaveKey { get; set; } - - /// - /// [可选]终端用户 - /// - [JsonProperty("endUser", NullValueHandling = NullValueHandling.Ignore)] - public string EndUser { get; set; } - - /// - /// [可选]返回URL - /// - [JsonProperty("returnUrl", NullValueHandling = NullValueHandling.Ignore)] - public string ReturnUrl { get; set; } - - /// - /// [可选]返回内容 - /// - [JsonProperty("returnBody", NullValueHandling = NullValueHandling.Ignore)] - public string ReturnBody { get; set; } - - /// - /// [可选]回调URL - /// - [JsonProperty("callbackUrl", NullValueHandling = NullValueHandling.Ignore)] - public string CallbackUrl { get; set; } - - /// - /// [可选]回调内容 - /// - [JsonProperty("callbackBody", NullValueHandling = NullValueHandling.Ignore)] - public string CallbackBody { get; set; } - - /// - /// [可选]回调内容类型 - /// - [JsonProperty("callbackBodyType", NullValueHandling = NullValueHandling.Ignore)] - public string CallbackBodyType { get; set; } - - /// - /// [可选]回调host - /// - [JsonProperty("callbackHost", NullValueHandling = NullValueHandling.Ignore)] - public string CallbackHost { get; set; } - - /// - /// [可选]回调fetchkey - /// - [JsonProperty("callbackFetchKey", NullValueHandling = NullValueHandling.Ignore)] - public int? CallbackFetchKey { get; set; } - - /// - /// [可选]上传预转持久化 - /// - [JsonProperty("persistentOps", NullValueHandling = NullValueHandling.Ignore)] - public string PersistentOps { get; set; } - - /// - /// [可选]持久化结果通知 - /// - [JsonProperty("persistentNotifyUrl", NullValueHandling = NullValueHandling.Ignore)] - public string PersistentNotifyUrl { get; set; } - - /// - /// [可选]私有队列 - /// - [JsonProperty("persistentPipeline", NullValueHandling = NullValueHandling.Ignore)] - public string PersistentPipeline { get; set; } - - /// - /// [可选]上传文件大小限制:最小值 - /// - [JsonProperty("fsizeMin", NullValueHandling = NullValueHandling.Ignore)] - public int? FsizeMin { get; set; } - - /// - /// [可选]上传文件大小限制:最大值 - /// - [JsonProperty("fsizeLimit", NullValueHandling = NullValueHandling.Ignore)] - public int? FsizeLimit { get; set; } - - /// - /// [可选]上传时是否自动检测MIME - /// - [JsonProperty("detectMime", NullValueHandling = NullValueHandling.Ignore)] - public int? DetectMime { get; set; } - - /// - /// [可选]上传文件MIME限制 - /// - [JsonProperty("mimeLimit", NullValueHandling = NullValueHandling.Ignore)] - public string MimeLimit { get; set; } - - /// - /// [可选]文件上传后多少天后自动删除 - /// - [JsonProperty("deleteAfterDays", NullValueHandling = NullValueHandling.Ignore)] - public int? DeleteAfterDays { get; set; } - - /// - /// [可选]文件的存储类型,默认为普通存储,设置为1为低频存储 - /// - [JsonProperty("fileType", NullValueHandling = NullValueHandling.Ignore)] - public int? FileType { get; set; } - - /// - /// 设置上传凭证有效期(配置Deadline属性) - /// - /// - public void SetExpires(int expireInSeconds) - { - this.Deadline = (int)Util.UnixTimestamp.GetUnixTimestamp(expireInSeconds); - } - - /// - /// 转换为JSON字符串 - /// - /// JSON字符串 - public string ToJsonString() - { - if (this.Deadline == 0) - { - //默认一个小时有效期 - this.SetExpires(3600); - } - return JsonConvert.SerializeObject(this); - } - - } -} diff --git a/src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/Storage/QiniuException.cs b/src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/Storage/QiniuException.cs deleted file mode 100644 index e955448..0000000 --- a/src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/Storage/QiniuException.cs +++ /dev/null @@ -1,24 +0,0 @@ -using System; -using Qiniu.Http; - -namespace Qiniu.Storage -{ - class QiniuException :Exception - { - public string message; - public HttpResult HttpResult; - public QiniuException(HttpResult httpResult, string message) - { - this.HttpResult = httpResult == null ? new HttpResult() : httpResult; - this.message = message; - } - - public override string Message - { - get - { - return this.message; - } - } - } -} diff --git a/src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/Storage/ResumableUploader.cs b/src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/Storage/ResumableUploader.cs deleted file mode 100644 index bf3a67a..0000000 --- a/src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/Storage/ResumableUploader.cs +++ /dev/null @@ -1,849 +0,0 @@ -using System; -using System.IO; -using System.Text; -using System.Collections.Generic; -using System.Threading; -using Qiniu.Util; -using Qiniu.Http; -using Newtonsoft.Json; - -namespace Qiniu.Storage -{ - /// - /// 分片上传/断点续上传,适合于以下"情形2~3": - /// (1)网络较好并且待上传的文件体积较小时(比如100MB或更小一点)使用简单上传; - /// (2)文件较大或者网络状况不理想时请使用分片上传; - /// (3)文件较大并且需要支持断点续上传,请使用分片上传(断点续上传) - /// 上传时需要提供正确的上传凭证(由对应的上传策略生成) - /// 上传策略 https://developer.qiniu.com/kodo/manual/1206/put-policy - /// 上传凭证 https://developer.qiniu.com/kodo/manual/1208/upload-token - /// - public class ResumableUploader - { - private Config config; - - // HTTP请求管理器(GET/POST等) - private HttpManager httpManager; - - /// - /// 初始化 - /// - /// 分片上传的配置信息 - public ResumableUploader(Config config) - { - if (config == null) - { - this.config = new Config(); - } - else - { - this.config = config; - } - this.httpManager = new HttpManager(); - } - - - /// - /// 分片上传,支持断点续上传,带有自定义进度处理、高级控制功能 - /// - /// 本地待上传的文件名 - /// 要保存的文件名称 - /// 上传凭证 - /// 上传可选配置 - /// 上传文件后的返回结果 - public HttpResult UploadFile(string localFile, string key, string token, PutExtra putExtra) - { - try - { - FileStream fs = new FileStream(localFile, FileMode.Open); - return this.UploadStream(fs, key, token, putExtra); - } - catch (Exception ex) - { - HttpResult ret = HttpResult.InvalidFile; - ret.RefText = ex.Message; - return ret; - } - } - - - - /// - /// 分片上传/断点续上传,带有自定义进度处理和上传控制,检查CRC32,可自动重试 - /// - /// 待上传文件流 - /// 要保存的文件名称 - /// 上传凭证 - /// 可选配置参数 - /// 上传文件后返回结果 - public HttpResult UploadStream(Stream stream, string key, string upToken, PutExtra putExtra) - { - HttpResult result = new HttpResult(); - string encodedObjectName = ""; - if (putExtra != null && putExtra.Version == "v2") - { - encodedObjectName = Base64.GetEncodedObjectName(key); - } - - //check put extra - if (putExtra == null) - { - putExtra = new PutExtra(); - } - if (putExtra.ProgressHandler == null) - { - putExtra.ProgressHandler = DefaultUploadProgressHandler; - } - if (putExtra.UploadController == null) - { - putExtra.UploadController = DefaultUploadController; - } - - if (!(putExtra.BlockUploadThreads > 0 && putExtra.BlockUploadThreads <= 64)) - { - putExtra.BlockUploadThreads = 1; - } - - using (stream) - { - //start to upload - try - { - long uploadedBytes = 0; - long fileSize = stream.Length; - long blockCount = (fileSize + putExtra.PartSize - 1) / putExtra.PartSize; - int partNumber = 1; - - //check resume record file - ResumeInfo resumeInfo = null; - if (File.Exists(putExtra.ResumeRecordFile)) - { - - resumeInfo = ResumeHelper.Load(putExtra.ResumeRecordFile); - - if (resumeInfo != null && fileSize == resumeInfo.FileSize) - { - //check whether ctx expired - if (UnixTimestamp.IsContextExpired(resumeInfo.ExpiredAt)) - { - resumeInfo = null; - } - } - } - if (resumeInfo == null) - { - if (putExtra.Version == "v1") - { - resumeInfo = new ResumeInfo() - { - FileSize = fileSize, - BlockCount = blockCount, - Contexts = new string[blockCount], - ExpiredAt = 0, - }; - } - else - { - HttpResult res = initReq(encodedObjectName, upToken); - Dictionary responseBody = JsonConvert.DeserializeObject>(res.Text); - if (res.Code != 200) - { - return res; - } - - resumeInfo = new ResumeInfo() - { - FileSize = fileSize, - BlockCount = blockCount, - Etags = new Dictionary[blockCount], - Uploaded = 0, - ExpiredAt = long.Parse(responseBody["expireAt"]), - UploadId = responseBody["uploadId"] - }; - } - - } - - //calc upload progress - for (long blockIndex = 0; blockIndex < blockCount; blockIndex++) - { - - if (putExtra.Version == "v1") - { - string context = resumeInfo.Contexts[blockIndex]; - if (!string.IsNullOrEmpty(context)) - { - uploadedBytes += putExtra.PartSize; - } - } - else - { - Dictionary etag = resumeInfo.Etags[blockIndex]; - if (etag != null) - { - if (blockIndex > 0) - { - partNumber += 1; - } - uploadedBytes += putExtra.PartSize; - resumeInfo.Uploaded = uploadedBytes; - } - } - - } - - //set upload progress - putExtra.ProgressHandler(uploadedBytes, fileSize); - - //init block upload error - //check not finished blocks to upload - UploadControllerAction upCtrl = putExtra.UploadController(); - ManualResetEvent manualResetEvent = new ManualResetEvent(false); - Dictionary blockDataDict = new Dictionary(); - Dictionary blockMakeResults = new Dictionary(); - Dictionary uploadedBytesDict = new Dictionary(); - uploadedBytesDict.Add("UploadProgress", uploadedBytes); - byte[] blockBuffer = new byte[putExtra.PartSize]; - for (long blockIndex = 0; blockIndex < blockCount; blockIndex++) - { - string context = null; - if (putExtra.Version == "v1") - { - context = resumeInfo.Contexts[blockIndex]; - } - else - { - Dictionary etag = resumeInfo.Etags[blockIndex]; - if (etag != null && etag.Count > 0) - { - context = "~"; - } - } - - if (string.IsNullOrEmpty(context)) - { - //check upload controller action before each chunk - while (true) - { - upCtrl = putExtra.UploadController(); - - if (upCtrl == UploadControllerAction.Aborted) - { - result.Code = (int)HttpCode.USER_CANCELED; - result.RefCode = (int)HttpCode.USER_CANCELED; - result.RefText += string.Format("[{0}] [ResumableUpload] Info: upload task is aborted\n", - DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.ffff")); - manualResetEvent.Set(); - return result; - } - else if (upCtrl == UploadControllerAction.Suspended) - { - result.RefCode = (int)HttpCode.USER_PAUSED; - result.RefText += string.Format("[{0}] [ResumableUpload] Info: upload task is paused\n", - DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.ffff")); - manualResetEvent.WaitOne(1000); - } - else if (upCtrl == UploadControllerAction.Activated) - { - break; - } - } - - long offset = blockIndex * putExtra.PartSize; - stream.Seek(offset, SeekOrigin.Begin); - int blockLen = stream.Read(blockBuffer, 0, putExtra.PartSize); - byte[] blockData = new byte[blockLen]; - Array.Copy(blockBuffer, blockData, blockLen); - blockDataDict.Add(blockIndex, blockData); - - if (blockDataDict.Count == putExtra.BlockUploadThreads) - { - - processMakeBlocks(blockDataDict, upToken, putExtra, resumeInfo, blockMakeResults, uploadedBytesDict, fileSize, - encodedObjectName); - //check mkblk results - foreach (int blkIndex in blockMakeResults.Keys) - { - HttpResult mkblkRet = blockMakeResults[blkIndex]; - if (mkblkRet.Code != 200) - { - result = mkblkRet; - manualResetEvent.Set(); - return result; - } - } - blockDataDict.Clear(); - blockMakeResults.Clear(); - if (!string.IsNullOrEmpty(putExtra.ResumeRecordFile)) - { - ResumeHelper.Save(resumeInfo, putExtra.ResumeRecordFile); - } - } - } - } - - if (blockDataDict.Count > 0) - { - processMakeBlocks(blockDataDict, upToken, putExtra, resumeInfo, blockMakeResults, uploadedBytesDict, fileSize, - encodedObjectName); - //check mkblk results - foreach (int blkIndex in blockMakeResults.Keys) - { - HttpResult mkblkRet = blockMakeResults[blkIndex]; - if (mkblkRet.Code != 200) - { - result = mkblkRet; - manualResetEvent.Set(); - return result; - } - } - blockDataDict.Clear(); - blockMakeResults.Clear(); - if (!string.IsNullOrEmpty(putExtra.ResumeRecordFile)) - { - ResumeHelper.Save(resumeInfo, putExtra.ResumeRecordFile); - } - } - - if (upCtrl == UploadControllerAction.Activated) - { - HttpResult hr = new HttpResult();; - if (putExtra.Version == "v1") - { - hr = MakeFile(key, fileSize, key, upToken, putExtra, resumeInfo.Contexts); - } - else - { - hr = completeParts(key, resumeInfo, key, upToken, putExtra, encodedObjectName); - } - - if (hr.Code != (int)HttpCode.OK) - { - result.Shadow(hr); - result.RefText += string.Format("[{0}] [ResumableUpload] Error: mkfile: code = {1}, text = {2}\n", - DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.ffff"), hr.Code, hr.Text); - } - - if (File.Exists(putExtra.ResumeRecordFile)) - { - File.Delete(putExtra.ResumeRecordFile); - } - result.Shadow(hr); - result.RefText += string.Format("[{0}] [ResumableUpload] Uploaded: \"{1}\" ==> \"{2}\"\n", - DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.ffff"), putExtra.ResumeRecordFile, key); - } - else - { - result.Code = (int)HttpCode.USER_CANCELED; - result.RefCode = (int)HttpCode.USER_CANCELED; - result.RefText += string.Format("[{0}] [ResumableUpload] Info: upload task is aborted, mkfile\n", - DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.ffff")); - } - - manualResetEvent.Set(); - return result; - } - catch (Exception ex) - { - Console.WriteLine(ex.StackTrace); - StringBuilder sb = new StringBuilder(); - sb.AppendFormat("[{0}] [ResumableUpload] Error: ", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.ffff")); - Exception e = ex; - while (e != null) - { - sb.Append(e.Message + " "); - e = e.InnerException; - } - sb.AppendLine(); - - result.RefCode = (int)HttpCode.USER_UNDEF; - result.RefText += sb.ToString(); - } - } - - return result; - } - - private void processMakeBlocks(Dictionary blockDataDict, string upToken, - PutExtra putExtra, ResumeInfo resumeInfo, Dictionary blockMakeResults, - Dictionary uploadedBytesDict, long fileSize, string encodedObjectName) - { - int taskMax = blockDataDict.Count; - ManualResetEvent[] doneEvents = new ManualResetEvent[taskMax]; - int eventIndex = 0; - object progressLock = new object(); - foreach (long blockIndex in blockDataDict.Keys) - { - //signal task - ManualResetEvent doneEvent = new ManualResetEvent(false); - doneEvents[eventIndex] = doneEvent; - eventIndex += 1; - - //queue task - byte[] blockData = blockDataDict[blockIndex]; - ResumeBlocker resumeBlocker = new ResumeBlocker(doneEvent, blockData, blockIndex, upToken, putExtra, - resumeInfo, blockMakeResults, progressLock, uploadedBytesDict, fileSize, encodedObjectName); - ThreadPool.QueueUserWorkItem(new WaitCallback(this.MakeBlock), resumeBlocker); - } - - try - { - WaitHandle.WaitAll(doneEvents); - } - catch (Exception ex) - { - Console.WriteLine("wait all exceptions:" + ex.StackTrace); - //pass - } - } - - /// - /// 创建块(携带首片数据),v1检查CRC32,v2检查md5 - /// - /// 创建分片上次的块请求 - private void MakeBlock(object resumeBlockerObj) - { - ResumeBlocker resumeBlocker = (ResumeBlocker)resumeBlockerObj; - ManualResetEvent doneEvent = resumeBlocker.DoneEvent; - Dictionary blockMakeResults = resumeBlocker.BlockMakeResults; - PutExtra putExtra = resumeBlocker.PutExtra; - long blockIndex = resumeBlocker.BlockIndex; - HttpResult result = new HttpResult(); - //check whether to cancel - while (true) - { - UploadControllerAction upCtl = resumeBlocker.PutExtra.UploadController(); - if (upCtl == UploadControllerAction.Suspended) - { - doneEvent.WaitOne(1000); - continue; - } - else if (upCtl == UploadControllerAction.Aborted) - { - doneEvent.Set(); - - result.Code = (int)HttpCode.USER_CANCELED; - result.RefCode = (int)HttpCode.USER_CANCELED; - result.RefText += string.Format("[{0}] [ResumableUpload] Info: upload task is aborted, mkblk {1}\n", - DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.ffff"), blockIndex); - blockMakeResults.Add(blockIndex, result); - return; - } - else - { - break; - } - } - - byte[] blockBuffer = resumeBlocker.BlockBuffer; - int blockSize = blockBuffer.Length; - - string upToken = resumeBlocker.UploadToken; - Dictionary uploadedBytesDict = resumeBlocker.UploadedBytesDict; - long fileSize = resumeBlocker.FileSize; - object progressLock = resumeBlocker.ProgressLock; - ResumeInfo resumeInfo = resumeBlocker.ResumeInfo; - - try - { - //get upload host - string ak = UpToken.GetAccessKeyFromUpToken(upToken); - string bucket = UpToken.GetBucketFromUpToken(upToken); - if (ak == null || bucket == null) - { - result = HttpResult.InvalidToken; - doneEvent.Set(); - return; - } - - string uploadHost = this.config.UpHost(ak, bucket); - string url = ""; - if (putExtra.Version == "v1") - { - url = string.Format("{0}/mkblk/{1}", uploadHost, blockSize); - } - else - { - url = string.Format("{0}/buckets/{1}/objects/{2}/uploads/{3}/{4}", uploadHost, bucket, resumeBlocker.encodedObjectName, - resumeInfo.UploadId, blockIndex+1); - } - - string upTokenStr = string.Format("UpToken {0}", upToken); - using (MemoryStream ms = new MemoryStream(blockBuffer, 0, blockSize)) - { - byte[] data = ms.ToArray(); - if (putExtra.Version == "v1") - { - result = httpManager.PostData(url, data, upTokenStr); - } - else - { - Dictionary headers = new Dictionary(); - headers.Add("Authorization", upTokenStr); - // data to md5 - string md5 = LabMD5.GenerateMD5(blockBuffer); - headers.Add("Content-MD5", md5); - result = httpManager.PutDataWithHeaders(url, data, headers); - } - - - if (result.Code == (int)HttpCode.OK) - { - if (putExtra.Version == "v1") - { - ResumeContext rc = JsonConvert.DeserializeObject(result.Text); - - if (rc.Crc32 > 0) - { - uint crc_1 = rc.Crc32; - uint crc_2 = CRC32.CheckSumSlice(blockBuffer, 0, blockSize); - if (crc_1 != crc_2) - { - result.RefCode = (int)HttpCode.USER_NEED_RETRY; - result.RefText += string.Format(" CRC32: remote={0}, local={1}\n", crc_1, crc_2); - } - else - { - //write the mkblk context - resumeInfo.Contexts[blockIndex] = rc.Ctx; - resumeInfo.ExpiredAt = rc.ExpiredAt; - lock (progressLock) - { - uploadedBytesDict["UploadProgress"] += blockSize; - } - putExtra.ProgressHandler(uploadedBytesDict["UploadProgress"], fileSize); - } - } - else - { - result.RefText += string.Format("[{0}] JSON Decode Error: text = {1}", - DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.ffff"), result.Text); - result.RefCode = (int)HttpCode.USER_NEED_RETRY; - } - } - else - { - Dictionary rc = JsonConvert.DeserializeObject>(result.Text); - string md5 = LabMD5.GenerateMD5(blockBuffer); - if (md5 != rc["md5"]) - { - result.RefCode = (int)HttpCode.USER_NEED_RETRY; - result.RefText += string.Format(" md5: remote={0}, local={1}\n", rc["md5"], md5); - } - else - { - Dictionary etag = new Dictionary(); - etag.Add("etag", rc["etag"]); - etag.Add("partNumber", blockIndex + 1); - resumeInfo.Etags[blockIndex] = etag; - lock (progressLock) - { - uploadedBytesDict["UploadProgress"] += blockSize; - resumeInfo.Uploaded += blockSize; - } - putExtra.ProgressHandler(uploadedBytesDict["UploadProgress"], fileSize); - } - } - - } - else - { - result.RefCode = (int)HttpCode.USER_NEED_RETRY; - } - } - } - catch (Exception ex) - { - StringBuilder sb = new StringBuilder(); - sb.AppendFormat("[{0}] mkblk Error: ", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.ffff")); - Exception e = ex; - while (e != null) - { - sb.Append(e.Message + " "); - e = e.InnerException; - } - sb.AppendLine(); - - if (ex is QiniuException) - { - QiniuException qex = (QiniuException)ex; - result.Code = qex.HttpResult.Code; - result.RefCode = qex.HttpResult.Code; - result.Text = qex.HttpResult.Text; - result.RefText += sb.ToString(); - } - else - { - result.RefCode = (int)HttpCode.USER_UNDEF; - result.RefText += sb.ToString(); - } - } - - //return the http result - blockMakeResults.Add(blockIndex, result); - doneEvent.Set(); - } - - /// - /// 根据已上传的所有分片数据创建文件 - /// - /// 源文件名 - /// 文件大小 - /// 要保存的文件名 - /// 所有数据块的Context - /// 上传凭证 - /// 用户指定的额外参数 - /// 此操作执行后的返回结果 - private HttpResult MakeFile(string fileName, long size, string key, string upToken, PutExtra putExtra, string[] contexts) - { - HttpResult result = new HttpResult(); - - try - { - string fnameStr = "fname"; - string mimeTypeStr = ""; - string keyStr = ""; - string paramStr = ""; - //check file name - if (!string.IsNullOrEmpty(fileName)) - { - fnameStr = string.Format("/fname/{0}", Base64.UrlSafeBase64Encode(fileName)); - } - - //check mime type - if (!string.IsNullOrEmpty(putExtra.MimeType)) - { - mimeTypeStr = string.Format("/mimeType/{0}", Base64.UrlSafeBase64Encode(putExtra.MimeType)); - } - - //check key - if (!string.IsNullOrEmpty(key)) - { - keyStr = string.Format("/key/{0}", Base64.UrlSafeBase64Encode(key)); - } - - //check extra params - if (putExtra.Params != null && putExtra.Params.Count > 0) - { - StringBuilder sb = new StringBuilder(); - foreach (var kvp in putExtra.Params) - { - string k = kvp.Key; - string v = kvp.Value; - if (k.StartsWith("x:") && !string.IsNullOrEmpty(v)) - { - sb.AppendFormat("/{0}/{1}", k, v); - } - } - - paramStr = sb.ToString(); - } - - //get upload host - string ak = UpToken.GetAccessKeyFromUpToken(upToken); - string bucket = UpToken.GetBucketFromUpToken(upToken); - if (ak == null || bucket == null) - { - return HttpResult.InvalidToken; - } - - string uploadHost = this.config.UpHost(ak, bucket); - - string url = string.Format("{0}/mkfile/{1}{2}{3}{4}{5}", uploadHost, size, mimeTypeStr, fnameStr, keyStr, paramStr); - string body = string.Join(",", contexts); - string upTokenStr = string.Format("UpToken {0}", upToken); - - result = httpManager.PostText(url, body, upTokenStr); - } - catch (Exception ex) - { - StringBuilder sb = new StringBuilder(); - sb.AppendFormat("[{0}] mkfile Error: ", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.ffff")); - Exception e = ex; - while (e != null) - { - sb.Append(e.Message + " "); - e = e.InnerException; - } - sb.AppendLine(); - - if (ex is QiniuException) - { - QiniuException qex = (QiniuException)ex; - result.Code = qex.HttpResult.Code; - result.RefCode = qex.HttpResult.Code; - result.Text = qex.HttpResult.Text; - result.RefText += sb.ToString(); - } - else - { - result.RefCode = (int)HttpCode.USER_UNDEF; - result.RefText += sb.ToString(); - } - } - - return result; - } - - /// - /// 初始化上传任务 - /// - /// 上传凭证 - /// Base64编码后的资源名 - /// 此操作执行后的返回结果 - private HttpResult initReq(string encodedObjectName, string upToken) - { - HttpResult result = new HttpResult(); - - try - { - string ak = UpToken.GetAccessKeyFromUpToken(upToken); - string bucket = UpToken.GetBucketFromUpToken(upToken); - if (ak == null || bucket == null) - { - return HttpResult.InvalidToken; - } - - string uploadHost = this.config.UpHost(ak, bucket); - string url = string.Format("{0}/buckets/{1}/objects/{2}/uploads", uploadHost, bucket, encodedObjectName); - string upTokenStr = string.Format("UpToken {0}", upToken); - result = httpManager.PostText(url, null, upTokenStr); - } - catch (Exception ex) - { - StringBuilder sb = new StringBuilder(); - sb.AppendFormat("[{0}] mkfile Error: ", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.ffff")); - Exception e = ex; - while (e != null) - { - sb.Append(e.Message + " "); - e = e.InnerException; - } - sb.AppendLine(); - - if (ex is QiniuException) - { - QiniuException qex = (QiniuException)ex; - result.Code = qex.HttpResult.Code; - result.RefCode = qex.HttpResult.Code; - result.Text = qex.HttpResult.Text; - result.RefText += sb.ToString(); - } - else - { - result.RefCode = (int)HttpCode.USER_UNDEF; - result.RefText += sb.ToString(); - } - } - return result; - } - - /// - /// 根据已上传的所有分片数据创建文件 - /// - /// 源文件名 - /// 分片上传记录信息 - /// 要保存的文件名 - /// 上传凭证 - /// 用户指定的额外参数 - /// Base64编码后的资源名 - /// 此操作执行后的返回结果 - private HttpResult completeParts(string fileName, ResumeInfo resumeInfo, string key, string upToken, PutExtra putExtra, string encodedObjectName) - { - HttpResult result = new HttpResult(); - - try - { - string paramStr = "{}"; - if (string.IsNullOrEmpty(fileName)) { - fileName = "fname"; - } - if (string.IsNullOrEmpty(putExtra.MimeType)) - { - putExtra.MimeType = ""; - } - if (string.IsNullOrEmpty(key)) - { - key = ""; - } - if (putExtra.Params != null) - { - paramStr = JsonConvert.SerializeObject(putExtra.Params); - } - //get upload host - string ak = UpToken.GetAccessKeyFromUpToken(upToken); - string bucket = UpToken.GetBucketFromUpToken(upToken); - if (ak == null || bucket == null) - { - return HttpResult.InvalidToken; - } - - string uploadHost = this.config.UpHost(ak, bucket); - - string upTokenStr = string.Format("UpToken {0}", upToken); - Dictionary body = new Dictionary(); - body.Add("fname", fileName); - body.Add("mimeType", putExtra.MimeType); - body.Add("customVars", null); - body.Add("parts", resumeInfo.Etags); - string url = string.Format("{0}/buckets/{1}/objects/{2}/uploads/{3}", uploadHost, bucket, encodedObjectName, resumeInfo.UploadId); - string bodyStr = JsonConvert.SerializeObject(body); - result = httpManager.PostJson(url, bodyStr, upTokenStr); - } - catch (Exception ex) - { - StringBuilder sb = new StringBuilder(); - sb.AppendFormat("[{0}] completeParts Error: ", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.ffff")); - Exception e = ex; - while (e != null) - { - sb.Append(e.Message + " "); - e = e.InnerException; - } - sb.AppendLine(); - - if (ex is QiniuException) - { - QiniuException qex = (QiniuException)ex; - result.Code = qex.HttpResult.Code; - result.RefCode = qex.HttpResult.Code; - result.Text = qex.HttpResult.Text; - result.RefText += sb.ToString(); - } - else - { - result.RefCode = (int)HttpCode.USER_UNDEF; - result.RefText += sb.ToString(); - } - } - - return result; - } - - /// - /// 默认的进度处理函数-上传文件 - /// - /// 已上传的字节数 - /// 文件总字节数 - public static void DefaultUploadProgressHandler(long uploadedBytes, long totalBytes) - { - if (uploadedBytes < totalBytes) - { - Console.WriteLine("[{0}] [ResumableUpload] Progress: {1,7:0.000}%", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.ffff"), 100.0 * uploadedBytes / totalBytes); - } - else - { - Console.WriteLine("[{0}] [ResumableUpload] Progress: {1,7:0.000}%\n", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.ffff"), 100.0); - } - } - - /// - /// 默认的上传控制函数,默认不执行任何控制 - /// - /// 控制状态 - public static UploadControllerAction DefaultUploadController() - { - return UploadControllerAction.Activated; - } - } -} diff --git a/src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/Storage/ResumeBlocker.cs b/src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/Storage/ResumeBlocker.cs deleted file mode 100644 index 1de3e65..0000000 --- a/src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/Storage/ResumeBlocker.cs +++ /dev/null @@ -1,38 +0,0 @@ -using Qiniu.Http; -using System.Collections.Generic; -using System.Threading; - -namespace Qiniu.Storage -{ - class ResumeBlocker - { - public ManualResetEvent DoneEvent { set; get; } - public byte[] BlockBuffer { set; get; } - public long BlockIndex { set; get; } - public string UploadToken { set; get; } - public PutExtra PutExtra { set; get; } - public ResumeInfo ResumeInfo { set; get; } - public Dictionary BlockMakeResults; - public object ProgressLock { set; get; } - public Dictionary UploadedBytesDict { set; get; } - public long FileSize { set; get; } - public string encodedObjectName { set; get; } - - public ResumeBlocker(ManualResetEvent doneEvent, byte[] blockBuffer, long blockIndex, string uploadToken, - PutExtra putExtra, ResumeInfo resumeInfo, Dictionary blockMakeResults, - object progressLock, Dictionary uploadedBytesDict, long fileSize, string encodedObjectName) - { - this.DoneEvent = doneEvent; - this.BlockBuffer = blockBuffer; - this.BlockIndex = blockIndex; - this.UploadToken = uploadToken; - this.PutExtra = putExtra; - this.ResumeInfo = resumeInfo; - this.BlockMakeResults = blockMakeResults; - this.ProgressLock = progressLock; - this.UploadedBytesDict = uploadedBytesDict; - this.FileSize = fileSize; - this.encodedObjectName = encodedObjectName; - } - } -} diff --git a/src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/Storage/ResumeContext.cs b/src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/Storage/ResumeContext.cs deleted file mode 100644 index 3b7a020..0000000 --- a/src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/Storage/ResumeContext.cs +++ /dev/null @@ -1,59 +0,0 @@ -using Newtonsoft.Json; -using System.Collections.Generic; - -namespace Qiniu.Storage -{ - /// - /// 分片上传的上下文信息 - /// - public class ResumeContext - { - /// - /// 上下文信息 - /// - [JsonProperty("ctx")] - public string Ctx { get; set; } - - /// - /// 校验和 - /// - [JsonProperty("checksum")] - public string Checksum { get; set; } - - /// - /// crc32校验值 - /// - [JsonProperty("crc32")] - public uint Crc32 { get; set; } - - /// - /// 文件偏移位置 - /// - [JsonProperty("offset")] - public long Offset { get; set; } - - /// - /// 上传目的host - /// - [JsonProperty("host")] - public string Host { get; set; } - - /// - /// ctx失效时刻 - /// - [JsonProperty("expired_at")] - public long ExpiredAt { get; set; } - - /// - /// 新版分片上传上下文etag - /// - [JsonProperty("etag")] - public Dictionary Etag { get; set; } - - /// - /// 新版分片上传md5校验值 - /// - [JsonProperty("md5")] - public string Md5 { get; set; } - } -} diff --git a/src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/Storage/ResumeHelper.cs b/src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/Storage/ResumeHelper.cs deleted file mode 100644 index 740c5dc..0000000 --- a/src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/Storage/ResumeHelper.cs +++ /dev/null @@ -1,74 +0,0 @@ -using System; -using System.IO; -using Qiniu.Util; -using Newtonsoft.Json; - -namespace Qiniu.Storage -{ - /// - /// 断点续上传辅助函数Load/Save - /// - public class ResumeHelper - { - - /// - /// 生成默认的断点记录文件名称 - /// - /// 待上传的本地文件 - /// 要保存的目标key - /// 用于记录断点信息的文件名 - public static string GetDefaultRecordKey(string localFile, string key) - { - string tempDir = System.Environment.GetEnvironmentVariable("TEMP"); - System.IO.FileInfo fileInfo = new System.IO.FileInfo(localFile); - string uniqueKey = string.Format("{0}:{1}:{2}", localFile, key, fileInfo.LastWriteTime.ToFileTime()); - return Path.Combine(tempDir, "QiniuResume_" + Hashing.CalcMD5X(uniqueKey)); - } - - /// - /// 尝试从从文件载入断点信息 - /// - /// 断点记录文件 - /// 断点信息 - public static ResumeInfo Load(string recordFile) - { - ResumeInfo resumeInfo = null; - - try - { - using (FileStream fs = new FileStream(recordFile, FileMode.Open)) - { - using (StreamReader sr = new StreamReader(fs)) - { - string jsonStr = sr.ReadToEnd(); - resumeInfo=JsonConvert.DeserializeObject(jsonStr); - } - } - } - catch (Exception) - { - resumeInfo = null; - } - - return resumeInfo; - } - - /// - /// 保存断点信息到文件 - /// - /// 断点信息 - /// 断点记录文件 - public static void Save(ResumeInfo resumeInfo, string recordFile) - { - string jsonStr = resumeInfo.ToJsonStr(); - - using (FileStream fs = new FileStream(recordFile, FileMode.Create)) - { - using (StreamWriter sw = new StreamWriter(fs)) - { - sw.Write(jsonStr); - } - } - } - } -} diff --git a/src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/Storage/ResumeInfo.cs b/src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/Storage/ResumeInfo.cs deleted file mode 100644 index 79b25f7..0000000 --- a/src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/Storage/ResumeInfo.cs +++ /dev/null @@ -1,62 +0,0 @@ -using Newtonsoft.Json; -using System.Collections.Generic; -namespace Qiniu.Storage -{ - /// - /// 分片上传的记录信息 - /// - public class ResumeInfo - { - /// - /// 文件大小 - /// - [JsonProperty("fileSize")] - public long FileSize { get; set; } - - /// - /// 文件块总数 - /// - [JsonProperty("blockCount")] - public long BlockCount { get; set; } - - /// - /// 上下文信息列表 - /// - [JsonProperty("contexts")] - public string[] Contexts { get; set; } - - /// - /// Ctx过期时间戳(单位秒) - /// - [JsonProperty("expiredAt")] - public long ExpiredAt { get; set; } - - /// - /// 上传进度信息序列化 - /// - /// - - /// - /// 新版分片上下文信息列表 - /// - [JsonProperty("etags")] - public Dictionary[] Etags { get; set; } - - /// - /// 新版分片上传id - /// - [JsonProperty("uploadId")] - public string UploadId { get; set; } - - /// - /// 完成上传的字节数 - /// - [JsonProperty("uploaded")] - public long Uploaded { get; set; } - - public string ToJsonStr() - { - return JsonConvert.SerializeObject(this); - } - } -} diff --git a/src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/Storage/StatResult.cs b/src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/Storage/StatResult.cs deleted file mode 100644 index 3fe51f7..0000000 --- a/src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/Storage/StatResult.cs +++ /dev/null @@ -1,74 +0,0 @@ -using System.Text; -using Qiniu.Http; -using Newtonsoft.Json; - -namespace Qiniu.Storage -{ - /// - /// 获取空间文件信息(stat操作)的返回消息 - /// - public class StatResult : HttpResult - { - /// - /// stat信息列表 - /// - public FileInfo Result - { - get - { - FileInfo info = null; - if ((Code == (int)HttpCode.OK) && (!string.IsNullOrEmpty(Text))) - { - info = JsonConvert.DeserializeObject(Text); - } - return info; - } - } - - /// - /// 转换为易读字符串格式 - /// - /// 便于打印和阅读的字符串 - public override string ToString() - { - StringBuilder sb = new StringBuilder(); - - sb.AppendFormat("code: {0}\n", Code); - - if (Result != null) - { - sb.AppendFormat("Size={0}, Type={1}, Hash={2}, Time={3}\n", - Result.Fsize, Result.MimeType, Result.Hash, Result.PutTime); - - } - else - { - if (!string.IsNullOrEmpty(Text)) - { - sb.AppendLine("text:"); - sb.AppendLine(Text); - } - } - sb.AppendLine(); - - sb.AppendFormat("ref-code: {0}\n", RefCode); - - if (!string.IsNullOrEmpty(RefText)) - { - sb.AppendLine("ref-text:"); - sb.AppendLine(RefText); - } - - if (RefInfo != null) - { - sb.AppendFormat("ref-info:\n"); - foreach (var d in RefInfo) - { - sb.AppendLine(string.Format("{0}: {1}", d.Key, d.Value)); - } - } - - return sb.ToString(); - } - } -} diff --git a/src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/Storage/UploadController.cs b/src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/Storage/UploadController.cs deleted file mode 100644 index 04bbc9f..0000000 --- a/src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/Storage/UploadController.cs +++ /dev/null @@ -1,29 +0,0 @@ -namespace Qiniu.Storage -{ - /// - /// 上传任务的状态 - /// - public enum UploadControllerAction - { - /// - /// 任务状态:激活 - /// - Activated, - - /// - /// 任务状态:暂停 - /// - Suspended, - - /// - /// 任务状态:退出 - /// - Aborted - }; - - /// - /// 上传任务的控制函数 - /// - /// - public delegate UploadControllerAction UploadController(); -} diff --git a/src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/Storage/UploadManager.cs b/src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/Storage/UploadManager.cs deleted file mode 100644 index 4aa6d6b..0000000 --- a/src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/Storage/UploadManager.cs +++ /dev/null @@ -1,94 +0,0 @@ -using System.IO; -using Qiniu.Util; -using Qiniu.Http; -using System.Collections.Generic; - -namespace Qiniu.Storage -{ - /// - /// 上传管理器,根据文件/数据(流)大小以及阈值设置自动选择合适的上传方式 - /// - public class UploadManager - { - private Config config; - - /// - /// 初始化 - /// - /// 文件上传的配置信息 - public UploadManager(Config config) - { - this.config = config; - } - - /// - /// 上传数据 - /// - /// 待上传的数据 - /// 要保存的文件名称 - /// 上传凭证 - /// 上传可选设置 - /// 上传文件后的返回结果 - public HttpResult UploadData(byte[] data, string key, string token, PutExtra extra) - { - FormUploader formUploader = new FormUploader(this.config); - return formUploader.UploadData(data, key, token, extra); - } - - /// - /// 上传文件,根据文件大小以及设置的阈值(用户初始化UploadManager时可指定该值)自动选择: - /// 若文件大小超过设定阈值,使用ResumableUploader,否则使用FormUploader - /// - /// 本地待上传的文件名 - /// 要保存的文件名称 - /// 上传凭证 - /// 上传可选设置 - /// 上传文件后的返回结果 - public HttpResult UploadFile(string localFile, string key, string token, PutExtra extra) - { - HttpResult result = new HttpResult(); - - System.IO.FileInfo fi = new System.IO.FileInfo(localFile); - if (fi.Length > this.config.PutThreshold) - { - ResumableUploader resumeUploader = new ResumableUploader(config); - result = resumeUploader.UploadFile(localFile, key, token, extra); - } - else - { - FormUploader formUploader = new FormUploader(config); - result = formUploader.UploadFile(localFile, key, token, extra); - } - - return result; - } - - - /// - /// 上传文件数据流,根据文件大小以及设置的阈值(用户初始化UploadManager时可指定该值)自动选择: - /// 若文件大小超过设定阈值,使用ResumableUploader,否则使用FormUploader - /// - /// 待上传的数据流 - /// 要保存的文件名称 - /// 上传凭证 - /// 上传可选设置 - /// 上传文件后的返回结果 - public HttpResult UploadStream(Stream stream, string key, string token, PutExtra extra) - { - HttpResult result = new HttpResult(); - - if (stream.Length > this.config.PutThreshold) - { - ResumableUploader resumeUploader = new ResumableUploader(this.config); - result = resumeUploader.UploadStream(stream, key, token, extra); - } - else - { - FormUploader formUploader = new FormUploader(this.config); - result = formUploader.UploadStream(stream, key, token, extra); - } - - return result; - } - } -} diff --git a/src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/Storage/UploadProgressHandler.cs b/src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/Storage/UploadProgressHandler.cs deleted file mode 100644 index 8c5e7be..0000000 --- a/src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/Storage/UploadProgressHandler.cs +++ /dev/null @@ -1,9 +0,0 @@ -namespace Qiniu.Storage -{ - /// - /// 分片上传进度处理 - /// - /// 已上传的字节数 - /// 文件总字节数 - public delegate void UploadProgressHandler(long uploadedBytes, long totalBytes); -} diff --git a/src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/Storage/Zone.cs b/src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/Storage/Zone.cs deleted file mode 100644 index 63b1702..0000000 --- a/src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/Storage/Zone.cs +++ /dev/null @@ -1,107 +0,0 @@ -namespace Qiniu.Storage -{ - /// - /// 目前已支持的区域:华东/华北/华南/北美/新加坡 - /// - public class Zone - { - /// - /// 资源管理 - /// - public string RsHost { set; get; } - - /// - /// 源列表 - /// - public string RsfHost { set; get; } - - /// - /// 数据处理 - /// - public string ApiHost { set; get; } - - /// - /// 镜像刷新、资源抓取 - /// - public string IovipHost { set; get; } - - /// - /// 资源上传 - /// - public string[] SrcUpHosts { set; get; } - - /// - /// CDN加速 - /// - public string[] CdnUpHosts { set; get; } - - /// - /// 华东 - /// - public static Zone ZONE_CN_East = new Zone() - { - RsHost = "rs.qbox.me", - RsfHost = "rsf.qbox.me", - ApiHost = "api.qiniu.com", - IovipHost = "iovip.qbox.me", - SrcUpHosts = new string[] { "up.qiniup.com", - "up-nb.qiniup.com", "up-xs.qiniup.com" }, - CdnUpHosts = new string[] { "upload.qiniup.com", - "upload-nb.qiniup.com", "upload-xs.qiniup.com" } - }; - - /// - /// 华北 - /// - public static Zone ZONE_CN_North = new Zone() - { - RsHost = "rs-z1.qbox.me", - RsfHost = "rsf-z1.qbox.me", - ApiHost = "api-z1.qiniu.com", - IovipHost = "iovip-z1.qbox.me", - SrcUpHosts = new string[] { "up-z1.qiniup.com" }, - CdnUpHosts = new string[] { "upload-z1.qiniup.com" } - }; - - /// - /// 华南 - /// - public static Zone ZONE_CN_South = new Zone() - { - RsHost = "rs-z2.qbox.me", - RsfHost = "rsf-z2.qbox.me", - ApiHost = "api-z2.qiniu.com", - IovipHost = "iovip-z2.qbox.me", - SrcUpHosts = new string[] { "up-z2.qiniup.com", - "up-gz.qiniup.com", "up-fs.qiniup.com" }, - CdnUpHosts = new string[] { "upload-z2.qiniup.com", - "upload-gz.qiniup.com", "upload-fs.qiniup.com" } - }; - - /// - /// 北美 - /// - public static Zone ZONE_US_North = new Zone() - { - RsHost = "rs-na0.qbox.me", - RsfHost = "rsf-na0.qbox.me", - ApiHost = "api-na0.qiniu.com", - IovipHost = "iovip-na0.qbox.me", - SrcUpHosts = new string[] { "up-na0.qiniup.com" }, - CdnUpHosts = new string[] { "upload-na0.qiniup.com" } - }; - - /// - /// 新加坡 - /// - public static Zone ZONE_AS_Singapore = new Zone() - { - RsHost = "rs-as0.qbox.me", - RsfHost = "rsf-as0.qbox.me", - ApiHost = "api-as0.qiniu.com", - IovipHost = "iovip-as0.qbox.me", - SrcUpHosts = new string[] { "up-as0.qiniup.com" }, - CdnUpHosts = new string[] { "upload-as0.qiniup.com" } - }; - } -} diff --git a/src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/Storage/ZoneHelper.cs b/src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/Storage/ZoneHelper.cs deleted file mode 100644 index ebcc237..0000000 --- a/src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/Storage/ZoneHelper.cs +++ /dev/null @@ -1,123 +0,0 @@ -using System; -using System.Text; -using System.Collections.Generic; -using Qiniu.Http; -using Newtonsoft.Json; - -namespace Qiniu.Storage -{ - /// - /// Zone辅助类,查询及配置Zone - /// - public class ZoneHelper - { - private static Dictionary zoneCache = new Dictionary(); - private static object rwLock = new object(); - - /// - /// 从uc.qbox.me查询得到回复后,解析出upHost,然后根据upHost确定Zone - /// - /// AccessKek - /// 空间名称 - public static Zone QueryZone(string accessKey, string bucket) - { - Zone zone = null; - - string cacheKey = string.Format("{0}:{1}", accessKey, bucket); - - //check from cache - lock (rwLock) - { - if (zoneCache.ContainsKey(cacheKey)) - { - zone = zoneCache[cacheKey]; - } - } - - if (zone != null) - { - return zone; - } - - //query from uc api - HttpResult hr = null; - try - { - string queryUrl = string.Format("https://uc.qbox.me/v2/query?ak={0}&bucket={1}", accessKey, bucket); - HttpManager httpManager = new HttpManager(); - hr = httpManager.Get(queryUrl, null); - if (hr.Code == (int)HttpCode.OK) - { - ZoneInfo zInfo = JsonConvert.DeserializeObject(hr.Text); - if (zInfo != null) - { - zone = new Zone(); - zone.SrcUpHosts = zInfo.Up.Src.Main; - zone.CdnUpHosts = zInfo.Up.Acc.Main; - zone.IovipHost = zInfo.Io.Src.Main[0]; - if (zone.IovipHost.Contains("z1")) - { - zone.ApiHost = "api-z1.qiniu.com"; - zone.RsHost = "rs-z1.qiniu.com"; - zone.RsfHost = "rsf-z1.qiniu.com"; - } - else if (zone.IovipHost.Contains("z2")) - { - zone.ApiHost = "api-z2.qiniu.com"; - zone.RsHost = "rs-z2.qiniu.com"; - zone.RsfHost = "rsf-z2.qiniu.com"; - } - else if (zone.IovipHost.Contains("na0")) - { - zone.ApiHost = "api-na0.qiniu.com"; - zone.RsHost = "rs-na0.qiniu.com"; - zone.RsfHost = "rsf-na0.qiniu.com"; - } - else if (zone.IovipHost.Contains("as0")) - { - zone.ApiHost = "api-as0.qiniu.com"; - zone.RsHost = "rs-as0.qiniu.com"; - zone.RsfHost = "rsf-as0.qiniu.com"; - } - else - { - zone.ApiHost = "api.qiniu.com"; - zone.RsHost = "rs.qiniu.com"; - zone.RsfHost = "rsf.qiniu.com"; - } - - lock (rwLock) - { - zoneCache[cacheKey] = zone; - } - } - else - { - throw new Exception("JSON Deserialize failed: " + hr.Text); - } - } - else - { - throw new Exception("code: " + hr.Code + ", text: " + hr.Text + ", ref-text:" + hr.RefText); - } - } - catch (Exception ex) - { - StringBuilder sb = new StringBuilder(); - sb.AppendFormat("[{0}] QueryZone Error: ", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.ffff")); - Exception e = ex; - while (e != null) - { - sb.Append(e.Message + " "); - e = e.InnerException; - } - sb.AppendLine(); - - throw new QiniuException(hr, sb.ToString()); - } - - return zone; - } - } - -} diff --git a/src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/Storage/ZoneInfo.cs b/src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/Storage/ZoneInfo.cs deleted file mode 100644 index 395acad..0000000 --- a/src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/Storage/ZoneInfo.cs +++ /dev/null @@ -1,36 +0,0 @@ -namespace Qiniu.Storage -{ - /// - /// 从uc.qbox.me返回的消息 - /// - internal class ZoneInfo - { - public int Ttl { get; set; } - public Io Io { set; get; } - public Up Up { set; get; } - } - - internal class Io - { - public Src Src { set; get; } - } - - internal class Src - { - public string[] Main { set; get; } - } - - internal class Up - { - public UpDomain Acc { set; get; } - public UpDomain OldAcc { set; get; } - public UpDomain Src { set; get; } - public UpDomain OldSrc { set; get; } - } - internal class UpDomain - { - public string[] Main { set; get; } - public string[] Backup { set; get; } - public string Info { set; get; } - } -} diff --git a/src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/Util/Auth.cs b/src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/Util/Auth.cs deleted file mode 100644 index 0fe4934..0000000 --- a/src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/Util/Auth.cs +++ /dev/null @@ -1,161 +0,0 @@ -namespace Qiniu.Util -{ - /// - /// Authentication/Authorization - /// - public class Auth - { - private Signature signature; - - /// - /// 一般初始化 - /// - /// 账号(密钥) - public Auth(Mac mac) - { - signature = new Signature(mac); - } - - /// - /// 生成管理凭证 - /// 有关管理凭证请参阅 - /// http://developer.qiniu.com/article/developer/security/access-token.html - /// - /// 请求的URL - /// 请求的主体内容 - /// 生成的管理凭证 - public string CreateManageToken(string url,byte[] body) - { - return string.Format("QBox {0}", signature.SignRequest(url, body)); - } - - /// - /// 生成管理凭证-不包含body - /// - /// 请求的URL - /// 生成的管理凭证 - public string CreateManageToken(string url) - { - return CreateManageToken(url, null); - } - - /// - /// 生成上传凭证 - /// - /// 上传策略对应的JSON字符串 - /// 生成的上传凭证 - public string CreateUploadToken(string jsonStr) - { - return signature.SignWithData(jsonStr); - } - - /// - /// 生成下载凭证 - /// - /// 原始链接 - /// - public string CreateDownloadToken(string url) - { - return signature.Sign(url); - } - - /// - /// 生成推流地址使用的凭证 - /// - /// - /// - public string CreateStreamPublishToken(string path) - { - return signature.Sign(path); - } - - /// - /// 生成流管理凭证 - /// - /// - /// - public string CreateStreamManageToken(string data) - { - return string.Format("Qiniu {0}", signature.SignWithData(data)); - } - - #region STATIC - - /// - /// 生成管理凭证 - /// 有关管理凭证请参阅 - /// http://developer.qiniu.com/article/developer/security/access-token.html - /// - /// 账号(密钥) - /// 访问的URL - /// 请求的body - /// 生成的管理凭证 - public static string CreateManageToken(Mac mac, string url, byte[] body) - { - Signature sx = new Signature(mac); - return string.Format("QBox {0}", sx.SignRequest(url, body)); - } - - /// - /// 生成管理凭证-不包含body - /// - /// 账号(密钥) - /// 请求的URL - /// 生成的管理凭证 - public static string CreateManageToken(Mac mac, string url) - { - return CreateManageToken(mac, url, null); - } - - /// - /// 生成上传凭证 - /// - /// 账号(密钥) - /// 上传策略JSON串 - /// 生成的上传凭证 - public static string CreateUploadToken(Mac mac, string jsonBody) - { - Signature sx = new Signature(mac); - return sx.SignWithData(jsonBody); - } - - /// - /// 生成下载凭证 - /// - /// 账号(密钥) - /// 原始链接 - /// - public static string CreateDownloadToken(Mac mac, string url) - { - Signature sx = new Signature(mac); - return sx.Sign(url); - } - - /// - /// 生成推流地址使用的凭证 - /// - /// 账号(密钥) - /// URL路径 - /// - public static string CreateStreamPublishToken(Mac mac,string path) - { - Signature sx = new Signature(mac); - return sx.Sign(path); - } - - /// - /// 生成流管理凭证 - /// - /// 账号(密钥) - /// 待签数据 - /// - public static string CreateStreamManageToken(Mac mac, string data) - { - Signature sx = new Signature(mac); - return string.Format("Qiniu {0}", sx.Sign(data)); - } - - #endregion STATIC - - } -} diff --git a/src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/Util/Base64.cs b/src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/Util/Base64.cs deleted file mode 100644 index bdc0552..0000000 --- a/src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/Util/Base64.cs +++ /dev/null @@ -1,67 +0,0 @@ -using System; -using System.Text; - -namespace Qiniu.Util -{ - /// - /// Base64 编码/解码 - /// - public class Base64 - { - /// - /// 获取字符串Url安全Base64编码值 - /// - /// 源字符串 - /// 已编码字符串 - public static string UrlSafeBase64Encode(string text) - { - return UrlSafeBase64Encode(Encoding.UTF8.GetBytes(text)); - } - - /// - /// URL安全的base64编码 - /// - /// 需要编码的字节数据 - /// - public static string UrlSafeBase64Encode(byte[] data) - { - return Convert.ToBase64String(data).Replace('+', '-').Replace('/', '_'); - } - - /// - /// bucket:key 编码 - /// - /// 空间名称 - /// 文件key - /// 编码 - public static string UrlSafeBase64Encode(string bucket, string key) - { - return UrlSafeBase64Encode(bucket + ":" + key); - } - - /// - /// Base64解码 - /// - /// 待解码的字符串 - /// 已解码字符串 - public static byte[] UrlsafeBase64Decode(string text) - { - return Convert.FromBase64String(text.Replace('-', '+').Replace('_', '/')); - } - - /// - /// 获取EncodedObjectName - /// - /// 待加密的字符串 - /// 已加密的字符串 - public static string GetEncodedObjectName(string key) - { - string encodedObjectName = "~"; - if (!string.IsNullOrEmpty(key)) - { - encodedObjectName = UrlSafeBase64Encode(key); - } - return encodedObjectName; - } - } -} diff --git a/src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/Util/CRC32.cs b/src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/Util/CRC32.cs deleted file mode 100644 index d488265..0000000 --- a/src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/Util/CRC32.cs +++ /dev/null @@ -1,133 +0,0 @@ -using System; -using System.IO; - -namespace Qiniu.Util -{ - /// - /// CRC32计算器 - /// - public class CRC32 - { - /// - /// magic - /// - public const uint IEEE = 0xedb88320; - private uint[] Table; - private uint Value; - - /// - /// 初始化 - /// - public CRC32() - { - Value = 0; - Table = makeTable(IEEE); - } - - /// - /// 写入 - /// - /// 字节数据 - /// 偏移位置 - /// 字节数 - public void Write(byte[] p, int offset, int count) - { - this.Value = Update(this.Value, this.Table, p, offset, count); - } - - /// - /// 校验和 - /// - /// 校验和 - public uint Sum() - { - return this.Value; - } - - private static uint[] makeTable(uint poly) - { - uint[] table = new uint[256]; - for (int i = 0; i < 256; i++) - { - uint crc = (uint)i; - for (int j = 0; j < 8; j++) - { - if ((crc & 1) == 1) - crc = (crc >> 1) ^ poly; - else - crc >>= 1; - } - table[i] = crc; - } - return table; - } - - /// - /// 更新 - /// - /// crc32 - /// 表 - /// 字节数据 - /// 偏移位置 - /// 字节数 - /// - public static uint Update(UInt32 crc, UInt32[] table, byte[] p, int offset, int count) - { - crc = ~crc; - for (int i = 0; i < count; i++) - { - crc = table[((byte)crc) ^ p[offset + i]] ^ (crc >> 8); - } - return ~crc; - } - - /// - /// 计算字节数据的crc32值 - /// - /// 二进制数据 - /// crc32值 - public static uint CheckSumBytes(byte[] data) - { - CRC32 crc = new CRC32(); - crc.Write(data, 0, data.Length); - return crc.Sum(); - } - - /// - /// 检验 - /// - /// 字节数据 - /// 偏移位置 - /// 字节数 - /// - public static uint CheckSumSlice(byte[] data, int offset, int count) - { - CRC32 crc = new CRC32(); - crc.Write(data, offset, count); - return crc.Sum(); - } - - /// - /// 计算沙盒文件的crc32值 - /// - /// 沙盒文件全路径 - /// crc32值 - public static uint checkSumFile(string filePath) - { - CRC32 crc = new CRC32(); - int bufferLen = 32 * 1024; - using (FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read)) - { - byte[] buffer = new byte[bufferLen]; - while (true) - { - int n = fs.Read(buffer, 0, bufferLen); - if (n == 0) - break; - crc.Write(buffer, 0, n); - } - } - return crc.Sum(); - } - } -} \ No newline at end of file diff --git a/src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/Util/ETag.cs b/src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/Util/ETag.cs deleted file mode 100644 index 2b57f95..0000000 --- a/src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/Util/ETag.cs +++ /dev/null @@ -1,73 +0,0 @@ -using System; -using System.IO; - -namespace Qiniu.Util -{ - /// - /// QINIU ETAG(文件hash) - /// - public class ETag - { - // 块大小(固定为4MB) - private const int BLOCK_SIZE = 4 * 1024 * 1024; - - // 计算时以20B为单位 - private static int BLOCK_SHA1_SIZE = 20; - - /// - /// 计算文件hash(ETAG) - /// - /// - /// 文件hash - public static string CalcHash(string filePath) - { - string qetag = ""; - - try - { - using (FileStream stream = new FileStream(filePath, FileMode.Open, FileAccess.Read)) - { - long fileLength = stream.Length; - byte[] buffer = new byte[BLOCK_SIZE]; - byte[] finalBuffer = new byte[BLOCK_SHA1_SIZE + 1]; - if (fileLength <= BLOCK_SIZE) - { - int readByteCount = stream.Read(buffer, 0, BLOCK_SIZE); - byte[] readBuffer = new byte[readByteCount]; - Array.Copy(buffer, readBuffer, readByteCount); - - byte[] sha1Buffer = Hashing.CalcSHA1(readBuffer); - - finalBuffer[0] = 0x16; - Array.Copy(sha1Buffer, 0, finalBuffer, 1, sha1Buffer.Length); - } - else - { - long blockCount = (fileLength % BLOCK_SIZE == 0) ? (fileLength / BLOCK_SIZE) : (fileLength / BLOCK_SIZE + 1); - byte[] sha1AllBuffer = new byte[BLOCK_SHA1_SIZE * blockCount]; - - for (int i = 0; i < blockCount; i++) - { - int readByteCount = stream.Read(buffer, 0, BLOCK_SIZE); - byte[] readBuffer = new byte[readByteCount]; - Array.Copy(buffer, readBuffer, readByteCount); - - byte[] sha1Buffer = Hashing.CalcSHA1(readBuffer); - Array.Copy(sha1Buffer, 0, sha1AllBuffer, i * BLOCK_SHA1_SIZE, sha1Buffer.Length); - } - - byte[] sha1AllBufferSha1 = Hashing.CalcSHA1(sha1AllBuffer); - - finalBuffer[0] = 0x96; - Array.Copy(sha1AllBufferSha1, 0, finalBuffer, 1, sha1AllBufferSha1.Length); - - } - qetag = Base64.UrlSafeBase64Encode(finalBuffer); - } - } - catch (Exception) { } - - return qetag; - } - } -} \ No newline at end of file diff --git a/src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/Util/Hashing.cs b/src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/Util/Hashing.cs deleted file mode 100644 index a1933bb..0000000 --- a/src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/Util/Hashing.cs +++ /dev/null @@ -1,76 +0,0 @@ -using System.Text; -#if WINDOWS_UWP -using Windows.Security.Cryptography; -using Windows.Security.Cryptography.Core; -#else -using System.Security.Cryptography; -#endif - -namespace Qiniu.Util -{ - /// - /// 计算hash值 - /// 特别注意,不同平台使用的Cryptography可能略有不同,使用中如有遇到问题,请反馈 - /// 提交您的issue到 https://github.com/qiniu/csharp-sdk - /// - public class Hashing - { - /// - /// 计算SHA1 - /// - /// 字节数据 - /// SHA1 - public static byte[] CalcSHA1(byte[] data) - { -#if WINDOWS_UWP - var sha = HashAlgorithmProvider.OpenAlgorithm(HashAlgorithmNames.Sha1); - var buf = CryptographicBuffer.CreateFromByteArray(data); - var digest = sha.HashData(buf); - var hashBytes = new byte[digest.Length]; - CryptographicBuffer.CopyToByteArray(digest, out hashBytes); - return hashBytes; -#else - SHA1 sha1 = SHA1.Create(); - return sha1.ComputeHash(data); -#endif - } - - /// - /// 计算MD5哈希(可能需要关闭FIPS) - /// - /// 待计算的字符串 - /// MD5结果 - public static string CalcMD5(string str) - { -#if WINDOWS_UWP - var md5 = HashAlgorithmProvider.OpenAlgorithm(HashAlgorithmNames.Md5); - var buf = CryptographicBuffer.ConvertStringToBinary(str, BinaryStringEncoding.Utf8); - var digest = md5.HashData(buf); - return CryptographicBuffer.EncodeToHexString(digest); -#else - MD5 md5 = MD5.Create(); - byte[] data = Encoding.UTF8.GetBytes(str); - byte[] hashData = md5.ComputeHash(data); - StringBuilder sb = new StringBuilder(hashData.Length * 2); - foreach (byte b in hashData) - { - sb.AppendFormat("{0:x2}", b); - } - return sb.ToString(); -#endif - } - - /// - /// 计算MD5哈希(第三方实现) - /// - /// 待计算的字符串,避免FIPS-Exception - /// MD5结果 - public static string CalcMD5X(string str) - { - byte[] data = Encoding.UTF8.GetBytes(str); - LabMD5 md5 = new LabMD5(); - return md5.ComputeHash(data); - } - - } -} diff --git a/src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/Util/LabMD5.cs b/src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/Util/LabMD5.cs deleted file mode 100644 index 23e77af..0000000 --- a/src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/Util/LabMD5.cs +++ /dev/null @@ -1,272 +0,0 @@ -using System.Security.Cryptography; -namespace Qiniu.Util -{ - /// - /// MD5算法的3rdParty实现 - /// 参考https://github.com/Dozer74/MD5 - /// - public class LabMD5 - { - #region Helper - - private sealed class Digest - { - public uint A; - public uint B; - public uint C; - public uint D; - - public Digest() - { - A = 0x67452301; - B = 0xEFCDAB89; - C = 0x98BADCFE; - D = 0X10325476; - } - - public override string ToString() - { - string st; - st = BitHelper.ReverseByte(A).ToString("x8") + - BitHelper.ReverseByte(B).ToString("x8") + - BitHelper.ReverseByte(C).ToString("x8") + - BitHelper.ReverseByte(D).ToString("x8"); - return st; - } - } - - private static class BitHelper - { - /// - /// rotate - /// - /// num - /// shift - /// - public static uint RotateLeft(uint num, ushort shift) - { - return (num >> (32 - shift)) | (num << shift); - } - - /// - /// reverse - /// - public static uint ReverseByte(uint num) - { - return ((num & 0x000000ff) << 24) | - (num >> 24) | - ((num & 0x00ff0000) >> 8) | - ((num & 0x0000ff00) << 8); - } - } - - #endregion Helper - - #region Table - - /// - /// table 4294967296*sin(i) - /// - private static readonly uint[] T = - { - 0xd76aa478, 0xe8c7b756, 0x242070db, 0xc1bdceee, - 0xf57c0faf, 0x4787c62a, 0xa8304613, 0xfd469501, - 0x698098d8, 0x8b44f7af, 0xffff5bb1, 0x895cd7be, - 0x6b901122, 0xfd987193, 0xa679438e, 0x49b40821, - 0xf61e2562, 0xc040b340, 0x265e5a51, 0xe9b6c7aa, - 0xd62f105d, 0x2441453, 0xd8a1e681, 0xe7d3fbc8, - 0x21e1cde6, 0xc33707d6, 0xf4d50d87, 0x455a14ed, - 0xa9e3e905, 0xfcefa3f8, 0x676f02d9, 0x8d2a4c8a, - 0xfffa3942, 0x8771f681, 0x6d9d6122, 0xfde5380c, - 0xa4beea44, 0x4bdecfa9, 0xf6bb4b60, 0xbebfbc70, - 0x289b7ec6, 0xeaa127fa, 0xd4ef3085, 0x4881d05, - 0xd9d4d039, 0xe6db99e5, 0x1fa27cf8, 0xc4ac5665, - 0xf4292244, 0x432aff97, 0xab9423a7, 0xfc93a039, - 0x655b59c3, 0x8f0ccc92, 0xffeff47d, 0x85845dd1, - 0x6fa87e4f, 0xfe2ce6e0, 0xa3014314, 0x4e0811a1, - 0xf7537e82, 0xbd3af235, 0x2ad7d2bb, 0xeb86d391 - }; - - #endregion Table - - private uint[] X = new uint[16]; - - /// - /// ComputeHash - /// - public string ComputeHash(byte[] bytes) - { - var dg = new Digest(); - var bMsg = CreatePaddedBuffer(bytes); - - var mesLength = (uint)(bMsg.Length * 8) / 32; - - for (uint i = 0; i < mesLength / 16; i++) - { - CopyBlock(bMsg, i); - Transform(ref dg.A, ref dg.B, ref dg.C, ref dg.D); - } - return dg.ToString(); - } - - private void Transform(ref uint A, ref uint B, ref uint C, ref uint D) - { - var AA = A; - var BB = B; - var CC = C; - var DD = D; - - /* Round 1 */ - F(ref A, B, C, D, 0, 7, 1); - F(ref D, A, B, C, 1, 12, 2); - F(ref C, D, A, B, 2, 17, 3); - F(ref B, C, D, A, 3, 22, 4); - F(ref A, B, C, D, 4, 7, 5); - F(ref D, A, B, C, 5, 12, 6); - F(ref C, D, A, B, 6, 17, 7); - F(ref B, C, D, A, 7, 22, 8); - F(ref A, B, C, D, 8, 7, 9); - F(ref D, A, B, C, 9, 12, 10); - F(ref C, D, A, B, 10, 17, 11); - F(ref B, C, D, A, 11, 22, 12); - F(ref A, B, C, D, 12, 7, 13); - F(ref D, A, B, C, 13, 12, 14); - F(ref C, D, A, B, 14, 17, 15); - F(ref B, C, D, A, 15, 22, 16); - - /* Round 2 */ - G(ref A, B, C, D, 1, 5, 17); - G(ref D, A, B, C, 6, 9, 18); - G(ref C, D, A, B, 11, 14, 19); - G(ref B, C, D, A, 0, 20, 20); - G(ref A, B, C, D, 5, 5, 21); - G(ref D, A, B, C, 10, 9, 22); - G(ref C, D, A, B, 15, 14, 23); - G(ref B, C, D, A, 4, 20, 24); - G(ref A, B, C, D, 9, 5, 25); - G(ref D, A, B, C, 14, 9, 26); - G(ref C, D, A, B, 3, 14, 27); - G(ref B, C, D, A, 8, 20, 28); - G(ref A, B, C, D, 13, 5, 29); - G(ref D, A, B, C, 2, 9, 30); - G(ref C, D, A, B, 7, 14, 31); - G(ref B, C, D, A, 12, 20, 32); - - /* Round 3 */ - H(ref A, B, C, D, 5, 4, 33); - H(ref D, A, B, C, 8, 11, 34); - H(ref C, D, A, B, 11, 16, 35); - H(ref B, C, D, A, 14, 23, 36); - H(ref A, B, C, D, 1, 4, 37); - H(ref D, A, B, C, 4, 11, 38); - H(ref C, D, A, B, 7, 16, 39); - H(ref B, C, D, A, 10, 23, 40); - H(ref A, B, C, D, 13, 4, 41); - H(ref D, A, B, C, 0, 11, 42); - H(ref C, D, A, B, 3, 16, 43); - H(ref B, C, D, A, 6, 23, 44); - H(ref A, B, C, D, 9, 4, 45); - H(ref D, A, B, C, 12, 11, 46); - H(ref C, D, A, B, 15, 16, 47); - H(ref B, C, D, A, 2, 23, 48); - - /* Round 4 */ - I(ref A, B, C, D, 0, 6, 49); - I(ref D, A, B, C, 7, 10, 50); - I(ref C, D, A, B, 14, 15, 51); - I(ref B, C, D, A, 5, 21, 52); - I(ref A, B, C, D, 12, 6, 53); - I(ref D, A, B, C, 3, 10, 54); - I(ref C, D, A, B, 10, 15, 55); - I(ref B, C, D, A, 1, 21, 56); - I(ref A, B, C, D, 8, 6, 57); - I(ref D, A, B, C, 15, 10, 58); - I(ref C, D, A, B, 6, 15, 59); - I(ref B, C, D, A, 13, 21, 60); - I(ref A, B, C, D, 4, 6, 61); - I(ref D, A, B, C, 11, 10, 62); - I(ref C, D, A, B, 2, 15, 63); - I(ref B, C, D, A, 9, 21, 64); - - A = A + AA; - B = B + BB; - C = C + CC; - D = D + DD; - } - - private byte[] CreatePaddedBuffer(byte[] mes) - { - var padSize = 448 - mes.Length * 8 % 512; - - - var pad = (uint)((padSize + 512) % 512); - if (pad == 0) pad = 512; - - var sizeMsgBuff = (uint)(mes.Length + pad / 8 + 8); - var sizeMsg = (ulong)mes.Length * 8; - var bMsg = new byte[sizeMsgBuff]; - - for (var i = 0; i < mes.Length; i++) - bMsg[i] = mes[i]; - - bMsg[mes.Length] |= 0x80; - - for (var i = 8; i > 0; i--) - bMsg[sizeMsgBuff - i] = (byte)((sizeMsg >> ((8 - i) * 8)) & 0x00000000000000ff); - return bMsg; - } - - private void CopyBlock(byte[] bMsg, uint block) - { - block = block << 6; - for (uint j = 0; j < 61; j += 4) - X[j >> 2] = ((uint)bMsg[block + j + 3] << 24) | - ((uint)bMsg[block + j + 2] << 16) | - ((uint)bMsg[block + j + 1] << 8) | - bMsg[block + j]; - } - - #region Transform - - private void F(ref uint a, uint b, uint c, uint d, uint k, ushort s, uint i) - { - a = b + BitHelper.RotateLeft(a + ((b & c) | (~b & d)) + X[k] + T[i - 1], s); - } - - private void G(ref uint a, uint b, uint c, uint d, uint k, ushort s, uint i) - { - a = b + BitHelper.RotateLeft(a + ((b & d) | (c & ~d)) + X[k] + T[i - 1], s); - } - - private void H(ref uint a, uint b, uint c, uint d, uint k, ushort s, uint i) - { - a = b + BitHelper.RotateLeft(a + (b ^ c ^ d) + X[k] + T[i - 1], s); - } - - private void I(ref uint a, uint b, uint c, uint d, uint k, ushort s, uint i) - { - a = b + BitHelper.RotateLeft(a + (c ^ (b | ~d)) + X[k] + T[i - 1], s); - } - - #endregion Transform - - /// - /// 计算字节数据md5值 - /// - /// 字节数据 - /// 偏移位置 - /// 字节数 - /// - public static string GenerateMD5(byte[] data) - { - MD5 md5 = MD5.Create(); - byte[] md5buffer = md5.ComputeHash(data); - string str = null; - foreach (byte b in md5buffer) - { - str += b.ToString("x2"); - } - return str; - } - } -} \ No newline at end of file diff --git a/src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/Util/Mac.cs b/src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/Util/Mac.cs deleted file mode 100644 index 69c59ac..0000000 --- a/src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/Util/Mac.cs +++ /dev/null @@ -1,29 +0,0 @@ -namespace Qiniu.Util -{ - /// - /// 账户访问控制(密钥) - /// - public class Mac - { - /// - /// 密钥-AccessKey - /// - public string AccessKey { set; get; } - - /// - /// 密钥-SecretKey - /// - public string SecretKey { set; get; } - - /// - /// 初始化密钥AK/SK - /// - /// AccessKey - /// SecretKey - public Mac(string accessKey, string secretKey) - { - this.AccessKey = accessKey; - this.SecretKey = secretKey; - } - } -} \ No newline at end of file diff --git a/src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/Util/QETag.cs b/src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/Util/QETag.cs deleted file mode 100644 index 9bd8f1b..0000000 --- a/src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/Util/QETag.cs +++ /dev/null @@ -1,73 +0,0 @@ -using System; -using System.IO; - -namespace Qiniu.Util -{ - /// - /// QINIU ETAG(文件hash) - /// - public class QETag - { - // 块大小(固定为4MB) - private const int BLOCK_SIZE = 4 * 1024 * 1024; - - // 计算时以20B为单位 - private static int BLOCK_SHA1_SIZE = 20; - - /// - /// 计算文件hash(ETAG) - /// - /// - /// 文件hash - public static string calcHash(string filePath) - { - string qetag = ""; - - try - { - using (FileStream stream = new FileStream(filePath, FileMode.Open, FileAccess.Read)) - { - long fileLength = stream.Length; - byte[] buffer = new byte[BLOCK_SIZE]; - byte[] finalBuffer = new byte[BLOCK_SHA1_SIZE + 1]; - if (fileLength <= BLOCK_SIZE) - { - int readByteCount = stream.Read(buffer, 0, BLOCK_SIZE); - byte[] readBuffer = new byte[readByteCount]; - Array.Copy(buffer, readBuffer, readByteCount); - - byte[] sha1Buffer = Hashing.CalcSHA1(readBuffer); - - finalBuffer[0] = 0x16; - Array.Copy(sha1Buffer, 0, finalBuffer, 1, sha1Buffer.Length); - } - else - { - long blockCount = (fileLength % BLOCK_SIZE == 0) ? (fileLength / BLOCK_SIZE) : (fileLength / BLOCK_SIZE + 1); - byte[] sha1AllBuffer = new byte[BLOCK_SHA1_SIZE * blockCount]; - - for (int i = 0; i < blockCount; i++) - { - int readByteCount = stream.Read(buffer, 0, BLOCK_SIZE); - byte[] readBuffer = new byte[readByteCount]; - Array.Copy(buffer, readBuffer, readByteCount); - - byte[] sha1Buffer = Hashing.CalcSHA1(readBuffer); - Array.Copy(sha1Buffer, 0, sha1AllBuffer, i * BLOCK_SHA1_SIZE, sha1Buffer.Length); - } - - byte[] sha1AllBufferSha1 = Hashing.CalcSHA1(sha1AllBuffer); - - finalBuffer[0] = 0x96; - Array.Copy(sha1AllBufferSha1, 0, finalBuffer, 1, sha1AllBufferSha1.Length); - - } - qetag = Base64.UrlSafeBase64Encode(finalBuffer); - } - } - catch (Exception) { } - - return qetag; - } - } -} \ No newline at end of file diff --git a/src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/Util/Signature.cs b/src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/Util/Signature.cs deleted file mode 100644 index 37919a6..0000000 --- a/src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/Util/Signature.cs +++ /dev/null @@ -1,126 +0,0 @@ -using System; -using System.IO; -#if WINDOWS_UWP -using Windows.Security.Cryptography; -using Windows.Security.Cryptography.Core; -#else -using System.Security.Cryptography; -#endif -using System.Text; - -namespace Qiniu.Util -{ - /// - /// 签名/加密 - /// 特别注意,不同平台使用的Cryptography可能略有不同,使用中如有遇到问题,请反馈 - /// 提交您的issue到 https://github.com/qiniu/csharp-sdk - /// - public class Signature - { - private Mac mac; - - /// - /// 初始化 - /// - /// 账号(密钥) - public Signature(Mac mac) - { - this.mac = mac; - } - - private string encodedSign(byte[] data) - { - HMACSHA1 hmac = new HMACSHA1(Encoding.UTF8.GetBytes(mac.SecretKey)); - byte[] digest = hmac.ComputeHash(data); - return Base64.UrlSafeBase64Encode(digest); - } - - private string encodedSign(string str) - { - byte[] data = Encoding.UTF8.GetBytes(str); - return encodedSign(data); - } - - /// - /// 签名-字节数据 - /// - /// 待签名的数据 - /// - public string Sign(byte[] data) - { - return string.Format("{0}:{1}", mac.AccessKey, encodedSign(data)); - } - - /// - /// 签名-字符串数据 - /// - /// 待签名的数据 - /// - public string Sign(string str) - { - byte[] data = Encoding.UTF8.GetBytes(str); - return Sign(data); - } - - /// - /// 附带数据的签名 - /// - /// 待签名的数据 - /// - public string SignWithData(byte[] data) - { - string sstr = Base64.UrlSafeBase64Encode(data); - return string.Format("{0}:{1}:{2}", mac.AccessKey, encodedSign(sstr), sstr); - } - - /// - /// 附带数据的签名 - /// - /// 待签名的数据 - /// 签名结果 - public string SignWithData(string str) - { - byte[] data = Encoding.UTF8.GetBytes(str); - return SignWithData(data); - } - - /// - /// HTTP请求签名 - /// - /// 请求目标的URL - /// 请求的主体数据 - /// - public string SignRequest(string url, byte[] body) - { - Uri u = new Uri(url); - string pathAndQuery = u.PathAndQuery; - byte[] pathAndQueryBytes = Encoding.UTF8.GetBytes(pathAndQuery); - - using (MemoryStream buffer = new MemoryStream()) - { - buffer.Write(pathAndQueryBytes, 0, pathAndQueryBytes.Length); - buffer.WriteByte((byte)'\n'); - if (body != null && body.Length > 0) - { - buffer.Write(body, 0, body.Length); - } - HMACSHA1 hmac = new HMACSHA1(Encoding.UTF8.GetBytes(mac.SecretKey)); - byte[] digest = hmac.ComputeHash(buffer.ToArray()); - string digestBase64 = Base64.UrlSafeBase64Encode(digest); - return string.Format("{0}:{1}", mac.AccessKey, digestBase64); - } - } - - /// - /// HTTP请求签名 - /// - /// 请求目标的URL - /// 请求的主体数据 - /// - public string SignRequest(string url, string body) - { - byte[] data = Encoding.UTF8.GetBytes(body); - return SignRequest(url, data); - } - } -} diff --git a/src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/Util/StringHelper.cs b/src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/Util/StringHelper.cs deleted file mode 100644 index 5b5621d..0000000 --- a/src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/Util/StringHelper.cs +++ /dev/null @@ -1,42 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Text; - -namespace Qiniu.Util -{ - /// - /// 字符串处理工具 - /// - public class StringHelper - { - - - /// - /// URL编码 - /// - /// 源字符串 - /// URL编码字符串 - public static string UrlEncode(string text) - { - return Uri.EscapeDataString(text); - } - - /// - /// URL键值对编码 - /// - /// 键值对 - /// URL编码的键值对数据 - public static string UrlFormEncode(Dictionary values) - { - StringBuilder urlValuesBuilder = new StringBuilder(); - - foreach (KeyValuePair kvp in values) - { - urlValuesBuilder.AppendFormat("{0}={1}&", Uri.EscapeDataString(kvp.Key), Uri.EscapeDataString(kvp.Value)); - } - string encodedStr=urlValuesBuilder.ToString(); - return encodedStr.Substring(0, encodedStr.Length - 1); - } - - } -} \ No newline at end of file diff --git a/src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/Util/UnixTimestamp.cs b/src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/Util/UnixTimestamp.cs deleted file mode 100644 index 099cb81..0000000 --- a/src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/Util/UnixTimestamp.cs +++ /dev/null @@ -1,88 +0,0 @@ -using System; - -namespace Qiniu.Util -{ - /// - /// 时间戳与日期时间转换 - /// - public class UnixTimestamp - { - /// - /// 基准时间 - /// - private static DateTime dtBase = new DateTime(1970, 1, 1).ToLocalTime(); - - /// - /// 时间戳末尾7位(补0或截断) - /// - private const long TICK_BASE = 10000000; - - /// - /// 从现在(调用此函数时刻)起若干秒以后那个时间点的时间戳 - /// - /// 从现在起多少秒以后 - /// Unix时间戳 - public static long GetUnixTimestamp(long secondsAfterNow) - { - DateTime dt = DateTime.Now.AddSeconds(secondsAfterNow).ToLocalTime(); - TimeSpan tsx = dt.Subtract(dtBase); - return tsx.Ticks / TICK_BASE; - } - - /// - /// 日期时间转换为时间戳 - /// - /// 日期时间 - /// 时间戳 - public static long ConvertToTimestamp(DateTime dt) - { - TimeSpan tsx = dt.Subtract(dtBase); - return tsx.Ticks / TICK_BASE; - } - - /// - /// 从UNIX时间戳转换为DateTime - /// - /// 时间戳字符串 - /// 日期时间 - public static DateTime ConvertToDateTime(string timestamp) - { - long ticks = long.Parse(timestamp) * TICK_BASE; - return dtBase.AddTicks(ticks); - } - - /// - /// 从UNIX时间戳转换为DateTime - /// - /// 时间戳 - /// 日期时间 - public static DateTime ConvertToDateTime(long timestamp) - { - long ticks = timestamp * TICK_BASE; - return dtBase.AddTicks(ticks); - } - - /// - /// 检查Ctx是否过期,我们给当前时间加上一天来看看是否超过了过期时间 - /// 而不是直接比较是否超过了过期时间,是给这个文件最大1天的上传持续时间 - /// - /// - /// - public static bool IsContextExpired(long expiredAt) - { - if (expiredAt == 0) - { - return false; - } - bool expired = false; - DateTime now = DateTime.Now.AddDays(1); - long nowTs = ConvertToTimestamp(now); - if (nowTs > expiredAt) - { - expired = true; - } - return expired; - } - - } -} diff --git a/src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/Util/UpToken.cs b/src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/Util/UpToken.cs deleted file mode 100644 index afecdc8..0000000 --- a/src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/Util/UpToken.cs +++ /dev/null @@ -1,58 +0,0 @@ -using System; -using System.Text; -using Newtonsoft.Json; -using Qiniu.Storage; -namespace Qiniu.Util -{ - /// - /// 上传凭证工具类 - /// - public class UpToken - { - /// - /// 从上传凭证获取AccessKey - /// - /// 上传凭证 - /// AccessKey - public static string GetAccessKeyFromUpToken(string upToken) - { - string accessKey = null; - string[] items = upToken.Split(':'); - if (items.Length == 3) - { - accessKey = items[0]; - } - return accessKey; - } - - /// - /// 从上传凭证获取Bucket - /// - /// 上传凭证 - /// Bucket - public static string GetBucketFromUpToken(string upToken) - { - string bucket = null; - string[] items = upToken.Split(':'); - if (items.Length == 3) - { - string encodedPolicy = items[2]; - try - { - string policyStr = Encoding.UTF8.GetString(Base64.UrlsafeBase64Decode(encodedPolicy)); - PutPolicy putPolicy = JsonConvert.DeserializeObject(policyStr); - string scope = putPolicy.Scope; - string[] scopeItems = scope.Split(':'); - if (scopeItems.Length >= 1) - { - bucket = scopeItems[0]; - } - }catch(Exception) - { - - } - } - return bucket; - } - } -} diff --git a/src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/Util/UrlHelper.cs b/src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/Util/UrlHelper.cs deleted file mode 100644 index b9982d3..0000000 --- a/src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/Util/UrlHelper.cs +++ /dev/null @@ -1,110 +0,0 @@ -using System.Text.RegularExpressions; - -namespace Qiniu.Util -{ - /// - /// URL辅助工具(RegExp) - /// - public class UrlHelper - { - private static Regex regx = new Regex(@"(http|https):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?^=%&:/~\+#]*[\w\-\@?^=%&/~\+#])?"); - - private static Regex regu = new Regex(@"(http|https):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\.,/~\+#]*)?"); - - private static Regex regd = new Regex(@"(http|https):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\.,/~\+#]*)?/"); - - /// - /// 是否合法URL - /// - /// 待判断的url - /// - public static bool IsValidUrl(string _url) - { - return regx.IsMatch(_url); - } - - /// - /// 是否一般URL(不包含?等后缀参数) - /// - /// 待判断的url - /// - public static bool IsNormalUrl(string _url) - { - return regu.IsMatch(_url); - } - - /// - /// 是否合法URL目录 - /// - /// 待判断的url目录 - /// - public static bool IsValidDir(string _dir) - { - return regd.IsMatch(_dir); - } - - /// - /// 从原始URL转换为一般URL(根据需要截断) - /// - /// 待转换的url - /// - public static string GetNormalUrl(string _url) - { - var m = regu.Match(_url); - return m.Value; - } - - /// - /// URL分析,拆分出Host,Path,File,Query各个部分 - /// - /// 原始URL - /// host部分 - /// path部分 - /// 文件名 - /// 参数 - public static void UrlSplit(string url, out string host, out string path, out string file, out string query) - { - host = ""; - path = ""; - file = ""; - query = ""; - - if(string.IsNullOrEmpty(url)) - { - return; - } - - int start = 0; - - try - { - Regex regHost = new Regex(@"(http|https):\/\/[\w\-_]+(\.[\w\-_]+)+"); - host = regHost.Match(url, start).Value; - start += host.Length; - - Regex regPath = new Regex(@"(/(\w|\-)*)+/"); - path = regPath.Match(url, start).Value; - if (!string.IsNullOrEmpty(path)) - { - start += path.Length; - } - - int index = url.IndexOf('?', start); - if (index > 0) - { - file = url.Substring(start, index - start); - query = url.Substring(index); - } - else - { - file = url.Substring(start); - query = ""; - } - } - catch(System.Exception) - { - // - } - } - } -} diff --git a/src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/Util/UserEnv.cs b/src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/Util/UserEnv.cs deleted file mode 100644 index 4559299..0000000 --- a/src/src/OnceMi.AspNetCore.OSS/SDK/Qiniu/Util/UserEnv.cs +++ /dev/null @@ -1,111 +0,0 @@ -using System; - -#if WINDOWS_UWP -using System.Threading.Tasks; -using Windows.Storage; -#else -using System.IO; -#endif - -namespace Qiniu.Util -{ - /// - /// 环境变量-用户路径 - /// - public class UserEnv - { - -#if Net20 || Net35 || Net40 || Net45 || Net46 - - /// - /// 找到QHome目录(在用户目录下建立的"QHome"文件夹) - /// - /// QHOME路径 - public static string GetHomeFolder() - { - // Windows下Home目录 = %HOMEDRIVE% + %HOMEPATH% - string homeDir = Environment.GetEnvironmentVariable("HOMEDRIVE") + Environment.GetEnvironmentVariable("HOMEPATH"); - - if (string.IsNullOrEmpty(homeDir)) - { - // 如果获取失败,就设置为当前路径 - homeDir = Path.GetFullPath("."); - } - - string homeFolder = Path.Combine(homeDir, "QHome"); - - if(!Directory.Exists(homeFolder)) - { - Directory.CreateDirectory(homeFolder); - } - - return homeFolder; - } - -#elif NetCore - - /// - /// 找到QHome目录(在用户目录下建立的"QHome"文件夹) - /// - /// QHOME路径 - public static string GetHomeFolder() - { - // Windows下Home目录 = %HOMEDRIVE% + %HOMEPATH% - string homeDir = Environment.GetEnvironmentVariable("HOMEDRIVE") + Environment.GetEnvironmentVariable("HOMEPATH"); - - // OSX/Ubuntu下Home目录 = $HOME - if (string.IsNullOrEmpty(homeDir)) - { - homeDir = Environment.GetEnvironmentVariable("HOME"); - } - - if (string.IsNullOrEmpty(homeDir)) - { - // 如果获取失败,就设置为当前路径 - homeDir = Path.GetFullPath("."); - } - - string homeFolder = Path.Combine(homeDir, "QHome"); - - if(!Directory.Exists(homeFolder)) - { - Directory.CreateDirectory(homeFolder); - } - - return homeFolder; - } - -#elif WINDOWS_UWP - - /// - /// 找到QHome目录(在"应用缓存"目录下建立的"QHome"文件夹) - /// - /// QHOME路径 - public static async Task GetHomeFolderAsync() - { - return await ApplicationData.Current.LocalCacheFolder.CreateFolderAsync("QHome", CreationCollisionOption.OpenIfExists); - //return await KnownFolders.DocumentsLibrary.CreateFolderAsync("QHome", CreationCollisionOption.OpenIfExists); - } - -#else - - /// - /// 找到QHome目录(在当前目录下建立的"QHome"文件夹) - /// - /// QHOME路径 - public static string GetHomeFolder() - { - //当前路径 - string homeFolder = Path.GetFullPath("./QHome"); - - if(!Directory.Exists(homeFolder)) - { - Directory.CreateDirectory(homeFolder); - } - return homeFolder; - } - -#endif - - } -}