浏览代码

删除接口和复制接口

CrazyIter_Bin 3 年之前
父节点
当前提交
15a1c663e1

+ 1 - 0
Client/Program.cs

@@ -20,6 +20,7 @@ namespace Client
             //SSE
             try
             {
+                Console.WriteLine("12536".PadLeft(7, '0'));
                 var cts = new CancellationTokenSource();
                 var header = new Dictionary<string, string>() { { "X-Auth-Name", "IES5" } };
                //var sse = new EventSource(new Uri("https://localhost:5001/service/sse"), header, 5000);

+ 49 - 1
TEAMModelFunction/ActivityHttpTrigger.cs

@@ -573,6 +573,54 @@ namespace TEAMModelFunction
                 return new BadRequestResult();
             }
         }
+        /// <summary>
+        /// 修复容器的内容显示
+        /// </summary>
+        /// <param name="req"></param>
+        /// <param name="log"></param>
+        /// <returns></returns>
+        [FunctionName("fix-blob-content")]
+        public async Task<IActionResult> FixBlobContent(
+            [HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequest req,
+            ILogger log)
+        {
+            try
+            {   
+                string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
+                var data = System.Text.Json.JsonSerializer.Deserialize<JsonElement>(requestBody);
+                if (data.TryGetProperty("name", out JsonElement name) ) {
+                    var client = _azureCosmos.GetCosmosClient();
+                    List<string> prefixs = new List<string>() { "audio","doc","image","other","res","video", "thum" };
+                    var ContainerClient = _azureStorage.GetBlobContainerClient($"{name}");
+                    string scope = "private";
+                    if (data.TryGetProperty("scope", out JsonElement _scope)){
+                        scope = $"{_scope}";
+                    }
+                    var tb = "Teacher";
+                    if (scope != "private") {
+                        tb = "School";
+                    }
+                    long now = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
+                   // List<Task<ItemResponse<Bloblog>>> responses = new List<Task<ItemResponse<Bloblog>>>();
+                    foreach (var prefix in prefixs) {
+                        List<string> items = await ContainerClient.List(prefix);
+                        foreach (var item in items) {
+                            var urlsSize = await ContainerClient.GetBlobsSize(item);
+                            Bloblog bloblog = new Bloblog { id =   Guid.NewGuid().ToString(),code= $"Bloblog-{name}", pk = "Bloblog", time = now,url= item, size = urlsSize != null && urlsSize.HasValue ? urlsSize.Value : 0, type = prefix};
+                              await client.GetContainer("TEAMModelOS", tb).UpsertItemAsync(bloblog, new Azure.Cosmos.PartitionKey(bloblog.code)) ;
+                        }
+                    }
+                  //  await Task.WhenAll(responses);
+                }
+                return new OkObjectResult(new { });
+
+            }
+            catch (Exception ex)
+            {
+                await _dingDing.SendBotMsg($"TEAMModelFunction,ActivityHttpTrigger,fix-blob-content()\n{ex.Message}{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
+                return new BadRequestResult();
+            }
+        }
+
     }
-  
 }

+ 2 - 2
TEAMModelFunction/MonitorServicesBus.cs

@@ -177,8 +177,8 @@ namespace TEAMModelFunction
                     }
                     await _azureRedis.GetRedisClient(8).HashSetAsync($"Blob:Record", new RedisValue($"{name}"), new RedisValue($"{blobsize}"));
 
-                    await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-ServiceBus,Blob() 容器:{name}使用:{u},文件分类:{list.ToJsonString()}",
-                        GroupNames.成都开发測試群組);
+                    //await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-ServiceBus,Blob() 容器:{name}使用:{u},文件分类:{list.ToJsonString()}",
+                    //    GroupNames.成都开发測試群組);
                 }
             }
             catch (Exception ex)

+ 4 - 0
TEAMModelOS.SDK/Models/Cosmos/Common/SheetConfig.cs

@@ -9,6 +9,10 @@ namespace TEAMModelOS.SDK.Models.Cosmos.Common
         public string school { get; set; }
         public string creatorId { get; set; }
         public string scope { get; set; }
+        /// <summary>
+        /// 关联id,如果没有关联则为null
+        /// </summary>
+        public string sid { get; set; } = null;
 
         /// <summary>
         ///  //列数

+ 34 - 22
TEAMModelOS/Controllers/Client/HiScanController.cs

@@ -79,33 +79,36 @@ namespace TEAMModelOS.Controllers.Core
         {
             try {
               //  if (!request.TryGetProperty("sid", out JsonElement sid)) return BadRequest();
-                if (!request.TryGetProperty("id_token", out JsonElement id_token)) return BadRequest();
+               // if (!request.TryGetProperty("id", out JsonElement id_token)) return BadRequest();
                 
                 //IServerSentEventsClient sseClient;
                 //if (Guid.TryParse($"{sid}", out Guid guid) && (sseClient = _sse.GetClient(guid)) != null) {
                     //var clientName = sseClient.GetProperty<string>("NAME");
                     //var clientDID= sseClient.GetProperty<string>("DID");
                    // var isHiTeach = clientName.Contains("HiScan", StringComparison.OrdinalIgnoreCase);
-                    var jwt = new JwtSecurityToken(id_token.GetString());
+                    //var jwt = new JwtSecurityToken(id_token.GetString());
                     //TODO 此驗證IdToken先簡單檢查,後面需向Core ID新API,驗證Token
-                    if (!jwt.Payload.Iss.Equals("account.teammodel", StringComparison.OrdinalIgnoreCase)) return BadRequest();
-                    var id = jwt.Payload.Sub;
-                    jwt.Payload.TryGetValue("name", out object name);
-                    jwt.Payload.TryGetValue("picture", out object picture);
+                   // if (!jwt.Payload.Iss.Equals("account.teammodel", StringComparison.OrdinalIgnoreCase)) return BadRequest();
+                   // var id = jwt.Payload.Sub;
+                    //jwt.Payload.TryGetValue("name", out object name);
+                    //jwt.Payload.TryGetValue("picture", out object picture);
 
                     List<ScanSchool> schools = new List<ScanSchool>();
-                   
-                    //TODO 取得Teacher 個人相關數據(課程清單、虛擬教室清單、歷史紀錄清單等),學校數據另外API處理,多校切換時不同
-                    var client = _azureCosmos.GetCosmosClient();
-                    var response = await client.GetContainer("TEAMModelOS", "Teacher").ReadItemStreamAsync(id, new PartitionKey("Base"));
+                if (!request.TryGetProperty("id", out JsonElement id)) return BadRequest();
+                //TODO 取得Teacher 個人相關數據(課程清單、虛擬教室清單、歷史紀錄清單等),學校數據另外API處理,多校切換時不同
+                var client = _azureCosmos.GetCosmosClient();
+                    var response = await client.GetContainer("TEAMModelOS", "Teacher").ReadItemStreamAsync($"{id}", new PartitionKey("Base"));
                     int size = 0;
                     //老師個人資料(含初始化)
                     if (response.Status == 200)
                     {
                         var json = await JsonDocument.ParseAsync(response.ContentStream);
-                        if (json.RootElement.TryGetProperty("schools", out JsonElement value))
+                    string name = $"{json.RootElement.GetProperty("name")}";
+                    string picture = $"{json.RootElement.GetProperty("picture")}";
+                    if (json.RootElement.TryGetProperty("schools", out JsonElement value))
                         {
-                            if (json.RootElement.TryGetProperty("size", out JsonElement _size) && _size.ValueKind.Equals(JsonValueKind.Number))
+                           
+                        if (json.RootElement.TryGetProperty("size", out JsonElement _size) && _size.ValueKind.Equals(JsonValueKind.Number))
                             {
                                 size = _size.GetInt32();
                             }
@@ -130,7 +133,7 @@ namespace TEAMModelOS.Controllers.Core
                                     }
                                     if (count > 0) {
                                         //生成token
-                                        var  stoken = JwtAuthExtension.CreateAuthToken(_option.HostName, id, name?.ToString(), picture?.ToString(), _option.JwtSecretKey, roles: new[] { "teacher" }, schoolID: $"{schoolId}");
+                                        var  stoken = JwtAuthExtension.CreateAuthToken(_option.HostName, $"{id}", name?.ToString(), picture?.ToString(), _option.JwtSecretKey, roles: new[] { "teacher" }, schoolID: $"{schoolId}");
                                         //获取学校线下阅卷评测
                                         var sexams= await GetExam($"{schoolId}", "school", client);
                                         var container = _azureStorage.GetBlobContainerClient($"{schoolId}");
@@ -141,8 +144,8 @@ namespace TEAMModelOS.Controllers.Core
                                 }
                             }
                         }
-                        var ttoken = JwtAuthExtension.CreateAuthToken(_option.HostName, id, name?.ToString(), picture?.ToString(), _option.JwtSecretKey, roles: new[] { "teacher" });
-                        var (tblob_uri, tblob_sas) = _azureStorage.GetBlobContainerSAS(id, BlobContainerSasPermissions.Write | BlobContainerSasPermissions.Read | BlobContainerSasPermissions.List | BlobContainerSasPermissions.Delete);
+                        var ttoken = JwtAuthExtension.CreateAuthToken(_option.HostName, $"{id}", name?.ToString(), picture?.ToString(), _option.JwtSecretKey, roles: new[] { "teacher" });
+                        var (tblob_uri, tblob_sas) = _azureStorage.GetBlobContainerSAS($"{id}", BlobContainerSasPermissions.Write | BlobContainerSasPermissions.Read | BlobContainerSasPermissions.List | BlobContainerSasPermissions.Delete);
                         //获取个人线下阅卷评测
                         var exams = await GetExam($"{id}", "private", client);
                         //換取AuthToken,提供給前端
@@ -170,15 +173,24 @@ namespace TEAMModelOS.Controllers.Core
                 //await foreach (var item in client.GetContainer("TEAMModelOS", "Common").GetItemQueryIterator<Correct>(queryText: "SELECT  * FROM c where c.source='2' and c.progress='going' order by c.createTime  ", requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Correct-{code}") }))
                 await foreach (var item in client.GetContainer("TEAMModelOS", "Common").GetItemQueryIterator<Correct>(queryText: "SELECT  * FROM c   order by c.createTime  ", requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Correct-{code}") }))
                 {
-                    ExamInfo exam = await client.GetContainer("TEAMModelOS", "Common").ReadItemAsync<ExamInfo>(item.id, new PartitionKey($"Exam-{code}"));
-
+                  
+                    ExamInfo exam =null;
+                    try {
+                        exam= await client.GetContainer("TEAMModelOS", "Common").ReadItemAsync<ExamInfo>(item.id, new PartitionKey($"Exam-{code}"));
+                    } catch (CosmosException ex) {
+                        if (ex.Status == 404) {
+                            exam = null;
+                        }
+                    }
                     List<ExamClass> classes = new List<ExamClass>();
-                    foreach (var cls in exam.classes) {
-                        (List<string> tmdids, List<Students> students) stulist = await TriggerStuActivity.GetStuList(client, _dingDing, new List<string> { cls }, code);
-                        classes.Add(new ExamClass { classId = cls, tmdids = stulist.tmdids, stulist = stulist.students });
+                    if (exam != null) {
+                        foreach (var cls in exam.classes)
+                        {
+                            (List<string> tmdids, List<Students> students) stulist = await TriggerStuActivity.GetStuList(client, _dingDing, new List<string> { cls }, code);
+                            classes.Add(new ExamClass { classId = cls, tmdids = stulist.tmdids, stulist = stulist.students });
+                        }
+                        corrects.Add(new ExamData { exam = exam, correct = item, classes = classes });
                     }
-                    corrects.Add(new ExamData { exam = exam, correct = item, classes= classes });
-
                 }
             }
             else if(scope.Equals("private")){

+ 85 - 8
TEAMModelOS/Controllers/Common/SheetConfigController.cs

@@ -56,6 +56,73 @@ namespace TEAMModelOS.Controllers.Common
             _azureStorage = azureStorage;
         }
 
+        /// <summary>
+        ///查询答题卡
+        /// </summary>
+        /// <param name="request"></param>
+        /// <returns></returns>
+        [ProducesDefaultResponseType]
+        [HttpPost("copy")]
+        public async Task<IActionResult> Copy(JsonElement request)
+        {
+            try
+            {
+                var client = _azureCosmos.GetCosmosClient();
+                if (!request.TryGetProperty("ids", out JsonElement ids)) return BadRequest();
+                if (!request.TryGetProperty("code", out JsonElement code)) return BadRequest();
+                if (!request.TryGetProperty("scope", out JsonElement scope)) return BadRequest();
+                List<string> inids = new List<string>();
+                ids.ToObject<List<string>>().ForEach(x => { inids.Add($"'{x}'"); });
+                var insql = string.Join(",", inids);
+                var queryslt = $"SELECT  value(c) FROM c where c.id in ({insql})";
+                List<SheetConfig> sheets = new List<SheetConfig>();
+                List<dynamic> datas = new List<dynamic>();
+                string table = "School";
+                if ($"{scope}" != "school")
+                {
+                    table = "Teacher";
+                }
+                await foreach (var item in client.GetContainer("TEAMModelOS", table).GetItemQueryIterator<SheetConfig>(queryText: queryslt, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"SheetConfig-{code}") }))
+                {
+                    string sid = item.id;
+                    string id = $"{_option.LocationNum}{Utils.CreatSaltString(7, "0123456789")}";
+                    for (int i = 0; i < 10; i++)
+                    {
+                        Response response = null;
+                        response = await client.GetContainer("TEAMModelOS", table).ReadItemStreamAsync($"{id}", new PartitionKey($"SheetConfig-{code}"));
+                        if (response.Status == 404)
+                        {
+                            break;
+                        }
+                        else
+                        {
+                            if (i == 9)
+                            {
+                                await _dingDing.SendBotMsg($"OS,{_option.Location},common/SheetConfig/upsert()\n id生成异常,重复生成次数超过10次", GroupNames.醍摩豆服務運維群組);
+                                return BadRequest();
+                            }
+                            else
+                            {
+                                id = $"{_option.LocationNum}{Utils.CreatSaltString(6, "0123456789")}";
+                            }
+                        }
+                    }
+                    item.id = id;
+                    SheetConfig config = await client.GetContainer("TEAMModelOS", table).CreateItemAsync<SheetConfig>(item, new PartitionKey($"SheetConfig-{code}"));
+                    datas.Add(new { sid = sid, newitem = item });
+                }
+                return Ok(new { datas = datas, status = 200 });
+            }
+            catch (CosmosException e)
+            {
+                return Ok(new { status = e.Response.Status });
+            }
+            catch (Exception ex)
+            {
+                await _dingDing.SendBotMsg($"OS,{_option.Location},common/SheetConfig/upsert()\n{ex.Message}", GroupNames.醍摩豆服務運維群組);
+                return BadRequest(ex.StackTrace);
+            }
+        }
         /// <summary>
         ///查询答题卡
         /// </summary>
@@ -109,7 +176,7 @@ namespace TEAMModelOS.Controllers.Common
                 request.ttl = -1;
                 if (string.IsNullOrEmpty(request.id))
                 {
-                    int id=  Utils.CreatSaltInt(9999999);
+                    string id =  $"{_option.LocationNum}{Utils.CreatSaltString(7, "0123456789")}"; 
                     for (int i = 0; i < 10; i++)
                     {
                         Response response = null;
@@ -131,12 +198,13 @@ namespace TEAMModelOS.Controllers.Common
                                 return BadRequest();
                             }
                             else {
-                                id = Utils.CreatSaltInt(9999999);
+                                id = $"{_option.LocationNum}{Utils.CreatSaltString(7, "0123456789")}";
                             }
                         }
                          
                     }
                     request.id = $"{id}";
+                  
                     if (request.scope == "school")
                     {
                         request = await client.GetContainer("TEAMModelOS", "School").CreateItemAsync(request, new PartitionKey($"{request.code}"));
@@ -156,7 +224,11 @@ namespace TEAMModelOS.Controllers.Common
                         request = await client.GetContainer("TEAMModelOS", "Teacher").ReplaceItemAsync(request, request.id, new PartitionKey($"{request.code}"));
                     }
                  }
-                return Ok(new { config = request });
+                return Ok(new { config = request, status=200 });
+            }
+            catch (CosmosException ex)
+            {
+                return Ok(new { status = ex.Status });
             }
             catch (Exception e)
             {
@@ -176,17 +248,22 @@ namespace TEAMModelOS.Controllers.Common
             try
             {
                 var client = _azureCosmos.GetCosmosClient();
-                if (!request.TryGetProperty("id", out JsonElement id)) return BadRequest();
+                if (!request.TryGetProperty("ids", out JsonElement ids)) return BadRequest();
                 if (!request.TryGetProperty("code", out JsonElement code)) return BadRequest();
                 if (!request.TryGetProperty("scope", out JsonElement scope)) return BadRequest();
+                List<string> idslist = ids.ToObject<List<string>>();
                 if ($"{scope}" == "school")
                 {
-                    await client.GetContainer("TEAMModelOS", "School").DeleteItemStreamAsync( $"{id}", new PartitionKey($"{code}"));
+                    await client.GetContainer("TEAMModelOS", "School").DeleteItemsStreamAsync(idslist, $"SheetConfig-{code}");
                 }
-                else {
-                    await client.GetContainer("TEAMModelOS", "Teacher").DeleteItemStreamAsync($"{id}", new PartitionKey($"{code}"));
+                else
+                {
+                    await client.GetContainer("TEAMModelOS", "Teacher").DeleteItemsStreamAsync(idslist, $"SheetConfig-{code}");
                 }
-                return Ok(new { status=200  });
+                return Ok(new { status = 404 });
+            }
+            catch (CosmosException ex) {
+                return Ok(new { status = ex.Status });
             }
             catch (Exception e)
             {

+ 4 - 0
TEAMModelOS/Controllers/School/CorrectController.cs

@@ -218,6 +218,10 @@ namespace TEAMModelOS.Controllers
                 Correct correct = await client.GetContainer("TEAMModelOS", "Common").ReadItemAsync<Correct>(id.GetString(), new PartitionKey($"Correct-{code}"));
                 return Ok(new { correct });
             }
+            catch (CosmosException ex){
+                Correct correct = null;
+                return Ok(new { correct ,status=ex.Status });
+            }
             catch (Exception ex)
             {
                 await _dingDing.SendBotMsg($"OS,{_option.Location},common/Correct/find-id()\n{ex.Message}", GroupNames.醍摩豆服務運維群組);

+ 54 - 0
TEAMModelOS/Controllers/XTest/TestController.cs

@@ -196,6 +196,60 @@ namespace TEAMModelOS.Controllers.XTest
             return  Ok(new { });
             
         }
+
+        /// <summary>
+        /// 删除
+        /// </summary>
+        /// <param name="request"></param>
+        /// <returns></returns>
+        [ProducesDefaultResponseType]
+        //[AuthToken(Roles = "teacher")]
+        [HttpPost("fix-blob-content")]
+        public async Task<IActionResult> FixBlobContent(JsonElement request)
+        {
+            try
+            {
+                if (!request.TryGetProperty("name", out JsonElement name)) return BadRequest();
+                if (!request.TryGetProperty("scope", out JsonElement _scope)) return BadRequest();
+                
+                
+                    var client = _azureCosmos.GetCosmosClient();
+                    List<string> prefixs = new List<string>() { "audio", "doc", "image", "other", "res", "video", "thum" };
+                    var ContainerClient = _azureStorage.GetBlobContainerClient($"{name}");
+                    string scope = "private";
+                     
+                     
+                        scope = $"{_scope}";
+                   
+                    var tb = "Teacher";
+                    if (scope != "private")
+                    {
+                        tb = "School";
+                    }
+                    long now = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
+                    
+                    foreach (var prefix in prefixs)
+                    {
+                        List<string> items = await ContainerClient.List(prefix);
+                        foreach (var item in items)
+                        {
+                            var urlsSize = await ContainerClient.GetBlobsSize(item);
+                            Bloblog bloblog = new Bloblog { id = Guid.NewGuid().ToString(), code = $"Bloblog-{name}", pk = "Bloblog", time = now, size = urlsSize != null && urlsSize.HasValue ? urlsSize.Value : 0, type = prefix };
+                           await client.GetContainer("TEAMModelOS", tb).UpsertItemAsync(bloblog, new Azure.Cosmos.PartitionKey(bloblog.code)) ;
+                        }
+                    }
+                     
+               
+                return new OkObjectResult(new { });
+
+            }
+            catch (Exception ex)
+            {
+                await _dingDing.SendBotMsg($"TEAMModelFunction,ActivityHttpTrigger,fix-blob-content()\n{ex.Message}{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
+                return new BadRequestResult();
+            }
+        }
+
         /// <summary>
         /// 删除
         /// </summary>