瀏覽代碼

调整验证APIAuth

CrazyIter_Bin 4 年之前
父節點
當前提交
882c1fc79d

+ 4 - 2
TEAMModelFunction/MonitorServicesBus.cs

@@ -159,7 +159,8 @@ namespace TEAMModelFunction
                     && jsonMsg.RootElement.TryGetProperty("root", out JsonElement root) && root.ValueKind == JsonValueKind.String)
                     && jsonMsg.RootElement.TryGetProperty("root", out JsonElement root) && root.ValueKind == JsonValueKind.String)
                 {
                 {
                     List<Dictionary<string, double?>> list = new List<Dictionary<string, double?>>();
                     List<Dictionary<string, double?>> list = new List<Dictionary<string, double?>>();
-                    string u = System.Web.HttpUtility.UrlDecode($"{root}", Encoding.UTF8).Split("/")[0];
+                    string[] uls = System.Web.HttpUtility.UrlDecode($"{root}", Encoding.UTF8).Split("/");
+                    string u = !string.IsNullOrEmpty(uls[0]) ? uls[0] : uls[1];
                     var client = _azureStorage.GetBlobContainerClient($"{name}");
                     var client = _azureStorage.GetBlobContainerClient($"{name}");
                     var size = await client.GetBlobsSize(u);
                     var size = await client.GetBlobsSize(u);
                     await _azureRedis.GetRedisClient(8).SortedSetRemoveAsync($"Blob:Catalog:{name}", u);
                     await _azureRedis.GetRedisClient(8).SortedSetRemoveAsync($"Blob:Catalog:{name}", u);
@@ -171,11 +172,12 @@ namespace TEAMModelFunction
                         foreach (var score in scores)
                         foreach (var score in scores)
                         {
                         {
                             blobsize = blobsize + score.Score;
                             blobsize = blobsize + score.Score;
+                            list.Add(new Dictionary<string, double?>() { { score.Element.ToString(), score.Score } });
                         }
                         }
                     }
                     }
                     await _azureRedis.GetRedisClient(8).HashSetAsync($"Blob:Record", new RedisValue($"{name}"), new RedisValue($"{blobsize}"));
                     await _azureRedis.GetRedisClient(8).HashSetAsync($"Blob:Record", new RedisValue($"{name}"), new RedisValue($"{blobsize}"));
 
 
-                    await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-ServiceBus,Blob() 容器:{name}使用:{root},文件分类:{list.ToJsonString()}",
+                    await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-ServiceBus,Blob() 容器:{name}使用:{u},文件分类:{list.ToJsonString()}",
                         GroupNames.成都开发測試群組);
                         GroupNames.成都开发測試群組);
                 }
                 }
             }
             }

+ 2 - 2
TEAMModelOS.SDK/Extension/JwtAuthExtension.cs

@@ -42,7 +42,7 @@ namespace TEAMModelOS.SDK.Extension
 
 
             return serializeToken;
             return serializeToken;
         }
         }
-        public static string CreateApiToken(string issuer, string id,  string salt,string  name , string schoolID = "", int expire = 1)
+        public static string CreateApiToken(string issuer, string id,  string salt,string  name,List<int> auth , string schoolID = "", int expire = 1)
         {
         {
            
            
             // 設定要加入到 JWT Token 中的聲明資訊(Claims)  
             // 設定要加入到 JWT Token 中的聲明資訊(Claims)  
@@ -56,7 +56,7 @@ namespace TEAMModelOS.SDK.Extension
                 //{ JwtRegisteredClaimNames.Exp,DateTimeOffset.UtcNow.AddHours(expire).ToUnixTimeSeconds().ToString()},  // 到期的時間,必須為數字
                 //{ JwtRegisteredClaimNames.Exp,DateTimeOffset.UtcNow.AddHours(expire).ToUnixTimeSeconds().ToString()},  // 到期的時間,必須為數字
                 //{ "name",name}, // 用戶的顯示名稱
                 //{ "name",name}, // 用戶的顯示名稱
                 //{ "picture",picture}, // 用戶頭像
                 //{ "picture",picture}, // 用戶頭像
-                //{ "roles",roles}, // 登入者的角色,角色類型 (Admin、Teacher、Student) 
+                { "auth",auth}, // 登入者的角色,角色類型 (Admin、Teacher、Student) 
                // { "permissions",permissions} //登入者的權限請求
                // { "permissions",permissions} //登入者的權限請求
             };
             };
 
 

+ 3 - 2
TEAMModelOS.SDK/Models/Cosmos/Api/OpenApi.cs

@@ -32,14 +32,15 @@ namespace TEAMModelOS.SDK.Models
         public string url { get; set; }
         public string url { get; set; }
         public string method { get; set; }
         public string method { get; set; }
         public string descr { get; set; }
         public string descr { get; set; }
-     
+        public int auth { get; set; }
+
     }
     }
 
 
     public class OpenApp : CosmosEntity {
     public class OpenApp : CosmosEntity {
         public string icon { get; set; }
         public string icon { get; set; }
         public string name { get; set; }
         public string name { get; set; }
         public string descr { get; set; }
         public string descr { get; set; }
-        public List<string> apis { get; set; } = new List<string>();
+        public List<int> auths { get; set; } = new List<int>();
         public string school { get; set; }
         public string school { get; set; }
         public string token { get; set; }
         public string token { get; set; }
         /// <summary>
         /// <summary>

+ 5 - 1
TEAMModelOS.SDK/Models/Cosmos/Common/Bloblog.cs

@@ -11,8 +11,12 @@ namespace TEAMModelOS.SDK.Models
     {
     {
         public string name { get; set; }
         public string name { get; set; }
         public string url { get; set; }
         public string url { get; set; }
-        public string time { get; set; }
+        public long  time { get; set; }
         public long  size { get; set; }
         public long  size { get; set; }
         public string period { get; set; }
         public string period { get; set; }
+        /// <summary>
+        /// 
+        /// </summary>
+        public string type { get; set; }
     }
     }
 }
 }

+ 3 - 3
TEAMModelOS.SDK/Models/Cosmos/Common/Snode.cs

@@ -9,11 +9,11 @@ namespace TEAMModelOS.SDK.Models.Cosmos.Common
     /// 课纲节点父类
     /// 课纲节点父类
     /// </summary>
     /// </summary>
     public  class Snode
     public  class Snode
-    {  
+    {
         /// <summary>
         /// <summary>
-        /// 试题 ,试卷,内容资源,外部链接(只有link,和name),
+        ///0 分支节点,1资源节点,2 试题 ,3试卷,4内容资源,5外部链接(只有link,和name),
         /// </summary>
         /// </summary>
-        public int type { get; set; }
+        public int type { get; set; } = 0;
         public string title { get; set; }
         public string title { get; set; }
 
 
     }
     }

+ 1 - 1
TEAMModelOS/ClientApp/src/api/blob.js

@@ -1,4 +1,4 @@
-import { fetch, post } from '@/api/http'
+import { fetch, post } from '@/api/http'
 export default {
 export default {
     getBlobSAS: function(data) {
     getBlobSAS: function(data) {
         return post('/api/File/getBlobSAS', data)
         return post('/api/File/getBlobSAS', data)

+ 220 - 81
TEAMModelOS/Controllers/Core/BlobController.cs

@@ -24,6 +24,10 @@ using TEAMModelOS.SDK.Helper.Common.CollectionHelper;
 using Microsoft.AspNetCore.Http;
 using Microsoft.AspNetCore.Http;
 using TEAMModelOS.SDK.Context.Constant.Common;
 using TEAMModelOS.SDK.Context.Constant.Common;
 using HTEXLib.COMM.Helpers;
 using HTEXLib.COMM.Helpers;
+using TEAMModelOS.Models;
+using Microsoft.Extensions.Options;
+using TEAMModelOS.SDK.Models;
+using Azure.Cosmos;
 
 
 namespace TEAMModelOS.Controllers.Core
 namespace TEAMModelOS.Controllers.Core
 {
 {
@@ -36,17 +40,25 @@ namespace TEAMModelOS.Controllers.Core
         private readonly IHttpClientFactory _clientFactory;
         private readonly IHttpClientFactory _clientFactory;
         private readonly AzureRedisFactory _azureRedis;
         private readonly AzureRedisFactory _azureRedis;
         private readonly AzureServiceBusFactory _serviceBus;
         private readonly AzureServiceBusFactory _serviceBus;
+        private readonly DingDing _dingDing;
+        private readonly Option _option;
+        private readonly AzureCosmosFactory _azureCosmos;
         public IConfiguration _configuration { get; set; }
         public IConfiguration _configuration { get; set; }
-        public BlobController(AzureStorageFactory azureStorage, AzureServiceBusFactory serviceBus, IHttpClientFactory clientFactory, AzureRedisFactory azureRedis, IConfiguration configuration)
+        public BlobController(AzureStorageFactory azureStorage, AzureServiceBusFactory serviceBus, IHttpClientFactory clientFactory, AzureRedisFactory azureRedis, IConfiguration configuration,
+            DingDing dingDing,
+            IOptionsSnapshot<Option> option, AzureCosmosFactory azureCosmos)
         {
         {
             _azureStorage = azureStorage;
             _azureStorage = azureStorage;
             _clientFactory = clientFactory;
             _clientFactory = clientFactory;
             _serviceBus = serviceBus;
             _serviceBus = serviceBus;
             _azureRedis = azureRedis;
             _azureRedis = azureRedis;
-            _configuration = configuration;
+            _configuration = configuration; 
+            _dingDing = dingDing;
+            _option = option?.Value;
+            _azureCosmos = azureCosmos;
         }
         }
         /// <summary>
         /// <summary>
-        /// 获取某个容器的只读权限
+        /// 上传文件到指定的0-public
         /// </summary>
         /// </summary>
         /// <param name="request"></param>
         /// <param name="request"></param>
         /// <returns></returns>
         /// <returns></returns>
@@ -94,7 +106,7 @@ namespace TEAMModelOS.Controllers.Core
             //dict.Add(d.Key, d.Value);
             //dict.Add(d.Key, d.Value);
             return Ok(_azureStorage.GetContainerSasUri(request, false));
             return Ok(_azureStorage.GetContainerSasUri(request, false));
         }
         }
-
+     
         /// <summary>
         /// <summary>
         /// 删除prefix
         /// 删除prefix
         /// 
         /// 
@@ -131,33 +143,18 @@ namespace TEAMModelOS.Controllers.Core
             }
             }
             if (prefix != null && blobContainerName != null)
             if (prefix != null && blobContainerName != null)
             {
             {
-                long? size=  await  _azureStorage.GetBlobContainerClient(blobContainerName). GetBlobsSize( prefix);
                 var status = await _azureStorage.GetBlobServiceClient().DelectBlobs(blobContainerName, prefix);
                 var status = await _azureStorage.GetBlobServiceClient().DelectBlobs(blobContainerName, prefix);
-                RedisValue value = default;
-                long blobSize = 0;
-                value = _azureRedis.GetRedisClient(8).HashGet($"Blob:Record", blobContainerName);
-                if (value != default && !value.IsNullOrEmpty)
+                string u ="";
+                string[] uls = System.Web.HttpUtility.UrlDecode($"{prefixjson}", Encoding.UTF8).Split("/");
+                if (uls != null)
                 {
                 {
-                    JsonElement record = value.ToString().ToObject<JsonElement>();
-                    if (record.TryGetInt64(out blobSize))
-                    {
-                    }
-                }
-                long? useSize = blobSize - size;
-                await _azureRedis.GetRedisClient(8).HashSetAsync($"Blob:Record", blobContainerName, useSize);
-                Dictionary<string, double?> catalog = new Dictionary<string, double?>();
-                string u = System.Web.HttpUtility.UrlDecode(prefix, Encoding.UTF8).Split("/")[0];
-                await _azureRedis.GetRedisClient(8).SortedSetIncrementAsync($"Blob:Catalog:{blobContainerName}", u, size.HasValue? - size.Value:0);
-                catalog[u] = await _azureRedis.GetRedisClient(8).SortedSetScoreAsync($"Blob:Catalog:{blobContainerName}", u);
-                if (catalog[u] < 0) {
-                    await _azureRedis.GetRedisClient(8).SortedSetRemoveAsync($"Blob:Catalog:{blobContainerName}", u);
-                    catalog[u] = 0;
+                      u = !string.IsNullOrEmpty(uls[0]) ? uls[0] : uls[1];
                 }
                 }
-                var messageBlob = new ServiceBusMessage(new { id = Guid.NewGuid().ToString(), progress = "update",root=new string[] { u }, name = blobContainerName }.ToJsonString());
-                messageBlob.ApplicationProperties.Add("name", "Blob");
+                var messageBlob = new ServiceBusMessage(new { id = Guid.NewGuid().ToString(), progress = "update", root =u, name = $"{blobContainerName}" }.ToJsonString()); ;
+                messageBlob.ApplicationProperties.Add("name", "BlobRoot");
                 var ActiveTask = _configuration.GetValue<string>("Azure:ServiceBus:ActiveTask");
                 var ActiveTask = _configuration.GetValue<string>("Azure:ServiceBus:ActiveTask");
                 await _serviceBus.GetServiceBusClient().SendMessageAsync(ActiveTask, messageBlob);
                 await _serviceBus.GetServiceBusClient().SendMessageAsync(ActiveTask, messageBlob);
-                return Ok(new { status, catalog,size=useSize });
+                return Ok(new { status });
             }
             }
             else {
             else {
                 return BadRequest();
                 return BadRequest();
@@ -165,6 +162,7 @@ namespace TEAMModelOS.Controllers.Core
             
             
         }
         }
 
 
+         
         /// <summary>
         /// <summary>
         /// 删除多个Url
         /// 删除多个Url
         /// 
         /// 
@@ -211,41 +209,25 @@ namespace TEAMModelOS.Controllers.Core
                 if (blobContainerName != null && uris != null && uris.Count > 0)
                 if (blobContainerName != null && uris != null && uris.Count > 0)
                 {
                 {
                     var urls = urlsjson.ToObject<List<string>>();
                     var urls = urlsjson.ToObject<List<string>>();
-                    var urlSize= await _azureStorage.GetBlobServiceClient().GetBlobContainerClient(blobContainerName).GetBlobsSize(urls);
                     var status = await _azureStorage.GetBlobServiceClient().DelectBlobs(blobContainerName, uris);
                     var status = await _azureStorage.GetBlobServiceClient().DelectBlobs(blobContainerName, uris);
-                    RedisValue value = default;
-                    long blobSize = 0;
-                    value = _azureRedis.GetRedisClient(8).HashGet($"Blob:Record", blobContainerName);
-                    if (value != default && !value.IsNullOrEmpty)
-                    {
-                        JsonElement record = value.ToString().ToObject<JsonElement>();
-                        if (record.TryGetInt64(out blobSize))
-                        {
-                        }
-                    }
                     //释放的空间
                     //释放的空间
-                    long? useSize = blobSize + urlSize.Select(x=>x.size).Sum();
-                    await _azureRedis.GetRedisClient(8).HashSetAsync($"Blob:Record", blobContainerName, useSize);
-                    Dictionary<string, double?> catalog = new Dictionary<string, double?>();
                     HashSet<string> root = new HashSet<string>();
                     HashSet<string> root = new HashSet<string>();
-                    foreach (var x in urlSize)
+                    foreach (var x in urls)
                     {
                     {
-                        string u = System.Web.HttpUtility.UrlDecode(x.url, Encoding.UTF8).Split("/")[0];
-                        root.Add(u);
-                        //释放文件夹空间
-                        await _azureRedis.GetRedisClient(8).SortedSetIncrementAsync($"Blob:Catalog:{blobContainerName}", u, -x.size);
-                        catalog[u] = await _azureRedis.GetRedisClient(8).SortedSetScoreAsync($"Blob:Catalog:{blobContainerName}", u);
-                        if (catalog[u] < 0)
+                        string[] uls = System.Web.HttpUtility.UrlDecode(x, Encoding.UTF8).Split("/");
+                        if (uls != null)
                         {
                         {
-                            await _azureRedis.GetRedisClient(8).SortedSetRemoveAsync($"Blob:Catalog:{blobContainerName}", u);
-                            catalog[u] = 0;
+                            string u = !string.IsNullOrEmpty(uls[0]) ? uls[0] : uls[1];
+                            root.Add(u);
                         }
                         }
                     }
                     }
-                    var messageBlob = new ServiceBusMessage(new { id = Guid.NewGuid().ToString(), progress = "update", root = root.ToArray(), name = blobContainerName }.ToJsonString());
-                    messageBlob.ApplicationProperties.Add("name", "Blob");
-                    var ActiveTask = _configuration.GetValue<string>("Azure:ServiceBus:ActiveTask");
-                    await _serviceBus.GetServiceBusClient().SendMessageAsync(ActiveTask, messageBlob);
-                    return Ok(new { status,size= useSize,catalog });
+                    root.ToList().ForEach(async x => {
+                        var messageBlob = new ServiceBusMessage(new { id = Guid.NewGuid().ToString(), progress = "update", root = x, name = $"{blobContainerName}" }.ToJsonString()); ;
+                        messageBlob.ApplicationProperties.Add("name", "BlobRoot");
+                        var ActiveTask = _configuration.GetValue<string>("Azure:ServiceBus:ActiveTask");
+                        await _serviceBus.GetServiceBusClient().SendMessageAsync(ActiveTask, messageBlob);
+                    });
+                    return Ok(new { status  });
                 }
                 }
                 else
                 else
                 {
                 {
@@ -255,7 +237,6 @@ namespace TEAMModelOS.Controllers.Core
             else {
             else {
                 return BadRequest("只能删除本人管理的文件");
                 return BadRequest("只能删除本人管理的文件");
             }
             }
-            
         }
         }
 
 
 
 
@@ -316,17 +297,18 @@ namespace TEAMModelOS.Controllers.Core
         }
         }
         
         
         /// <summary>
         /// <summary>
-        /// 测试单个文本内容的上传
+        /// 获取容器的 分类及总量
         /// </summary>
         /// </summary>
         /// <param name="azureBlobSASDto"></param>
         /// <param name="azureBlobSASDto"></param>
         /// <returns></returns>
         /// <returns></returns>
         [HttpPost("get-blobsize")]
         [HttpPost("get-blobsize")]
         public async Task<ActionResult> GetBlobsSize(JsonElement request)
         public async Task<ActionResult> GetBlobsSize(JsonElement request)
         {
         {
-            request.TryGetProperty("containerName", out JsonElement containerName);
-            request.TryGetProperty("cache", out JsonElement cache);
-            var name =containerName.GetString();
-            try {
+            try
+            {
+                request.TryGetProperty("containerName", out JsonElement containerName);
+                request.TryGetProperty("cache", out JsonElement cache);
+                var name =containerName.GetString();
                 if (cache.GetBoolean())
                 if (cache.GetBoolean())
                 {
                 {
                     long blobsize = 0;
                     long blobsize = 0;
@@ -335,34 +317,66 @@ namespace TEAMModelOS.Controllers.Core
                     if (value != default && !value.IsNullOrEmpty)
                     if (value != default && !value.IsNullOrEmpty)
                     {
                     {
                         JsonElement record = value.ToString().ToObject<JsonElement>();
                         JsonElement record = value.ToString().ToObject<JsonElement>();
-                        if (record.TryGetInt64(out  blobsize))
+                        if (record.TryGetInt64(out blobsize))
                         {
                         {
-                           
                         }
                         }
                     }
                     }
+                    else
+                    {
+                        var client = _azureStorage.GetBlobContainerClient(name);
+                        var size = await client.GetBlobsCatalogSize();
+                        await _azureRedis.GetRedisClient(8).HashSetAsync($"Blob:Record", name, size.Item1);
+                        foreach (var key in size.Item2.Keys)
+                        {
+                            await _azureRedis.GetRedisClient(8).SortedSetRemoveAsync($"Blob:Catalog:{name}", key);
+                            await _azureRedis.GetRedisClient(8).SortedSetIncrementAsync($"Blob:Catalog:{name}", key, size.Item2[key].HasValue ? size.Item2[key].Value : 0);
+                        }
+                        return Ok(new { size = size.Item1, catalog = size.Item2 });
+                    }
                     Dictionary<string, double> catalog = new Dictionary<string, double>();
                     Dictionary<string, double> catalog = new Dictionary<string, double>();
                     SortedSetEntry[] Scores = _azureRedis.GetRedisClient(8).SortedSetRangeByScoreWithScores($"Blob:Catalog:{name}");
                     SortedSetEntry[] Scores = _azureRedis.GetRedisClient(8).SortedSetRangeByScoreWithScores($"Blob:Catalog:{name}");
-                    if (Scores != null )
+                    if (Scores != null)
                     {
                     {
-                        foreach (var score in Scores) {
+                        foreach (var score in Scores)
+                        {
                             double val = score.Score;
                             double val = score.Score;
                             string key = score.Element.ToString();
                             string key = score.Element.ToString();
                             catalog.Add(key, val);
                             catalog.Add(key, val);
-                        }   
+                        }
+                        return Ok(new { size = blobsize, catalog = catalog });
+                    }
+                    else {
+                        var client = _azureStorage.GetBlobContainerClient(name);
+                        var size = await client.GetBlobsCatalogSize();
+                        await _azureRedis.GetRedisClient(8).HashSetAsync($"Blob:Record", name, size.Item1);
+                        foreach (var key in size.Item2.Keys)
+                        {
+                            await _azureRedis.GetRedisClient(8).SortedSetRemoveAsync($"Blob:Catalog:{name}", key);
+                            await _azureRedis.GetRedisClient(8).SortedSetIncrementAsync($"Blob:Catalog:{name}", key, size.Item2[key].HasValue ? size.Item2[key].Value : 0);
+                        }
+                        return Ok(new { size = size.Item1, catalog = size.Item2 });
                     }
                     }
-                    return Ok(new { size = blobsize, catalog= catalog });
                 }
                 }
-            } catch { }
-            var client = _azureStorage.GetBlobContainerClient(name);
-            var size = await client.GetBlobsCatalogSize();
-            await _azureRedis.GetRedisClient(8).HashSetAsync($"Blob:Record", name, size.Item1);
-            foreach (var key in size.Item2.Keys) {
-                await _azureRedis.GetRedisClient(8).SortedSetRemoveAsync($"Blob:Catalog:{name}", key);
-                await _azureRedis.GetRedisClient(8).SortedSetIncrementAsync($"Blob:Catalog:{name}", key, size.Item2[key].HasValue?size.Item2[key].Value:0);
+                else {
+                    var client = _azureStorage.GetBlobContainerClient(name);
+                    var size = await client.GetBlobsCatalogSize();
+                    await _azureRedis.GetRedisClient(8).HashSetAsync($"Blob:Record", name, size.Item1);
+                    foreach (var key in size.Item2.Keys)
+                    {
+                        await _azureRedis.GetRedisClient(8).SortedSetRemoveAsync($"Blob:Catalog:{name}", key);
+                        await _azureRedis.GetRedisClient(8).SortedSetIncrementAsync($"Blob:Catalog:{name}", key, size.Item2[key].HasValue ? size.Item2[key].Value : 0);
+                    }
+                    return Ok(new { size = size.Item1, catalog = size.Item2 });
+                }
+                
+            }
+            catch (Exception  ex){
+                await _dingDing.SendBotMsg($"IES5,{_option.Location},blon/get-blobsize()\n{ex.Message}{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
             }
             }
-            return Ok(new { size = size.Item1, catalog = size.Item2 });
+            return BadRequest();
         }
         }
 
 
+        //TODO 不要了
         /// <summary>
         /// <summary>
         /// 测试单个文本内容的上传
         /// 测试单个文本内容的上传
         /// {"containerName":"hbcn","urls":["video/xxx.mp4","res/xxx.png"],"prefix":["res/xxx","res/aaa"]}
         /// {"containerName":"hbcn","urls":["video/xxx.mp4","res/xxx.png"],"prefix":["res/xxx","res/aaa"]}
@@ -401,6 +415,7 @@ namespace TEAMModelOS.Controllers.Core
             ]
             ]
          }
          }
         */
         */
+        //TODO 不要了
         /// <summary>
         /// <summary>
         /// 测试单个文本内容的上传
         /// 测试单个文本内容的上传
         /// {"containerName":"hbcn","uploadSize":5000,"optUrls":[{"url":"video/37Z888piCvm9.mp4","size":0},{}]}
         /// {"containerName":"hbcn","uploadSize":5000,"optUrls":[{"url":"video/37Z888piCvm9.mp4","size":0},{}]}
@@ -431,13 +446,19 @@ namespace TEAMModelOS.Controllers.Core
             Dictionary<string, double?> catalog = new Dictionary<string, double?>();
             Dictionary<string, double?> catalog = new Dictionary<string, double?>();
             HashSet<string> root = new HashSet<string>();
             HashSet<string> root = new HashSet<string>();
             foreach (var x in urls) {
             foreach (var x in urls) {
-                string u = System.Web.HttpUtility.UrlDecode(x.url, Encoding.UTF8).Split("/")[0];
-                root.Add(u);
-                await _azureRedis.GetRedisClient(8).SortedSetIncrementAsync($"Blob:Catalog:{name}", u, x.size);
-                catalog[u]= await _azureRedis.GetRedisClient(8).SortedSetScoreAsync($"Blob:Catalog:{name}", u);
-                if (catalog[u] < 0) {
-                    await _azureRedis.GetRedisClient(8).SortedSetRemoveAsync($"Blob:Catalog:{name}", u);
-                    catalog[u] = 0;
+                string[] uls = System.Web.HttpUtility.UrlDecode(x.url, Encoding.UTF8).Split("/");
+                if (uls != null)
+                {
+                    string u = !string.IsNullOrEmpty(uls[0]) ? uls[0] : uls[1];
+                    root.Add(u);
+
+                    await _azureRedis.GetRedisClient(8).SortedSetIncrementAsync($"Blob:Catalog:{name}", u, x.size);
+                    catalog[u] = await _azureRedis.GetRedisClient(8).SortedSetScoreAsync($"Blob:Catalog:{name}", u);
+                    if (catalog[u] < 0)
+                    {
+                        await _azureRedis.GetRedisClient(8).SortedSetRemoveAsync($"Blob:Catalog:{name}", u);
+                        catalog[u] = 0;
+                    }
                 }
                 }
             }
             }
             var messageBlob = new ServiceBusMessage(new {id=Guid.NewGuid().ToString(), progress = "update", root= root.ToArray(), name=name}.ToJsonString());;
             var messageBlob = new ServiceBusMessage(new {id=Guid.NewGuid().ToString(), progress = "update", root= root.ToArray(), name=name}.ToJsonString());;
@@ -447,6 +468,38 @@ namespace TEAMModelOS.Controllers.Core
             return Ok(new { size=useSize, catalog });
             return Ok(new { size=useSize, catalog });
         }
         }
 
 
+        /// <summary>
+        /// {"name":"hbcn","urls":["root/xxxx/xxx.json","root/xxxx/xxx.json"]}
+        /// </summary>
+        /// <param name="azureBlobSASDto"></param>
+        /// <returns></returns>
+        [HttpPost("refresh-blobsize")]
+        public async Task<ActionResult> RefreshBlob(JsonElement request) {
+            try {
+                request.TryGetProperty("name", out JsonElement name);
+                request.TryGetProperty("urls", out JsonElement jurls);
+                var urls = jurls.ToObject<List<string>>();
+                HashSet<string> root = new HashSet<string>();
+                foreach (var x in urls)
+                {
+                    string[] uls = System.Web.HttpUtility.UrlDecode(x, Encoding.UTF8).Split("/");
+                    if (uls != null) {
+                        string u = !string.IsNullOrEmpty(uls[0]) ? uls[0] : uls[1];
+                        root.Add(u);
+                    }
+                }
+                 root.ToList().ForEach(async x => {
+                    var messageBlob = new ServiceBusMessage(new { id = Guid.NewGuid().ToString(), progress = "update", root =x, name = $"{name}" }.ToJsonString()); ;
+                    messageBlob.ApplicationProperties.Add("name", "BlobRoot");
+                    var ActiveTask = _configuration.GetValue<string>("Azure:ServiceBus:ActiveTask");
+                    await _serviceBus.GetServiceBusClient().SendMessageAsync(ActiveTask, messageBlob);
+                });
+                return Ok(new { status = 200 });
+            } catch (Exception ex) {
+                await _dingDing.SendBotMsg($"IES5,{_option.Location},blon/refresh-blob()\n{ex.Message}{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
+            }
+            return Ok(new { status = 500 });
+        }
         private static (string, string) BlobUrlString(string sasUrl)
         private static (string, string) BlobUrlString(string sasUrl)
         {
         {
             sasUrl = sasUrl.Substring(8);
             sasUrl = sasUrl.Substring(8);
@@ -462,5 +515,91 @@ namespace TEAMModelOS.Controllers.Core
             return System.Text.RegularExpressions.Regex.IsMatch(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}$)");
              @"(?!((^(con)$)|^(con)\\..*|(^(prn)$)|^(prn)\\..*|(^(aux)$)|^(aux)\\..*|(^(nul)$)|^(nul)\\..*|(^(com)[1-9]$)|^(com)[1-9]\\..*|(^(lpt)[1-9]$)|^(lpt)[1-9]\\..*)|^\\s+|.*\\s$)(^[^\\\\\\:\\<\\>\\*\\?\\\\\\""\\\\|]{1,255}$)");
         }
         }
+
+        [HttpPost("bloblog-list")]
+        public async Task<ActionResult> BloblogList(JsonElement request) {
+            request.TryGetProperty("name", out JsonElement name);
+            request.TryGetProperty("type", out JsonElement type);
+            var client = _azureCosmos.GetCosmosClient();
+            var queryslt = $"SELECT  value(c) FROM c WHERE c.type='{type}' c.code = 'Bloblog-{name}'";
+            List<Bloblog> bloblogs = new List<Bloblog>();
+            await foreach (var item in client.GetDatabaseQueryIterator<Bloblog>(queryText: queryslt, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Bloblog-{name}") })) {
+                bloblogs.Add(item);
+            }
+            return Ok(new { bloblogs = bloblogs });
+        }
+
+
+        /// <summary>
+        /// 
+        /// </summary>
+        /// <param name="request"></param>
+        /// <returns></returns>
+        [HttpPost("bloblog-upsert")]
+        public async Task<ActionResult> BloblogUpsert(JsonElement request) {
+
+            try
+            {
+                request.TryGetProperty("period", out JsonElement period);
+                request.TryGetProperty("scope", out JsonElement scope);
+                request.TryGetProperty("name", out JsonElement name);
+                request.TryGetProperty("url", out JsonElement jurl);
+                request.TryGetProperty("opt", out JsonElement opt);
+                request.TryGetProperty("id", out JsonElement id);
+                request.TryGetProperty("type", out JsonElement type);
+                var url = System.Web.HttpUtility.UrlDecode(jurl.GetString(), Encoding.UTF8);
+                string[] uls = url.Split("/");
+                if (uls != null)
+                {
+                  var  u = !string.IsNullOrEmpty(uls[0]) ? uls[0] : uls[1];
+                    
+                }
+                var size = await _azureStorage.GetBlobContainerClient($"{name}").GetBlobsSize(url);
+                long now = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
+                //获取文件的大小
+                var client = _azureCosmos.GetCosmosClient();
+                if (opt.GetString().Equals("add"))
+                {
+                    var blob = new Bloblog
+                    {
+                        id = Guid.NewGuid().ToString(),
+                        pk = "Bloblog",
+                        code = $"Bloblog-{name}",
+                        url = url,
+                        time = now,
+                        size = size != null && size.HasValue ? size.Value : 0,
+                        period = $"{period}"
+                    };
+                    if (scope.GetString().Equals("school"))
+                    {
+                        await client.GetContainer("TEAMModelOS", "school").CreateItemAsync(blob, new Azure.Cosmos.PartitionKey(blob.code));
+                    }
+                    else if (scope.GetString().Equals("teacher"))
+                    {
+                        await client.GetContainer("TEAMModelOS", "teacher").CreateItemAsync(blob, new Azure.Cosmos.PartitionKey(blob.code));
+                    }
+                }
+                else if (opt.GetString().Equals("del"))
+                {
+                    if (scope.GetString().Equals("school"))
+                    {
+                        await client.GetContainer("TEAMModelOS", "school").DeleteItemStreamAsync($"{id}", new Azure.Cosmos.PartitionKey($"Bloblog-{name}"));
+                    }
+                    else if (scope.GetString().Equals("teacher"))
+                    {
+                        await client.GetContainer("TEAMModelOS", "teacher").DeleteItemStreamAsync($"{id}", new Azure.Cosmos.PartitionKey($"Bloblog-{name}"));
+                    }
+                }
+                else { return BadRequest(); }
+                return Ok(new { status = 200 });
+            }
+            catch (Exception ex)
+            {
+                await _dingDing.SendBotMsg($"IES5,{_option.Location},blon/refresh-blob()\n{ex.Message}{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
+            }
+            return Ok(new { status = 200 });
+        }
+
+
     }
     }
 }
 }

+ 71 - 47
TEAMModelOS/Controllers/Core/OpenApiController.cs

@@ -36,6 +36,42 @@ namespace TEAMModelOS.Controllers.Core
             _option = option?.Value;
             _option = option?.Value;
         }
         }
         /// <summary>
         /// <summary>
+        /// {"code":"hbcn学校编码"} 
+        /// </summary>
+        /// <param name="requert"></param>
+        /// <returns></returns>
+        [ProducesDefaultResponseType]
+        //[AuthToken(Roles = "admin")]
+        [HttpPost("find-app")]
+        public async Task<IActionResult> FindApp(JsonElement request)
+        {
+            try
+            {
+                if (!request.TryGetProperty("code", out JsonElement code)) { return BadRequest(); }
+                var client = _azureCosmos.GetCosmosClient();
+                List<OpenApp> apps = new List<OpenApp>();
+                await foreach (var item in client.GetContainer("TEAMModelOS", "School").GetItemQueryIterator<OpenApp>(queryText: $"select value(c) from c ",
+                requestOptions: new QueryRequestOptions() { PartitionKey = new Azure.Cosmos.PartitionKey($"OpenApp-{code}") }))
+                {
+                    apps.Add(item);
+                }
+                return Ok(new { apps });
+
+            }
+            catch (Exception ex)
+            {
+                await _dingDing.SendBotMsg($"OS,{_option.Location},open-api/find-app()\n{ex.Message}", GroupNames.醍摩豆服務運維群組);
+                return BadRequest();
+            }
+        }
+
+
+
+        /*
+         数据实例
+        json:{}
+         */
+        /// <summary>
         /// 获取
         /// 获取
         /// </summary>
         /// </summary>
         /// <param name="request"></param>
         /// <param name="request"></param>
@@ -47,6 +83,9 @@ namespace TEAMModelOS.Controllers.Core
             List<OpenApi> apis = await _azureStorage.FindListByDict<OpenApi>(new Dictionary<string, object>() { { "PartitionKey", "IES5-API" } });
             List<OpenApi> apis = await _azureStorage.FindListByDict<OpenApi>(new Dictionary<string, object>() { { "PartitionKey", "IES5-API" } });
             return Ok(new { apis });
             return Ok(new { apis });
         }
         }
+
+
+        
         /// <summary>
         /// <summary>
         /// {"id":"uuid","code":"hbcn学校编码"} 
         /// {"id":"uuid","code":"hbcn学校编码"} 
         /// </summary>
         /// </summary>
@@ -63,23 +102,22 @@ namespace TEAMModelOS.Controllers.Core
                 if (!request.TryGetProperty("id", out JsonElement id)) return BadRequest();
                 if (!request.TryGetProperty("id", out JsonElement id)) return BadRequest();
                 //
                 //
                 if (!request.TryGetProperty("code", out JsonElement code)) return BadRequest();
                 if (!request.TryGetProperty("code", out JsonElement code)) return BadRequest();
-                
-                    var response = await client.GetContainer("TEAMModelOS", "School").ReadItemStreamAsync(id.GetString(), new PartitionKey($"OpenApp-{code}")) ;
-                    if (response.Status == 200)
-                    {
-                        using var json = await JsonDocument.ParseAsync(response.ContentStream);
-                        var info = json.ToObject<OpenApp>();
-                        //创建Token
-                        //域名  应用的id, jwtkey  学校编码
-                        var auth_token = JwtAuthExtension.CreateApiToken(_option.HostName, info.id, _option.JwtSecretKey, info.name, info.school);
-                        info.token = auth_token;
-                        info = await client.GetContainer("TEAMModelOS", "School").ReplaceItemAsync(info, info.id, new PartitionKey($"{info.code}"));
-                        return Ok(new { auth_token });
-                    }
-                    else
-                    {
-                        return BadRequest();
-                    }
+                var response = await client.GetContainer("TEAMModelOS", "School").ReadItemStreamAsync(id.GetString(), new PartitionKey($"OpenApp-{code}")) ;
+                if (response.Status == 200)
+                {
+                    using var json = await JsonDocument.ParseAsync(response.ContentStream);
+                    var info = json.ToObject<OpenApp>();
+                    //创建Token
+                    //域名  应用的id, jwtkey  学校编码
+                    var auth_token = JwtAuthExtension.CreateApiToken(_option.HostName, info.id, _option.JwtSecretKey,info.name, info.auths, info.school);
+                    info.token = auth_token;
+                    info = await client.GetContainer("TEAMModelOS", "School").ReplaceItemAsync(info, info.id, new PartitionKey($"{info.code}"));
+                    return Ok(new { auth_token });
+                }
+                else
+                {
+                    return BadRequest();
+                }
             }
             }
             catch (Exception e)
             catch (Exception e)
             {
             {
@@ -87,35 +125,21 @@ namespace TEAMModelOS.Controllers.Core
                 return BadRequest();
                 return BadRequest();
             }
             }
         }
         }
-        /// <summary>
-        /// {"code":"hbcn学校编码"} 
-        /// </summary>
-        /// <param name="requert"></param>
-        /// <returns></returns>
-        [ProducesDefaultResponseType]
-        [AuthToken(Roles = "admin")]
-        [HttpPost("find-app")]
-        public async Task<IActionResult> FindApp(JsonElement request)
-        {
-            try
-            {
-                if (!request.TryGetProperty("code", out JsonElement code)) { return BadRequest(); }
-                var client = _azureCosmos.GetCosmosClient();
-                List<OpenApp> apps = new List<OpenApp>();
-                await foreach (var item in client.GetContainer("TEAMModelOS", "School").GetItemQueryIterator<OpenApp>(queryText: $"select value(c) from c ",
-                requestOptions: new QueryRequestOptions() { PartitionKey = new Azure.Cosmos.PartitionKey($"OpenApp-{code}") }))
-                {
-                    apps.Add(item);
-                }
-                return Ok(new { apps });
+       
 
 
-            }
-            catch (Exception ex)
-            {
-                await _dingDing.SendBotMsg($"OS,{_option.Location},open-api/find-app()\n{ex.Message}", GroupNames.醍摩豆服務運維群組);
-                return BadRequest();
-            }
-        }
+        /*
+         {
+            "id": "4a54e95e-ef13-46ec-91ac-e55919d09f9e",
+            "code":"hbcn",
+            "pk":"OpenApp",
+            "name":"醍摩豆接入紫藤课纲应用",
+            "descr":"xxxxxx",
+            "apis":["school/get"],
+            "school":"hbcn",
+            "token":null,
+            "status":1
+         }
+         */
         /// <summary>
         /// <summary>
         /// {
         /// {
         ///   
         ///   
@@ -125,7 +149,7 @@ namespace TEAMModelOS.Controllers.Core
         /// <returns></returns>
         /// <returns></returns>
         [ProducesDefaultResponseType]
         [ProducesDefaultResponseType]
         //[AuthToken(Roles = "Teacher")]
         //[AuthToken(Roles = "Teacher")]
-        [HttpPost("upsert")]
+        [HttpPost("upsert-app")]
         public async ValueTask<IActionResult> Upsert(OpenApp request)
         public async ValueTask<IActionResult> Upsert(OpenApp request)
         {
         {
             try
             try
@@ -170,7 +194,7 @@ namespace TEAMModelOS.Controllers.Core
         /// <param name="requert"></param>
         /// <param name="requert"></param>
         /// <returns></returns>
         /// <returns></returns>
         [ProducesDefaultResponseType]
         [ProducesDefaultResponseType]
-        [HttpPost("delete")]
+        [HttpPost("delete-app")]
         public async Task<IActionResult> Delete(JsonElement requert)
         public async Task<IActionResult> Delete(JsonElement requert)
         {
         {
             try
             try

+ 6 - 1
TEAMModelOS/Controllers/XTest/TestController.cs

@@ -56,14 +56,19 @@ namespace TEAMModelOS.Controllers.XTest
                     foreach (var score in scores)
                     foreach (var score in scores)
                     {
                     {
                         blobsize = blobsize + score.Score;
                         blobsize = blobsize + score.Score;
+                        list.Add(new Dictionary<string, double?>() { { score.Element.ToString(), score.Score } });
                     }
                     }
                 }
                 }
                 await _azureRedis.GetRedisClient(8).HashSetAsync($"Blob:Record", new RedisValue($"{name}"), new RedisValue($"{blobsize}"));
                 await _azureRedis.GetRedisClient(8).HashSetAsync($"Blob:Record", new RedisValue($"{name}"), new RedisValue($"{blobsize}"));
 
 
                 await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-ServiceBus,Blob() 容器:{name}使用:{root},文件分类:{list.ToJsonString()}",
                 await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-ServiceBus,Blob() 容器:{name}使用:{root},文件分类:{list.ToJsonString()}",
                     GroupNames.成都开发測試群組);
                     GroupNames.成都开发測試群組);
+                return Ok(list);
             }
             }
-            return Ok();
+            else {
+                return Ok();
+            }
+            
         }
         }