├── src
├── pack
│ ├── clear.bat
│ ├── nuget.exe
│ ├── pack.bat
│ ├── pack.Magicodes.Storage.Core.bat
│ ├── pack.Magicodes.Storage.Abp.Core.bat
│ ├── pack.Magicodes.Storage.Local.Core.bat
│ ├── pack.Magicodes.Storage.Tencent.Core.bat
│ └── pack.Magicodes.Storage.AliyunOss.Core.bat
├── Magicodes.Storage.Tests
│ ├── Res
│ │ └── img.jpg
│ ├── Helper
│ │ └── ConfigHelper.cs
│ ├── Magicodes.Storage.Tests.csproj
│ ├── TestBase.cs
│ ├── AliyunOssStorageTest.cs
│ ├── TencentStorageTests.cs
│ └── LocalStorageTests.cs
├── Magicodes.Storage.Core
│ ├── BlobUrlAccess.cs
│ ├── Extentions.cs
│ ├── Magicodes.Storage.Core.csproj
│ ├── Helper
│ │ ├── EnumHelper.cs
│ │ ├── EncryptHelper.cs
│ │ └── DateTimeHelper.cs
│ ├── StorageError.cs
│ ├── StorageException.cs
│ ├── BlobFileInfo.cs
│ ├── IStorageProvider.cs
│ └── StorageErrorCode.cs
├── Magicodes.Storage.Abp.Core
│ ├── IStorageManager.cs
│ ├── StorageModule.cs
│ ├── Magicodes.Storage.Abp.Core.csproj
│ └── StorageManager.cs
├── Magicodes.Storage.Local.Core
│ ├── LocalStorageConfig.cs
│ ├── Magicodes.Storage.Local.Core.csproj
│ ├── LocalStorageProvider.cs
│ └── MimeInfo.cs
├── Magicodes.Storage.Tencent.Core
│ ├── Magicodes.Storage.Tencent.Core.csproj
│ ├── TencentCosConfig.cs
│ ├── Extentions.cs
│ └── TencentStorageProvider.cs
├── Magicodes.Storage.AliyunOss.Core
│ ├── AliyunOssConfig.cs
│ ├── Magicodes.Storage.AliyunOss.Core.csproj
│ ├── Extentions.cs
│ └── AliyunOssStorageProvider.cs
├── Magicodes.Storage
│ ├── BlobSecurity.cs
│ ├── StorageError.cs
│ ├── BlobUrlAccess.cs
│ ├── BlobProperties.cs
│ ├── StorageErrorCode.cs
│ ├── StorageException.cs
│ ├── Properties
│ │ └── AssemblyInfo.cs
│ ├── BlobDescriptor.cs
│ ├── Extentions.cs
│ ├── Magicodes.Storage.csproj
│ ├── NullStorageProvider.cs
│ ├── AsyncHelpers.cs
│ └── IStorageProvider.cs
└── Magicodes.Storage.sln
├── README.md
├── res
├── 1.png
├── 2.png
├── 3.png
├── 4.png
├── 5.png
└── wechat.jpg
├── .gitignore
└── LICENSE
/src/pack/clear.bat:
--------------------------------------------------------------------------------
1 | cd ./nupkgs/
2 | del *.nupkg /f /q /a
3 | cd ../
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/xin-lai/Magicodes.Storage/HEAD/README.md
--------------------------------------------------------------------------------
/res/1.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/xin-lai/Magicodes.Storage/HEAD/res/1.png
--------------------------------------------------------------------------------
/res/2.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/xin-lai/Magicodes.Storage/HEAD/res/2.png
--------------------------------------------------------------------------------
/res/3.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/xin-lai/Magicodes.Storage/HEAD/res/3.png
--------------------------------------------------------------------------------
/res/4.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/xin-lai/Magicodes.Storage/HEAD/res/4.png
--------------------------------------------------------------------------------
/res/5.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/xin-lai/Magicodes.Storage/HEAD/res/5.png
--------------------------------------------------------------------------------
/res/wechat.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/xin-lai/Magicodes.Storage/HEAD/res/wechat.jpg
--------------------------------------------------------------------------------
/src/pack/nuget.exe:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/xin-lai/Magicodes.Storage/HEAD/src/pack/nuget.exe
--------------------------------------------------------------------------------
/src/pack/pack.bat:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/xin-lai/Magicodes.Storage/HEAD/src/pack/pack.bat
--------------------------------------------------------------------------------
/src/Magicodes.Storage.Tests/Res/img.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/xin-lai/Magicodes.Storage/HEAD/src/Magicodes.Storage.Tests/Res/img.jpg
--------------------------------------------------------------------------------
/src/pack/pack.Magicodes.Storage.Core.bat:
--------------------------------------------------------------------------------
1 | call ./pack.bat "Magicodes.Storage.Core.*.nupkg" "../Magicodes.Storage.Core/Magicodes.Storage.Core.csproj"
2 | @pause
3 |
4 |
--------------------------------------------------------------------------------
/src/pack/pack.Magicodes.Storage.Abp.Core.bat:
--------------------------------------------------------------------------------
1 | call ./pack.bat "Magicodes.Storage.Abp.Core.*.nupkg" "../Magicodes.Storage.Abp.Core/Magicodes.Storage.Abp.Core.csproj"
2 | @pause
--------------------------------------------------------------------------------
/src/pack/pack.Magicodes.Storage.Local.Core.bat:
--------------------------------------------------------------------------------
1 | call ./pack.bat "Magicodes.Storage.Local.Core.*.nupkg" "../Magicodes.Storage.Local.Core/Magicodes.Storage.Local.Core.csproj"
2 | @pause
3 |
4 |
--------------------------------------------------------------------------------
/src/pack/pack.Magicodes.Storage.Tencent.Core.bat:
--------------------------------------------------------------------------------
1 | call ./pack.bat "Magicodes.Storage.Tencent.Core.*.nupkg" "../Magicodes.Storage.Tencent.Core/Magicodes.Storage.Tencent.Core.csproj"
2 | @pause
--------------------------------------------------------------------------------
/src/pack/pack.Magicodes.Storage.AliyunOss.Core.bat:
--------------------------------------------------------------------------------
1 | call ./pack.bat "Magicodes.Storage.AliyunOss.Core.*.nupkg" "../Magicodes.Storage.AliyunOss.Core/Magicodes.Storage.AliyunOss.Core.csproj"
2 | @pause
--------------------------------------------------------------------------------
/src/Magicodes.Storage.Core/BlobUrlAccess.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Text;
4 |
5 | namespace Magicodes.Storage.Core
6 | {
7 | ///
8 | /// 容器地址访问类型(允许多个状态组合)
9 | ///
10 | [Flags]
11 | public enum BlobUrlAccess
12 | {
13 | None = 0,
14 | Read = 1,
15 | Write = 2,
16 | Delete = 4,
17 | All = Read | Write | Delete
18 | }
19 | }
20 |
--------------------------------------------------------------------------------
/src/Magicodes.Storage.Abp.Core/IStorageManager.cs:
--------------------------------------------------------------------------------
1 | using Abp;
2 | using Abp.Dependency;
3 | using Magicodes.Storage.Core;
4 | using System;
5 | using System.Collections.Generic;
6 | using System.Text;
7 |
8 | namespace Magicodes.Storage.Abp.Core
9 | {
10 | public interface IStorageManager : ISingletonDependency, IShouldInitialize
11 | {
12 | ///
13 | /// 存储提供程序
14 | ///
15 | IStorageProvider StorageProvider { get; set; }
16 | }
17 | }
18 |
--------------------------------------------------------------------------------
/src/Magicodes.Storage.Local.Core/LocalStorageConfig.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Text;
4 |
5 | namespace Magicodes.Storage.Local.Core
6 | {
7 | public class LocalStorageConfig
8 | {
9 | ///
10 | /// 根目录
11 | ///
12 | public string RootPath { get; set; }
13 |
14 | ///
15 | /// 根Url
16 | ///
17 | public string RootUrl { get; set; }
18 | }
19 | }
20 |
--------------------------------------------------------------------------------
/src/Magicodes.Storage.Tencent.Core/Magicodes.Storage.Tencent.Core.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | netcoreapp2.0
5 | 1.1.0
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
--------------------------------------------------------------------------------
/src/Magicodes.Storage.Abp.Core/StorageModule.cs:
--------------------------------------------------------------------------------
1 | using Abp.Modules;
2 | using Abp.Reflection.Extensions;
3 | using System;
4 |
5 | namespace Magicodes.Storage.Abp.Core
6 | {
7 | public class StorageModule : AbpModule
8 | {
9 | public override void PreInitialize()
10 | {
11 | }
12 |
13 | public override void Initialize()
14 | {
15 | IocManager.RegisterAssemblyByConvention(typeof(StorageModule).GetAssembly());
16 | }
17 |
18 | public override void PostInitialize()
19 | {
20 | }
21 | }
22 | }
23 |
--------------------------------------------------------------------------------
/src/Magicodes.Storage.AliyunOss.Core/AliyunOssConfig.cs:
--------------------------------------------------------------------------------
1 | namespace Magicodes.Storage.AliyunOss.Core
2 | {
3 | public class AliyunOssConfig
4 | {
5 | ///
6 | /// OSS的访问ID
7 | ///
8 | public string AccessKeyId { get; set; }
9 |
10 | ///
11 | /// OSS的访问密钥
12 | ///
13 | public string AccessKeySecret { get; set; }
14 |
15 | ///
16 | /// OSS的访问地址
17 | ///
18 | public string Endpoint { get; set; }
19 |
20 | ///
21 | /// 存储桶名称
22 | ///
23 | public string BucketName { get; set; }
24 | }
25 | }
26 |
--------------------------------------------------------------------------------
/src/Magicodes.Storage.Core/Extentions.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Text;
4 | using Magicodes.Storage.Core.Helper;
5 |
6 | namespace Magicodes.Storage.Core
7 | {
8 | ///
9 | /// 扩展方法
10 | ///
11 | public static class Extentions
12 | {
13 | ///
14 | /// 根据错误类型返回错误异常
15 | ///
16 | ///
17 | ///
18 | public static StorageError ToStorageError(this StorageErrorCode code) => new StorageError()
19 | {
20 | Code = (int)code,
21 | Message = code.GetDisplayContent()
22 | };
23 | }
24 | }
25 |
--------------------------------------------------------------------------------
/src/Magicodes.Storage/BlobSecurity.cs:
--------------------------------------------------------------------------------
1 | // ======================================================================
2 | //
3 | // Copyright (C) 2016-2020 湖南心莱信息科技有限公司
4 | // All rights reserved
5 | //
6 | // filename : BlobSecurity.cs
7 | // description :
8 | //
9 | // created by 李文强 at 2016/09/23 9:41
10 | // Blog:http://www.cnblogs.com/codelove/
11 | // GitHub : https://github.com/xin-lai
12 | // Home:http://xin-lai.com
13 | //
14 | // ======================================================================
15 |
16 | namespace Magicodes.Storage
17 | {
18 | public enum BlobSecurity
19 | {
20 | Private,
21 | Public
22 | }
23 | }
--------------------------------------------------------------------------------
/src/Magicodes.Storage/StorageError.cs:
--------------------------------------------------------------------------------
1 | // ======================================================================
2 | //
3 | // Copyright (C) 2016-2020 湖南心莱信息科技有限公司
4 | // All rights reserved
5 | //
6 | // filename : StorageError.cs
7 | // description :
8 | //
9 | // created by 李文强 at 2016/09/23 9:41
10 | // Blog:http://www.cnblogs.com/codelove/
11 | // GitHub : https://github.com/xin-lai
12 | // Home:http://xin-lai.com
13 | //
14 | // ======================================================================
15 |
16 | namespace Magicodes.Storage
17 | {
18 | public class StorageError
19 | {
20 | public int Code { get; set; }
21 |
22 | public string Message { get; set; }
23 |
24 | public string ProviderMessage { get; set; }
25 | }
26 | }
--------------------------------------------------------------------------------
/src/Magicodes.Storage.Abp.Core/Magicodes.Storage.Abp.Core.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | netcoreapp3.1
5 | 0.0.2
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
--------------------------------------------------------------------------------
/src/Magicodes.Storage/BlobUrlAccess.cs:
--------------------------------------------------------------------------------
1 | // ======================================================================
2 | //
3 | // Copyright (C) 2016-2020 湖南心莱信息科技有限公司
4 | // All rights reserved
5 | //
6 | // filename : BlobUrlAccess.cs
7 | // description :
8 | //
9 | // created by 李文强 at 2016/09/23 9:41
10 | // Blog:http://www.cnblogs.com/codelove/
11 | // GitHub : https://github.com/xin-lai
12 | // Home:http://xin-lai.com
13 | //
14 | // ======================================================================
15 |
16 | using System;
17 |
18 | namespace Magicodes.Storage
19 | {
20 | ///
21 | /// 容器地址访问类型(允许多个状态组合)
22 | ///
23 | [Flags]
24 | public enum BlobUrlAccess
25 | {
26 | None = 0,
27 | Read = 1,
28 | Write = 2,
29 | Delete = 4,
30 | All = Read | Write | Delete
31 | }
32 | }
--------------------------------------------------------------------------------
/src/Magicodes.Storage/BlobProperties.cs:
--------------------------------------------------------------------------------
1 | // ======================================================================
2 | //
3 | // Copyright (C) 2016-2020 湖南心莱信息科技有限公司
4 | // All rights reserved
5 | //
6 | // filename : BlobProperties.cs
7 | // description :
8 | //
9 | // created by 李文强 at 2016/09/23 9:41
10 | // Blog:http://www.cnblogs.com/codelove/
11 | // GitHub : https://github.com/xin-lai
12 | // Home:http://xin-lai.com
13 | //
14 | // ======================================================================
15 |
16 | namespace Magicodes.Storage
17 | {
18 | public class BlobProperties
19 | {
20 | public static readonly BlobProperties Empty = new BlobProperties
21 | {
22 | Security = BlobSecurity.Private
23 | };
24 |
25 | public BlobSecurity Security { get; set; }
26 |
27 | public string ContentType { get; set; }
28 | }
29 | }
--------------------------------------------------------------------------------
/src/Magicodes.Storage/StorageErrorCode.cs:
--------------------------------------------------------------------------------
1 | // ======================================================================
2 | //
3 | // Copyright (C) 2016-2020 湖南心莱信息科技有限公司
4 | // All rights reserved
5 | //
6 | // filename : StorageErrorCode.cs
7 | // description :
8 | //
9 | // created by 李文强 at 2016/09/23 9:41
10 | // Blog:http://www.cnblogs.com/codelove/
11 | // GitHub : https://github.com/xin-lai
12 | // Home:http://xin-lai.com
13 | //
14 | // ======================================================================
15 |
16 | namespace Magicodes.Storage
17 | {
18 | public enum StorageErrorCode
19 | {
20 | None = 0,
21 | InvalidCredentials = 1000,
22 | GenericException = 1001,
23 | InvalidAccess = 1002,
24 | BlobInUse = 1003,
25 | InvalidBlobName = 1004,
26 | InvalidContainerName = 1005,
27 | ErrorOpeningBlob = 1006,
28 | NoCredentialsProvided = 1007
29 | }
30 | }
--------------------------------------------------------------------------------
/src/Magicodes.Storage/StorageException.cs:
--------------------------------------------------------------------------------
1 | // ======================================================================
2 | //
3 | // Copyright (C) 2016-2020 湖南心莱信息科技有限公司
4 | // All rights reserved
5 | //
6 | // filename : StorageException.cs
7 | // description :
8 | //
9 | // created by 李文强 at 2016/09/23 9:41
10 | // Blog:http://www.cnblogs.com/codelove/
11 | // GitHub : https://github.com/xin-lai
12 | // Home:http://xin-lai.com
13 | //
14 | // ======================================================================
15 |
16 | using System;
17 |
18 | namespace Magicodes.Storage
19 | {
20 | public class StorageException : Exception
21 | {
22 | public StorageException(StorageError error, Exception ex) : base(error.Message, ex)
23 | {
24 | ErrorCode = error.Code;
25 | ProviderMessage = ex?.Message;
26 | }
27 |
28 | public int ErrorCode { get; private set; }
29 |
30 | public string ProviderMessage { get; set; }
31 | }
32 | }
--------------------------------------------------------------------------------
/src/Magicodes.Storage.AliyunOss.Core/Magicodes.Storage.AliyunOss.Core.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | netcoreapp2.0
5 | Magicodes.Storage.Core为湖南心莱信息科技有限公司封装的存储通用库,以便扩展支持本地存储、Azure存储等,支持.NET Core。其中,Magicodes.Storage.AliyunOss.Core为本地存储。\n官方网址:http://xin-lai.com \n开源库地址:https://github.com/xin-lai \n博客地址:http://www.cnblogs.com/codelove/ \n交流QQ群(.NET 技术交流群):85318032 \n关注公众号“magiccodes”以获取最新资讯和教程。
6 | https://github.com/xin-lai
7 | https://github.com/xin-lai
8 | Magicodes.Storage.AliyunOss.Core
9 | true
10 | 1.0.2
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
--------------------------------------------------------------------------------
/src/Magicodes.Storage.Local.Core/Magicodes.Storage.Local.Core.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | netstandard2.0
5 | Magicodes.Storage.Core为湖南心莱信息科技有限公司封装的存储通用库,以便扩展支持本地存储、Azure存储等,支持.NET Core。其中,Magicodes.Storage.Local.Core为本地存储。\n官方网址:http://xin-lai.com \n开源库地址:https://github.com/xin-lai \n博客地址:http://www.cnblogs.com/codelove/ \n交流QQ群(.NET 技术交流群):85318032 \n小店地址:https://shop113059108.taobao.com/
6 | https://github.com/xin-lai
7 | https://github.com/xin-lai
8 | Magicodes.Storage.Local.Core
9 |
10 |
11 | bin\$(Configuration)\$(TargetFramework)\$(AssemblyName).xml
12 | 2.0.2
13 | true
14 |
15 |
16 |
17 |
18 |
--------------------------------------------------------------------------------
/src/Magicodes.Storage.Core/Magicodes.Storage.Core.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 | netstandard2.0
4 | 湖南心莱信息科技有限公司
5 | Magicodes.Storage.Core为湖南心莱信息科技有限公司封装的存储通用库,以便扩展支持本地存储、Azure存储等,支持.NET Core。\n官方网址:http://xin-lai.com \n开源库地址:https://github.com/xin-lai \n博客地址:http://www.cnblogs.com/codelove/ \n交流QQ群(.NET 技术交流群):85318032 \n小店地址:https://shop113059108.taobao.com/
6 | Copyright © 2018
7 | http://xin-lai.com
8 | https://github.com/xin-lai
9 | Magicodes.Storage.Core
10 | Magicodes.Storage.Core
11 |
12 |
13 | bin\$(Configuration)\$(TargetFramework)\$(AssemblyName).xml
14 | 2.0.1
15 | true
16 |
17 |
18 |
19 |
20 |
--------------------------------------------------------------------------------
/src/Magicodes.Storage.Core/Helper/EnumHelper.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.ComponentModel.DataAnnotations;
4 | using System.Reflection;
5 | using System.Text;
6 |
7 | namespace Magicodes.Storage.Core.Helper
8 | {
9 | ///
10 | /// 枚举帮助类
11 | ///
12 | public static class EnumHelper
13 | {
14 | ///
15 | /// 获取枚举的显示内容
16 | ///
17 | /// 枚举
18 | /// 返回枚举的描述
19 | public static string GetDisplayContent(this Enum en)
20 | {
21 | var type = en.GetType(); //获取类型
22 | var memberInfos = type.GetMember(en.ToString()); //获取成员
23 | if (memberInfos != null && memberInfos.Length > 0)
24 | {
25 | //获取特性
26 | if (memberInfos[0].GetCustomAttributes(typeof(DisplayAttribute), false) is DisplayAttribute[] attrs && attrs.Length > 0)
27 | {
28 | return attrs[0].Name ?? attrs[0].Description; //返回当前名称
29 | }
30 | }
31 | return en.ToString();
32 | }
33 | }
34 | }
35 |
--------------------------------------------------------------------------------
/src/Magicodes.Storage.Core/StorageError.cs:
--------------------------------------------------------------------------------
1 | // ======================================================================
2 | //
3 | // Copyright (C) 2016-2020 湖南心莱信息科技有限公司
4 | // All rights reserved
5 | //
6 | // filename : StorageError.cs
7 | // description :
8 | //
9 | // created by 李文强 at 2018/03/25 9:41
10 | // Blog:http://www.cnblogs.com/codelove/
11 | // GitHub : https://github.com/xin-lai
12 | // Home:http://xin-lai.com
13 | // 交流QQ群(.NET 技术交流群):85318032
14 | //
15 | // ======================================================================
16 |
17 | using Magicodes.Storage.Core.Helper;
18 |
19 | namespace Magicodes.Storage.Core
20 | {
21 | ///
22 | /// 错误
23 | ///
24 | public class StorageError
25 | {
26 | ///
27 | /// 错误码
28 | ///
29 | public int Code { get; set; }
30 |
31 | ///
32 | /// 错误消息
33 | ///
34 | public string Message { get; set; }
35 |
36 | ///
37 | /// 处理程序错误消息
38 | ///
39 | public string ProviderMessage { get; set; }
40 | }
41 | }
--------------------------------------------------------------------------------
/src/Magicodes.Storage.Core/Helper/EncryptHelper.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Security.Cryptography;
5 | using System.Text;
6 |
7 | namespace Magicodes.Storage.Core.Helper
8 | {
9 | ///
10 | /// 加密帮助类
11 | ///
12 | public class EncryptHelper
13 | {
14 | ///
15 | /// 对明文进行SHA1加密
16 | ///
17 | /// 明文
18 | ///
19 | public static string HashSHA1(string content)
20 | {
21 | var buff = SHA1.Create().ComputeHash(Encoding.UTF8.GetBytes(content));
22 | return string.Concat(buff.Select(k => k.ToString("x2")));
23 | }
24 |
25 | ///
26 | /// 对明文进行SHA加密
27 | ///
28 | /// 加密秘钥key
29 | /// 待加密明文
30 | ///
31 | public static string HashHMACSHA1(string key, string content)
32 | {
33 | var buff = new HMACSHA1(Encoding.UTF8.GetBytes(key)).ComputeHash(Encoding.UTF8.GetBytes(content));
34 | return string.Concat(buff.Select(k => k.ToString("x2")));
35 | }
36 | }
37 | }
38 |
--------------------------------------------------------------------------------
/src/Magicodes.Storage.Core/StorageException.cs:
--------------------------------------------------------------------------------
1 | // ======================================================================
2 | //
3 | // Copyright (C) 2016-2020 湖南心莱信息科技有限公司
4 | // All rights reserved
5 | //
6 | // filename : StorageException.cs
7 | // description :
8 | //
9 | // created by 李文强 at 2018/03/25 9:41
10 | // Blog:http://www.cnblogs.com/codelove/
11 | // GitHub : https://github.com/xin-lai
12 | // Home:http://xin-lai.com
13 | // 交流QQ群(.NET 技术交流群):85318032
14 | //
15 | // ======================================================================
16 |
17 | using System;
18 |
19 | namespace Magicodes.Storage.Core
20 | {
21 | ///
22 | ///
23 | ///
24 | public class StorageException : Exception
25 | {
26 | public StorageException(StorageError error, Exception ex) : base(error.Message, ex)
27 | {
28 | ErrorCode = error.Code;
29 | ProviderMessage = ex?.Message;
30 | }
31 |
32 | ///
33 | /// 错误码
34 | ///
35 | public int ErrorCode { get; private set; }
36 |
37 | ///
38 | /// 提供程序消息
39 | ///
40 | public string ProviderMessage { get; set; }
41 | }
42 | }
--------------------------------------------------------------------------------
/src/Magicodes.Storage.Tests/Helper/ConfigHelper.cs:
--------------------------------------------------------------------------------
1 | // ======================================================================
2 | //
3 | // Copyright (C) 2018-2020 湖南心莱信息科技有限公司
4 | // All rights reserved
5 | //
6 | // filename : ConfigHelper.cs
7 | // description :
8 | //
9 | // created by 雪雁 at 2018-12-11 21:45
10 | // Mail: wenqiang.li@xin-lai.com
11 | // QQ群:85318032(技术交流)
12 | // Blog:http://www.cnblogs.com/codelove/
13 | // GitHub:https://github.com/xin-lai
14 | // Home:http://xin-lai.com
15 | //
16 | // ======================================================================
17 |
18 | using System.IO;
19 | using System.Text;
20 | using Newtonsoft.Json;
21 |
22 | namespace Magicodes.Storage.Tests.Helper
23 | {
24 | public class ConfigHelper
25 | {
26 | public static T LoadConfig(string name) where T : class, new()
27 | {
28 | var config = new T();
29 | var filePath = Path.Combine(Directory.GetCurrentDirectory(), name + ".json");
30 | if (File.Exists(filePath))
31 | {
32 | config = JsonConvert.DeserializeObject(File.ReadAllText(filePath));
33 | }
34 | else
35 | {
36 | File.WriteAllText(filePath, JsonConvert.SerializeObject(config), Encoding.UTF8);
37 | }
38 |
39 | return config;
40 | }
41 | }
42 | }
--------------------------------------------------------------------------------
/src/Magicodes.Storage.Tencent.Core/TencentCosConfig.cs:
--------------------------------------------------------------------------------
1 | // ======================================================================
2 | //
3 | // Copyright (C) 2018-2020 湖南心莱信息科技有限公司
4 | // All rights reserved
5 | //
6 | // filename : TencentCosConfig.cs
7 | // description :
8 | //
9 | // created by 雪雁 at 2018-08-02 9:59
10 | // Mail: wenqiang.li@xin-lai.com
11 | // QQ群:85318032(技术交流)
12 | // Blog:http://www.cnblogs.com/codelove/
13 | // GitHub:https://github.com/xin-lai
14 | // Home:http://xin-lai.com
15 | //
16 | // ======================================================================
17 |
18 | namespace Magicodes.Storage.Tencent.Core
19 | {
20 | ///
21 | /// 腾讯云COS配置类
22 | ///
23 | public class TencentCosConfig
24 | {
25 | ///
26 | /// 应用ID。
27 | ///
28 | public string AppId { get; set; }
29 |
30 | ///
31 | /// 秘钥id
32 | ///
33 | public string SecretId { get; set; }
34 |
35 | ///
36 | /// 秘钥Key
37 | ///
38 | public string SecretKey { get; set; }
39 |
40 | ///
41 | /// 区域
42 | ///
43 | public string Region { get; set; } = "ap-guangzhou";
44 |
45 | ///
46 | /// 存储桶名称
47 | ///
48 | public string BucketName { get; set; }
49 | }
50 | }
--------------------------------------------------------------------------------
/src/Magicodes.Storage.Tencent.Core/Extentions.cs:
--------------------------------------------------------------------------------
1 | // ======================================================================
2 | //
3 | // Copyright (C) 2018-2020 湖南心莱信息科技有限公司
4 | // All rights reserved
5 | //
6 | // filename : Extentions.cs
7 | // description :
8 | //
9 | // created by 雪雁 at 2018-12-11 20:19
10 | // Mail: wenqiang.li@xin-lai.com
11 | // QQ群:85318032(技术交流)
12 | // Blog:http://www.cnblogs.com/codelove/
13 | // GitHub:https://github.com/xin-lai
14 | // Home:http://xin-lai.com
15 | //
16 | // ======================================================================
17 |
18 | using System;
19 | using System.Threading.Tasks;
20 | using COSXML.Model;
21 | using Magicodes.Storage.Core;
22 |
23 | namespace Magicodes.Storage.Tencent.Core
24 | {
25 | ///
26 | /// 扩展方法
27 | ///
28 | public static class Extentions
29 | {
30 | ///
31 | /// 根据错误类型返回错误异常
32 | ///
33 | ///
34 | public static Task HandlerError(this CosResult response, string friendlyMessage = null)
35 | {
36 | var code = (int)response.httpCode;
37 | if (code < 300 || code >= 600) return Task.FromResult(0);
38 |
39 | var message = response.httpMessage;
40 | throw new StorageException(
41 | new StorageError { Code = code, Message = friendlyMessage ?? message, ProviderMessage = message },
42 | new Exception($"腾讯云存储错误!"));
43 | }
44 | }
45 | }
--------------------------------------------------------------------------------
/src/Magicodes.Storage/Properties/AssemblyInfo.cs:
--------------------------------------------------------------------------------
1 | // ======================================================================
2 | //
3 | // Copyright (C) 2016-2020 湖南心莱信息科技有限公司
4 | // All rights reserved
5 | //
6 | // filename : AssemblyInfo.cs
7 | // description :
8 | //
9 | // created by 李文强 at 2016/09/23 9:41
10 | // Blog:http://www.cnblogs.com/codelove/
11 | // GitHub : https://github.com/xin-lai
12 | // Home:http://xin-lai.com
13 | //
14 | // ======================================================================
15 |
16 | using System.Reflection;
17 | using System.Runtime.InteropServices;
18 |
19 | // 有关程序集的一般信息由以下
20 | // 控制。更改这些特性值可修改
21 | // 与程序集关联的信息。
22 |
23 | [assembly: AssemblyTitle("Magicodes.Storage")]
24 | [assembly: AssemblyDescription("Magicodes存储提供程序核心库")]
25 | [assembly: AssemblyConfiguration("")]
26 | [assembly: AssemblyCompany("湖南心莱信息科技有限公司")]
27 | [assembly: AssemblyProduct("Magicodes.Storage")]
28 | [assembly: AssemblyCopyright("Copyright © 2016")]
29 | [assembly: AssemblyTrademark("")]
30 | [assembly: AssemblyCulture("")]
31 |
32 | //将 ComVisible 设置为 false 将使此程序集中的类型
33 | //对 COM 组件不可见。 如果需要从 COM 访问此程序集中的类型,
34 | //请将此类型的 ComVisible 特性设置为 true。
35 |
36 | [assembly: ComVisible(false)]
37 |
38 | // 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID
39 |
40 | [assembly: Guid("3c02cdbb-d19e-4113-a0ca-78ea9531b506")]
41 |
42 | // 程序集的版本信息由下列四个值组成:
43 | //
44 | // 主版本
45 | // 次版本
46 | // 生成号
47 | // 修订号
48 | //
49 | //可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值,
50 | // 方法是按如下所示使用“*”: :
51 | // [assembly: AssemblyVersion("1.0.*")]
52 |
53 | [assembly: AssemblyVersion("1.0.*")]
54 | //[assembly: AssemblyFileVersion("1.0.0.0")]
--------------------------------------------------------------------------------
/src/Magicodes.Storage.Core/Helper/DateTimeHelper.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Text;
4 |
5 | namespace Magicodes.Storage.Core.Helper
6 | {
7 |
8 |
9 | ///
10 | /// 日期时间帮助类
11 | ///
12 | public static class DateTimeHelper
13 | {
14 |
15 | ///
16 | /// 获取指定时间的Unix时间戳 10位
17 | ///
18 | ///
19 | public static long GetTimeStampTen(this DateTime date)
20 | {
21 | return (date.ToUniversalTime().Ticks - 621355968000000000) / 10000000;
22 | }
23 |
24 | ///
25 | /// 将时间戳转换为日期类型,并格式化
26 | ///
27 | ///
28 | ///
29 | private static string LongDateTimeToDateTimeString(this string longDateTime)
30 | {
31 | //用来格式化long类型时间的,声明的变量
32 | long unixDate;
33 | DateTime start;
34 | DateTime date;
35 | //ENd
36 |
37 | unixDate = long.Parse(longDateTime);
38 | start = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
39 | date = start.AddMilliseconds(unixDate).ToLocalTime();
40 | return date.ToString("yyyy-MM-dd HH:mm:ss");
41 | }
42 |
43 | ///
44 | /// 获取时间戳 13位
45 | ///
46 | ///
47 | public static long GetTimeStamp(this DateTime date)
48 | {
49 | TimeSpan ts = date.ToUniversalTime() - new DateTime(1970, 1, 1, 0, 0, 0, 0);
50 | return Convert.ToInt64(ts.TotalSeconds * 1000);
51 | }
52 | }
53 | }
54 |
--------------------------------------------------------------------------------
/src/Magicodes.Storage.Core/BlobFileInfo.cs:
--------------------------------------------------------------------------------
1 | // ======================================================================
2 | //
3 | // Copyright (C) 2016-2020 湖南心莱信息科技有限公司
4 | // All rights reserved
5 | //
6 | // filename : BlobDescriptor.cs
7 | // description :
8 | //
9 | // created by 李文强 at 2018/03/25 9:41
10 | // Blog:http://www.cnblogs.com/codelove/
11 | // GitHub : https://github.com/xin-lai
12 | // Home:http://xin-lai.com
13 | // 交流QQ群(.NET 技术交流群):85318032
14 | //
15 | // ======================================================================
16 |
17 | using System;
18 |
19 | namespace Magicodes.Storage.Core
20 | {
21 | ///
22 | /// 文件对象描述
23 | ///
24 | public class BlobFileInfo
25 | {
26 | ///
27 | /// 内容类型
28 | ///
29 | public string ContentType { get; set; }
30 |
31 | ///
32 | /// 内容MD5
33 | ///
34 | public string ContentMD5 { get; set; }
35 |
36 | public string ETag { get; set; }
37 |
38 | ///
39 | /// 大小
40 | ///
41 | public long Length { get; set; }
42 |
43 | ///
44 | /// 最后修改时间
45 | ///
46 | public DateTime? LastModified { get; set; }
47 |
48 | ///
49 | /// 名称
50 | ///
51 | public string Name { get; set; }
52 |
53 | ///
54 | /// 容器
55 | ///
56 | public string Container { get; set; }
57 |
58 | ///
59 | /// 路径
60 | ///
61 | public string Url { get; set; }
62 | }
63 | }
--------------------------------------------------------------------------------
/src/Magicodes.Storage.Tests/Magicodes.Storage.Tests.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | netcoreapp2.0
5 | Magicodes.Storage.Core为湖南心莱信息科技有限公司封装的存储通用库,以便扩展支持本地存储、Azure存储等,支持.NET Core。其中,Magicodes.Storage.Local.Core为本地存储。\n官方网址:http://xin-lai.com \n开源库地址:https://github.com/xin-lai \n博客地址:http://www.cnblogs.com/codelove/ \n交流QQ群(.NET 技术交流群):85318032 \n小店地址:https://shop113059108.taobao.com/
6 | https://github.com/xin-lai
7 | https://github.com/xin-lai
8 |
9 |
10 |
11 |
12 |
13 |
14 | all
15 | runtime; build; native; contentfiles; analyzers
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 | Always
28 |
29 |
30 |
31 |
--------------------------------------------------------------------------------
/src/Magicodes.Storage.Tests/TestBase.cs:
--------------------------------------------------------------------------------
1 | // ======================================================================
2 | //
3 | // Copyright (C) 2018-2020 湖南心莱信息科技有限公司
4 | // All rights reserved
5 | //
6 | // filename : TestBase.cs
7 | // description :
8 | //
9 | // created by 雪雁 at 2018-06-07 10:31
10 | // Mail: wenqiang.li@xin-lai.com
11 | // QQ群:85318032(技术交流)
12 | // Blog:http://www.cnblogs.com/codelove/
13 | // GitHub:https://github.com/xin-lai
14 | // Home:http://xin-lai.com
15 | //
16 | // ======================================================================
17 |
18 | using System;
19 | using System.IO;
20 | using System.Text;
21 | using Magicodes.Storage.Core;
22 |
23 | namespace Magicodes.Storage.Tests
24 | {
25 | public class TestBase
26 | {
27 | public TestBase()
28 | {
29 | //var path = Path.Combine(Directory.GetCurrentDirectory(), "demo.txt");
30 | //File.WriteAllText(path, "demo");
31 | var str = "demo";
32 | var array = Encoding.UTF8.GetBytes(str);
33 | TestStream = new MemoryStream(array);
34 | ContainerName = "magicodes";
35 | }
36 |
37 | protected IStorageProvider StorageProvider { get; set; }
38 |
39 | public Stream TestStream { get; set; }
40 |
41 | protected string ContainerName { get; set; }
42 |
43 | protected string GetTestFileName()
44 | {
45 | return Guid.NewGuid().ToString("N") + ".txt";
46 | }
47 |
48 | protected string GetTestContent()
49 | {
50 | return "Test";
51 | }
52 |
53 | protected string GetTestContainerName()
54 | {
55 | return Guid.NewGuid().ToString("N");
56 | }
57 | }
58 | }
--------------------------------------------------------------------------------
/src/Magicodes.Storage/BlobDescriptor.cs:
--------------------------------------------------------------------------------
1 | // ======================================================================
2 | //
3 | // Copyright (C) 2016-2020 湖南心莱信息科技有限公司
4 | // All rights reserved
5 | //
6 | // filename : BlobDescriptor.cs
7 | // description :
8 | //
9 | // created by 李文强 at 2016/09/23 9:41
10 | // Blog:http://www.cnblogs.com/codelove/
11 | // GitHub : https://github.com/xin-lai
12 | // Home:http://xin-lai.com
13 | //
14 | // ======================================================================
15 |
16 | using System;
17 |
18 | namespace Magicodes.Storage
19 | {
20 | ///
21 | /// 容器描述
22 | ///
23 | public class BlobDescriptor
24 | {
25 | ///
26 | /// 内容类型
27 | ///
28 | public string ContentType { get; set; }
29 |
30 | ///
31 | /// 内容MD5
32 | ///
33 | public string ContentMD5 { get; set; }
34 |
35 | public string ETag { get; set; }
36 |
37 | ///
38 | /// 大小
39 | ///
40 | public long Length { get; set; }
41 |
42 | ///
43 | /// 最后修改时间
44 | ///
45 | public DateTimeOffset? LastModified { get; set; }
46 |
47 | ///
48 | /// 安全设置类型
49 | ///
50 | public BlobSecurity Security { get; set; }
51 |
52 | ///
53 | /// 名称
54 | ///
55 | public string Name { get; set; }
56 |
57 | ///
58 | /// 容器
59 | ///
60 | public string Container { get; set; }
61 |
62 | ///
63 | /// 路径
64 | ///
65 | public string Url { get; set; }
66 | }
67 | }
--------------------------------------------------------------------------------
/src/Magicodes.Storage.AliyunOss.Core/Extentions.cs:
--------------------------------------------------------------------------------
1 | // ======================================================================
2 | //
3 | // Copyright (C) 2018-2020 湖南心莱信息科技有限公司
4 | // All rights reserved
5 | //
6 | // filename : Extentions.cs
7 | // description :
8 | //
9 | // created by 雪雁 at 2018-12-11 20:19
10 | // Mail: wenqiang.li@xin-lai.com
11 | // QQ群:85318032(技术交流)
12 | // Blog:http://www.cnblogs.com/codelove/
13 | // GitHub:https://github.com/xin-lai
14 | // Home:http://xin-lai.com
15 | //
16 | // ======================================================================
17 |
18 | using System;
19 | using Aliyun.OSS.Model;
20 | using Magicodes.Storage.Core;
21 |
22 | namespace Magicodes.Storage.AliyunOss.Core
23 | {
24 | ///
25 | /// 扩展方法
26 | ///
27 | public static class Extentions
28 | {
29 | ///
30 | /// 根据错误类型返回错误异常
31 | ///
32 | ///
33 | public static TRespose HandlerError(this TRespose response, string friendlyMessage = null) where TRespose : GenericResult
34 | {
35 | var code = (int) response.HttpStatusCode;
36 | if (code < 300 || code >= 600) return response;
37 | var message = response.ResponseMetadata["Message"];
38 | var requestId = response.ResponseMetadata["RequestId"];
39 | var traceId = response.ResponseMetadata["TraceId"];
40 | var resource = response.ResponseMetadata["Resource"];
41 | throw new StorageException(
42 | new StorageError {Code = code, Message = friendlyMessage ?? message, ProviderMessage = message},
43 | new Exception($"阿里云存储错误,详细信息:RequestId:{requestId},traceId:{traceId},resource:{resource}"));
44 | }
45 | }
46 | }
--------------------------------------------------------------------------------
/src/Magicodes.Storage/Extentions.cs:
--------------------------------------------------------------------------------
1 | // ======================================================================
2 | //
3 | // Copyright (C) 2016-2020 湖南心莱信息科技有限公司
4 | // All rights reserved
5 | //
6 | // filename : Extentions.cs
7 | // description :
8 | //
9 | // created by 李文强 at 2016/09/23 9:41
10 | // Blog:http://www.cnblogs.com/codelove/
11 | // GitHub : https://github.com/xin-lai
12 | // Home:http://xin-lai.com
13 | //
14 | // ======================================================================
15 |
16 | using System;
17 | using System.Collections.Generic;
18 | using System.Linq;
19 |
20 | namespace Magicodes.Storage
21 | {
22 | public static class Extentions
23 | {
24 | private static readonly Dictionary Errors = new Dictionary
25 | {
26 | {
27 | 1000,
28 | "无效的安全凭据"
29 | },
30 | {
31 | 1001,
32 | "提供程序出现未知错误"
33 | },
34 | {
35 | 1002,
36 | "无效的访问凭据"
37 | },
38 | {
39 | 1003,
40 | "Blob 正在使用"
41 | },
42 | {
43 | 1004,
44 | "无效的 blob 或者 container 名称"
45 | },
46 | {
47 | 1005,
48 | "无效的 container 名称."
49 | },
50 | {
51 | 1006,
52 | "打开 blob 时出现错误"
53 | }
54 | };
55 |
56 | public static StorageError ToStorageError(this int code)
57 | {
58 | return Errors
59 | .Where(x => x.Key == code)
60 | .Select(x => new StorageError {Code = x.Key, Message = x.Value})
61 | .FirstOrDefault();
62 | }
63 |
64 | public static StorageError ToStorageError(this StorageErrorCode code)
65 | {
66 | return Errors
67 | .Where(x => x.Key == (int) code)
68 | .Select(x => new StorageError {Code = x.Key, Message = x.Value})
69 | .FirstOrDefault();
70 | }
71 |
72 | public static List SelectToListOrEmpty(this IEnumerable e, Func f)
73 | {
74 | if (e == null)
75 | return new List();
76 |
77 | return e.Select(f).ToList();
78 | }
79 |
80 | public static List WhereToListOrEmpty(this IEnumerable e, Func f)
81 | {
82 | if (e == null)
83 | return new List();
84 |
85 | return e.Where(f).ToList();
86 | }
87 | }
88 | }
--------------------------------------------------------------------------------
/src/Magicodes.Storage/Magicodes.Storage.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | Debug
6 | AnyCPU
7 | {3C02CDBB-D19E-4113-A0CA-78EA9531B506}
8 | Library
9 | Properties
10 | Magicodes.Storage
11 | Magicodes.Storage
12 | v4.5
13 | 512
14 |
15 |
16 |
17 | true
18 | full
19 | false
20 | bin\Debug\
21 | DEBUG;TRACE
22 | prompt
23 | 4
24 |
25 |
26 | pdbonly
27 | true
28 | bin\Release\
29 | TRACE
30 | prompt
31 | 4
32 |
33 |
34 |
35 |
36 |
37 |
38 |
39 |
40 |
41 |
42 |
43 |
44 |
45 |
46 |
47 |
48 |
49 |
50 |
51 |
52 |
53 |
54 |
55 |
56 |
57 |
58 |
65 |
--------------------------------------------------------------------------------
/src/Magicodes.Storage.Core/IStorageProvider.cs:
--------------------------------------------------------------------------------
1 | // ======================================================================
2 | //
3 | // Copyright (C) 2016-2020 湖南心莱信息科技有限公司
4 | // All rights reserved
5 | //
6 | // filename : IStorageProvider.cs
7 | // description :
8 | //
9 | // created by 李文强 at 2018/03/25 9:41
10 | // Blog:http://www.cnblogs.com/codelove/
11 | // GitHub : https://github.com/xin-lai
12 | // Home:http://xin-lai.com
13 | // 交流QQ群(.NET 技术交流群):85318032
14 | //
15 | // ======================================================================
16 |
17 | using System;
18 | using System.Collections.Generic;
19 | using System.IO;
20 | using System.Threading.Tasks;
21 |
22 | namespace Magicodes.Storage.Core
23 | {
24 | ///
25 | /// 程序提供程序
26 | ///
27 | public interface IStorageProvider
28 | {
29 | ///
30 | /// 提供程序名称
31 | ///
32 | string ProviderName { get; }
33 |
34 | ///
35 | /// 保存对象到指定的容器
36 | ///
37 | /// 目录名称
38 | /// 文件对象名称
39 | /// 流
40 | Task SaveBlobStream(string containerName, string blobName, Stream source);
41 |
42 | ///
43 | /// 获取对象
44 | ///
45 | /// 目录
46 | /// 文件对象名称
47 | ///
48 | Task GetBlobStream(string containerName, string blobName);
49 |
50 | ///
51 | /// 获取文件链接
52 | ///
53 | ///
54 | ///
55 | ///
56 | Task GetBlobUrl(string containerName, string blobName);
57 |
58 | ///
59 | /// 获取对象属性
60 | ///
61 | ///
62 | ///
63 | ///
64 | Task GetBlobFileInfo(string containerName, string blobName);
65 |
66 | ///
67 | /// 列出指定容器下的对象列表
68 | ///
69 | ///
70 | ///
71 | Task> ListBlobs(string containerName);
72 |
73 | ///
74 | /// 删除对象
75 | ///
76 | ///
77 | ///
78 | Task DeleteBlob(string containerName, string blobName);
79 |
80 | ///
81 | /// 删除容器
82 | ///
83 | ///
84 | Task DeleteContainer(string containerName);
85 |
86 | ///
87 | /// 获取授权访问链接
88 | ///
89 | /// 容器名称
90 | /// 文件名称
91 | /// 过期时间
92 | /// 是否允许下载
93 | /// 文件名
94 | /// 内容类型
95 | /// 访问限制
96 | ///
97 | Task GetBlobUrl(string containerName, string blobName, DateTime expiry, bool isDownload = false, string fileName = null, string contentType = null, BlobUrlAccess access = BlobUrlAccess.Read);
98 | }
99 | }
--------------------------------------------------------------------------------
/src/Magicodes.Storage/NullStorageProvider.cs:
--------------------------------------------------------------------------------
1 | // ======================================================================
2 | //
3 | // Copyright (C) 2016-2020 湖南心莱信息科技有限公司
4 | // All rights reserved
5 | //
6 | // filename : NullStorageProvider.cs
7 | // description :
8 | //
9 | // created by 李文强 at 2016/10/04 20:35
10 | // Blog:http://www.cnblogs.com/codelove/
11 | // GitHub:https://github.com/xin-lai
12 | // Home:http://xin-lai.com
13 | //
14 | // ======================================================================
15 |
16 | using System;
17 | using System.Collections.Generic;
18 | using System.IO;
19 | using System.Threading.Tasks;
20 |
21 | namespace Magicodes.Storage
22 | {
23 | ///
24 | /// 空存储提供程序实现,已增加程序的容错能力
25 | ///
26 | public class NullStorageProvider : IStorageProvider
27 | {
28 | public void SaveBlobStream(string containerName, string blobName, Stream source,
29 | BlobProperties properties = null)
30 | {
31 | }
32 |
33 | public Task SaveBlobStreamAsync(string containerName, string blobName, Stream source,
34 | BlobProperties properties = null)
35 | {
36 | return Task.FromResult(0);
37 | }
38 |
39 | public Stream GetBlobStream(string containerName, string blobName)
40 | {
41 | return null;
42 | }
43 |
44 | public Task GetBlobStreamAsync(string containerName, string blobName)
45 | {
46 | return Task.FromResult((Stream) null);
47 | }
48 |
49 | public string GetBlobUrl(string containerName, string blobName)
50 | {
51 | return null;
52 | }
53 |
54 | public string GetBlobSasUrl(string containerName, string blobName, DateTimeOffset expiry,
55 | bool isDownload = false,
56 | string fileName = null, string contentType = null, BlobUrlAccess access = BlobUrlAccess.Read)
57 | {
58 | return null;
59 | }
60 |
61 | public BlobDescriptor GetBlobDescriptor(string containerName, string blobName)
62 | {
63 | return null;
64 | }
65 |
66 | public Task GetBlobDescriptorAsync(string containerName, string blobName)
67 | {
68 | return Task.FromResult((BlobDescriptor) null);
69 | }
70 |
71 | public IList ListBlobs(string containerName)
72 | {
73 | return null;
74 | }
75 |
76 | public Task> ListBlobsAsync(string containerName)
77 | {
78 | return Task.FromResult((IList) null);
79 | }
80 |
81 | public void DeleteBlob(string containerName, string blobName)
82 | {
83 | }
84 |
85 | public Task DeleteBlobAsync(string containerName, string blobName)
86 | {
87 | return Task.FromResult(0);
88 | }
89 |
90 | public void DeleteContainer(string containerName)
91 | {
92 | }
93 |
94 | public Task DeleteContainerAsync(string containerName)
95 | {
96 | return Task.FromResult(0);
97 | }
98 |
99 | public void UpdateBlobProperties(string containerName, string blobName, BlobProperties properties)
100 | {
101 | }
102 |
103 | public Task UpdateBlobPropertiesAsync(string containerName, string blobName, BlobProperties properties)
104 | {
105 | return Task.FromResult(0);
106 | }
107 | }
108 | }
--------------------------------------------------------------------------------
/src/Magicodes.Storage.sln:
--------------------------------------------------------------------------------
1 |
2 | Microsoft Visual Studio Solution File, Format Version 12.00
3 | # Visual Studio Version 16
4 | VisualStudioVersion = 16.0.29709.97
5 | MinimumVisualStudioVersion = 10.0.40219.1
6 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Magicodes.Storage.Core", "Magicodes.Storage.Core\Magicodes.Storage.Core.csproj", "{51B86AF9-5029-48C8-AB53-DDA8786BD427}"
7 | EndProject
8 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Magicodes.Storage.Local.Core", "Magicodes.Storage.Local.Core\Magicodes.Storage.Local.Core.csproj", "{E0455428-372A-449D-AD38-CEA289F55147}"
9 | EndProject
10 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Magicodes.Storage.Tests", "Magicodes.Storage.Tests\Magicodes.Storage.Tests.csproj", "{EC66D526-32F4-459C-972B-63853E3B5801}"
11 | EndProject
12 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Magicodes.Storage.Tencent.Core", "Magicodes.Storage.Tencent.Core\Magicodes.Storage.Tencent.Core.csproj", "{AA762A03-98CE-40B4-803F-5D66E0C89327}"
13 | EndProject
14 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Magicodes.Storage.AliyunOss.Core", "Magicodes.Storage.AliyunOss.Core\Magicodes.Storage.AliyunOss.Core.csproj", "{CD1656DE-BA57-4723-A5F2-785683E4F364}"
15 | EndProject
16 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{3CA27E11-C493-4343-BF72-0395221B7FED}"
17 | ProjectSection(SolutionItems) = preProject
18 | ..\README.md = ..\README.md
19 | EndProjectSection
20 | EndProject
21 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Magicodes.Storage.Abp.Core", "Magicodes.Storage.Abp.Core\Magicodes.Storage.Abp.Core.csproj", "{28BB0062-5E90-4C62-8034-6F7268DE883C}"
22 | EndProject
23 | Global
24 | GlobalSection(SolutionConfigurationPlatforms) = preSolution
25 | Debug|Any CPU = Debug|Any CPU
26 | Release|Any CPU = Release|Any CPU
27 | EndGlobalSection
28 | GlobalSection(ProjectConfigurationPlatforms) = postSolution
29 | {51B86AF9-5029-48C8-AB53-DDA8786BD427}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
30 | {51B86AF9-5029-48C8-AB53-DDA8786BD427}.Debug|Any CPU.Build.0 = Debug|Any CPU
31 | {51B86AF9-5029-48C8-AB53-DDA8786BD427}.Release|Any CPU.ActiveCfg = Release|Any CPU
32 | {51B86AF9-5029-48C8-AB53-DDA8786BD427}.Release|Any CPU.Build.0 = Release|Any CPU
33 | {E0455428-372A-449D-AD38-CEA289F55147}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
34 | {E0455428-372A-449D-AD38-CEA289F55147}.Debug|Any CPU.Build.0 = Debug|Any CPU
35 | {E0455428-372A-449D-AD38-CEA289F55147}.Release|Any CPU.ActiveCfg = Release|Any CPU
36 | {E0455428-372A-449D-AD38-CEA289F55147}.Release|Any CPU.Build.0 = Release|Any CPU
37 | {EC66D526-32F4-459C-972B-63853E3B5801}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
38 | {EC66D526-32F4-459C-972B-63853E3B5801}.Debug|Any CPU.Build.0 = Debug|Any CPU
39 | {EC66D526-32F4-459C-972B-63853E3B5801}.Release|Any CPU.ActiveCfg = Release|Any CPU
40 | {EC66D526-32F4-459C-972B-63853E3B5801}.Release|Any CPU.Build.0 = Release|Any CPU
41 | {AA762A03-98CE-40B4-803F-5D66E0C89327}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
42 | {AA762A03-98CE-40B4-803F-5D66E0C89327}.Debug|Any CPU.Build.0 = Debug|Any CPU
43 | {AA762A03-98CE-40B4-803F-5D66E0C89327}.Release|Any CPU.ActiveCfg = Release|Any CPU
44 | {AA762A03-98CE-40B4-803F-5D66E0C89327}.Release|Any CPU.Build.0 = Release|Any CPU
45 | {CD1656DE-BA57-4723-A5F2-785683E4F364}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
46 | {CD1656DE-BA57-4723-A5F2-785683E4F364}.Debug|Any CPU.Build.0 = Debug|Any CPU
47 | {CD1656DE-BA57-4723-A5F2-785683E4F364}.Release|Any CPU.ActiveCfg = Release|Any CPU
48 | {CD1656DE-BA57-4723-A5F2-785683E4F364}.Release|Any CPU.Build.0 = Release|Any CPU
49 | {28BB0062-5E90-4C62-8034-6F7268DE883C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
50 | {28BB0062-5E90-4C62-8034-6F7268DE883C}.Debug|Any CPU.Build.0 = Debug|Any CPU
51 | {28BB0062-5E90-4C62-8034-6F7268DE883C}.Release|Any CPU.ActiveCfg = Release|Any CPU
52 | {28BB0062-5E90-4C62-8034-6F7268DE883C}.Release|Any CPU.Build.0 = Release|Any CPU
53 | EndGlobalSection
54 | GlobalSection(SolutionProperties) = preSolution
55 | HideSolutionNode = FALSE
56 | EndGlobalSection
57 | GlobalSection(ExtensibilityGlobals) = postSolution
58 | SolutionGuid = {EC74E527-A5D6-4047-AB08-B7ADE63813AE}
59 | EndGlobalSection
60 | EndGlobal
61 |
--------------------------------------------------------------------------------
/src/Magicodes.Storage.Core/StorageErrorCode.cs:
--------------------------------------------------------------------------------
1 | // ======================================================================
2 | //
3 | // Copyright (C) 2016-2020 湖南心莱信息科技有限公司
4 | // All rights reserved
5 | //
6 | // filename : StorageErrorCode.cs
7 | // description :
8 | //
9 | // created by 李文强 at 2018/03/25 9:41
10 | // Blog:http://www.cnblogs.com/codelove/
11 | // GitHub : https://github.com/xin-lai
12 | // Home:http://xin-lai.com
13 | // 交流QQ群(.NET 技术交流群):85318032
14 | //
15 | // ======================================================================
16 |
17 | using System.ComponentModel.DataAnnotations;
18 |
19 | namespace Magicodes.Storage.Core
20 | {
21 | ///
22 | /// 错误码
23 | ///
24 | public enum StorageErrorCode
25 | {
26 | ///
27 | /// 没有错误
28 | ///
29 | [Display(Name = "没有错误")]
30 | None = 0,
31 |
32 | ///
33 | /// 无效的安全凭据
34 | ///
35 | [Display(Name = "无效的安全凭据")]
36 | InvalidCredentials = 1000,
37 |
38 | ///
39 | /// 提供程序出现未知错误
40 | ///
41 | [Display(Name = "提供程序出现未知错误")]
42 | GenericException = 1001,
43 |
44 | ///
45 | /// 无效的访问凭据
46 | ///
47 | [Display(Name = "无效的访问凭据")]
48 | InvalidAccess = 1002,
49 |
50 | ///
51 | /// 文件被占用
52 | ///
53 | [Display(Name = "文件被占用")]
54 | BlobInUse = 1003,
55 |
56 | ///
57 | /// 无效的文件名称
58 | ///
59 | [Display(Name = "无效的文件名称")]
60 | InvalidBlobName = 1004,
61 |
62 | ///
63 | /// 无效的容器名称
64 | ///
65 | [Display(Name = "无效的容器名称")]
66 | InvalidContainerName = 1005,
67 |
68 | ///
69 | /// 读取文件错误
70 | ///
71 | [Display(Name = "读取文件错误")]
72 | ErrorOpeningBlob = 1006,
73 |
74 | ///
75 | /// 凭据或证书错误
76 | ///
77 | [Display(Name = "凭据或证书错误")]
78 | NoCredentialsProvided = 1007,
79 |
80 | ///
81 | /// 没有找到该文件
82 | ///
83 | [Display(Name = "没有找到该文件")]
84 | FileNotFound = 1008,
85 |
86 | ///
87 | /// 没有找到该目录
88 | ///
89 | [Display(Name = "没有找到该容器")]
90 | ContainerNotFound = 1009,
91 |
92 |
93 | ///
94 | /// 部分操作执行成功
95 | ///
96 | [Display(Name = "部分操作执行成功")]
97 | PartlyOK = 1010,
98 |
99 | ///
100 | /// 没有找到该文件或容器
101 | ///
102 | [Display(Name = "没有找到该文件或容器")]
103 | NotFound = 1011,
104 |
105 | ///
106 | /// 请求错误
107 | ///
108 | [Display(Name = "请求错误")]
109 | PostError = 1012,
110 |
111 | ///
112 | /// 请求资源大小不符合要求
113 | ///
114 | [Display(Name = "请求资源大小不符合要求")]
115 | SizeError = 1013,
116 |
117 | ///
118 | /// 网络错误
119 | ///
120 | [Display(Name = "网络错误")]
121 | NetworkError = 1014,
122 |
123 | ///
124 | /// 处理超时
125 | ///
126 | [Display(Name = "处理超时")]
127 | TimeoutError = 1015,
128 |
129 | ///
130 | /// 访问限制(比如单个资源访问频率过高)
131 | ///
132 | [Display(Name = "访问限制(比如单个资源访问频率过高)")]
133 | AccessLimitError = 1016,
134 |
135 | ///
136 | /// 目标资源已存在
137 | ///
138 | [Display(Name = "目标资源已存在")]
139 | ExistError = 1017,
140 |
141 | ///
142 | /// 数量达到上限
143 | ///
144 | [Display(Name = "数量达到上限")]
145 | CountLimitError = 1018,
146 |
147 | ///
148 | /// 不支持的文件类型
149 | ///
150 | [Display(Name = "不支持的文件类型")]
151 | UnsupportedFileType = 1019,
152 | }
153 | }
--------------------------------------------------------------------------------
/src/Magicodes.Storage.Abp.Core/StorageManager.cs:
--------------------------------------------------------------------------------
1 | using Abp.Configuration;
2 | using Abp.Dependency;
3 | using Abp.Json;
4 | using Castle.Core.Logging;
5 | using Magicodes.Storage.AliyunOss.Core;
6 | using Magicodes.Storage.Core;
7 | using Magicodes.Storage.Local.Core;
8 | using Magicodes.Storage.Tencent.Core;
9 | using Microsoft.AspNetCore.Hosting;
10 | using Microsoft.Extensions.Configuration;
11 | using Microsoft.Extensions.Hosting;
12 | using System;
13 | using System.Collections.Generic;
14 | using System.IO;
15 | using System.Text;
16 | using System.Threading.Tasks;
17 |
18 | namespace Magicodes.Storage.Abp.Core
19 | {
20 | public class StorageManager : IStorageManager
21 | {
22 | public ILogger Logger { get; set; }
23 |
24 | public StorageManager(IConfiguration appConfiguration, IIocManager iocManager)
25 | {
26 | Logger = NullLogger.Instance;
27 | AppConfiguration = appConfiguration;
28 | IocManager = iocManager;
29 | }
30 |
31 | //public IStorageProvider LocalStorageProvider { get; set; }
32 |
33 | public IStorageProvider StorageProvider { get; set; }
34 |
35 | public IConfiguration AppConfiguration { get; set; }
36 |
37 | public IIocManager IocManager { get; set; }
38 |
39 | ///
40 | /// 根据key从站点配置文件或设置中获取支付配置
41 | ///
42 | ///
43 | ///
44 | private Task GetConfigFromConfigOrSettingsByKey(string key) where TConfig : class, new()
45 | {
46 | var settings = AppConfiguration?.GetSection(key: key)?.Get();
47 | if (settings != null) return Task.FromResult(settings);
48 |
49 | using (var obj = IocManager.ResolveAsDisposable())
50 | {
51 | var value = obj.Object.GetSettingValue(key);
52 | if (string.IsNullOrWhiteSpace(value))
53 | {
54 | return Task.FromResult(null);
55 | }
56 | settings = value.FromJsonString();
57 | return Task.FromResult(settings);
58 | }
59 | }
60 |
61 | public void Initialize()
62 | {
63 | //日志函数
64 | void LogAction(string tag, string message)
65 | {
66 | if (tag.Equals("error", StringComparison.CurrentCultureIgnoreCase))
67 | Logger.Error(message);
68 | else
69 | Logger.Debug(message);
70 | }
71 |
72 | #region 配置存储程序
73 | switch (AppConfiguration["StorageProvider:Type"])
74 | {
75 | case "LocalStorageProvider":
76 | {
77 | var config = GetConfigFromConfigOrSettingsByKey("LocalStorageProvider").Result;
78 |
79 | if (config != null)
80 | {
81 | if (!config.RootPath.Contains(":"))
82 | {
83 | var hostingEnvironment = IocManager.Resolve();
84 | config.RootPath = Path.Combine(hostingEnvironment.WebRootPath, config.RootPath);
85 | }
86 | }
87 | if (!Directory.Exists(config.RootPath)) Directory.CreateDirectory(config.RootPath);
88 |
89 | StorageProvider = new LocalStorageProvider(config);
90 | break;
91 | }
92 | case "AliyunOssStorageProvider":
93 | {
94 | var aliyunOssConfig = GetConfigFromConfigOrSettingsByKey("AliyunOssStorageProvider").Result; ;
95 | StorageProvider = new AliyunOssStorageProvider(aliyunOssConfig);
96 | break;
97 | }
98 | case "TencentCosStorageProvider":
99 | {
100 | var config = GetConfigFromConfigOrSettingsByKey("TencentCosStorageProvider").Result; ;
101 | StorageProvider = new TencentStorageProvider(config);
102 | break;
103 | }
104 | default:
105 | break;
106 | }
107 | #endregion
108 | }
109 | }
110 | }
111 |
--------------------------------------------------------------------------------
/src/Magicodes.Storage.Tests/AliyunOssStorageTest.cs:
--------------------------------------------------------------------------------
1 | // ======================================================================
2 | //
3 | // Copyright (C) 2018-2020 湖南心莱信息科技有限公司
4 | // All rights reserved
5 | //
6 | // filename : AliyunOssStorageTest.cs
7 | // description :
8 | //
9 | // created by 雪雁 at 2018-09-04 13:55
10 | // Mail: wenqiang.li@xin-lai.com
11 | // QQ群:85318032(技术交流)
12 | // Blog:http://www.cnblogs.com/codelove/
13 | // GitHub:https://github.com/xin-lai
14 | // Home:http://xin-lai.com
15 | //
16 | // ======================================================================
17 |
18 | using System;
19 | using System.IO;
20 | using System.Threading.Tasks;
21 | using Magicodes.Storage.AliyunOss.Core;
22 | using Magicodes.Storage.Tests.Helper;
23 | using Shouldly;
24 | using Xunit;
25 |
26 | namespace Magicodes.Storage.Tests
27 | {
28 | [Trait("Group", "阿里云存储测试")]
29 | public class AliyunOssStorageTest : TestBase, IDisposable
30 | {
31 | public AliyunOssStorageTest()
32 | {
33 | var config = new AliyunOssConfig
34 | {
35 | //这里使用自己的相关配置完成测试
36 | AccessKeyId = "",
37 | AccessKeySecret = "",
38 | Endpoint = ""
39 | };
40 | //如果没填,尝试从配置文件加载
41 | if (string.IsNullOrWhiteSpace(config.AccessKeyId))
42 | {
43 | config = ConfigHelper.LoadConfig("AliyunOssStorage");
44 | }
45 | var storage = new AliyunOssStorageProvider(config);
46 | StorageProvider = new AliyunOssStorageProvider(config);
47 | }
48 | public void Dispose()
49 | {
50 | }
51 |
52 | [Fact(DisplayName = "阿里云_删除对象")]
53 | public async Task DeleteBlob_Test()
54 | {
55 | var fileName = await CreateTestFile();
56 | await StorageProvider.DeleteBlob(ContainerName, fileName);
57 |
58 | }
59 |
60 | private async Task CreateTestFile()
61 | {
62 | var fileName = GetTestFileName();
63 | await StorageProvider.SaveBlobStream(ContainerName, fileName, TestStream);
64 | return fileName;
65 | }
66 |
67 | [Fact(DisplayName = "阿里云_删除容器")]
68 | public async Task DeleteContainer_Test()
69 | {
70 | var fileName = GetTestFileName();
71 | await StorageProvider.DeleteContainer(ContainerName);
72 | }
73 |
74 | [Fact(DisplayName = "阿里云_获取文件信息")]
75 | public async Task GetBlobFileInfo_Test()
76 | {
77 | var fileName = await CreateTestFile();
78 | var result = await StorageProvider.GetBlobFileInfo(ContainerName, fileName);
79 | result.Name.ShouldBe(fileName);
80 | result.Length.ShouldBeGreaterThan(0);
81 | result.Url.ShouldNotBeNullOrWhiteSpace();
82 | result.ETag.ShouldNotBeNull();
83 | result.ContentType.ShouldNotBeNull();
84 | }
85 |
86 | [Fact(DisplayName = "获取文件的流信息")]
87 | public async Task GetBlobStream_Test()
88 | {
89 | var fileName = await CreateTestFile();
90 | var result = await StorageProvider.GetBlobStream(ContainerName, fileName);
91 | result.ShouldNotBeNull();
92 |
93 | }
94 |
95 | [Fact(DisplayName = "阿里云_获取授权访问链接")]
96 | public async Task GetBlobUrl_Test()
97 | {
98 | var fileName = await CreateTestFile();
99 | var result = await StorageProvider.GetBlobUrl(ContainerName, fileName, DateTime.Now);
100 | result.ShouldNotBeNullOrWhiteSpace();
101 | }
102 |
103 | [Fact(DisplayName = "阿里云_获取访问链接(两个参数)")]
104 | public async Task GetBlobUrl1_Test()
105 | {
106 | var fileName = await CreateTestFile();
107 | var result = await StorageProvider.GetBlobUrl(ContainerName, fileName);
108 | result.ShouldNotBeNullOrWhiteSpace();
109 | }
110 |
111 | [Fact(DisplayName = "阿里云_列出指定容器下的对象列表")]
112 | public async Task ListBlobs_Test()
113 | {
114 | var fileName = await CreateTestFile();
115 | var result = await StorageProvider.ListBlobs(ContainerName);
116 | result.ShouldNotBeNull();
117 | result.Count.ShouldBeGreaterThan(0);
118 | }
119 |
120 | [Fact(DisplayName = "阿里云_本地文件上传测试")]
121 | public async Task SaveBlobStream_Test()
122 | {
123 | var testFileName = GetTestFileName();
124 | await StorageProvider.SaveBlobStream(ContainerName, testFileName, TestStream);
125 | var result = await StorageProvider.GetBlobFileInfo(ContainerName, testFileName);
126 | result.ShouldNotBeNull();
127 | result.Name.ShouldNotBeNullOrWhiteSpace();
128 | result.Name.ShouldBe(testFileName);
129 | }
130 | }
131 | }
--------------------------------------------------------------------------------
/src/Magicodes.Storage/AsyncHelpers.cs:
--------------------------------------------------------------------------------
1 | // ======================================================================
2 | //
3 | // Copyright (C) 2016-2020 湖南心莱信息科技有限公司
4 | // All rights reserved
5 | //
6 | // filename : AsyncHelpers.cs
7 | // description :
8 | //
9 | // created by 李文强 at 2016/09/23 9:41
10 | // Blog:http://www.cnblogs.com/codelove/
11 | // GitHub : https://github.com/xin-lai
12 | // Home:http://xin-lai.com
13 | //
14 | // ======================================================================
15 |
16 | using System;
17 | using System.Collections.Generic;
18 | using System.Threading;
19 | using System.Threading.Tasks;
20 |
21 | namespace Magicodes.Storage
22 | {
23 | public static class AsyncHelpers
24 | {
25 | ///
26 | /// 执行异步任务
27 | ///
28 | /// 需要执行的异步方法
29 | public static void RunSync(Func task)
30 | {
31 | var oldContext = SynchronizationContext.Current;
32 | var synch = new ExclusiveSynchronizationContext();
33 | SynchronizationContext.SetSynchronizationContext(synch);
34 | synch.Post(async _ =>
35 | {
36 | try
37 | {
38 | await task();
39 | }
40 | catch (Exception e)
41 | {
42 | synch.InnerException = e;
43 | throw;
44 | }
45 | finally
46 | {
47 | synch.EndMessageLoop();
48 | }
49 | }, null);
50 | synch.BeginMessageLoop();
51 |
52 | SynchronizationContext.SetSynchronizationContext(oldContext);
53 | }
54 |
55 | ///
56 | /// 执行异步任务
57 | ///
58 | /// 返回类型
59 | /// 待执行的异步方法
60 | ///
61 | public static T RunSync(Func> task)
62 | {
63 | var oldContext = SynchronizationContext.Current;
64 | var synch = new ExclusiveSynchronizationContext();
65 | SynchronizationContext.SetSynchronizationContext(synch);
66 | var ret = default(T);
67 | synch.Post(async _ =>
68 | {
69 | try
70 | {
71 | ret = await task();
72 | }
73 | catch (Exception e)
74 | {
75 | synch.InnerException = e;
76 | throw;
77 | }
78 | finally
79 | {
80 | synch.EndMessageLoop();
81 | }
82 | }, null);
83 | synch.BeginMessageLoop();
84 | SynchronizationContext.SetSynchronizationContext(oldContext);
85 | return ret;
86 | }
87 |
88 | private class ExclusiveSynchronizationContext : SynchronizationContext
89 | {
90 | private readonly Queue> _items =
91 | new Queue>();
92 |
93 | private readonly AutoResetEvent _workItemsWaiting = new AutoResetEvent(false);
94 | private bool _done;
95 | public Exception InnerException { get; set; }
96 |
97 | public override void Send(SendOrPostCallback d, object state)
98 | {
99 | throw new NotSupportedException("We cannot send to our same thread");
100 | }
101 |
102 | public override void Post(SendOrPostCallback d, object state)
103 | {
104 | lock (_items)
105 | {
106 | _items.Enqueue(Tuple.Create(d, state));
107 | }
108 | _workItemsWaiting.Set();
109 | }
110 |
111 | public void EndMessageLoop()
112 | {
113 | Post(_ => _done = true, null);
114 | }
115 |
116 | public void BeginMessageLoop()
117 | {
118 | while (!_done)
119 | {
120 | Tuple task = null;
121 | lock (_items)
122 | {
123 | if (_items.Count > 0)
124 | task = _items.Dequeue();
125 | }
126 | if (task != null)
127 | {
128 | task.Item1(task.Item2);
129 | if (InnerException != null)
130 | throw InnerException;
131 | }
132 | else
133 | {
134 | _workItemsWaiting.WaitOne();
135 | }
136 | }
137 | }
138 |
139 | public override SynchronizationContext CreateCopy()
140 | {
141 | return this;
142 | }
143 | }
144 | }
145 | }
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | ## Ignore Visual Studio temporary files, build results, and
2 | ## files generated by popular Visual Studio add-ons.
3 |
4 | # User-specific files
5 | *.suo
6 | *.user
7 | *.userosscache
8 | *.sln.docstates
9 |
10 | # User-specific files (MonoDevelop/Xamarin Studio)
11 | *.userprefs
12 |
13 | # Build results
14 | [Dd]ebug/
15 | [Dd]ebugPublic/
16 | [Rr]elease/
17 | [Rr]eleases/
18 | x64/
19 | x86/
20 | bld/
21 | [Bb]in/
22 | [Oo]bj/
23 | [Ll]og/
24 |
25 | # Visual Studio 2015 cache/options directory
26 | .vs/
27 | # Uncomment if you have tasks that create the project's static files in wwwroot
28 | #wwwroot/
29 |
30 | # MSTest test Results
31 | [Tt]est[Rr]esult*/
32 | [Bb]uild[Ll]og.*
33 |
34 | # NUNIT
35 | *.VisualState.xml
36 | TestResult.xml
37 |
38 | # Build Results of an ATL Project
39 | [Dd]ebugPS/
40 | [Rr]eleasePS/
41 | dlldata.c
42 |
43 | # DNX
44 | project.lock.json
45 | artifacts/
46 |
47 | *_i.c
48 | *_p.c
49 | *_i.h
50 | *.ilk
51 | *.meta
52 | *.obj
53 | *.pch
54 | *.pdb
55 | *.pgc
56 | *.pgd
57 | *.rsp
58 | *.sbr
59 | *.tlb
60 | *.tli
61 | *.tlh
62 | *.tmp
63 | *.tmp_proj
64 | *.log
65 | *.vspscc
66 | *.vssscc
67 | .builds
68 | *.pidb
69 | *.svclog
70 | *.scc
71 |
72 | # Chutzpah Test files
73 | _Chutzpah*
74 |
75 | # Visual C++ cache files
76 | ipch/
77 | *.aps
78 | *.ncb
79 | *.opendb
80 | *.opensdf
81 | *.sdf
82 | *.cachefile
83 | *.VC.db
84 | *.VC.VC.opendb
85 |
86 | # Visual Studio profiler
87 | *.psess
88 | *.vsp
89 | *.vspx
90 | *.sap
91 |
92 | # TFS 2012 Local Workspace
93 | $tf/
94 |
95 | # Guidance Automation Toolkit
96 | *.gpState
97 |
98 | # ReSharper is a .NET coding add-in
99 | _ReSharper*/
100 | *.[Rr]e[Ss]harper
101 | *.DotSettings.user
102 |
103 | # JustCode is a .NET coding add-in
104 | .JustCode
105 |
106 | # TeamCity is a build add-in
107 | _TeamCity*
108 |
109 | # DotCover is a Code Coverage Tool
110 | *.dotCover
111 |
112 | # NCrunch
113 | _NCrunch_*
114 | .*crunch*.local.xml
115 | nCrunchTemp_*
116 |
117 | # MightyMoose
118 | *.mm.*
119 | AutoTest.Net/
120 |
121 | # Web workbench (sass)
122 | .sass-cache/
123 |
124 | # Installshield output folder
125 | [Ee]xpress/
126 |
127 | # DocProject is a documentation generator add-in
128 | DocProject/buildhelp/
129 | DocProject/Help/*.HxT
130 | DocProject/Help/*.HxC
131 | DocProject/Help/*.hhc
132 | DocProject/Help/*.hhk
133 | DocProject/Help/*.hhp
134 | DocProject/Help/Html2
135 | DocProject/Help/html
136 |
137 | # Click-Once directory
138 | publish/
139 |
140 | # Publish Web Output
141 | *.[Pp]ublish.xml
142 | *.azurePubxml
143 | # TODO: Comment the next line if you want to checkin your web deploy settings
144 | # but database connection strings (with potential passwords) will be unencrypted
145 | *.pubxml
146 | *.publishproj
147 |
148 | # Microsoft Azure Web App publish settings. Comment the next line if you want to
149 | # checkin your Azure Web App publish settings, but sensitive information contained
150 | # in these scripts will be unencrypted
151 | PublishScripts/
152 |
153 | # NuGet Packages
154 | *.nupkg
155 | # The packages folder can be ignored because of Package Restore
156 | **/packages/*
157 | # except build/, which is used as an MSBuild target.
158 | !**/packages/build/
159 | # Uncomment if necessary however generally it will be regenerated when needed
160 | #!**/packages/repositories.config
161 | # NuGet v3's project.json files produces more ignoreable files
162 | *.nuget.props
163 | *.nuget.targets
164 |
165 | # Microsoft Azure Build Output
166 | csx/
167 | *.build.csdef
168 |
169 | # Microsoft Azure Emulator
170 | ecf/
171 | rcf/
172 |
173 | # Windows Store app package directories and files
174 | AppPackages/
175 | BundleArtifacts/
176 | Package.StoreAssociation.xml
177 | _pkginfo.txt
178 |
179 | # Visual Studio cache files
180 | # files ending in .cache can be ignored
181 | *.[Cc]ache
182 | # but keep track of directories ending in .cache
183 | !*.[Cc]ache/
184 |
185 | # Others
186 | ClientBin/
187 | ~$*
188 | *~
189 | *.dbmdl
190 | *.dbproj.schemaview
191 | *.pfx
192 | *.publishsettings
193 | node_modules/
194 | orleans.codegen.cs
195 |
196 | # Since there are multiple workflows, uncomment next line to ignore bower_components
197 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
198 | #bower_components/
199 |
200 | # RIA/Silverlight projects
201 | Generated_Code/
202 |
203 | # Backup & report files from converting an old project file
204 | # to a newer Visual Studio version. Backup files are not needed,
205 | # because we have git ;-)
206 | _UpgradeReport_Files/
207 | Backup*/
208 | UpgradeLog*.XML
209 | UpgradeLog*.htm
210 |
211 | # SQL Server files
212 | *.mdf
213 | *.ldf
214 |
215 | # Business Intelligence projects
216 | *.rdl.data
217 | *.bim.layout
218 | *.bim_*.settings
219 |
220 | # Microsoft Fakes
221 | FakesAssemblies/
222 |
223 | # GhostDoc plugin setting file
224 | *.GhostDoc.xml
225 |
226 | # Node.js Tools for Visual Studio
227 | .ntvs_analysis.dat
228 |
229 | # Visual Studio 6 build log
230 | *.plg
231 |
232 | # Visual Studio 6 workspace options file
233 | *.opt
234 |
235 | # Visual Studio LightSwitch build output
236 | **/*.HTMLClient/GeneratedArtifacts
237 | **/*.DesktopClient/GeneratedArtifacts
238 | **/*.DesktopClient/ModelManifest.xml
239 | **/*.Server/GeneratedArtifacts
240 | **/*.Server/ModelManifest.xml
241 | _Pvt_Extensions
242 |
243 | # Paket dependency manager
244 | .paket/paket.exe
245 | paket-files/
246 |
247 | # FAKE - F# Make
248 | .fake/
249 |
250 | # JetBrains Rider
251 | .idea/
252 | *.sln.iml
253 |
--------------------------------------------------------------------------------
/src/Magicodes.Storage/IStorageProvider.cs:
--------------------------------------------------------------------------------
1 | // ======================================================================
2 | //
3 | // Copyright (C) 2016-2020 湖南心莱信息科技有限公司
4 | // All rights reserved
5 | //
6 | // filename : IStorageProvider.cs
7 | // description :
8 | //
9 | // created by 李文强 at 2016/09/23 9:41
10 | // Blog:http://www.cnblogs.com/codelove/
11 | // GitHub : https://github.com/xin-lai
12 | // Home:http://xin-lai.com
13 | //
14 | // ======================================================================
15 |
16 | using System;
17 | using System.Collections.Generic;
18 | using System.IO;
19 | using System.Threading.Tasks;
20 |
21 | namespace Magicodes.Storage
22 | {
23 | ///
24 | /// 程序提供程序
25 | ///
26 | public interface IStorageProvider
27 | {
28 | ///
29 | /// 保存对象到指定的容器
30 | ///
31 | ///
32 | ///
33 | ///
34 | ///
35 | void SaveBlobStream(string containerName, string blobName, Stream source, BlobProperties properties = null);
36 | ///
37 | /// 保存对象到指定的容器
38 | ///
39 | ///
40 | ///
41 | ///
42 | ///
43 | ///
44 | Task SaveBlobStreamAsync(string containerName, string blobName, Stream source, BlobProperties properties = null);
45 | ///
46 | /// 获取对象
47 | ///
48 | ///
49 | ///
50 | ///
51 | Stream GetBlobStream(string containerName, string blobName);
52 | ///
53 | /// 获取对象
54 | ///
55 | ///
56 | ///
57 | ///
58 | Task GetBlobStreamAsync(string containerName, string blobName);
59 | ///
60 | /// 获取Url
61 | ///
62 | ///
63 | ///
64 | ///
65 | string GetBlobUrl(string containerName, string blobName);
66 | ///
67 | /// 获取SAS Url
68 | ///
69 | ///
70 | ///
71 | ///
72 | ///
73 | ///
74 | ///
75 | ///
76 | ///
77 | string GetBlobSasUrl(string containerName, string blobName, DateTimeOffset expiry, bool isDownload = false,
78 | string fileName = null, string contentType = null, BlobUrlAccess access = BlobUrlAccess.Read);
79 | ///
80 | /// 获取对象属性
81 | ///
82 | ///
83 | ///
84 | ///
85 | BlobDescriptor GetBlobDescriptor(string containerName, string blobName);
86 | ///
87 | /// 获取对象属性
88 | ///
89 | ///
90 | ///
91 | ///
92 | Task GetBlobDescriptorAsync(string containerName, string blobName);
93 | ///
94 | /// 列出指定容器下的对象列表
95 | ///
96 | ///
97 | ///
98 | IList ListBlobs(string containerName);
99 | ///
100 | /// 列出指定容器下的对象列表
101 | ///
102 | ///
103 | ///
104 | Task> ListBlobsAsync(string containerName);
105 | ///
106 | /// 删除对象
107 | ///
108 | ///
109 | ///
110 | void DeleteBlob(string containerName, string blobName);
111 | ///
112 | /// 删除对象
113 | ///
114 | ///
115 | ///
116 | ///
117 | Task DeleteBlobAsync(string containerName, string blobName);
118 | ///
119 | /// 删除容器
120 | ///
121 | ///
122 | void DeleteContainer(string containerName);
123 | ///
124 | /// 删除容器
125 | ///
126 | ///
127 | ///
128 | Task DeleteContainerAsync(string containerName);
129 | ///
130 | /// 更新属性
131 | ///
132 | ///
133 | ///
134 | ///
135 | void UpdateBlobProperties(string containerName, string blobName, BlobProperties properties);
136 | ///
137 | /// 更新属性
138 | ///
139 | ///
140 | ///
141 | ///
142 | ///
143 | Task UpdateBlobPropertiesAsync(string containerName, string blobName, BlobProperties properties);
144 | }
145 | }
--------------------------------------------------------------------------------
/src/Magicodes.Storage.Tests/TencentStorageTests.cs:
--------------------------------------------------------------------------------
1 | // ======================================================================
2 | //
3 | // Copyright (C) 2018-2020 湖南心莱信息科技有限公司
4 | // All rights reserved
5 | //
6 | // filename : TencentStorageTests.cs
7 | // description :
8 | //
9 | // created by 雪雁 at 2018-08-02 9:58
10 | // Mail: wenqiang.li@xin-lai.com
11 | // QQ群:85318032(技术交流)
12 | // Blog:http://www.cnblogs.com/codelove/
13 | // GitHub:https://github.com/xin-lai
14 | // Home:http://xin-lai.com
15 | //
16 | // ======================================================================
17 |
18 | using Magicodes.Storage.Tencent.Core;
19 | using Magicodes.Storage.Tests.Helper;
20 | using Shouldly;
21 | using System;
22 | using System.IO;
23 | using System.Net;
24 | using System.Reflection;
25 | using System.Text;
26 | using System.Threading.Tasks;
27 | using Xunit;
28 |
29 | namespace Magicodes.Storage.Tests
30 | {
31 | [Trait("Group", "腾讯云存储测试")]
32 | public class TencentStorageTests : TestBase, IDisposable
33 | {
34 | public TencentStorageTests()
35 | {
36 | var cosConfig = new TencentCosConfig
37 | {
38 | //这里使用自己的腾讯云相关配置
39 | AppId = "",
40 | SecretId = "",
41 | SecretKey = "",
42 | BucketName = "test",
43 | Region = "ap-chengdu"
44 | };
45 | //如果没填,尝试从配置文件加载
46 | if (string.IsNullOrWhiteSpace(cosConfig.AppId))
47 | {
48 | cosConfig = ConfigHelper.LoadConfig("TencentStorage");
49 | }
50 | var tencentStorage = new TencentStorageProvider(cosConfig);
51 | StorageProvider = tencentStorage;
52 | }
53 |
54 | public void Dispose()
55 | {
56 | }
57 |
58 | [Fact(DisplayName = "腾讯云_删除对象")]
59 | public async Task DeleteBlob_Test()
60 | {
61 | var fileName = await CreateTestFile();
62 | await StorageProvider.DeleteBlob(ContainerName, fileName);
63 |
64 | }
65 |
66 | private async Task CreateTestFile()
67 | {
68 | var fileName = GetTestFileName();
69 | await StorageProvider.SaveBlobStream(ContainerName, fileName, TestStream);
70 | return fileName;
71 | }
72 |
73 | [Fact(DisplayName = "腾讯云_删除容器")]
74 | public async Task DeleteContainer_Test()
75 | {
76 | var fileName = GetTestFileName();
77 | await StorageProvider.DeleteContainer(ContainerName);
78 | }
79 |
80 | [Fact(DisplayName = "腾讯云_获取文件信息")]
81 | public async Task GetBlobFileInfo_Test()
82 | {
83 | var fileName = await CreateTestFile();
84 | var result = await StorageProvider.GetBlobFileInfo(ContainerName, fileName);
85 | result.Name.ShouldBe(fileName);
86 | result.Length.ShouldBeGreaterThan(0);
87 | result.Url.ShouldNotBeNullOrWhiteSpace();
88 | result.ETag.ShouldNotBeNull();
89 | result.ContentType.ShouldNotBeNull();
90 |
91 | ////System.Threading.Thread.Sleep(20000);
92 | //result = await StorageProvider.GetBlobFileInfo(ContainerName, fileName);
93 | //result.Name.ShouldBe(fileName);
94 | //result.Length.ShouldBeGreaterThan(0);
95 | //result.Url.ShouldNotBeNullOrWhiteSpace();
96 | //result.ETag.ShouldNotBeNull();
97 | //result.ContentType.ShouldNotBeNull();
98 |
99 | }
100 |
101 | [Fact(DisplayName = "获取文件的流信息")]
102 | public async Task GetBlobStream_Test()
103 | {
104 | var fileName = await CreateTestFile();
105 | var result = await StorageProvider.GetBlobStream(ContainerName, fileName);
106 | result.Length.ShouldBeGreaterThan(0);
107 |
108 | }
109 |
110 | [Fact(DisplayName = "腾讯云_获取授权访问链接")]
111 | public async Task GetBlobUrl_Test()
112 | {
113 | var fileName = await CreateTestFile();
114 | var result = await StorageProvider.GetBlobUrl(ContainerName, fileName, DateTime.Now);
115 | result.ShouldNotBeNullOrWhiteSpace();
116 | }
117 |
118 | [Fact(DisplayName = "腾讯云_获取访问链接(两个参数)")]
119 | public async Task GetBlobUrl1_Test()
120 | {
121 | var fileName = await CreateTestFile();
122 | var result = await StorageProvider.GetBlobUrl(ContainerName, fileName);
123 | result.ShouldNotBeNullOrWhiteSpace();
124 | }
125 |
126 | [Fact(DisplayName = "腾讯云_列出指定容器下的对象列表")]
127 | public async Task ListBlobs_Test()
128 | {
129 | var fileName = await CreateTestFile();
130 | var result = await StorageProvider.ListBlobs(ContainerName);
131 | result.ShouldNotBeNull();
132 | result.Count.ShouldBeGreaterThan(0);
133 | }
134 |
135 | [Fact(DisplayName = "腾讯云_本地文件上传测试")]
136 | public async Task SaveBlobStream_Test()
137 | {
138 | var testFileName = GetTestFileName();
139 | await StorageProvider.SaveBlobStream(ContainerName, testFileName, TestStream);
140 | var result = await StorageProvider.GetBlobFileInfo(ContainerName, testFileName);
141 | result.ShouldNotBeNull();
142 | result.Name.ShouldNotBeNullOrWhiteSpace();
143 | result.Name.ShouldBe(testFileName);
144 |
145 |
146 | testFileName = "中文测试.txt";
147 | var str = "中文";
148 | var array = Encoding.UTF8.GetBytes(str);
149 | TestStream = new MemoryStream(array);
150 | await StorageProvider.SaveBlobStream(ContainerName, testFileName, TestStream);
151 | result = await StorageProvider.GetBlobFileInfo(ContainerName, testFileName);
152 | result.ShouldNotBeNull();
153 | result.Name.ShouldNotBeNullOrWhiteSpace();
154 | result.Name.ShouldBe(testFileName);
155 | }
156 |
157 | //private static readonly Encoding ContentDispositionHeaderEncoding = Encoding.GetEncoding("ISO-8859-1");
158 | private static readonly Encoding ContentDispositionHeaderEncoding = Encoding.GetEncoding("utf-8");
159 |
160 | public static string GetWebSafeFileName(string fileName)
161 | {
162 | // We need to convert the file name to ISO-8859-1 due to browser compatibility problems with the Content-Disposition Header (see: https://stackoverflow.com/a/216777/1038611)
163 | var webSafeFileName = Encoding.Convert(Encoding.Unicode, ContentDispositionHeaderEncoding, Encoding.Unicode.GetBytes(fileName));
164 |
165 | // Furthermore, any characters not supported by ISO-8859-1 will be replaced by « ? », which is not an acceptable file name character. So we replace these as well.
166 | return ContentDispositionHeaderEncoding.GetString(webSafeFileName).Replace('?', '-');
167 | }
168 | }
169 | }
--------------------------------------------------------------------------------
/src/Magicodes.Storage.Tests/LocalStorageTests.cs:
--------------------------------------------------------------------------------
1 | // ======================================================================
2 | //
3 | // Copyright (C) 2018-2020 湖南心莱信息科技有限公司
4 | // All rights reserved
5 | //
6 | // filename : LocalStorageTests.cs
7 | // description :
8 | //
9 | // created by 雪雁 at 2018-06-07 10:31
10 | // Mail: wenqiang.li@xin-lai.com
11 | // QQ群:85318032(技术交流)
12 | // Blog:http://www.cnblogs.com/codelove/
13 | // GitHub:https://github.com/xin-lai
14 | // Home:http://xin-lai.com
15 | //
16 | // ======================================================================
17 |
18 | using System;
19 | using System.IO;
20 | using System.Threading;
21 | using System.Threading.Tasks;
22 | using Magicodes.Storage.Core;
23 | using Magicodes.Storage.Local.Core;
24 | using Shouldly;
25 | using Xunit;
26 |
27 | namespace Magicodes.Storage.Tests
28 | {
29 | [Trait("Group", "本地存储测试")]
30 | public class LocalStorageTests : TestBase, IDisposable
31 | {
32 | public LocalStorageTests()
33 | {
34 | rootPath = Path.Combine(Directory.GetCurrentDirectory(), "Files");
35 | if (!Directory.Exists(rootPath)) Directory.CreateDirectory(rootPath);
36 |
37 | rootUrl = "/";
38 | StorageProvider = new LocalStorageProvider(rootPath, rootUrl);
39 | }
40 |
41 | public void Dispose()
42 | {
43 | //TODO:数据清理
44 | }
45 |
46 | private readonly string rootPath;
47 | private readonly string rootUrl;
48 |
49 | [Fact(DisplayName = "本地文件删除测试")]
50 | public async Task DeleteBlob_Test()
51 | {
52 | var containerPath = Path.Combine(rootPath, ContainerName);
53 | if (!Directory.Exists(containerPath)) Directory.CreateDirectory(containerPath);
54 |
55 | File.WriteAllText(Path.Combine(containerPath, "1.txt"), GetTestContent());
56 | File.WriteAllText(Path.Combine(containerPath, "2.txt"), GetTestContent());
57 | File.WriteAllText(Path.Combine(containerPath, "3.txt"), GetTestContent());
58 |
59 | await StorageProvider.DeleteBlob(ContainerName, "1.txt");
60 | await StorageProvider.DeleteBlob(ContainerName, "2.txt");
61 | await StorageProvider.DeleteBlob(ContainerName, "3.txt");
62 |
63 | await Assert.ThrowsAnyAsync(async () =>
64 | await StorageProvider.DeleteBlob("AAAAAAAAAAAAA", "notfound.txt")
65 | );
66 | }
67 |
68 | [Fact(DisplayName = "本地目录删除测试")]
69 | public async Task DeleteContainer_Test()
70 | {
71 | var containerName = GetTestContainerName();
72 | var containerPath = Path.Combine(rootPath, containerName);
73 | if (!Directory.Exists(containerPath)) Directory.CreateDirectory(containerPath);
74 |
75 | await StorageProvider.DeleteContainer(containerName);
76 |
77 | await Assert.ThrowsAnyAsync(async () =>
78 | await StorageProvider.DeleteContainer("AAAAAAAAAAAAA")
79 | );
80 | }
81 |
82 |
83 | [Fact(DisplayName = "本地文件详情获取测试")]
84 | public async Task GetBlobFileInfo_Test()
85 | {
86 | var containerPath = Path.Combine(rootPath, ContainerName);
87 | if (!Directory.Exists(containerPath)) Directory.CreateDirectory(containerPath);
88 |
89 | File.WriteAllText(Path.Combine(containerPath, "1.txt"), GetTestContent());
90 |
91 | var result = await StorageProvider.GetBlobFileInfo(ContainerName, "1.txt");
92 |
93 | result.ShouldNotBeNull();
94 | result.Name.ShouldBe("1.txt");
95 | result.Container.ShouldBe(ContainerName);
96 | result.Length.ShouldBeGreaterThan(0);
97 | result.ContentType.ShouldNotBeNullOrWhiteSpace();
98 |
99 | await Assert.ThrowsAnyAsync(async () =>
100 | await StorageProvider.GetBlobFileInfo(ContainerName, "notfound.txt")
101 | );
102 | }
103 |
104 | [Fact(DisplayName = "本地签名链接获取测试")]
105 | public async Task GetBlobSasUrl_Test()
106 | {
107 | var containerPath = Path.Combine(rootPath, ContainerName);
108 | if (!Directory.Exists(containerPath)) Directory.CreateDirectory(containerPath);
109 |
110 | await Assert.ThrowsAnyAsync(async () =>
111 | await StorageProvider.GetBlobUrl(ContainerName, "notfound.txt", DateTime.Now.AddDays(1))
112 | );
113 | }
114 |
115 | [Fact(DisplayName = "本地文件流获取测试")]
116 | public async Task GetBlobStream_Test()
117 | {
118 | var containerPath = Path.Combine(rootPath, ContainerName);
119 | if (!Directory.Exists(containerPath)) Directory.CreateDirectory(containerPath);
120 |
121 | File.WriteAllText(Path.Combine(containerPath, "1.txt"), GetTestContent());
122 |
123 | var result = await StorageProvider.GetBlobStream(ContainerName, "1.txt");
124 |
125 | result.ShouldNotBeNull();
126 | result.Length.ShouldBeGreaterThan(0);
127 |
128 | await Assert.ThrowsAnyAsync(async () =>
129 | await StorageProvider.GetBlobStream(ContainerName, "notfound.txt")
130 | );
131 | }
132 |
133 | [Fact(DisplayName = "本地文件Url获取测试")]
134 | public async Task GetBlobUrl_Test()
135 | {
136 | var containerPath = Path.Combine(rootPath, ContainerName);
137 | if (!Directory.Exists(containerPath)) Directory.CreateDirectory(containerPath);
138 |
139 | var testName = GetTestFileName();
140 | File.WriteAllText(Path.Combine(containerPath, testName), GetTestContent());
141 | Thread.Sleep(10);
142 |
143 | var result = await StorageProvider.GetBlobUrl(ContainerName, testName);
144 |
145 | result.ShouldNotBeNull();
146 | result.Length.ShouldBeGreaterThan(0);
147 | result.ShouldContain("/" + ContainerName + "/");
148 |
149 | await Assert.ThrowsAnyAsync(async () =>
150 | await StorageProvider.GetBlobUrl(ContainerName, "notfound.txt")
151 | );
152 | }
153 |
154 | [Fact(DisplayName = "本地文件列表获取测试")]
155 | public async Task ListBlobs_Test()
156 | {
157 | var containerPath = Path.Combine(rootPath, ContainerName);
158 | Directory.CreateDirectory(containerPath);
159 |
160 | File.WriteAllText(Path.Combine(containerPath, GetTestFileName()), GetTestContent());
161 | File.WriteAllText(Path.Combine(containerPath, GetTestFileName()), GetTestContent());
162 | File.WriteAllText(Path.Combine(containerPath, GetTestFileName()), GetTestContent());
163 | Thread.Sleep(10);
164 |
165 | var result = await StorageProvider.ListBlobs(ContainerName);
166 |
167 | result.ShouldNotBeNull();
168 | result.Count.ShouldBeGreaterThan(0);
169 | }
170 |
171 | [Fact(DisplayName = "本地文件上传测试")]
172 | public async Task SaveBlobStream_Test()
173 | {
174 | var containerPath = Path.Combine(rootPath, ContainerName);
175 | if (Directory.Exists(containerPath)) Directory.Delete(containerPath, true);
176 | Directory.CreateDirectory(containerPath);
177 |
178 | await StorageProvider.SaveBlobStream(ContainerName, "1.txt", TestStream);
179 |
180 | File.Exists(Path.Combine(containerPath, "1.txt")).ShouldBe(true);
181 | }
182 | }
183 | }
--------------------------------------------------------------------------------
/src/Magicodes.Storage.Tencent.Core/TencentStorageProvider.cs:
--------------------------------------------------------------------------------
1 | // ======================================================================
2 | //
3 | // Copyright (C) 2018-2020 湖南心莱信息科技有限公司
4 | // All rights reserved
5 | //
6 | // filename : TencentStorageProvider.cs
7 | // description :
8 | //
9 | // created by 雪雁 at 2018-08-02 9:59
10 | // Mail: wenqiang.li@xin-lai.com
11 | // QQ群:85318032(技术交流)
12 | // Blog:http://www.cnblogs.com/codelove/
13 | // GitHub:https://github.com/xin-lai
14 | // Home:http://xin-lai.com
15 | //
16 | // ======================================================================
17 |
18 | using COSXML;
19 | using COSXML.Auth;
20 | using COSXML.Model.Object;
21 | using COSXML.Model.Bucket;
22 | using COSXML.CosException;
23 | using Magicodes.Storage.Core;
24 | using System;
25 | using System.Collections.Generic;
26 | using System.IO;
27 | using System.Linq;
28 | using System.Net;
29 | using System.Threading.Tasks;
30 | using COSXML.Utils;
31 | using COSXML.Model.Tag;
32 |
33 | namespace Magicodes.Storage.Tencent.Core
34 | {
35 | ///
36 | /// 腾讯云存储提供服务
37 | ///
38 | public class TencentStorageProvider : IStorageProvider
39 | {
40 | private readonly TencentCosConfig _tcConfig;
41 | private readonly CosXmlServer _cosXmlServer;
42 |
43 | ///
44 | /// 腾讯云存储对象提供构造函数
45 | ///
46 | /// 配置信息
47 | public TencentStorageProvider(TencentCosConfig tcConfig)
48 | {
49 | _tcConfig = tcConfig;
50 | var config = new CosXmlConfig.Builder()
51 | .SetConnectionTimeoutMs(60000) //设置连接超时时间,单位毫秒,默认45000ms
52 | .SetReadWriteTimeoutMs(40000) //设置读写超时时间,单位毫秒,默认45000ms
53 | .IsHttps(true) //设置默认 HTTPS 请求
54 | .SetAppid(tcConfig.AppId) //设置腾讯云账户的账户标识 APPID
55 | .SetRegion(tcConfig.Region) //设置一个默认的存储桶地域
56 | .SetDebugLog(true) //显示日志
57 | .Build(); //创建 CosXmlConfig 对象
58 |
59 | //初始化 QCloudCredentialProvider,COS SDK 中提供了3种方式:永久密钥、临时密钥、自定义
60 | QCloudCredentialProvider cosCredentialProvider = new DefaultQCloudCredentialProvider(tcConfig.SecretId, tcConfig.SecretKey, 600);
61 |
62 |
63 | //初始化 CosXmlServer
64 | _cosXmlServer = new CosXmlServer(config, cosCredentialProvider);
65 | }
66 |
67 | ///
68 | /// 提供服务名称
69 | ///
70 | public string ProviderName => "TencentCOS";
71 |
72 |
73 | ///
74 | /// 删除对象
75 | ///
76 | /// 容器(Bucket)的地址
77 | /// 文件名称
78 | public async Task DeleteBlob(string containerName, string blobName)
79 | {
80 | var request = new DeleteObjectRequest(_tcConfig.BucketName, $"{containerName}/{blobName}");
81 | //设置签名有效时长
82 | request.SetSign(TimeUtils.GetCurrentTime(TimeUnit.SECONDS), 600);
83 | var response = _cosXmlServer.DeleteObject(request);
84 | await response.HandlerError("删除对象出错!");
85 | }
86 |
87 | ///
88 | /// 删除容器
89 | ///
90 | ///
91 | ///
92 | public async Task DeleteContainer(string containerName)
93 | {
94 | //删除目录等于删除该目录下的所有文件
95 | var objs = await ListBlobs(containerName);
96 | var count = objs.Count / 1000 + (objs.Count % 1000 > 0 ? 1 : 0);
97 |
98 | for (var i = 0; i < count; i++)
99 | {
100 | var request = new DeleteMultiObjectRequest(_tcConfig.BucketName);
101 | request.SetObjectKeys(objs.Skip(i * 1000).Take(1000).Select(p => p.Name).ToList());
102 | var response = _cosXmlServer.DeleteMultiObjects(request);
103 | await response.HandlerError("删除对象时出错(删除目录会删除该目录下所有的文件)!");
104 | }
105 | }
106 |
107 | ///
108 | /// 获取文件信息
109 | ///
110 | ///
111 | ///
112 | ///
113 | public async Task GetBlobFileInfo(string containerName, string blobName)
114 | {
115 | var key = $"{containerName}/{blobName}";
116 | var request = new HeadObjectRequest(_tcConfig.BucketName, key);
117 | var response = _cosXmlServer.HeadObject(request);
118 | await response.HandlerError("获取文件信息出错!");
119 | return new BlobFileInfo
120 | {
121 | Container = containerName,
122 | //ContentMD5 = response.Headers.ContentMD5,
123 | ContentType = response.responseHeaders.ContainsKey("Content-Type") ? (response.responseHeaders["Content-Type"].FirstOrDefault()) : null,
124 | ETag = response.eTag,
125 | Length = response.size,
126 | LastModified = response.responseHeaders.ContainsKey("Last-Modified") ? DateTime.Parse(response.responseHeaders["Last-Modified"].FirstOrDefault()) : (DateTime?)null,
127 | Name = blobName,
128 | Url = GetUrlByKey(key)
129 | };
130 | }
131 |
132 | ///
133 | /// 获取文件的流信息
134 | ///
135 | ///
136 | ///
137 | ///
138 | public async Task GetBlobStream(string containerName, string blobName)
139 | {
140 | var request = new GetObjectBytesRequest(_tcConfig.BucketName, $"{containerName}/{blobName}");
141 |
142 | var response = _cosXmlServer.GetObject(request);
143 |
144 |
145 | await response.HandlerError("下载文件出错!");
146 | byte[] content = response.content;
147 | return new MemoryStream(content);
148 | }
149 |
150 |
151 |
152 | public Task GetBlobUrl(string containerName, string blobName)
153 | {
154 | var preSignatureStruct = new PreSignatureStruct();
155 | preSignatureStruct.appid = _tcConfig.AppId;//腾讯云账号 APPID
156 | preSignatureStruct.region = _tcConfig.Region; //存储桶地域
157 | preSignatureStruct.bucket = _tcConfig.BucketName; //存储桶
158 | preSignatureStruct.key = $"{containerName}/{blobName}"; //对象键
159 | preSignatureStruct.httpMethod = "PUT"; //HTTP 请求方法
160 | preSignatureStruct.isHttps = true; //生成 HTTPS 请求 URL
161 | preSignatureStruct.signDurationSecond = 600; //请求签名时间为 600s
162 | preSignatureStruct.headers = null;//签名中需要校验的 header
163 | preSignatureStruct.queryParameters = null; //签名中需要校验的 URL 中请求参数
164 |
165 | var url = _cosXmlServer.GenerateSignURL(preSignatureStruct);
166 | return Task.FromResult(url);
167 | }
168 |
169 | ///
170 | /// 获取授权访问链接
171 | ///
172 | /// 容器名称
173 | /// 文件名称
174 | /// 过期时间
175 | /// 是否允许下载
176 | /// 文件名
177 | /// 内容类型
178 | /// 访问限制
179 | ///
180 | public Task GetBlobUrl(string containerName, string blobName, DateTime expiry, bool isDownload = false,
181 | string fileName = null, string contentType = null, BlobUrlAccess access = BlobUrlAccess.Read)
182 | {
183 | var preSignatureStruct = new PreSignatureStruct();
184 | preSignatureStruct.appid = _tcConfig.AppId;//腾讯云账号 APPID
185 | preSignatureStruct.region = _tcConfig.Region; //存储桶地域
186 | preSignatureStruct.bucket = _tcConfig.BucketName; //存储桶
187 | preSignatureStruct.key = $"{containerName}/{blobName}"; //对象键
188 | preSignatureStruct.httpMethod = "PUT"; //HTTP 请求方法
189 | preSignatureStruct.isHttps = true; //生成 HTTPS 请求 URL
190 | preSignatureStruct.signDurationSecond = (long)(expiry - DateTime.Now).TotalSeconds; //请求签名时间为 600s
191 | preSignatureStruct.headers = null;//签名中需要校验的 header
192 | preSignatureStruct.queryParameters = null; //签名中需要校验的 URL 中请求参数
193 |
194 | var url = _cosXmlServer.GenerateSignURL(preSignatureStruct);
195 | return Task.FromResult(url);
196 | }
197 |
198 | ///
199 | /// 列出指定容器下的对象列表
200 | ///
201 | ///
202 | ///
203 | public async Task> ListBlobs(string containerName)
204 | {
205 | if (!string.IsNullOrWhiteSpace(containerName) && !containerName.EndsWith("/"))
206 | {
207 | containerName += "/";
208 | }
209 |
210 | var req = new GetBucketRequest(_tcConfig.BucketName);
211 | req.SetPrefix(containerName);
212 | var resp = _cosXmlServer.GetBucket(req);
213 | await resp.HandlerError("获取对象列表出错!");
214 | var list = resp.listBucket.contentsList
215 | .Select(obj =>
216 | new BlobFileInfo
217 | {
218 | Container = containerName?.Trim('/'),
219 | ETag = obj.eTag,
220 | Length = obj.size,
221 | LastModified = Convert.ToDateTime(obj.lastModified),
222 | Name = obj.key.Replace(containerName, string.Empty),
223 | Url = GetUrlByKey(obj.key),
224 | //ContentMD5 =
225 | });
226 | return list.ToArray();
227 | }
228 |
229 | ///
230 | /// 根据对象Key获取Url
231 | ///
232 | ///
233 | ///
234 | private string GetUrlByKey(string key) => $"https://{_tcConfig.BucketName}.cos.{_tcConfig.Region}.myqcloud.com/{key}";
235 |
236 | ///
237 | /// 保存对象到指定的容器
238 | ///
239 | ///
240 | ///
241 | ///
242 | public async Task SaveBlobStream(string containerName, string blobName, Stream source)
243 | {
244 | byte[] bytes;
245 | using (var ms = new MemoryStream())
246 | {
247 | source.CopyTo(ms);
248 | bytes = ms.ToArray();
249 | }
250 |
251 | var request = new PutObjectRequest(_tcConfig.BucketName, $"{containerName}/{blobName}", bytes)
252 | {
253 | };
254 |
255 | var response = _cosXmlServer.PutObject(request);
256 |
257 | await response.HandlerError("上传对象出错!");
258 | }
259 |
260 | }
261 | }
--------------------------------------------------------------------------------
/src/Magicodes.Storage.AliyunOss.Core/AliyunOssStorageProvider.cs:
--------------------------------------------------------------------------------
1 | using Aliyun.OSS;
2 | using Aliyun.OSS.Util;
3 | using Magicodes.Storage.Core;
4 | using System;
5 | using System.Collections.Generic;
6 | using System.IO;
7 | using System.Linq;
8 | using System.Threading.Tasks;
9 |
10 | namespace Magicodes.Storage.AliyunOss.Core
11 | {
12 | public class AliyunOssStorageProvider : IStorageProvider
13 | {
14 | private readonly AliyunOssConfig _cfg;
15 | private readonly string _baseUrl;
16 | private readonly OssClient _ossClient;
17 |
18 | public AliyunOssStorageProvider(AliyunOssConfig cfg)
19 | {
20 | _cfg = cfg;
21 | _ossClient = new OssClient(cfg.Endpoint, cfg.AccessKeyId, cfg.AccessKeySecret);
22 |
23 | _baseUrl = $"https://{cfg.BucketName}.{cfg.Endpoint}";
24 | }
25 |
26 | public string ProviderName => "AliyunOss";
27 |
28 | ///
29 | /// 保存对象到指定的容器
30 | ///
31 | ///
32 | ///
33 | ///
34 | public async Task SaveBlobStream(string containerName, string blobName, Stream source)
35 | {
36 | try
37 | {
38 | await Task.Run(() =>
39 | {
40 | var key = $"{containerName}/{blobName}";
41 | var md5 = OssUtils.ComputeContentMd5(source, source.Length);
42 | var objectMeta = new ObjectMetadata();
43 | objectMeta.AddHeader("Content-MD5", md5);
44 | objectMeta.UserMetadata.Add("Content-MD5", md5);
45 | _ossClient.PutObject(_cfg.BucketName, key, source, objectMeta).HandlerError("上传对象出错");
46 | });
47 | }
48 | catch (Exception ex)
49 | {
50 | throw new StorageException(StorageErrorCode.PostError.ToStorageError(),
51 | new Exception(ex.ToString()));
52 | }
53 | }
54 |
55 | ///
56 | /// 获取对象
57 | ///
58 | ///
59 | ///
60 | ///
61 | public async Task GetBlobStream(string containerName, string blobName)
62 | {
63 | try
64 | {
65 | return await Task.Run(() =>
66 | {
67 | var key = $"{containerName}/{blobName}";
68 | var blob = _ossClient.GetObject(_cfg.BucketName, key).HandlerError("获取对象出错");
69 | if (blob == null || blob.ContentLength == 0)
70 | {
71 | throw new StorageException(StorageErrorCode.FileNotFound.ToStorageError(),
72 | new Exception("没有找到该文件"));
73 | }
74 | return blob.Content;
75 | });
76 | }
77 | catch (Exception ex)
78 | {
79 | throw new StorageException(StorageErrorCode.ErrorOpeningBlob.ToStorageError(),
80 | new Exception(ex.ToString()));
81 | }
82 | }
83 |
84 | ///
85 | /// 获取文件链接
86 | ///
87 | ///
88 | ///
89 | ///
90 | public async Task GetBlobUrl(string containerName, string blobName) => await Task.Run(() => $"{_baseUrl}/{containerName}/{blobName}");
91 |
92 | ///
93 | /// 获取对象属性
94 | ///
95 | ///
96 | ///
97 | ///
98 | public async Task GetBlobFileInfo(string containerName, string blobName)
99 | {
100 | try
101 | {
102 | return await Task.Run(() =>
103 | {
104 | var key = $"{containerName}/{blobName}";
105 | var result = _ossClient.GetObjectMetadata(_cfg.BucketName, key);
106 | return new BlobFileInfo
107 | {
108 | Container = containerName,
109 | ETag = result.ETag,
110 | LastModified = result.LastModified,
111 | Name = blobName,
112 | Length = result.ContentLength,
113 | Url = string.Format(_baseUrl, containerName, blobName),
114 | ContentMD5 = result.ContentMd5,
115 | ContentType = result.ContentType
116 | };
117 | });
118 | }
119 | catch (Exception ex)
120 | {
121 | throw new StorageException(StorageErrorCode.PostError.ToStorageError(),
122 | new Exception(ex.ToString()));
123 | }
124 | }
125 |
126 | ///
127 | /// 列出指定容器下的对象列表
128 | ///
129 | ///
130 | ///
131 | public async Task> ListBlobs(string containerName)
132 | {
133 | var blobFileInfos = new List();
134 | try
135 | {
136 | return await Task.Run(() =>
137 | {
138 | if (!string.IsNullOrWhiteSpace(containerName) && !containerName.EndsWith("/"))
139 | {
140 | containerName += "/";
141 | }
142 | var listObjectsRequest = new ListObjectsRequest(_cfg.BucketName)
143 | {
144 | Prefix = containerName
145 | };
146 | var result = _ossClient.ListObjects(listObjectsRequest).HandlerError("获取对象列表出错!");
147 | foreach (var summary in result.ObjectSummaries)
148 | {
149 | blobFileInfos.Add(new BlobFileInfo
150 | {
151 | Container = summary.BucketName,
152 | ETag = summary.ETag,
153 | LastModified = summary.LastModified,
154 | Name = summary.Key,
155 | Length = summary.Size,
156 | Url = string.Format(_baseUrl, summary.BucketName, summary.Key)
157 | });
158 | }
159 |
160 | return blobFileInfos;
161 | });
162 | }
163 | catch (Exception ex)
164 | {
165 | throw new StorageException(StorageErrorCode.PostError.ToStorageError(),
166 | new Exception(ex.ToString()));
167 | }
168 | }
169 |
170 | ///
171 | /// 删除对象
172 | ///
173 | ///
174 | ///
175 | public async Task DeleteBlob(string containerName, string blobName)
176 | {
177 | try
178 | {
179 | await Task.Run(() =>
180 | {
181 | var key = $"{containerName}/{blobName}";
182 | _ossClient.DeleteObject(_cfg.BucketName, key);
183 |
184 | });
185 | }
186 | catch (Exception ex)
187 | {
188 | throw new StorageException(StorageErrorCode.PostError.ToStorageError(),
189 | new Exception(ex.ToString()));
190 | }
191 | }
192 |
193 | ///
194 | /// 删除目录(会删除下面所有的文件)
195 | ///
196 | ///
197 | public async Task DeleteContainer(string containerName)
198 | {
199 | try
200 | {
201 | //删除目录等于删除该目录下的所有文件
202 | var blobs = await ListBlobs(containerName);
203 | await Task.Run(() =>
204 | {
205 | var count = blobs.Count / 1000 + (blobs.Count % 1000 > 0 ? 1 : 0);
206 |
207 | for (var i = 0; i < count; i++)
208 | {
209 | var request = new DeleteObjectsRequest(_cfg.BucketName,
210 | blobs.Skip(i * 1000).Take(1000).Select(p => $"{containerName}/{p.Name}").ToList());
211 |
212 | _ossClient.DeleteObjects(request).HandlerError("删除对象时出错(删除目录会删除该目录下所有的文件)!");
213 | }
214 | });
215 | }
216 | catch (Exception ex)
217 | {
218 | throw new StorageException(StorageErrorCode.PostError.ToStorageError(),
219 | new Exception(ex.ToString()));
220 | }
221 | }
222 |
223 | ///
224 | /// 获取授权访问链接
225 | ///
226 | /// 容器名称
227 | /// 文件名称
228 | /// 过期时间
229 | /// 是否允许下载
230 | /// 文件名
231 | /// 内容类型
232 | /// 访问限制
233 | ///
234 | public async Task GetBlobUrl(string containerName, string blobName, DateTime expiry,
235 | bool isDownload = false,
236 | string fileName = null, string contentType = null, BlobUrlAccess access = BlobUrlAccess.Read)
237 | {
238 | try
239 | {
240 | var httpMethod = SignHttpMethod.Get;
241 | return await Task.Run(() =>
242 | {
243 | switch (access)
244 | {
245 | case BlobUrlAccess.Read:
246 | httpMethod = SignHttpMethod.Get;
247 | break;
248 | case BlobUrlAccess.All:
249 | case BlobUrlAccess.Write:
250 | httpMethod = SignHttpMethod.Put;
251 | break;
252 | case BlobUrlAccess.Delete:
253 | httpMethod = SignHttpMethod.Delete;
254 | break;
255 | default:
256 | throw new StorageException(StorageErrorCode.InvalidAccess.ToStorageError(),
257 | new Exception("无效的访问凭据"));
258 | }
259 |
260 | var req = new GeneratePresignedUriRequest(containerName, blobName, httpMethod)
261 | {
262 | Expiration = expiry
263 | };
264 | var url = _ossClient.GeneratePresignedUri(req);
265 | return url.AbsoluteUri;
266 | });
267 | }
268 | catch (Exception ex)
269 | {
270 | throw new StorageException(StorageErrorCode.PostError.ToStorageError(),
271 | new Exception(ex.ToString()));
272 | }
273 | }
274 | }
275 | }
--------------------------------------------------------------------------------
/src/Magicodes.Storage.Local.Core/LocalStorageProvider.cs:
--------------------------------------------------------------------------------
1 | // ======================================================================
2 | //
3 | // Copyright (C) 2016-2020 湖南心莱信息科技有限公司
4 | // All rights reserved
5 | //
6 | // filename : LocalStorageProvider.cs
7 | // description :
8 | //
9 | // created by 李文强 at 2018/03/25 9:45
10 | // Blog:http://www.cnblogs.com/codelove/
11 | // GitHub : https://github.com/xin-lai
12 | // Home:http://xin-lai.com
13 | // 交流QQ群(.NET 技术交流群):85318032
14 | //
15 | // ======================================================================
16 |
17 | namespace Magicodes.Storage.Local.Core
18 | {
19 | using Magicodes.Storage.Core;
20 | using System;
21 | using System.Collections.Generic;
22 | using System.IO;
23 | using System.Threading.Tasks;
24 |
25 | ///
26 | /// 本地存储提供程序
27 | ///
28 | public class LocalStorageProvider : IStorageProvider
29 | {
30 | ///
31 | /// Defines the _rootPath
32 | ///
33 | private readonly string _rootPath;
34 |
35 | ///
36 | /// Defines the _rootUrl
37 | ///
38 | private readonly string _rootUrl;
39 |
40 | ///
41 | /// Gets the ProviderName
42 | ///
43 | public string ProviderName => "Local";
44 |
45 | ///
46 | /// Gets or sets the AllowExtensionList
47 | /// 允许的扩展列表
48 | ///
49 | public IList AllowExtensionList { get; set; }
50 |
51 | ///
52 | /// The ExceptionHandling
53 | ///
54 | /// The ioAction
55 | private void ExceptionHandling(Action ioAction)
56 | {
57 | try
58 | {
59 | ioAction();
60 | }
61 | catch (UnauthorizedAccessException ex)
62 | {
63 | throw new StorageException(StorageErrorCode.InvalidAccess.ToStorageError(), ex);
64 | }
65 | catch (ArgumentException ex)
66 | {
67 | throw new StorageException(StorageErrorCode.InvalidBlobName.ToStorageError(), ex);
68 | }
69 | catch (DirectoryNotFoundException ex)
70 | {
71 | throw new StorageException(StorageErrorCode.ContainerNotFound.ToStorageError(), ex);
72 | }
73 | catch (NotSupportedException ex)
74 | {
75 | throw new StorageException(StorageErrorCode.InvalidBlobName.ToStorageError(), ex);
76 | }
77 | catch (FileNotFoundException ex)
78 | {
79 | throw new StorageException(StorageErrorCode.FileNotFound.ToStorageError(), ex);
80 | }
81 | catch (IOException ex)
82 | {
83 | throw new StorageException(StorageErrorCode.BlobInUse.ToStorageError(), ex);
84 | }
85 | catch (Exception ex)
86 | {
87 | throw new StorageException(StorageErrorCode.GenericException.ToStorageError(), ex);
88 | }
89 | }
90 |
91 | ///
92 | /// The ExceptionHandling
93 | ///
94 | ///
95 | /// The ioFunc
96 | /// The
97 | private T ExceptionHandling(Func ioFunc)
98 | {
99 | try
100 | {
101 | return ioFunc();
102 | }
103 | catch (UnauthorizedAccessException ex)
104 | {
105 | throw new StorageException(StorageErrorCode.InvalidAccess.ToStorageError(), ex);
106 | }
107 | catch (ArgumentException ex)
108 | {
109 | throw new StorageException(StorageErrorCode.InvalidBlobName.ToStorageError(), ex);
110 | }
111 | catch (DirectoryNotFoundException ex)
112 | {
113 | throw new StorageException(StorageErrorCode.ContainerNotFound.ToStorageError(), ex);
114 | }
115 | catch (NotSupportedException ex)
116 | {
117 | throw new StorageException(StorageErrorCode.InvalidBlobName.ToStorageError(), ex);
118 | }
119 | catch (FileNotFoundException ex)
120 | {
121 | throw new StorageException(StorageErrorCode.FileNotFound.ToStorageError(), ex);
122 | }
123 | catch (IOException ex)
124 | {
125 | throw new StorageException(StorageErrorCode.BlobInUse.ToStorageError(), ex);
126 | }
127 | catch (Exception ex)
128 | {
129 | throw new StorageException(StorageErrorCode.GenericException.ToStorageError(), ex);
130 | }
131 | }
132 |
133 | ///
134 | /// Initializes a new instance of the class.
135 | ///
136 | /// 文件根路径
137 | /// 根Url
138 | public LocalStorageProvider(string rootPath, string rootUrl)
139 | {
140 | _rootPath = rootPath;
141 | _rootUrl = rootUrl;
142 | }
143 |
144 | public LocalStorageProvider(LocalStorageConfig localStorageConfig)
145 | {
146 | _rootPath = localStorageConfig.RootPath;
147 | _rootUrl = localStorageConfig.RootUrl;
148 | }
149 |
150 | ///
151 | /// 删除文件
152 | ///
153 | ///
154 | ///
155 | /// The
156 | public async Task DeleteBlob(string containerName, string blobName)
157 | {
158 | await Task.Run(() =>
159 | {
160 | ExceptionHandling(() =>
161 | {
162 | var path = Path.Combine(_rootPath, containerName, blobName);
163 | File.Delete(path);
164 | });
165 | });
166 | }
167 |
168 | ///
169 | /// 删除容器
170 | ///
171 | /// 容器名称
172 | /// The
173 | public async Task DeleteContainer(string containerName)
174 | {
175 | await Task.Run(() =>
176 | {
177 | ExceptionHandling(() =>
178 | {
179 | var path = Path.Combine(_rootPath, containerName);
180 | Directory.Delete(path, true);
181 | });
182 | });
183 | }
184 |
185 | ///
186 | /// 获取文件信息
187 | ///
188 | ///
189 | ///
190 | ///
191 | public async Task GetBlobFileInfo(string containerName, string blobName)
192 | {
193 | return await Task.Run(() => ExceptionHandling(() =>
194 | {
195 | var path = Path.Combine(_rootPath, containerName, blobName);
196 | var info = new FileInfo(path);
197 |
198 | return new BlobFileInfo
199 | {
200 | Container = containerName,
201 | ContentMD5 = "",
202 | ContentType = info.Extension.GetMimeType(),
203 | ETag = "",
204 | LastModified = info.LastWriteTimeUtc,
205 | Length = info.Length,
206 | Name = info.Name,
207 | Url = GetUrl(containerName, blobName)
208 | };
209 | }));
210 | }
211 |
212 | ///
213 | /// The GetBlobStream
214 | ///
215 | /// The containerName
216 | /// The blobName
217 | /// The
218 | public async Task GetBlobStream(string containerName, string blobName)
219 | {
220 | return await Task.Run(() =>
221 | {
222 | return ExceptionHandling(() =>
223 | {
224 | var path = Path.Combine(_rootPath, containerName, blobName);
225 | return (Stream)File.OpenRead(path);
226 | });
227 | });
228 | }
229 |
230 | ///
231 | /// The GetBlobUrl
232 | ///
233 | /// The containerName
234 | /// The blobName
235 | /// The
236 | public Task GetBlobUrl(string containerName, string blobName)
237 | {
238 | var path = Path.Combine(_rootPath, containerName, blobName);
239 | if (!Directory.Exists(Path.Combine(_rootPath, containerName)))
240 | {
241 | throw new StorageException(StorageErrorCode.ContainerNotFound.ToStorageError(), null);
242 | }
243 |
244 | if (!File.Exists(path))
245 | {
246 | throw new StorageException(StorageErrorCode.FileNotFound.ToStorageError(), null);
247 | }
248 | var url = GetUrl(containerName, blobName);
249 | return Task.FromResult(url);
250 | }
251 |
252 | private string GetUrl(string containerName, string blobName) => string.Format("{0}/{1}/{2}", _rootUrl.TrimEnd('/'), containerName, blobName);
253 | ///
254 | /// The ListBlobs
255 | ///
256 | /// The containerName
257 | /// The
258 | public async Task> ListBlobs(string containerName)
259 | {
260 | return await Task.Run(() =>
261 | {
262 | return ExceptionHandling(() =>
263 | {
264 | var localFilesInfo = new List();
265 | var dir = Path.Combine(_rootPath, containerName);
266 | var dirInfo = new DirectoryInfo(dir);
267 | var fileInfo = dirInfo.GetFiles();
268 |
269 | foreach (var f in fileInfo)
270 | localFilesInfo.Add(new BlobFileInfo
271 | {
272 | ContentMD5 = "",
273 | ETag = "",
274 | ContentType = f.Extension.GetMimeType(),
275 | Container = containerName,
276 | LastModified = f.LastWriteTime,
277 | Length = f.Length,
278 | Name = f.Name,
279 | Url = f.FullName,
280 | });
281 |
282 | return localFilesInfo;
283 | });
284 | });
285 | }
286 |
287 | ///
288 | /// The SaveBlobStream
289 | ///
290 | /// The containerName
291 | /// The blobName
292 | /// The source
293 | /// The
294 | public async Task SaveBlobStream(string containerName, string blobName, Stream source)
295 | {
296 | await Task.Run(() =>
297 | {
298 | ExceptionHandling(() =>
299 | {
300 | var dir = Path.Combine(_rootPath, containerName);
301 | Directory.CreateDirectory(dir);
302 | using (var file = File.Create(Path.Combine(dir, blobName)))
303 | {
304 | if (AllowExtensionList != null && AllowExtensionList.Contains((Path.GetExtension(blobName) ?? "".ToLower())))
305 | {
306 | throw new StorageException(StorageErrorCode.UnsupportedFileType.ToStorageError(), new Exception("不支持 " + Path.GetExtension(blobName) + " 类型的文件上传,请查看允许的扩展名设置!"));
307 | }
308 | source.CopyTo(file);
309 | }
310 | });
311 | });
312 | }
313 |
314 | ///
315 | /// The GetBlobUrl
316 | ///
317 | /// The containerName
318 | /// The blobName
319 | /// The expiry
320 | /// The isDownload
321 | /// The fileName
322 | /// The contentType
323 | /// The access
324 | /// The
325 | public Task GetBlobUrl(string containerName, string blobName, DateTime expiry, bool isDownload = false, string fileName = null, string contentType = null, BlobUrlAccess access = BlobUrlAccess.Read) => throw new NotSupportedException();
326 | }
327 | }
328 |
--------------------------------------------------------------------------------
/src/Magicodes.Storage.Local.Core/MimeInfo.cs:
--------------------------------------------------------------------------------
1 | // ======================================================================
2 | //
3 | // Copyright (C) 2016-2020 湖南心莱信息科技有限公司
4 | // All rights reserved
5 | //
6 | // filename : MimeInfo.cs
7 | // description :
8 | //
9 | // created by 李文强 at 2018/03/25 9:45
10 | // Blog:http://www.cnblogs.com/codelove/
11 | // GitHub : https://github.com/xin-lai
12 | // Home:http://xin-lai.com
13 | // 交流QQ群(.NET 技术交流群):85318032
14 | //
15 | // ======================================================================
16 |
17 | using System;
18 | using System.Collections.Generic;
19 |
20 | namespace Magicodes.Storage.Local.Core
21 | {
22 | public static class MimeInfo
23 | {
24 | private static readonly IDictionary MimeMappings =
25 | new Dictionary(StringComparer.CurrentCultureIgnoreCase)
26 | {
27 | {".323", "text/h323"},
28 | {".3g2", "video/3gpp2"},
29 | {".3gp", "video/3gpp"},
30 | {".3gp2", "video/3gpp2"},
31 | {".3gpp", "video/3gpp"},
32 | {".7z", "application/x-7z-compressed"},
33 | {".aa", "audio/audible"},
34 | {".AAC", "audio/aac"},
35 | {".aaf", "application/octet-stream"},
36 | {".aax", "audio/vnd.audible.aax"},
37 | {".ac3", "audio/ac3"},
38 | {".aca", "application/octet-stream"},
39 | {".accda", "application/msaccess.addin"},
40 | {".accdb", "application/msaccess"},
41 | {".accdc", "application/msaccess.cab"},
42 | {".accde", "application/msaccess"},
43 | {".accdr", "application/msaccess.runtime"},
44 | {".accdt", "application/msaccess"},
45 | {".accdw", "application/msaccess.webapplication"},
46 | {".accft", "application/msaccess.ftemplate"},
47 | {".acx", "application/internet-property-stream"},
48 | {".AddIn", "text/xml"},
49 | {".ade", "application/msaccess"},
50 | {".adobebridge", "application/x-bridge-url"},
51 | {".adp", "application/msaccess"},
52 | {".ADT", "audio/vnd.dlna.adts"},
53 | {".ADTS", "audio/aac"},
54 | {".afm", "application/octet-stream"},
55 | {".ai", "application/postscript"},
56 | {".aif", "audio/x-aiff"},
57 | {".aifc", "audio/aiff"},
58 | {".aiff", "audio/aiff"},
59 | {".air", "application/vnd.adobe.air-application-installer-package+zip"},
60 | {".amc", "application/x-mpeg"},
61 | {".application", "application/x-ms-application"},
62 | {".art", "image/x-jg"},
63 | {".asa", "application/xml"},
64 | {".asax", "application/xml"},
65 | {".ascx", "application/xml"},
66 | {".asd", "application/octet-stream"},
67 | {".asf", "video/x-ms-asf"},
68 | {".ashx", "application/xml"},
69 | {".asi", "application/octet-stream"},
70 | {".asm", "text/plain"},
71 | {".asmx", "application/xml"},
72 | {".aspx", "application/xml"},
73 | {".asr", "video/x-ms-asf"},
74 | {".asx", "video/x-ms-asf"},
75 | {".atom", "application/atom+xml"},
76 | {".au", "audio/basic"},
77 | {".avi", "video/x-msvideo"},
78 | {".axs", "application/olescript"},
79 | {".bas", "text/plain"},
80 | {".bcpio", "application/x-bcpio"},
81 | {".bin", "application/octet-stream"},
82 | {".bmp", "image/bmp"},
83 | {".c", "text/plain"},
84 | {".cab", "application/octet-stream"},
85 | {".caf", "audio/x-caf"},
86 | {".calx", "application/vnd.ms-office.calx"},
87 | {".cat", "application/vnd.ms-pki.seccat"},
88 | {".cc", "text/plain"},
89 | {".cd", "text/plain"},
90 | {".cdda", "audio/aiff"},
91 | {".cdf", "application/x-cdf"},
92 | {".cer", "application/x-x509-ca-cert"},
93 | {".chm", "application/octet-stream"},
94 | {".class", "application/x-java-applet"},
95 | {".clp", "application/x-msclip"},
96 | {".cmx", "image/x-cmx"},
97 | {".cnf", "text/plain"},
98 | {".cod", "image/cis-cod"},
99 | {".config", "application/xml"},
100 | {".contact", "text/x-ms-contact"},
101 | {".coverage", "application/xml"},
102 | {".cpio", "application/x-cpio"},
103 | {".cpp", "text/plain"},
104 | {".crd", "application/x-mscardfile"},
105 | {".crl", "application/pkix-crl"},
106 | {".crt", "application/x-x509-ca-cert"},
107 | {".cs", "text/plain"},
108 | {".csdproj", "text/plain"},
109 | {".csh", "application/x-csh"},
110 | {".csproj", "text/plain"},
111 | {".css", "text/css"},
112 | {".csv", "text/csv"},
113 | {".cur", "application/octet-stream"},
114 | {".cxx", "text/plain"},
115 | {".dat", "application/octet-stream"},
116 | {".datasource", "application/xml"},
117 | {".dbproj", "text/plain"},
118 | {".dcr", "application/x-director"},
119 | {".def", "text/plain"},
120 | {".deploy", "application/octet-stream"},
121 | {".der", "application/x-x509-ca-cert"},
122 | {".dgml", "application/xml"},
123 | {".dib", "image/bmp"},
124 | {".dif", "video/x-dv"},
125 | {".dir", "application/x-director"},
126 | {".disco", "text/xml"},
127 | {".dll", "application/x-msdownload"},
128 | {".dll.config", "text/xml"},
129 | {".dlm", "text/dlm"},
130 | {".doc", "application/msword"},
131 | {".docm", "application/vnd.ms-word.document.macroEnabled.12"},
132 | {".docx", "application/vnd.openxmlformats-officedocument.wordprocessingml.document"},
133 | {".dot", "application/msword"},
134 | {".dotm", "application/vnd.ms-word.template.macroEnabled.12"},
135 | {".dotx", "application/vnd.openxmlformats-officedocument.wordprocessingml.template"},
136 | {".dsp", "application/octet-stream"},
137 | {".dsw", "text/plain"},
138 | {".dtd", "text/xml"},
139 | {".dtsConfig", "text/xml"},
140 | {".dv", "video/x-dv"},
141 | {".dvi", "application/x-dvi"},
142 | {".dwf", "drawing/x-dwf"},
143 | {".dwp", "application/octet-stream"},
144 | {".dxr", "application/x-director"},
145 | {".eml", "message/rfc822"},
146 | {".emz", "application/octet-stream"},
147 | {".eot", "application/octet-stream"},
148 | {".eps", "application/postscript"},
149 | {".etl", "application/etl"},
150 | {".etx", "text/x-setext"},
151 | {".evy", "application/envoy"},
152 | {".exe", "application/octet-stream"},
153 | {".exe.config", "text/xml"},
154 | {".fdf", "application/vnd.fdf"},
155 | {".fif", "application/fractals"},
156 | {".filters", "Application/xml"},
157 | {".fla", "application/octet-stream"},
158 | {".flr", "x-world/x-vrml"},
159 | {".flv", "video/x-flv"},
160 | {".fsscript", "application/fsharp-script"},
161 | {".fsx", "application/fsharp-script"},
162 | {".generictest", "application/xml"},
163 | {".gif", "image/gif"},
164 | {".group", "text/x-ms-group"},
165 | {".gsm", "audio/x-gsm"},
166 | {".gtar", "application/x-gtar"},
167 | {".gz", "application/x-gzip"},
168 | {".h", "text/plain"},
169 | {".hdf", "application/x-hdf"},
170 | {".hdml", "text/x-hdml"},
171 | {".hhc", "application/x-oleobject"},
172 | {".hhk", "application/octet-stream"},
173 | {".hhp", "application/octet-stream"},
174 | {".hlp", "application/winhlp"},
175 | {".hpp", "text/plain"},
176 | {".hqx", "application/mac-binhex40"},
177 | {".hta", "application/hta"},
178 | {".htc", "text/x-component"},
179 | {".htm", "text/html"},
180 | {".html", "text/html"},
181 | {".htt", "text/webviewhtml"},
182 | {".hxa", "application/xml"},
183 | {".hxc", "application/xml"},
184 | {".hxd", "application/octet-stream"},
185 | {".hxe", "application/xml"},
186 | {".hxf", "application/xml"},
187 | {".hxh", "application/octet-stream"},
188 | {".hxi", "application/octet-stream"},
189 | {".hxk", "application/xml"},
190 | {".hxq", "application/octet-stream"},
191 | {".hxr", "application/octet-stream"},
192 | {".hxs", "application/octet-stream"},
193 | {".hxt", "text/html"},
194 | {".hxv", "application/xml"},
195 | {".hxw", "application/octet-stream"},
196 | {".hxx", "text/plain"},
197 | {".i", "text/plain"},
198 | {".ico", "image/x-icon"},
199 | {".ics", "application/octet-stream"},
200 | {".idl", "text/plain"},
201 | {".ief", "image/ief"},
202 | {".iii", "application/x-iphone"},
203 | {".inc", "text/plain"},
204 | {".inf", "application/octet-stream"},
205 | {".inl", "text/plain"},
206 | {".ins", "application/x-internet-signup"},
207 | {".ipa", "application/x-itunes-ipa"},
208 | {".ipg", "application/x-itunes-ipg"},
209 | {".ipproj", "text/plain"},
210 | {".ipsw", "application/x-itunes-ipsw"},
211 | {".iqy", "text/x-ms-iqy"},
212 | {".isp", "application/x-internet-signup"},
213 | {".ite", "application/x-itunes-ite"},
214 | {".itlp", "application/x-itunes-itlp"},
215 | {".itms", "application/x-itunes-itms"},
216 | {".itpc", "application/x-itunes-itpc"},
217 | {".IVF", "video/x-ivf"},
218 | {".jar", "application/java-archive"},
219 | {".java", "application/octet-stream"},
220 | {".jck", "application/liquidmotion"},
221 | {".jcz", "application/liquidmotion"},
222 | {".jfif", "image/pjpeg"},
223 | {".jnlp", "application/x-java-jnlp-file"},
224 | {".jpb", "application/octet-stream"},
225 | {".jpe", "image/jpeg"},
226 | {".jpeg", "image/jpeg"},
227 | {".jpg", "image/jpeg"},
228 | {".js", "application/x-javascript"},
229 | {".json", "application/json"},
230 | {".jsx", "text/jscript"},
231 | {".jsxbin", "text/plain"},
232 | {".latex", "application/x-latex"},
233 | {".library-ms", "application/windows-library+xml"},
234 | {".lit", "application/x-ms-reader"},
235 | {".loadtest", "application/xml"},
236 | {".lpk", "application/octet-stream"},
237 | {".lsf", "video/x-la-asf"},
238 | {".lst", "text/plain"},
239 | {".lsx", "video/x-la-asf"},
240 | {".lzh", "application/octet-stream"},
241 | {".m13", "application/x-msmediaview"},
242 | {".m14", "application/x-msmediaview"},
243 | {".m1v", "video/mpeg"},
244 | {".m2t", "video/vnd.dlna.mpeg-tts"},
245 | {".m2ts", "video/vnd.dlna.mpeg-tts"},
246 | {".m2v", "video/mpeg"},
247 | {".m3u", "audio/x-mpegurl"},
248 | {".m3u8", "audio/x-mpegurl"},
249 | {".m4a", "audio/m4a"},
250 | {".m4b", "audio/m4b"},
251 | {".m4p", "audio/m4p"},
252 | {".m4r", "audio/x-m4r"},
253 | {".m4v", "video/x-m4v"},
254 | {".mac", "image/x-macpaint"},
255 | {".mak", "text/plain"},
256 | {".man", "application/x-troff-man"},
257 | {".manifest", "application/x-ms-manifest"},
258 | {".map", "text/plain"},
259 | {".master", "application/xml"},
260 | {".mda", "application/msaccess"},
261 | {".mdb", "application/x-msaccess"},
262 | {".mde", "application/msaccess"},
263 | {".mdp", "application/octet-stream"},
264 | {".me", "application/x-troff-me"},
265 | {".mfp", "application/x-shockwave-flash"},
266 | {".mht", "message/rfc822"},
267 | {".mhtml", "message/rfc822"},
268 | {".mid", "audio/mid"},
269 | {".midi", "audio/mid"},
270 | {".mix", "application/octet-stream"},
271 | {".mk", "text/plain"},
272 | {".mmf", "application/x-smaf"},
273 | {".mno", "text/xml"},
274 | {".mny", "application/x-msmoney"},
275 | {".mod", "video/mpeg"},
276 | {".mov", "video/quicktime"},
277 | {".movie", "video/x-sgi-movie"},
278 | {".mp2", "video/mpeg"},
279 | {".mp2v", "video/mpeg"},
280 | {".mp3", "audio/mpeg"},
281 | {".mp4", "video/mp4"},
282 | {".mp4v", "video/mp4"},
283 | {".mpa", "video/mpeg"},
284 | {".mpe", "video/mpeg"},
285 | {".mpeg", "video/mpeg"},
286 | {".mpf", "application/vnd.ms-mediapackage"},
287 | {".mpg", "video/mpeg"},
288 | {".mpp", "application/vnd.ms-project"},
289 | {".mpv2", "video/mpeg"},
290 | {".mqv", "video/quicktime"},
291 | {".ms", "application/x-troff-ms"},
292 | {".msi", "application/octet-stream"},
293 | {".mso", "application/octet-stream"},
294 | {".mts", "video/vnd.dlna.mpeg-tts"},
295 | {".mtx", "application/xml"},
296 | {".mvb", "application/x-msmediaview"},
297 | {".mvc", "application/x-miva-compiled"},
298 | {".mxp", "application/x-mmxp"},
299 | {".nc", "application/x-netcdf"},
300 | {".nsc", "video/x-ms-asf"},
301 | {".nws", "message/rfc822"},
302 | {".ocx", "application/octet-stream"},
303 | {".oda", "application/oda"},
304 | {".odc", "text/x-ms-odc"},
305 | {".odh", "text/plain"},
306 | {".odl", "text/plain"},
307 | {".odp", "application/vnd.oasis.opendocument.presentation"},
308 | {".ods", "application/oleobject"},
309 | {".odt", "application/vnd.oasis.opendocument.text"},
310 | {".one", "application/onenote"},
311 | {".onea", "application/onenote"},
312 | {".onepkg", "application/onenote"},
313 | {".onetmp", "application/onenote"},
314 | {".onetoc", "application/onenote"},
315 | {".onetoc2", "application/onenote"},
316 | {".orderedtest", "application/xml"},
317 | {".osdx", "application/opensearchdescription+xml"},
318 | {".p10", "application/pkcs10"},
319 | {".p12", "application/x-pkcs12"},
320 | {".p7b", "application/x-pkcs7-certificates"},
321 | {".p7c", "application/pkcs7-mime"},
322 | {".p7m", "application/pkcs7-mime"},
323 | {".p7r", "application/x-pkcs7-certreqresp"},
324 | {".p7s", "application/pkcs7-signature"},
325 | {".pbm", "image/x-portable-bitmap"},
326 | {".pcast", "application/x-podcast"},
327 | {".pct", "image/pict"},
328 | {".pcx", "application/octet-stream"},
329 | {".pcz", "application/octet-stream"},
330 | {".pdf", "application/pdf"},
331 | {".pfb", "application/octet-stream"},
332 | {".pfm", "application/octet-stream"},
333 | {".pfx", "application/x-pkcs12"},
334 | {".pgm", "image/x-portable-graymap"},
335 | {".pic", "image/pict"},
336 | {".pict", "image/pict"},
337 | {".pkgdef", "text/plain"},
338 | {".pkgundef", "text/plain"},
339 | {".pko", "application/vnd.ms-pki.pko"},
340 | {".pls", "audio/scpls"},
341 | {".pma", "application/x-perfmon"},
342 | {".pmc", "application/x-perfmon"},
343 | {".pml", "application/x-perfmon"},
344 | {".pmr", "application/x-perfmon"},
345 | {".pmw", "application/x-perfmon"},
346 | {".png", "image/png"},
347 | {".pnm", "image/x-portable-anymap"},
348 | {".pnt", "image/x-macpaint"},
349 | {".pntg", "image/x-macpaint"},
350 | {".pnz", "image/png"},
351 | {".pot", "application/vnd.ms-powerpoint"},
352 | {".potm", "application/vnd.ms-powerpoint.template.macroEnabled.12"},
353 | {".potx", "application/vnd.openxmlformats-officedocument.presentationml.template"},
354 | {".ppa", "application/vnd.ms-powerpoint"},
355 | {".ppam", "application/vnd.ms-powerpoint.addin.macroEnabled.12"},
356 | {".ppm", "image/x-portable-pixmap"},
357 | {".pps", "application/vnd.ms-powerpoint"},
358 | {".ppsm", "application/vnd.ms-powerpoint.slideshow.macroEnabled.12"},
359 | {".ppsx", "application/vnd.openxmlformats-officedocument.presentationml.slideshow"},
360 | {".ppt", "application/vnd.ms-powerpoint"},
361 | {".pptm", "application/vnd.ms-powerpoint.presentation.macroEnabled.12"},
362 | {".pptx", "application/vnd.openxmlformats-officedocument.presentationml.presentation"},
363 | {".prf", "application/pics-rules"},
364 | {".prm", "application/octet-stream"},
365 | {".prx", "application/octet-stream"},
366 | {".ps", "application/postscript"},
367 | {".psc1", "application/PowerShell"},
368 | {".psd", "application/octet-stream"},
369 | {".psess", "application/xml"},
370 | {".psm", "application/octet-stream"},
371 | {".psp", "application/octet-stream"},
372 | {".pub", "application/x-mspublisher"},
373 | {".pwz", "application/vnd.ms-powerpoint"},
374 | {".qht", "text/x-html-insertion"},
375 | {".qhtm", "text/x-html-insertion"},
376 | {".qt", "video/quicktime"},
377 | {".qti", "image/x-quicktime"},
378 | {".qtif", "image/x-quicktime"},
379 | {".qtl", "application/x-quicktimeplayer"},
380 | {".qxd", "application/octet-stream"},
381 | {".ra", "audio/x-pn-realaudio"},
382 | {".ram", "audio/x-pn-realaudio"},
383 | {".rar", "application/octet-stream"},
384 | {".ras", "image/x-cmu-raster"},
385 | {".rat", "application/rat-file"},
386 | {".rc", "text/plain"},
387 | {".rc2", "text/plain"},
388 | {".rct", "text/plain"},
389 | {".rdlc", "application/xml"},
390 | {".resx", "application/xml"},
391 | {".rf", "image/vnd.rn-realflash"},
392 | {".rgb", "image/x-rgb"},
393 | {".rgs", "text/plain"},
394 | {".rm", "application/vnd.rn-realmedia"},
395 | {".rmi", "audio/mid"},
396 | {".rmp", "application/vnd.rn-rn_music_package"},
397 | {".roff", "application/x-troff"},
398 | {".rpm", "audio/x-pn-realaudio-plugin"},
399 | {".rqy", "text/x-ms-rqy"},
400 | {".rtf", "application/rtf"},
401 | {".rtx", "text/richtext"},
402 | {".ruleset", "application/xml"},
403 | {".s", "text/plain"},
404 | {".safariextz", "application/x-safari-safariextz"},
405 | {".scd", "application/x-msschedule"},
406 | {".sct", "text/scriptlet"},
407 | {".sd2", "audio/x-sd2"},
408 | {".sdp", "application/sdp"},
409 | {".sea", "application/octet-stream"},
410 | {".searchConnector-ms", "application/windows-search-connector+xml"},
411 | {".setpay", "application/set-payment-initiation"},
412 | {".setreg", "application/set-registration-initiation"},
413 | {".settings", "application/xml"},
414 | {".sgimb", "application/x-sgimb"},
415 | {".sgml", "text/sgml"},
416 | {".sh", "application/x-sh"},
417 | {".shar", "application/x-shar"},
418 | {".shtml", "text/html"},
419 | {".sit", "application/x-stuffit"},
420 | {".sitemap", "application/xml"},
421 | {".skin", "application/xml"},
422 | {".sldm", "application/vnd.ms-powerpoint.slide.macroEnabled.12"},
423 | {".sldx", "application/vnd.openxmlformats-officedocument.presentationml.slide"},
424 | {".slk", "application/vnd.ms-excel"},
425 | {".sln", "text/plain"},
426 | {".slupkg-ms", "application/x-ms-license"},
427 | {".smd", "audio/x-smd"},
428 | {".smi", "application/octet-stream"},
429 | {".smx", "audio/x-smd"},
430 | {".smz", "audio/x-smd"},
431 | {".snd", "audio/basic"},
432 | {".snippet", "application/xml"},
433 | {".snp", "application/octet-stream"},
434 | {".sol", "text/plain"},
435 | {".sor", "text/plain"},
436 | {".spc", "application/x-pkcs7-certificates"},
437 | {".spl", "application/futuresplash"},
438 | {".src", "application/x-wais-source"},
439 | {".srf", "text/plain"},
440 | {".SSISDeploymentManifest", "text/xml"},
441 | {".ssm", "application/streamingmedia"},
442 | {".sst", "application/vnd.ms-pki.certstore"},
443 | {".stl", "application/vnd.ms-pki.stl"},
444 | {".sv4cpio", "application/x-sv4cpio"},
445 | {".sv4crc", "application/x-sv4crc"},
446 | {".svc", "application/xml"},
447 | {".swf", "application/x-shockwave-flash"},
448 | {".t", "application/x-troff"},
449 | {".tar", "application/x-tar"},
450 | {".tcl", "application/x-tcl"},
451 | {".testrunconfig", "application/xml"},
452 | {".testsettings", "application/xml"},
453 | {".tex", "application/x-tex"},
454 | {".texi", "application/x-texinfo"},
455 | {".texinfo", "application/x-texinfo"},
456 | {".tgz", "application/x-compressed"},
457 | {".thmx", "application/vnd.ms-officetheme"},
458 | {".thn", "application/octet-stream"},
459 | {".tif", "image/tiff"},
460 | {".tiff", "image/tiff"},
461 | {".tlh", "text/plain"},
462 | {".tli", "text/plain"},
463 | {".toc", "application/octet-stream"},
464 | {".tr", "application/x-troff"},
465 | {".trm", "application/x-msterminal"},
466 | {".trx", "application/xml"},
467 | {".ts", "video/vnd.dlna.mpeg-tts"},
468 | {".tsv", "text/tab-separated-values"},
469 | {".ttf", "application/octet-stream"},
470 | {".tts", "video/vnd.dlna.mpeg-tts"},
471 | {".txt", "text/plain"},
472 | {".u32", "application/octet-stream"},
473 | {".uls", "text/iuls"},
474 | {".user", "text/plain"},
475 | {".ustar", "application/x-ustar"},
476 | {".vb", "text/plain"},
477 | {".vbdproj", "text/plain"},
478 | {".vbk", "video/mpeg"},
479 | {".vbproj", "text/plain"},
480 | {".vbs", "text/vbscript"},
481 | {".vcf", "text/x-vcard"},
482 | {".vcproj", "Application/xml"},
483 | {".vcs", "text/plain"},
484 | {".vcxproj", "Application/xml"},
485 | {".vddproj", "text/plain"},
486 | {".vdp", "text/plain"},
487 | {".vdproj", "text/plain"},
488 | {".vdx", "application/vnd.ms-visio.viewer"},
489 | {".vml", "text/xml"},
490 | {".vscontent", "application/xml"},
491 | {".vsct", "text/xml"},
492 | {".vsd", "application/vnd.visio"},
493 | {".vsi", "application/ms-vsi"},
494 | {".vsix", "application/vsix"},
495 | {".vsixlangpack", "text/xml"},
496 | {".vsixmanifest", "text/xml"},
497 | {".vsmdi", "application/xml"},
498 | {".vspscc", "text/plain"},
499 | {".vss", "application/vnd.visio"},
500 | {".vsscc", "text/plain"},
501 | {".vssettings", "text/xml"},
502 | {".vssscc", "text/plain"},
503 | {".vst", "application/vnd.visio"},
504 | {".vstemplate", "text/xml"},
505 | {".vsto", "application/x-ms-vsto"},
506 | {".vsw", "application/vnd.visio"},
507 | {".vsx", "application/vnd.visio"},
508 | {".vtx", "application/vnd.visio"},
509 | {".wav", "audio/wav"},
510 | {".wave", "audio/wav"},
511 | {".wax", "audio/x-ms-wax"},
512 | {".wbk", "application/msword"},
513 | {".wbmp", "image/vnd.wap.wbmp"},
514 | {".wcm", "application/vnd.ms-works"},
515 | {".wdb", "application/vnd.ms-works"},
516 | {".wdp", "image/vnd.ms-photo"},
517 | {".webarchive", "application/x-safari-webarchive"},
518 | {".webtest", "application/xml"},
519 | {".wiq", "application/xml"},
520 | {".wiz", "application/msword"},
521 | {".wks", "application/vnd.ms-works"},
522 | {".WLMP", "application/wlmoviemaker"},
523 | {".wlpginstall", "application/x-wlpg-detect"},
524 | {".wlpginstall3", "application/x-wlpg3-detect"},
525 | {".wm", "video/x-ms-wm"},
526 | {".wma", "audio/x-ms-wma"},
527 | {".wmd", "application/x-ms-wmd"},
528 | {".wmf", "application/x-msmetafile"},
529 | {".wml", "text/vnd.wap.wml"},
530 | {".wmlc", "application/vnd.wap.wmlc"},
531 | {".wmls", "text/vnd.wap.wmlscript"},
532 | {".wmlsc", "application/vnd.wap.wmlscriptc"},
533 | {".wmp", "video/x-ms-wmp"},
534 | {".wmv", "video/x-ms-wmv"},
535 | {".wmx", "video/x-ms-wmx"},
536 | {".wmz", "application/x-ms-wmz"},
537 | {".wpl", "application/vnd.ms-wpl"},
538 | {".wps", "application/vnd.ms-works"},
539 | {".wri", "application/x-mswrite"},
540 | {".wrl", "x-world/x-vrml"},
541 | {".wrz", "x-world/x-vrml"},
542 | {".wsc", "text/scriptlet"},
543 | {".wsdl", "text/xml"},
544 | {".wvx", "video/x-ms-wvx"},
545 | {".x", "application/directx"},
546 | {".xaf", "x-world/x-vrml"},
547 | {".xaml", "application/xaml+xml"},
548 | {".xap", "application/x-silverlight-app"},
549 | {".xbap", "application/x-ms-xbap"},
550 | {".xbm", "image/x-xbitmap"},
551 | {".xdr", "text/plain"},
552 | {".xht", "application/xhtml+xml"},
553 | {".xhtml", "application/xhtml+xml"},
554 | {".xla", "application/vnd.ms-excel"},
555 | {".xlam", "application/vnd.ms-excel.addin.macroEnabled.12"},
556 | {".xlc", "application/vnd.ms-excel"},
557 | {".xld", "application/vnd.ms-excel"},
558 | {".xlk", "application/vnd.ms-excel"},
559 | {".xll", "application/vnd.ms-excel"},
560 | {".xlm", "application/vnd.ms-excel"},
561 | {".xls", "application/vnd.ms-excel"},
562 | {".xlsb", "application/vnd.ms-excel.sheet.binary.macroEnabled.12"},
563 | {".xlsm", "application/vnd.ms-excel.sheet.macroEnabled.12"},
564 | {".xlsx", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"},
565 | {".xlt", "application/vnd.ms-excel"},
566 | {".xltm", "application/vnd.ms-excel.template.macroEnabled.12"},
567 | {".xltx", "application/vnd.openxmlformats-officedocument.spreadsheetml.template"},
568 | {".xlw", "application/vnd.ms-excel"},
569 | {".xml", "text/xml"},
570 | {".xmta", "application/xml"},
571 | {".xof", "x-world/x-vrml"},
572 | {".XOML", "text/plain"},
573 | {".xpm", "image/x-xpixmap"},
574 | {".xps", "application/vnd.ms-xpsdocument"},
575 | {".xrm-ms", "text/xml"},
576 | {".xsc", "application/xml"},
577 | {".xsd", "text/xml"},
578 | {".xsf", "text/xml"},
579 | {".xsl", "text/xml"},
580 | {".xslt", "text/xml"},
581 | {".xsn", "application/octet-stream"},
582 | {".xss", "application/xml"},
583 | {".xtp", "application/octet-stream"},
584 | {".xwd", "image/x-xwindowdump"},
585 | {".z", "application/x-compress"},
586 | {".zip", "application/x-zip-compressed"}
587 | };
588 |
589 | public static string GetMimeType(this string extension)
590 | {
591 | if (extension == null)
592 | throw new ArgumentNullException(nameof(extension));
593 |
594 | if (!extension.StartsWith("."))
595 | extension = "." + extension;
596 |
597 |
598 | return MimeMappings.TryGetValue(extension, out var mime) ? mime : "application/octet-stream";
599 | }
600 | }
601 | }
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 | {one line to give the program's name and a brief idea of what it does.}
635 | Copyright (C) {year} {name of author}
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | {project} Copyright (C) {year} {fullname}
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
675 |
--------------------------------------------------------------------------------