CrazyIter_Bin 3 年之前
父节点
当前提交
51a3821910
共有 1 个文件被更改,包括 63 次插入46 次删除
  1. 63 46
      TEAMModelOS.FunctionV4/ServiceBus/ActiveTaskTopic.cs

+ 63 - 46
TEAMModelOS.FunctionV4/ServiceBus/ActiveTaskTopic.cs

@@ -39,7 +39,7 @@ namespace TEAMModelOS.FunctionV4.ServiceBus
         private readonly NotificationService _notificationService;
         private readonly CoreAPIHttpService _coreAPIHttpService;
         private readonly IConfiguration _configuration;
-        public ActiveTaskTopic(CoreAPIHttpService  coreAPIHttpService,AzureCosmosFactory azureCosmos, DingDing dingDing, AzureStorageFactory azureStorage, AzureRedisFactory azureRedis, AzureServiceBusFactory serviceBus, IOptionsSnapshot<Option> option, NotificationService notificationService, IConfiguration configuration)
+        public ActiveTaskTopic(CoreAPIHttpService coreAPIHttpService, AzureCosmosFactory azureCosmos, DingDing dingDing, AzureStorageFactory azureStorage, AzureRedisFactory azureRedis, AzureServiceBusFactory serviceBus, IOptionsSnapshot<Option> option, NotificationService notificationService, IConfiguration configuration)
         {
             _azureCosmos = azureCosmos;
             _dingDing = dingDing;
@@ -337,7 +337,7 @@ namespace TEAMModelOS.FunctionV4.ServiceBus
             await _azureRedis.GetRedisClient(8).HashSetAsync($"Blob:Record", new RedisValue(name), new RedisValue($"{blobsize}"));
             long end = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
             long dis = (end - statr) / 1000;
-            long timeout = 60*5;
+            long timeout = 60 * 5;
             if (dis > timeout)
             {
                 await _dingDing.SendBotMsg($"ServiceBus,RefreshBlob:空间计算已经超过{timeout}秒\n容器名:{name}\n文件夹:{u}\n计算时长:{dis}", GroupNames.醍摩豆服務運維群組);
@@ -347,10 +347,10 @@ namespace TEAMModelOS.FunctionV4.ServiceBus
         /// <returns></returns>
         [Function("TeacherTrainChange")]
         public async Task TeacherTrainChangeFunc([ServiceBusTrigger("%Azure:ServiceBus:ActiveTask%", "teacher-train-change", Connection = "Azure:ServiceBus:ConnectionString")] string msg)
-        { 
-        
+        {
+
         }
-        
+
         /// <param name="msg"></param>
         /// <returns></returns>
         //[Function("TeacherTrainChange")]
@@ -700,7 +700,7 @@ namespace TEAMModelOS.FunctionV4.ServiceBus
                             }
                         }
                     }
-                    if(chgSchSizeCnt.Equals(0) && !school.size.Equals(schoolDefaultSize))
+                    if (chgSchSizeCnt.Equals(0) && !school.size.Equals(schoolDefaultSize))
                     {
                         school.size = schoolDefaultSize;
                         //updSchool = true; //關於學校空間初始式樣未定,目前暫定:若需要Reset空間,則先維持原空間數不更動
@@ -708,7 +708,7 @@ namespace TEAMModelOS.FunctionV4.ServiceBus
                     }
                 }
                 //變更學校基本資料
-                if(updSchool)
+                if (updSchool)
                 {
                     await client.GetContainer(Constant.TEAMModelOS, "School").ReplaceItemAsync<School>(school, $"{schoolId}", new PartitionKey("Base"));
                 }
@@ -916,22 +916,26 @@ namespace TEAMModelOS.FunctionV4.ServiceBus
                                 var duration = double.Parse($"{update.data}");
                                 lessonRecord.duration = duration;
                                 msgs.Add(update);
-                                try {
+                                try
+                                {
                                     BlobDownloadResult Recording = await _azureStorage.GetBlobContainerClient(blobname).GetBlobClient($"records/{_lessonId}/Record/.Recording.json").DownloadContentAsync();
                                     var RecordingJson = JsonDocument.Parse(new MemoryStream(Encoding.UTF8.GetBytes(Recording.Content.ToString()))).RootElement;
-                                    if (RecordingJson.TryGetProperty("duration",out JsonElement _duration) && _duration.ValueKind.Equals(JsonValueKind.Number)) {
+                                    if (RecordingJson.TryGetProperty("duration", out JsonElement _duration) && _duration.ValueKind.Equals(JsonValueKind.Number))
+                                    {
                                         var durationFile = double.Parse($"{_duration}");
-                                        if (duration < durationFile) {
+                                        if (duration < durationFile)
+                                        {
                                             lessonRecord.duration = durationFile;
                                         }
                                     }
-                                    if (RecordingJson.TryGetProperty("streamUrl", out JsonElement _streamUrl) &&!string.IsNullOrWhiteSpace($"{_streamUrl}"))
+                                    if (RecordingJson.TryGetProperty("streamUrl", out JsonElement _streamUrl) && !string.IsNullOrWhiteSpace($"{_streamUrl}"))
                                     {
                                         lessonRecord.hasVideo = 1;
                                     }
                                 }
-                                catch (Exception ex ) {
-                                  // await _dingDing.SendBotMsg($"{_option.Location}/LessonRecordEvent/课堂记录更新课堂时长出错records/{_lessonId}/Record/.Recording.json\n{ex.Message}{ex.StackTrace}{msg}", GroupNames.醍摩豆服務運維群組);
+                                catch (Exception ex)
+                                {
+                                    // await _dingDing.SendBotMsg($"{_option.Location}/LessonRecordEvent/课堂记录更新课堂时长出错records/{_lessonId}/Record/.Recording.json\n{ex.Message}{ex.StackTrace}{msg}", GroupNames.醍摩豆服務運維群組);
                                 }
                                 isReplace = true;
                                 break;
@@ -964,10 +968,10 @@ namespace TEAMModelOS.FunctionV4.ServiceBus
                                 //如果有更新 则去读取/{_lessonId}/IES/base.json
                                 try
                                 {
-                                   // await _dingDing.SendBotMsg($"{_option.Location},课堂id:{_lessonId} 收到更新", GroupNames.醍摩豆服務運維群組);
+                                    // await _dingDing.SendBotMsg($"{_option.Location},课堂id:{_lessonId} 收到更新", GroupNames.醍摩豆服務運維群組);
                                     BlobDownloadResult baseblobDownload = await _azureStorage.GetBlobContainerClient(blobname).GetBlobClient($"/records/{_lessonId}/IES/base.json").DownloadContentAsync();
                                     LessonBase lessonBase = baseblobDownload.Content.ToObjectFromJson<LessonBase>();
-                                    if (lessonBase != null  && lessonBase.summary!=null)
+                                    if (lessonBase != null && lessonBase.summary != null)
                                     {
                                         //lessonRecord.name = lessonBase.summary.activityName;
                                         lessonRecord.attendCount = lessonBase.summary.attendCount;
@@ -986,8 +990,8 @@ namespace TEAMModelOS.FunctionV4.ServiceBus
                                         lessonRecord.examCount = lessonBase.summary.examCount;
                                         lessonRecord.totalInteractPoint = lessonBase.summary.totalInteractPoint;
                                     }
-                                   // await _dingDing.SendBotMsg($"{_option.Location},课堂id:{_lessonId} 更新完成", GroupNames.醍摩豆服務運維群組);
-                                    long? size = await  _azureStorage.GetBlobContainerClient(blobname).GetBlobsSize($"records/{_lessonId}");
+                                    // await _dingDing.SendBotMsg($"{_option.Location},课堂id:{_lessonId} 更新完成", GroupNames.醍摩豆服務運維群組);
+                                    long? size = await _azureStorage.GetBlobContainerClient(blobname).GetBlobsSize($"records/{_lessonId}");
                                     Bloblog bloblog = new Bloblog
                                     {
                                         id = lessonRecord.id,
@@ -997,11 +1001,11 @@ namespace TEAMModelOS.FunctionV4.ServiceBus
                                         time = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(),
                                         type = "records",
                                         url = $"records/{_lessonId}",
-                                        subjectId =string.IsNullOrWhiteSpace(lessonRecord.subjectId)?new List<string>(): new List<string> { lessonRecord.subjectId },
+                                        subjectId = string.IsNullOrWhiteSpace(lessonRecord.subjectId) ? new List<string>() : new List<string> { lessonRecord.subjectId },
                                         periodId = string.IsNullOrWhiteSpace(lessonRecord.periodId) ? new List<string>() : new List<string> { lessonRecord.periodId },
                                         size = size.HasValue ? size.Value : 0,
                                     };
-                                    await client.GetContainer(Constant.TEAMModelOS,tbname).UpsertItemAsync(bloblog);
+                                    await client.GetContainer(Constant.TEAMModelOS, tbname).UpsertItemAsync(bloblog);
                                     var messageBlob = new ServiceBusMessage(new { id = Guid.NewGuid().ToString(), progress = "update", root = "records", name = $"{blobname}" }.ToJsonString()); ;
                                     messageBlob.ApplicationProperties.Add("name", "BlobRoot");
                                     var ActiveTask = _configuration.GetValue<string>("Azure:ServiceBus:ActiveTask");
@@ -1011,7 +1015,7 @@ namespace TEAMModelOS.FunctionV4.ServiceBus
                                 }
                                 catch (Exception ex)
                                 {
-                                   // await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}课程读取base.json,{_lessonId}\n{ex.Message}\n{ex.StackTrace}\n{lessonRecord.ToJsonString()}", GroupNames.醍摩豆服務運維群組);
+                                    // await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}课程读取base.json,{_lessonId}\n{ex.Message}\n{ex.StackTrace}\n{lessonRecord.ToJsonString()}", GroupNames.醍摩豆服務運維群組);
                                 }
                                 break;
                             //更新 时间线
@@ -1031,7 +1035,8 @@ namespace TEAMModelOS.FunctionV4.ServiceBus
                                 msgs.Add(update);
                                 break;
                             case "up-expire"://消除过期时间,消除后需要取消已经排程的通知订阅
-                                try {
+                                try
+                                {
                                     var table = _azureStorage.GetCloudTableClient().GetTableReference("ChangeRecord");
                                     List<ChangeRecord> records = await table.FindListByDict<ChangeRecord>(new Dictionary<string, object>() { { "RowKey", lessonRecord.id } });
                                     foreach (var record in records)
@@ -1046,7 +1051,9 @@ namespace TEAMModelOS.FunctionV4.ServiceBus
                                             continue;
                                         }
                                     }
-                                } catch (Exception) {
+                                }
+                                catch (Exception)
+                                {
                                     break;
                                 }
                                 isReplace = true;
@@ -1055,7 +1062,8 @@ namespace TEAMModelOS.FunctionV4.ServiceBus
                             case "delete":
                                 try
                                 {
-                                    if (lessonRecord.expire > 0) {
+                                    if (lessonRecord.expire > 0)
+                                    {
                                         var table = _azureStorage.GetCloudTableClient().GetTableReference("ChangeRecord");
                                         List<ChangeRecord> records = await table.FindListByDict<ChangeRecord>(new Dictionary<string, object>() { { "RowKey", lessonRecord.id } });
                                         foreach (var record in records)
@@ -1072,7 +1080,7 @@ namespace TEAMModelOS.FunctionV4.ServiceBus
                                         }
                                     }
                                     await _azureStorage.GetBlobServiceClient().DeleteBlobs(_dingDing, blobname, new List<string> { $"records/{_lessonId}" });
-                                    await client.GetContainer(Constant.TEAMModelOS, tbname).DeleteItemStreamAsync(lessonRecord.id,new PartitionKey ($"Bloblog-{blobname}"));
+                                    await client.GetContainer(Constant.TEAMModelOS, tbname).DeleteItemStreamAsync(lessonRecord.id, new PartitionKey($"Bloblog-{blobname}"));
                                     var messageBlob = new ServiceBusMessage(new { id = Guid.NewGuid().ToString(), progress = "update", root = "records", name = $"{blobname}" }.ToJsonString()); ;
                                     messageBlob.ApplicationProperties.Add("name", "BlobRoot");
                                     var ActiveTask = _configuration.GetValue<string>("Azure:ServiceBus:ActiveTask");
@@ -1116,7 +1124,8 @@ namespace TEAMModelOS.FunctionV4.ServiceBus
                                             }
                                         }
                                     }
-                                    catch (Exception ex) {
+                                    catch (Exception ex)
+                                    {
                                         await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-查询课程-CosmosDB异常{ex.Message}\n{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
                                     }
                                     /*catch (CosmosException ex) when (ex.Status != 404)
@@ -1141,7 +1150,7 @@ namespace TEAMModelOS.FunctionV4.ServiceBus
                                 {
                                     HashSet<string> grades = new HashSet<string>();
                                     List<GroupListDto> groups = await GroupListService.GetGroupListListids(client, _dingDing, lessonRecord.groupIds, lessonRecord.school);
-                                     
+
                                     List<GroupListDto> groupLists = groups?.FindAll(x => !string.IsNullOrEmpty(x.periodId) && x.year > 0 && !string.IsNullOrEmpty(x.school));
                                     if (groupLists.IsNotEmpty() && !string.IsNullOrWhiteSpace(lessonRecord.periodId))
                                     {
@@ -1193,23 +1202,25 @@ namespace TEAMModelOS.FunctionV4.ServiceBus
                                         {
 
                                         }
-                                        catch (Exception ex) {
+                                        catch (Exception ex)
+                                        {
                                             await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-处理课堂记录的-年级处理异常{ex.Message}\n{ex.StackTrace}\n{lessonRecord.ToJsonString()}", GroupNames.醍摩豆服務運維群組);
                                         }
                                     }
-                                    lessonRecord.grade= grades.ToList();
+                                    lessonRecord.grade = grades.ToList();
                                 }
                                 //个人课例保存规则
-                                try {
+                                try
+                                {
                                     if (scope.Equals("private"))
                                     {
-                                       
+
                                         if (teacher.lessonLimit != -1)
                                         {
 
                                             HashSet<string> ids = new HashSet<string>();
                                             //未定义的 以及过期时间小于等于0 的 课例
-                                            string private_count_sql = "select value(c.id) from  c where ( c.expire<=0 or IS_DEFINED(c.expire) = false  )  ";
+                                            string private_count_sql = $"select value(c.id) from  c where  ( c.expire<=0 or IS_DEFINED(c.expire) = false  ) and c.tmdid='{tmdid}'  ";
                                             await foreach (var item in client.GetContainer(Constant.TEAMModelOS, Constant.Teacher).GetItemQueryIterator<string>(
                                                 queryText: private_count_sql, requestOptions: new QueryRequestOptions { PartitionKey = new PartitionKey(code) }))
                                             {
@@ -1217,7 +1228,7 @@ namespace TEAMModelOS.FunctionV4.ServiceBus
                                                 ids.Add(item);
                                             }
                                             //包含收藏的本人的个人课例
-                                            string favorite_count_sql = $"select value(c.id) from  c where c.type='LessonRecord'    and c.scope='private' ";
+                                            string favorite_count_sql = $"select value(c.id) from  c where c.type='LessonRecord' and c.owner='{tmdid}'   and c.scope='private' ";
                                             await foreach (var item in client.GetContainer(Constant.TEAMModelOS, Constant.Teacher).GetItemQueryIterator<string>(
                                                 queryText: favorite_count_sql, requestOptions: new QueryRequestOptions { PartitionKey = new PartitionKey($"Favorite-{tmdid}") }))
                                             {
@@ -1240,7 +1251,7 @@ namespace TEAMModelOS.FunctionV4.ServiceBus
                                                 //var day3= now.AddDays(Constant.private_lesson_expire - 3).ToUnixTimeMilliseconds();
                                                 //result.Add(3, day3);
                                                 //剩余1天的通知
-                                                var day1 = now.AddDays(Constant.private_lesson_expire -6).ToUnixTimeMilliseconds();
+                                                var day1 = now.AddDays(Constant.private_lesson_expire - 6).ToUnixTimeMilliseconds();
                                                 result.Add(1, day1);
                                                 //到期通知
                                                 lessonRecord.expire = now.AddDays(Constant.private_lesson_expire).ToUnixTimeMilliseconds();
@@ -1253,7 +1264,8 @@ namespace TEAMModelOS.FunctionV4.ServiceBus
                                                     from = $"ies5:{ Environment.GetEnvironmentVariable("Option:Location")}:private",
                                                     to = new List<string> { tmdid },
                                                     label = $"{biz}_lessonRecord",
-                                                    body = new {
+                                                    body = new
+                                                    {
                                                         location = $"{Environment.GetEnvironmentVariable("Option:Location")}",
                                                         biz = biz,
                                                         tmdid = teacher.id,
@@ -1273,7 +1285,7 @@ namespace TEAMModelOS.FunctionV4.ServiceBus
                                                 var clientSecret = _configuration.GetValue<string>("HaBookAuth:CoreService:clientSecret");
                                                 var location = $"{Environment.GetEnvironmentVariable("Option:Location")}";
                                                 await _notificationService.SendNotification(clientID, clientSecret, location, url, notification); //站内发送消息
-                                               
+
                                                 var table = _azureStorage.GetCloudTableClient().GetTableReference("ChangeRecord");
                                                 List<ChangeRecord> records = await table.FindListByDict<ChangeRecord>(new Dictionary<string, object>() { { "RowKey", lessonRecord.id } });
                                                 if (records.Count <= 0)
@@ -1316,10 +1328,12 @@ namespace TEAMModelOS.FunctionV4.ServiceBus
                                             //=-1 则表示不限制上传数量
                                         }
                                     }
-                                } catch (Exception e) {
+                                }
+                                catch (Exception e)
+                                {
                                     await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-处理课堂记录的-CosmosDB异常{e.Message}\n{e.StackTrace}\n{lessonRecord.ToJsonString()}", GroupNames.醍摩豆服務運維群組);
                                 }
-                                
+
                                 msgs.Add(update);
                                 break;
                             default:
@@ -1327,7 +1341,8 @@ namespace TEAMModelOS.FunctionV4.ServiceBus
                         }
                     }
                     //如果被删除则不能再被更新
-                    if (isReplace) {
+                    if (isReplace)
+                    {
                         await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, tbname).ReplaceItemAsync<LessonRecord>(lessonRecord, lessonId, new PartitionKey(code));
                     }
                     //计算课堂更新前后的差值
@@ -1347,7 +1362,7 @@ namespace TEAMModelOS.FunctionV4.ServiceBus
         [Function("LessonRecordExpire")]
         public async Task LessonRecordExpireFunc([ServiceBusTrigger("%Azure:ServiceBus:ActiveTask%", "lesson-record-expire", Connection = "Azure:ServiceBus:ConnectionString")] string msg)
         {
-            
+
             try
             {
                 var jsonMsg = JsonDocument.Parse(msg).RootElement;
@@ -1363,10 +1378,11 @@ namespace TEAMModelOS.FunctionV4.ServiceBus
                 jsonMsg.TryGetProperty("school", out JsonElement _school);
                 var client = _azureCosmos.GetCosmosClient();
                 //处理到期删除
-                if ($"{progress}".Equals($"{Constant.private_lesson_expire}")) {
+                if ($"{progress}".Equals($"{Constant.private_lesson_expire}"))
+                {
                     string lessonId = $"{id}";
                     string tbname;
-                    string school=$"{_school}";
+                    string school = $"{_school}";
                     string code = "";
                     if ($"{scope}".Equals("school") && !string.IsNullOrEmpty($"{school}"))
                     {
@@ -1391,7 +1407,7 @@ namespace TEAMModelOS.FunctionV4.ServiceBus
                         lessonRecord.status = 404;
                         await client.GetContainer(Constant.TEAMModelOS, tbname).ReplaceItemAsync(lessonRecord, lessonRecord.id, new PartitionKey(lessonRecord.code));
                         var ActiveTask = _configuration.GetValue<string>("Azure:ServiceBus:ActiveTask");
-                        var messageChange = new ServiceBusMessage(new   { delete_id =lessonId, tmdid =tmdid,scope=scope,opt="delete",school=school}.ToJsonString());
+                        var messageChange = new ServiceBusMessage(new { delete_id = lessonId, tmdid = tmdid, scope = scope, opt = "delete", school = school }.ToJsonString());
                         messageChange.ApplicationProperties.Add("name", "LessonRecordEvent");
                         await _serviceBus.GetServiceBusClient().SendMessageAsync(ActiveTask, messageChange);
                         await _dingDing.SendBotMsg($"课例:【{lessonRecord.name}】\n课例ID:【{lessonRecord.id}】\n因时间到期,即将被自动删除,到期时间:" +
@@ -1406,12 +1422,13 @@ namespace TEAMModelOS.FunctionV4.ServiceBus
                     from = $"ies5:{_option.Location}:private",
                     to = new List<string> { $"{tmdid}" },
                     label = $"{biz}_lessonRecord",
-                    body = new {
+                    body = new
+                    {
                         location = $"{Environment.GetEnvironmentVariable("Option:Location")}",
                         biz = biz,
                         tmdid = $"{tmdid}",
                         tmdname = tmdname,
-                        sid =$"{id}",
+                        sid = $"{id}",
                         sname = $"{name}",
                         stime = long.Parse($"{startTime}"),
                         expire = long.Parse($"{expire}"),
@@ -1424,7 +1441,7 @@ namespace TEAMModelOS.FunctionV4.ServiceBus
                 var url = _configuration.GetValue<string>("HaBookAuth:CoreService:sendnotification");
                 var clientID = _configuration.GetValue<string>("HaBookAuth:CoreService:clientID");
                 var clientSecret = _configuration.GetValue<string>("HaBookAuth:CoreService:clientSecret");
-                var location =$"{Environment.GetEnvironmentVariable("Option:Location")}";
+                var location = $"{Environment.GetEnvironmentVariable("Option:Location")}";
                 await _notificationService.SendNotification(clientID, clientSecret, location, url, notification); //站内发送消息
             }
             catch (Exception ex)
@@ -1708,7 +1725,7 @@ namespace TEAMModelOS.FunctionV4.ServiceBus
                         catch (CosmosException ex)
                         {
                             continue;
-                           // await _dingDing.SendBotMsg($"OS,{ Environment.GetEnvironmentVariable("Option:Location")},CourseServiceBus -CosmosDB异常\n{ex.Message}{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
+                            // await _dingDing.SendBotMsg($"OS,{ Environment.GetEnvironmentVariable("Option:Location")},CourseServiceBus -CosmosDB异常\n{ex.Message}{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
                         }
                     }
                     foreach (var tmd in delTmdidsCls)