CrazyIter_Bin 3 years ago
parent
commit
d1fd8c6e7a

+ 48 - 36
TEAMModelOS.FunctionV4/ServiceBus/ActiveTaskTopic.cs

@@ -242,47 +242,59 @@ namespace TEAMModelOS.FunctionV4.ServiceBus
             {
 
                 var jsonMsg = JsonDocument.Parse(msg);
-                if (jsonMsg.RootElement.TryGetProperty("name", out JsonElement _name) && _name.ValueKind == JsonValueKind.String
-                    && jsonMsg.RootElement.TryGetProperty("root", out JsonElement root) && root.ValueKind == JsonValueKind.String)
+                if (jsonMsg.RootElement.TryGetProperty("name", out JsonElement _name) && _name.ValueKind == JsonValueKind.String)
                 {
-                    List<Dictionary<string, double?>> list = new List<Dictionary<string, double?>>();
-                    string[] uls = System.Web.HttpUtility.UrlDecode($"{root}", Encoding.UTF8).Split("/");
-                    string u = !string.IsNullOrEmpty(uls[0]) ? uls[0] : uls[1];
-                    string name = $"{_name}";
-                    string lockKey = $"Blob:Lock:{name}:{u}";
-                    bool exist = await _azureRedis.GetRedisClient(8).KeyExistsAsync(lockKey);
-
-                    if (!exist)
-                    {   ///key不存在则正常进行计算
-                        bool condition = false;
-                        TimeSpan timeSpan = new TimeSpan(DateTimeOffset.UtcNow.AddMinutes(5).Ticks);
-                        timeSpan = timeSpan - new TimeSpan(DateTimeOffset.UtcNow.Ticks);
-                        //准备处理Blob刷新时间
-                        long action = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
-                        await _azureRedis.GetRedisClient(8).StringSetAsync(lockKey, action, expiry: timeSpan);
-                        await RefreshBlob(name, u);
-                        //将action 与Redis最新的时间进行比较,如果
-                        var rds = await CheckLockKey(lockKey, action);
-                        condition = rds.condition;
-                        exist = rds.exist;
-                        if (condition || !exist)
-                        {
+                    if (jsonMsg.RootElement.TryGetProperty("root", out JsonElement root) && root.ValueKind == JsonValueKind.String && !string.IsNullOrWhiteSpace($"{root}"))
+                    {
+                        List<Dictionary<string, double?>> list = new List<Dictionary<string, double?>>();
+                        string[] uls = System.Web.HttpUtility.UrlDecode($"{root}", Encoding.UTF8).Split("/");
+                        string u = !string.IsNullOrEmpty(uls[0]) ? uls[0] : uls[1];
+                        string name = $"{_name}";
+                        string lockKey = $"Blob:Lock:{name}:{u}";
+                        bool exist = await _azureRedis.GetRedisClient(8).KeyExistsAsync(lockKey);
+
+                        if (!exist)
+                        {   ///key不存在则正常进行计算
+                            bool condition = false;
+                            TimeSpan timeSpan = new TimeSpan(DateTimeOffset.UtcNow.AddMinutes(5).Ticks);
+                            timeSpan = timeSpan - new TimeSpan(DateTimeOffset.UtcNow.Ticks);
+                            //准备处理Blob刷新时间
+                            long action = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
+                            await _azureRedis.GetRedisClient(8).StringSetAsync(lockKey, action, expiry: timeSpan);
                             await RefreshBlob(name, u);
-                        }
+                            //将action 与Redis最新的时间进行比较,如果
+                            var rds = await CheckLockKey(lockKey, action);
+                            condition = rds.condition;
+                            exist = rds.exist;
+                            if (condition || !exist)
+                            {
+                                await RefreshBlob(name, u);
+                            }
 
-                        //使用  CancellationToken 
-                        //while (condition || !exist)
-                        //{
+                            //使用  CancellationToken 
+                            //while (condition || !exist)
+                            //{
 
-                        //}
+                            //}
+                        }
+                        else
+                        {
+                            ///key存在则,则刷新key对应的值
+                            TimeSpan timeSpan = new TimeSpan(DateTimeOffset.UtcNow.AddMinutes(5).Ticks);
+                            timeSpan = timeSpan - new TimeSpan(DateTimeOffset.UtcNow.Ticks);
+                            long now = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
+                            await _azureRedis.GetRedisClient(8).StringSetAsync(lockKey, now, expiry: timeSpan);
+                        }
                     }
-                    else
-                    {
-                        ///key存在则,则刷新key对应的值
-                        TimeSpan timeSpan = new TimeSpan(DateTimeOffset.UtcNow.AddMinutes(5).Ticks);
-                        timeSpan = timeSpan - new TimeSpan(DateTimeOffset.UtcNow.Ticks);
-                        long now = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
-                        await _azureRedis.GetRedisClient(8).StringSetAsync(lockKey, now, expiry: timeSpan);
+                    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);
+                        }
                     }
                 }
             }

+ 83 - 6
TEAMModelOS/Controllers/Client/HiTeachController.cs

@@ -159,16 +159,21 @@ namespace TEAMModelOS.Controllers.Client
             LessonRecord lessonRecord = _lesson.ToObject<LessonRecord>();
             if (!string.IsNullOrEmpty(lessonRecord.scope) && !string.IsNullOrEmpty(lessonRecord.tmdid) && !string.IsNullOrEmpty(lessonRecord.id))
             {
+                RedisValue value = default;
                 string tbname = null;
+              
                 if (lessonRecord.scope.Equals("school") && !string.IsNullOrEmpty(lessonRecord.school))
                 {
                     lessonRecord.code = $"LessonRecord-{lessonRecord.school}";
                     tbname = "School";
+                    
+                   
                 }
                 if (lessonRecord.scope.Equals("private"))
                 {
                     lessonRecord.code = $"LessonRecord";
                     tbname = "Teacher";
+                   
                 }
                 if (tbname == null)
                 {
@@ -179,15 +184,15 @@ namespace TEAMModelOS.Controllers.Client
                     lessonRecord.startTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
                 }
                 lessonRecord.pk = "LessonRecord";
-                //处理课堂选用的名单
                 try
                 {
                     await client.GetContainer(Constant.TEAMModelOS, tbname).CreateItemAsync(lessonRecord, new PartitionKey(lessonRecord.code));
+                   
                     var ActiveTask = _configuration.GetValue<string>("Azure:ServiceBus:ActiveTask");
                     var messageChange = new ServiceBusMessage(lessonRecord.ToJsonString());
                     messageChange.ApplicationProperties.Add("name", "LessonRecordEvent");
                     await _serviceBus.GetServiceBusClient().SendMessageAsync(ActiveTask, messageChange);
-                    return Ok(new { status = 200 });
+                    return Ok(new { status = 200  });
                 }
                 catch (Exception ex)
                 {
@@ -216,7 +221,7 @@ namespace TEAMModelOS.Controllers.Client
                 var id = jwt.Payload.Sub;
                 jwt.Payload.TryGetValue("name", out object name);
                 jwt.Payload.TryGetValue("picture", out object picture);
-
+                int total = 0;
                 List<object> schools = new List<object>();
                 string defaultschool = null;
                 //TODK 取得Teacher 個人相關數據(課程清單、虛擬教室清單、歷史紀錄清單等),學校數據另外API處理,多校切換時不同
@@ -225,6 +230,11 @@ namespace TEAMModelOS.Controllers.Client
                 if (response.Status == 200)
                 {
                     var jsonsc = await JsonDocument.ParseAsync(response.ContentStream);
+                    if (jsonsc.RootElement.TryGetProperty("size", out JsonElement size) && size.ValueKind.Equals(JsonValueKind.Number))
+                    {
+                        total = int.Parse($"{size}");
+                        
+                    }
                     if (jsonsc.RootElement.TryGetProperty("schools", out JsonElement value))
                     {
                         foreach (var obj in value.EnumerateArray())
@@ -240,9 +250,16 @@ namespace TEAMModelOS.Controllers.Client
                                 schoolExtobj.status = obj.GetProperty("status");
                                 schoolExtobj.picture = school.RootElement.GetProperty("picture");
                                 schools.Add(schoolExtobj);
+                                var sctch = await client.GetContainer(Constant.TEAMModelOS, "School").ReadItemStreamAsync(id, new PartitionKey($"Teacher-{obj.GetProperty("schoolId")}"));
+                                if (sctch.Status == 200 && sctch != null && sctch.ContentStream != null) {
+                                    var jsonDoc = await JsonDocument.ParseAsync(sctch.ContentStream);
+                                    SchoolTeacher schoolTeacher = jsonDoc.RootElement.ToObject<SchoolTeacher>();
+                                    total += schoolTeacher.size;
+                                }
                             }
                         }
                     }
+                   
                     //預設學校ID
                     if (jsonsc.RootElement.TryGetProperty("defaultSchool", out JsonElement valueD) && !string.IsNullOrEmpty(valueD.ToString()))
                     {
@@ -265,9 +282,11 @@ namespace TEAMModelOS.Controllers.Client
                         defaultSchool = null,
                         schools = new List<Teacher.TeacherSchool>(),
                     };
+                    total = 1;
                     teacher = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Teacher").CreateItemAsync<Teacher>(teacher, new PartitionKey("Base"));
                 }
 
+               
                 //老師個人課程清單
                 List<object> courses = new List<object>();
                 await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Teacher").GetItemQueryStreamIterator(queryText: $"SELECT c.id, c.name, c.schedule, c.scope FROM c ", requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Course-{id}") }))
@@ -419,7 +438,26 @@ namespace TEAMModelOS.Controllers.Client
                 var (blob_uri, blob_sas) = _azureStorage.GetBlobContainerSAS(id, BlobContainerSasPermissions.Write | BlobContainerSasPermissions.Read | BlobContainerSasPermissions.List | BlobContainerSasPermissions.Delete);
                 var (blob_uri_read, blob_sas_read) = _azureStorage.GetBlobContainerSAS(id, BlobContainerSasPermissions.Read);
                 var (blob_uri_write, blob_sas_write) = _azureStorage.GetBlobContainerSAS(id, BlobContainerSasPermissions.Write);
-                return Ok(new { blob_uri, blob_sas, blob_sas_read, blob_sas_write, schools, defaultschool, courses, exams });
+
+                 RedisValue redisValue = default;
+                long blobsize = 0;
+                _azureRedis.GetRedisClient(8).HashGet($"Blob:Record", id);
+                if (redisValue != default && !redisValue.IsNullOrEmpty)
+                {
+                    JsonElement record = redisValue.ToString().ToObject<JsonElement>();
+                    if (record.TryGetInt64(out blobsize))
+                    {
+                    }
+                }
+                else
+                {
+                    var messageBlob = new ServiceBusMessage(new { id = Guid.NewGuid().ToString(), progress = "update", name = $"{id}" }.ToJsonString()); ;
+                    messageBlob.ApplicationProperties.Add("name", "BlobRoot");
+                    var ActiveTask = _configuration.GetValue<string>("Azure:ServiceBus:ActiveTask");
+                    await _serviceBus.GetServiceBusClient().SendMessageAsync(ActiveTask, messageBlob);
+                }
+                double blobUsed = blobsize / 1073741824.0 ; //1073741824  1G
+                return Ok(new { blob_uri, blob_sas, blob_sas_read, blob_sas_write, schools, defaultschool, courses, exams , blobTotal=total, blobUsed });
 
             }
             catch (Exception ex)
@@ -451,10 +489,15 @@ namespace TEAMModelOS.Controllers.Client
                 List<object> grades = new List<object>();
                 List<object> subjects = new List<object>();
                 List<object> examTypes = new List<object>();
+                int total = 0;
                 var responsesch = await client.GetContainer(Constant.TEAMModelOS, "School").ReadItemStreamAsync(school_code.ToString(), new PartitionKey($"Base"));
                 if (responsesch.Status == 200)
                 {
+
                     var jsons = await JsonDocument.ParseAsync(responsesch.ContentStream);
+                    if (jsons.RootElement.TryGetProperty("size", out JsonElement _size) && _size.ValueKind.Equals(JsonValueKind.Number)) {
+                        total = int.Parse($"{_size}");
+                    }
                     if (jsons.RootElement.TryGetProperty("period", out JsonElement periodJobj))
                     {
                         foreach (var periodinfo in periodJobj.EnumerateArray())
@@ -504,7 +547,7 @@ namespace TEAMModelOS.Controllers.Client
                 {
                     return BadRequest();
                 }
-
+               
                 //該老師排定的學校課程
                 List<object> courses = new List<object>();
                 List<string> classIds = new List<string>(); //班級ID列表 篩選校園評測用
@@ -745,7 +788,41 @@ namespace TEAMModelOS.Controllers.Client
                 var (blob_uri_read, blob_sas_read) = _azureStorage.GetBlobContainerSAS(school_code_blob, BlobContainerSasPermissions.Read); //讀
                 var (blob_uri_write, blob_sas_write) = _azureStorage.GetBlobContainerSAS(school_code_blob, BlobContainerSasPermissions.Write); //寫
 
-                return Ok(new { blob_uri, blob_sas, blob_sas_read, blob_sas_write, periods, grades, subjects, courses, examTypes, exams });
+                RedisValue redisValue = default;
+                long teach = 0;
+                long blobsize = 0;
+                _azureRedis.GetRedisClient(8).HashGet($"Blob:Record", $"{school_code}");
+                if (redisValue != default && !redisValue.IsNullOrEmpty)
+                {
+                    JsonElement record = redisValue.ToString().ToObject<JsonElement>();
+                    if (record.TryGetInt64(out blobsize))
+                    {
+                    }
+                }
+                else
+                {
+                    var messageBlob = new ServiceBusMessage(new { id = Guid.NewGuid().ToString(), progress = "update", name = $"{school_code}" }.ToJsonString()); ;
+                    messageBlob.ApplicationProperties.Add("name", "BlobRoot");
+                    var ActiveTask = _configuration.GetValue<string>("Azure:ServiceBus:ActiveTask");
+                    await _serviceBus.GetServiceBusClient().SendMessageAsync(ActiveTask, messageBlob);
+                }
+
+                //计算分配给学校教师的空间
+                await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryStreamIterator(queryText: $"SELECT sum(c.size) as size FROM c ",
+                    requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Teacher-{school_code}") }))
+                {
+                    var json = await JsonDocument.ParseAsync(item.ContentStream);
+                    foreach (var elmt in json.RootElement.GetProperty("Documents").EnumerateArray())
+                    {
+                        if (elmt.TryGetProperty("size", out JsonElement _size) && _size.ValueKind.Equals(JsonValueKind.Number))
+                        {
+                            teach = _size.GetInt32();
+                            break;
+                        }
+                    }
+                }
+                double blobUsed = blobsize / 1073741824.0 + teach; //1073741824  1G
+                return Ok(new { blob_uri, blob_sas, blob_sas_read, blob_sas_write, periods, grades, subjects, courses, examTypes, exams, blobTotal = total, blobUsed});
             }
             catch (Exception ex)
             {