Browse Source

blob调整

CrazyIter 4 năm trước cách đây
mục cha
commit
b9075a3dc4

+ 0 - 16
TEAMModelOS.SDK/Context/Constant/Constants.cs

@@ -20,22 +20,6 @@ namespace TEAMModelOS.SDK.Context.Constant.Common
         /// </summary>
 		public static readonly string CONTENT_TYPE_JSON = "application/json";
         /// <summary>
-        /// 资源,题目关联,htex关联,学习活动关联,教师基本信息关联
-        /// </summary>
-        public static string[] teacher = new string[] { "res", "item", "htex", "task", "info" };
-        /// <summary>
-        /// 资源,题目关联,htex关联,学习活动学生上传文件关联,基本信息关联,教室平面图关联,评测冷数据关联
-        /// </summary>
-        public static string[] school = new string[] { "res", "item", "htex", "task", "info", "room", "exam" };
-        /// <summary>
-        /// 答案及学习活动上传的文件,学生基本信息关联
-        /// </summary>
-        public static string[] student = new string[] { "ans/{studentId}",  "stu/{studentId}" };
-        /// <summary>
-        /// 资源,题目关联,htex关联,学习活动学生上传文件关联,基本信息关联,教室平面图关联,评测冷数据关联
-        /// </summary>
-        public static string[] system = new string[] { "res", "item", "htex", "task", "info", "room", "exam" };
-        /// <summary>
         /// 主题
         /// </summary>
         public static   string TopicName = "test_topic_ActiveTask";

+ 7 - 12
TEAMModelOS.SDK/Module/AzureBlob/Configuration/BlobSas.cs

@@ -1,5 +1,6 @@
 using System;
 using System.Collections.Generic;
+using System.ComponentModel.DataAnnotations;
 using System.Text;
 
 namespace TEAMModelOS.SDK.Module.AzureBlob.Configuration
@@ -9,23 +10,17 @@ namespace TEAMModelOS.SDK.Module.AzureBlob.Configuration
         /// <summary>
         /// 容器 学校编码,教师编码
         /// </summary>
+        [Required(ErrorMessage = "{0} 必须填写")]
         public string name { get; set; }
         /// <summary>
-        /// 角色 teacher,school,system
+        /// 角色 student,teacher,school,system
         /// </summary>
-        public List<string> role { get; set; }
+        [Required(ErrorMessage = "{0} 必须填写")]
+        public string role { get; set; }
         /// <summary>
-        /// 分类文件夹
+        ///如果是学生则有值
         /// </summary>
-        public string folder { get; set; }
-        /// <summary>
-        /// 文件名
-        /// </summary>
-        public string file { get; set; }
-    }
-    public class Role
-    {
-        public string name { get; set; }
+       
         public string code { get; set; }
     }
 }

+ 90 - 19
TEAMModelOS.SDK/Module/AzureBlob/Implements/AzureBlobDBRepository.cs

@@ -20,6 +20,8 @@ using TEAMModelOS.SDK.Context.Configuration;
 using Microsoft.AspNetCore.Hosting;
 using Microsoft.Azure.Cosmos.Linq;
 using System.Reflection.Metadata;
+using TEAMModelOS.SDK.Helper.Common.CollectionHelper;
+using Jaeger.Util;
 
 namespace TEAMModelOS.SDK.Module.AzureBlob.Implements
 {
@@ -586,7 +588,7 @@ namespace TEAMModelOS.SDK.Module.AzureBlob.Implements
                     // When the start time for the SAS is omitted, the start time is assumed to be the time when the storage service receives the request.
                     // Omitting the start time for a SAS that is effective immediately helps to avoid clock skew.
                     SharedAccessStartTime = DateTime.UtcNow.AddMinutes(-15),
-                    SharedAccessExpiryTime = DateTime.UtcNow.AddHours(2),
+                    SharedAccessExpiryTime = DateTime.UtcNow.AddHours(1),
                     Permissions =  SharedAccessBlobPermissions.Read
                 };
 
@@ -606,32 +608,101 @@ namespace TEAMModelOS.SDK.Module.AzureBlob.Implements
             // Return the URI string for the container, including the SAS token.
             return (blobContainer.Uri.ToString(), sasContainerToken);
         }
-
-        public async Task<object> GetContainerSasUri(BlobSas blobSas) {
-            string sasContainerToken;
-
-            blobContainer = await CreateContainer(blobSas.name);
+        public async Task<KeyValuePair<string, object>> GetContainerSasUri(BlobSas blobSas, bool isRead)
+        {
+            CloudBlobContainer blobContainer;
+            if (blobSas.role == "system")
+            {
+                blobContainer = await CreateContainer(_options.Container);
+            }
+            else
+            {
+                blobContainer = await CreateContainer(blobSas.name.ToLower().Replace("#", ""));
+            }
             // If no stored policy is specified, create a new access policy and define its constraints.
-            
+
             // Note that the SharedAccessBlobPolicy class is used both to define the parameters of an ad hoc SAS, and
             // to construct a shared access policy that is saved to the container's shared access policies.
+            DateTimeOffset dateTime = DateTime.UtcNow.AddHours(1);
+            long time = dateTime.ToUnixTimeMilliseconds();
             SharedAccessBlobPolicy adHocPolicy = new SharedAccessBlobPolicy()
-            {
-                // When the start time for the SAS is omitted, the start time is assumed to be the time when the storage service receives the request.
-                // Omitting the start time for a SAS that is effective immediately helps to avoid clock skew.
-                SharedAccessStartTime = DateTime.UtcNow.AddMinutes(-15),
-                SharedAccessExpiryTime = DateTime.UtcNow.AddHours(2),
-                Permissions = SharedAccessBlobPermissions.Write | SharedAccessBlobPermissions.Create | SharedAccessBlobPermissions.Read
-            };
+                {
+                    // When the start time for the SAS is omitted, the start time is assumed to be the time when the storage service receives the request.
+                    // Omitting the start time for a SAS that is effective immediately helps to avoid clock skew.
+                    SharedAccessStartTime = DateTime.UtcNow.AddMinutes(-15),
+                    SharedAccessExpiryTime = dateTime,
+                    Permissions = SharedAccessBlobPermissions.Read
+                };
             // Generate the shared access signature on the container, setting the constraints directly on the signature.
-            sasContainerToken = blobContainer.GetSharedAccessSignature(adHocPolicy, null);
-
-            
+            string   sasContainerToken = blobContainer.GetSharedAccessSignature(adHocPolicy, null);
+            KeyValuePair<string, object> dict = new KeyValuePair<string, object>(   blobContainer.Name,  new { url = blobContainer.Uri, sas = sasContainerToken, timeout = time } );
+            return dict;
+        }
+        public async Task<Dictionary<string,object>> GetBlobSasUri(BlobSas blobSas,bool isRead) {
+            string sasBlobToken;
 
-            // Return the URI string for the container, including the SAS token.
+            CloudBlobContainer blobContainer;
+            if (blobSas.role == "system")
+            {
+                  blobContainer = await CreateContainer(_options.Container);
+            }
+            else {
+                  blobContainer = await CreateContainer(blobSas.name.ToLower().Replace("#",""));
+            }
+            // Create a new access policy and define its constraints.
+            // Note that the SharedAccessBlobPolicy class is used both to define the parameters of an ad hoc SAS, and
+            // to construct a shared access policy that is saved to the container's shared access policies.
+            DateTimeOffset dateTime = DateTime.UtcNow.AddHours(1);
+            SharedAccessBlobPolicy adHocSAS = null;
+            if (isRead)
+            {
+                adHocSAS = new SharedAccessBlobPolicy()
+                {
+                    // When the start time for the SAS is omitted, the start time is assumed to be the time when the storage service receives the request.
+                    // Omitting the start time for a SAS that is effective immediately helps to avoid clock skew.
+                    SharedAccessStartTime = DateTime.UtcNow.AddMinutes(-5),
+                    SharedAccessExpiryTime = dateTime,
+                    Permissions = SharedAccessBlobPermissions.Read
+                };
+            }
+            else
+            {
+                adHocSAS = new SharedAccessBlobPolicy()
+                {
+                    // When the start time for the SAS is omitted, the start time is assumed to be the time when the storage service receives the request.
+                    // Omitting the start time for a SAS that is effective immediately helps to avoid clock skew.
+                    SharedAccessStartTime = DateTime.UtcNow.AddMinutes(-5),
+                    SharedAccessExpiryTime = dateTime,
+                    Permissions = SharedAccessBlobPermissions.Write | SharedAccessBlobPermissions.Create | SharedAccessBlobPermissions.Read
+                };
 
-            return (blobContainer.Uri.Scheme + "://" + blobContainer.Uri.Host.ToString(), blobContainer.Name, sasContainerToken);
+            }
+            Dictionary<string, object> dict = new Dictionary<string, object>();
+            long time = dateTime.ToUnixTimeMilliseconds();
+            List<string> folders = BaseConfigModel.Configuration.GetSection("Azure:Blob:" + blobSas.role).Get<List<string>>();
+            if (folders.IsNotEmpty())
+            {
+                foreach (string floder in folders) {
+                    string cates = floder;
+                    if (blobSas.role == "student") {
+                        if (string.IsNullOrEmpty(blobSas.code)) {
+                            throw new BizException("请设置学生编码!", ResponseCode.PARAMS_ERROR);
+                        }
+                        cates = floder.Replace("{studentId}", blobSas.code);
+                    }
+                    // Get a reference to a blob within the container.
+                    // Note that the blob may not exist yet, but a SAS can still be created for it.
+                    CloudBlockBlob blob = blobContainer.GetBlockBlobReference(cates);
+                    // Generate the shared access signature on the blob, setting the constraints directly on the signature.
+                    sasBlobToken = blob.GetSharedAccessSignature(adHocSAS);
+                    dict.Add(cates, new { url=blob.Uri,sas=sasBlobToken , timeout = time });
+                }
+            }
+            return dict;
         }
+
+   
+
         /// <summary>
         /// 若要为 blob 创建服务 SAS,请调用 CloudBlob.GetSharedAccessSignature 方法。
         ///下面的代码示例在 blob 上创建 SAS。 如果提供现有存储访问策略的名称,则该策略与 SAS 关联。 如果未提供存储访问策略,则代码会在 Blob 上创建一个临时 SAS。

+ 4 - 3
TEAMModelOS.SDK/Module/AzureBlob/Interfaces/IAzureBlobDBRepository.cs

@@ -26,9 +26,10 @@ namespace TEAMModelOS.SDK.Module.AzureBlob.Interfaces
         Task DeleteSharedAccessPolicyAsync(string policyName, string  containerName = null);
         Task Deleteblob(string sasUri);
 
-     Task<List<BlobFileDto>> GetBlobDirectory(string containerName, string blobName);
+         Task<List<BlobFileDto>> GetBlobDirectory(string containerName, string blobName);
+
+        Task<Dictionary<string, object>> GetBlobSasUri(BlobSas blobSas,bool isRead);
+        Task<KeyValuePair<string, object>> GetContainerSasUri(BlobSas blobSas, bool isRead);
 
-        Task<object> GetContainerSasUri(BlobSas blobSas);
-        
     }
 }

+ 57 - 9
TEAMModelOS/Controllers/Core/BlobController.cs

@@ -4,6 +4,7 @@ using System.Collections.Generic;
 using System.Text.Json;
 using System.Threading.Tasks;
 using TEAMModelOS.SDK.Context.Configuration;
+using TEAMModelOS.SDK.Context.Exception;
 using TEAMModelOS.SDK.Extension.DataResult.JsonRpcRequest;
 using TEAMModelOS.SDK.Extension.DataResult.JsonRpcResponse;
 using TEAMModelOS.SDK.Helper.Common.JsonHelper;
@@ -13,7 +14,9 @@ using TEAMModelOS.SDK.Module.AzureBlob.Interfaces;
 
 namespace TEAMModelOS.Controllers.Core
 {
-    public class BlobController
+    [Route("api/[controller]")]
+    [ApiController]
+    public class BlobController : BaseController
     {
         
         private readonly IAzureBlobDBRepository azureBlobDBRepository;
@@ -31,9 +34,10 @@ namespace TEAMModelOS.Controllers.Core
         {
             ///返回金钥过期时间
             JsonRPCResponseBuilder builder = new JsonRPCResponseBuilder();
-            string url = BaseConfigModel.Configuration["HaBookAuth:IES5Auth:url"];
-            Dictionary<string, object> token = BaseConfigModel.Configuration.GetSection("HaBookAuth:IES5Auth:refresh_token").Get<Dictionary<string, object>>();
-            return builder.build() ;
+            Dictionary<string, object> dict = await azureBlobDBRepository.GetBlobSasUri(request.@params,true);
+            KeyValuePair<string, object> d = await azureBlobDBRepository.GetContainerSasUri(request.@params, true);
+            dict.Add(d.Key, d.Value);
+            return builder.Data(dict).build() ;
         }
         /// <summary>
         /// 某个文件的上传SAS rcw权限
@@ -44,11 +48,55 @@ namespace TEAMModelOS.Controllers.Core
         public async Task<BaseJosnRPCResponse> BlobSasRCW(JosnRPCRequest<BlobSas> request)
         {///返回金钥过期时间
             JsonRPCResponseBuilder builder = new JsonRPCResponseBuilder();
-            string url = BaseConfigModel.Configuration["HaBookAuth:IES5Auth:url"];
-
-           await azureBlobDBRepository.GetContainerSasUri(request.@params);
-            Dictionary<string, object> token = BaseConfigModel.Configuration.GetSection("HaBookAuth:IES5Auth:refresh_token").Get<Dictionary<string, object>>();
-            return builder.build();
+            Dictionary<string,object> dict=  await azureBlobDBRepository.GetBlobSasUri(request.@params,false);
+            return builder.Data(dict).build();
+        }
+        /// <summary>
+        /// 链接只读(读)
+        /// </summary>
+        /// <param name="azureBlobSASDto"></param>
+        /// <returns></returns>
+        [HttpPost("urlSasR")]
+        public async Task<BaseJosnRPCResponse> GetContainerSASRead(JosnRPCRequest<string> azureBlobSASDto)
+        {
+            JsonRPCResponseBuilder responseBuilder = new JsonRPCResponseBuilder();
+            string azureBlobSAS = azureBlobSASDto.@params;
+            (string, string) a = BlobUrlString(azureBlobSAS);
+            string ContainerName = a.Item1;
+            string BlobName = a.Item2;
+            bool flg = IsBlobName(BlobName);
+            if (flg)
+            {
+                string SAS =await azureBlobDBRepository.GetBlobSasUriRead(ContainerName, BlobName);
+                return responseBuilder.Data(SAS).build();
+            }
+            else {
+                throw new BizException("文件名错误", ResponseCode.PARAMS_ERROR);
+            };
+        }
+        private static string ContainerUrlString(string sasUrl)
+        {
+            ///移除http://
+            sasUrl = sasUrl.Substring(8);
+            string[] sasUrls = sasUrl.Split("/");
+            string ContainerName;
+            ContainerName = sasUrls[1].Clone().ToString();
+            return ContainerName;
+        }
+        private static (string, string) BlobUrlString(string sasUrl)
+        {
+            sasUrl = sasUrl.Substring(8);
+            string[] sasUrls = sasUrl.Split("/");
+            string ContainerName;
+            ContainerName = sasUrls[1].Clone().ToString();
+            string item = sasUrls[0] + "/" + sasUrls[1] + "/";
+            string blob = sasUrl.Replace(item, "");
+            return (ContainerName, blob);
+        }
+        public static bool IsBlobName(string BlobName)
+        {
+            return System.Text.RegularExpressions.Regex.IsMatch(BlobName,
+             @"(?!((^(con)$)|^(con)\\..*|(^(prn)$)|^(prn)\\..*|(^(aux)$)|^(aux)\\..*|(^(nul)$)|^(nul)\\..*|(^(com)[1-9]$)|^(com)[1-9]\\..*|(^(lpt)[1-9]$)|^(lpt)[1-9]\\..*)|^\\s+|.*\\s$)(^[^\\\\\\:\\<\\>\\*\\?\\\\\\""\\\\|]{1,255}$)");
         }
     }
 }

+ 9 - 1
TEAMModelOS/appsettings.Development.json

@@ -19,7 +19,15 @@
     },
     "Blob": {
       "ConnectionString": "DefaultEndpointsProtocol=https;AccountName=teammodelstorage;AccountKey=Yq7D4dE6cFuer2d2UZIccTA/i0c3sJ/6ITc8tNOyW+K5f+/lWw9GCos3Mxhj47PyWQgDL8YbVD63B9XcGtrMxQ==;EndpointSuffix=core.chinacloudapi.cn",
-      "Container": "teammodelos"
+      "Container": "teammodelos",
+      //系统管理员 资源,题目关联,htex关联,学习活动学生上传文件关联,基本信息关联,教室平面图关联,评测冷数据关联
+      "system": [ "res", "item", "htex", "task", "info", "room", "exam" ],
+      //资源,题目关联,htex关联,学习活动学生上传文件关联,基本信息关联,教室平面图关联,评测冷数据关联
+      "school": [ "res", "item", "htex", "task", "info", "room", "exam" ],
+      //资源,题目关联,htex关联,学习活动关联,教师基本信息关联
+      "teacher": [ "res", "item", "htex", "task", "info" ],
+      //答案及学习活动上传的文件,学生基本信息关联
+      "student": [ "ans/{studentId}", "stu/{studentId}" ]
     },
     "CosmosDB": {
       "ConnectionString": "https://teammodelos.documents.azure.cn:443/",

+ 9 - 1
TEAMModelOS/appsettings.json

@@ -19,7 +19,15 @@
     },
     "Blob": {
       "ConnectionString": "DefaultEndpointsProtocol=https;AccountName=teammodelstorage;AccountKey=Yq7D4dE6cFuer2d2UZIccTA/i0c3sJ/6ITc8tNOyW+K5f+/lWw9GCos3Mxhj47PyWQgDL8YbVD63B9XcGtrMxQ==;EndpointSuffix=core.chinacloudapi.cn",
-      "Container": "teammodelos"
+      "Container": "teammodelos",
+      //系统管理员 资源,题目关联,htex关联,学习活动学生上传文件关联,基本信息关联,教室平面图关联,评测冷数据关联
+      "system": [ "res", "item", "htex", "task", "info", "room", "exam" ],
+      //资源,题目关联,htex关联,学习活动学生上传文件关联,基本信息关联,教室平面图关联,评测冷数据关联
+      "school": [ "res", "item", "htex", "task", "info", "room", "exam" ],
+      //资源,题目关联,htex关联,学习活动关联,教师基本信息关联
+      "teacher": [ "res", "item", "htex", "task", "info" ],
+      //答案及学习活动上传的文件,学生基本信息关联
+      "student": [ "ans/{studentId}", "stu/{studentId}" ]
     },
     "CosmosDB": {
       "ConnectionString": "https://teammodelos.documents.azure.cn:443/",