12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463 |
- using System;
- using System.Collections.Generic;
- using System.Text;
- using System.Text.Json;
- using System.Threading.Tasks;
- using Azure.Cosmos;
- using Azure.Messaging.ServiceBus;
- using Microsoft.Extensions.Logging;
- using StackExchange.Redis;
- using TEAMModelOS.SDK.DI;
- using TEAMModelOS.SDK.Extension;
- using TEAMModelOS.SDK;
- using TEAMModelOS.SDK.Models;
- using TEAMModelOS.SDK.Models.Cosmos;
- using TEAMModelOS.SDK.Models.Cosmos.Common;
- using System.Linq;
- using TEAMModelOS.SDK.Models.Service;
- using TEAMModelOS.SDK.Models.Cosmos.BI;
- using TEAMModelOS.Models;
- using Microsoft.Extensions.Options;
- using Microsoft.Extensions.Configuration;
- using HTEXLib.COMM.Helpers;
- using Microsoft.Azure.Functions.Worker;
- using TEAMModelOS.SDK.Services;
- using Azure.Storage.Blobs.Models;
- using System.IO;
- using Azure;
- namespace TEAMModelOS.FunctionV4.ServiceBus
- {
- public class ActiveTaskTopic
- {
- private readonly AzureCosmosFactory _azureCosmos;
- private readonly DingDing _dingDing;
- private readonly AzureStorageFactory _azureStorage;
- private readonly AzureRedisFactory _azureRedis;
- private readonly AzureServiceBusFactory _serviceBus;
- private readonly Option _option;
- 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)
- {
- _azureCosmos = azureCosmos;
- _dingDing = dingDing;
- _azureStorage = azureStorage;
- _azureRedis = azureRedis;
- _serviceBus = serviceBus;
- _option = option?.Value;
- _notificationService = notificationService;
- _configuration = configuration;
- _coreAPIHttpService = coreAPIHttpService;
- }
- [Function("Exam")]
- public async Task ExamFunc([ServiceBusTrigger("%Azure:ServiceBus:ActiveTask%", "exam", Connection = "Azure:ServiceBus:ConnectionString")] string msg)
- {
- try
- {
- var json = JsonDocument.Parse(msg);
- json.RootElement.TryGetProperty("id", out JsonElement id);
- json.RootElement.TryGetProperty("progress", out JsonElement progress);
- json.RootElement.TryGetProperty("code", out JsonElement code);
- //Dictionary<string, object> keyValuePairs = mySbMsg.ToObject<Dictionary<string, object>>();
- var client = _azureCosmos.GetCosmosClient();
- ExamInfo exam = await client.GetContainer(Constant.TEAMModelOS, "Common").ReadItemAsync<ExamInfo>(id.ToString(), new PartitionKey($"{code}"));
- exam.progress = progress.ToString();
- await client.GetContainer(Constant.TEAMModelOS, "Common").ReplaceItemAsync(exam, id.ToString(), new PartitionKey($"{code}"));
- }
- catch (CosmosException e)
- {
- await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-ServiceBus,ExamBus()-CosmosDB异常{e.Message}\n{e.Status}{e.StackTrace}\n{msg}", GroupNames.成都开发測試群組);
- }
- catch (Exception ex)
- {
- await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-ServiceBus,ExamBus()\n{ex.Message}\n{ex.StackTrace}\n{msg}", GroupNames.醍摩豆服務運維群組);
- }
- }
- [Function("Vote")]
- public async Task VoteFunc([ServiceBusTrigger("%Azure:ServiceBus:ActiveTask%", "vote", Connection = "Azure:ServiceBus:ConnectionString")] string msg)
- {
- try
- {
- var jsonMsg = JsonDocument.Parse(msg);
- jsonMsg.RootElement.TryGetProperty("id", out JsonElement id);
- jsonMsg.RootElement.TryGetProperty("progress", out JsonElement progress);
- jsonMsg.RootElement.TryGetProperty("code", out JsonElement code);
- var client = _azureCosmos.GetCosmosClient();
- Vote vote = await client.GetContainer(Constant.TEAMModelOS, "Common").ReadItemAsync<Vote>(id.ToString(), new PartitionKey($"{code}"));
- vote.progress = progress.ToString();
- await client.GetContainer(Constant.TEAMModelOS, "Common").ReplaceItemAsync(vote, id.ToString(), new PartitionKey($"{code}"));
- }
- catch (CosmosException e)
- {
- await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-ServiceBus,VoteBus()-CosmosDB异常{e.Message}\n{e.Status}{e.StackTrace}\n{msg}", GroupNames.成都开发測試群組);
- }
- catch (Exception ex)
- {
- await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-ServiceBus,VoteBus()\n{ex.Message}\n{ex.StackTrace}\n{msg}", GroupNames.醍摩豆服務運維群組);
- }
- }
- [Function("Correct")]
- public async Task CorrectFunc([ServiceBusTrigger("%Azure:ServiceBus:ActiveTask%", "correct", Connection = "Azure:ServiceBus:ConnectionString")] string msg)
- {
- try
- {
- var jsonMsg = JsonDocument.Parse(msg);
- jsonMsg.RootElement.TryGetProperty("id", out JsonElement id);
- jsonMsg.RootElement.TryGetProperty("progress", out JsonElement progress);
- jsonMsg.RootElement.TryGetProperty("code", out JsonElement code);
- var client = _azureCosmos.GetCosmosClient();
- Correct correct = await client.GetContainer(Constant.TEAMModelOS, "Common").ReadItemAsync<Correct>(id.ToString(), new PartitionKey($"{code}"));
- correct.progress = progress.ToString();
- await client.GetContainer(Constant.TEAMModelOS, "Common").ReplaceItemAsync(correct, id.ToString(), new PartitionKey($"{code}"));
- }
- catch (CosmosException e)
- {
- await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-ServiceBus,Correct()-CosmosDB异常{e.Message}\n{e.Status}{e.StackTrace}\n{msg}", GroupNames.成都开发測試群組);
- }
- catch (Exception ex)
- {
- await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-ServiceBus,Correct()\n{ex.Message}\n{ex.StackTrace}\n{msg}", GroupNames.醍摩豆服務運維群組);
- }
- }
- [Function("Survey")]
- public async Task SurveyFunc([ServiceBusTrigger("%Azure:ServiceBus:ActiveTask%", "survey", Connection = "Azure:ServiceBus:ConnectionString")] string msg)
- {
- try
- {
- var jsonMsg = JsonDocument.Parse(msg);
- jsonMsg.RootElement.TryGetProperty("id", out JsonElement id);
- jsonMsg.RootElement.TryGetProperty("progress", out JsonElement progress);
- jsonMsg.RootElement.TryGetProperty("code", out JsonElement code);
- //Dictionary<string, object> keyValuePairs = mySbMsg.ToObject<Dictionary<string, object>>();
- var client = _azureCosmos.GetCosmosClient();
- Survey survey = await client.GetContainer(Constant.TEAMModelOS, "Common").ReadItemAsync<Survey>(id.ToString(), new PartitionKey($"{code}"));
- survey.progress = progress.ToString();
- await client.GetContainer(Constant.TEAMModelOS, "Common").ReplaceItemAsync(survey, id.ToString(), new PartitionKey($"{code}"));
- }
- catch (CosmosException e)
- {
- await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-ServiceBus,SurveyBus()-CosmosDB异常{e.StackTrace}{e.Message}\n{e.Status}\n{msg}", GroupNames.成都开发測試群組);
- }
- catch (Exception ex)
- {
- await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-ServiceBus,SurveyBus()\n{ex.Message}\n{ex.StackTrace}\n{msg}", GroupNames.醍摩豆服務運維群組);
- }
- }
- [Function("Homework")]
- public async Task HomeworkFunc([ServiceBusTrigger("%Azure:ServiceBus:ActiveTask%", "homework", Connection = "Azure:ServiceBus:ConnectionString")] string msg)
- {
- try
- {
- var jsonMsg = JsonDocument.Parse(msg);
- jsonMsg.RootElement.TryGetProperty("id", out JsonElement id);
- jsonMsg.RootElement.TryGetProperty("progress", out JsonElement progress);
- jsonMsg.RootElement.TryGetProperty("code", out JsonElement code);
- var client = _azureCosmos.GetCosmosClient();
- Homework homework = await client.GetContainer(Constant.TEAMModelOS, "Common").ReadItemAsync<Homework>(id.ToString(), new PartitionKey($"{code}"));
- homework.progress = progress.ToString();
- await client.GetContainer(Constant.TEAMModelOS, "Common").ReplaceItemAsync(homework, id.ToString(), new PartitionKey($"{code}"));
- }
- catch (CosmosException e)
- {
- await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-ServiceBus,Homework()-CosmosDB异常{e.StackTrace}{e.Message}{e.StackTrace}\n{e.Status}\n{msg}", GroupNames.成都开发測試群組);
- }
- catch (Exception ex)
- {
- await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-ServiceBus,Homework()\n{ex.Message}\n{ex.StackTrace}\n{msg}", GroupNames.醍摩豆服務運維群組);
- }
- }
- [Function("Study")]
- public async Task StudyFunc([ServiceBusTrigger("%Azure:ServiceBus:ActiveTask%", "study", Connection = "Azure:ServiceBus:ConnectionString")] string msg)
- {
- string activityId = string.Empty;
- try
- {
- var jsonMsg = JsonDocument.Parse(msg);
- jsonMsg.RootElement.TryGetProperty("id", out JsonElement id);
- jsonMsg.RootElement.TryGetProperty("progress", out JsonElement progress);
- jsonMsg.RootElement.TryGetProperty("code", out JsonElement code);
- var client = _azureCosmos.GetCosmosClient();
- Study study = await client.GetContainer(Constant.TEAMModelOS, "Common").ReadItemAsync<Study>(id.ToString(), new PartitionKey($"{code}"));
- study.progress = progress.ToString();
- activityId = id.ToString();
- await client.GetContainer(Constant.TEAMModelOS, "Common").ReplaceItemAsync(study, id.ToString(), new PartitionKey($"{code}"));
- }
- catch (CosmosException e)
- {
- await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-ServiceBus,Study()-CosmosDB异常{e.StackTrace}{e.Message}\n{e.Status}\n{msg}", GroupNames.成都开发測試群組);
- }
- catch (Exception ex)
- {
- await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-ServiceBus,Study()\n{ex.Message}\n{ex.StackTrace}\n{msg}", GroupNames.醍摩豆服務運維群組);
- }
- }
- [Function("ExamLite")]
- public async Task ExamLiteFunc([ServiceBusTrigger("%Azure:ServiceBus:ActiveTask%", "examlite", Connection = "Azure:ServiceBus:ConnectionString")] string msg)
- {
- try
- {
- var jsonMsg = JsonDocument.Parse(msg);
- jsonMsg.RootElement.TryGetProperty("id", out JsonElement id);
- jsonMsg.RootElement.TryGetProperty("progress", out JsonElement progress);
- jsonMsg.RootElement.TryGetProperty("code", out JsonElement code);
- var client = _azureCosmos.GetCosmosClient();
- ExamLite lite = await client.GetContainer(Constant.TEAMModelOS, "Common").ReadItemAsync<ExamLite>(id.ToString(), new PartitionKey($"{code}"));
- lite.progress = progress.ToString();
- await client.GetContainer(Constant.TEAMModelOS, "Common").ReplaceItemAsync(lite, id.ToString(), new PartitionKey($"{code}"));
- }
- catch (CosmosException e)
- {
- await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-ServiceBus,ExamLite()-CosmosDB异常{e.StackTrace}{e.Message}\n{e.Status}\n{msg}", GroupNames.成都开发測試群組);
- }
- catch (Exception ex)
- {
- await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-ServiceBus,ExamLite()\n{ex.Message}\n{ex.StackTrace}\n{msg}", GroupNames.醍摩豆服務運維群組);
- }
- }
- /// <summary>
- /// 根据容器的根目录刷新redis并获取redis的最新使用情况
- /// </summary>
- /// <param name="msg"></param>
- /// <returns></returns>
- [Function("BlobRoot")]
- public async Task BlobRootFunc([ServiceBusTrigger("%Azure:ServiceBus:ActiveTask%", "blobroot", Connection = "Azure:ServiceBus:ConnectionString")] string msg)
- {
- try
- {
- 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)
- {
- //await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-ServiceBus,Blob() 容器:触发变更,{jsonMsg.ToJsonString()}",
- // GroupNames.成都开发測試群組);
- 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)
- //{
- //}
- }
- 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);
- }
- //await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-ServiceBus,Blob() 容器:{name}使用:{u},文件分类:{list.ToJsonString()}",
- // GroupNames.成都开发測試群組);
- }
- }
- catch (Exception ex)
- {
- await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-ServiceBus,Blob()\n{ex.Message}\n{ex.StackTrace}\n{msg}", GroupNames.醍摩豆服務運維群組);
- }
- }
- private async Task<(bool condition, bool exist)> CheckLockKey(string lockKey, long nowTime)
- {
- //Redis的最新时间
- long newestTime = 0;
- RedisValue value = await _azureRedis.GetRedisClient(8).StringGetAsync(lockKey);
- if (value != default && !value.IsNullOrEmpty)
- {
- JsonElement record = value.ToString().ToObject<JsonElement>();
- if (record.TryGetInt64(out newestTime))
- {
- }
- }
- //说明key已经不存在
- if (newestTime == 0)
- {
- return (false, true);
- }
- //说明key存在
- else
- {
- //说明Redis记录了最新的时间戳
- if (nowTime != newestTime)
- {
- return (true, false);
- }
- //时间相同,没有被再次记录最新的时间戳
- else
- {
- await _azureRedis.GetRedisClient(8).KeyDeleteAsync(lockKey);
- return (false, true);
- }
- }
- }
- private async Task RefreshBlob(string name, string u)
- {
- long statr = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
- var client = _azureStorage.GetBlobContainerClient(name);
- var size = await client.GetBlobsSize(u);
- await _azureRedis.GetRedisClient(8).SortedSetRemoveAsync($"Blob:Catalog:{name}", u);
- await _azureRedis.GetRedisClient(8).SortedSetIncrementAsync($"Blob:Catalog:{name}", u, size.HasValue ? size.Value : 0);
- var scores = await _azureRedis.GetRedisClient(8).SortedSetRangeByRankWithScoresAsync($"Blob:Catalog:{name}");
- double blobsize = 0;
- if (scores != default && scores != null)
- {
- foreach (var score in scores)
- {
- blobsize = blobsize + score.Score;
- }
- }
- 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 = 10;
- if (dis > timeout)
- {
- await _dingDing.SendBotMsg($"ServiceBus,RefreshBlob:空间计算已经超过{timeout}秒\n容器名:{name}\n文件夹:{u}\n计算时长:{dis}", GroupNames.醍摩豆服務運維群組);
- }
- }
- /// <summary>
- /// 完善课程变更,StuListChange, originCode是学校编码 则表示名单是学校自定义名单,如果是tmdid则表示醍摩豆的私有名单,scope=school,private。
- /// </summary>
- /// <data msg>
- /// CourseChange
- ///// </data>
- /// <param name="msg"></param>
- /// <returns></returns>
- [Function("TeacherTrainChange")]
- public async Task TeacherTrainChangeFunc([ServiceBusTrigger("%Azure:ServiceBus:ActiveTask%", "teacher-train-change", Connection = "Azure:ServiceBus:ConnectionString")] string msg)
- {
- try
- {
- // await _dingDing.SendBotMsg($"teacher-train-change\n{msg}",GroupNames.成都开发測試群組);
- TeacherTrainChange change = msg.ToObject<TeacherTrainChange>();
- if (change.update == null || change.update.Count <= 0 || change.tmdids.IsEmpty())
- {
- return;
- }
- var client = _azureCosmos.GetCosmosClient();
- string insql = $"where c.id in ({string.Join(",", change.tmdids.Select(x => $"'{x}'"))})";
- string selsql = $"select value(c) from c {insql} ";
- List<TeacherTrain> teacherTrains = new List<TeacherTrain>();
- await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Teacher").GetItemQueryIterator<TeacherTrain>(queryText: selsql,
- requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"TeacherTrain-{change.school}") }))
- {
- teacherTrains.Add(item);
- }
- if (change.statistics != 1)
- {
- List<Task<ItemResponse<TeacherTrain>>> task = new List<Task<ItemResponse<TeacherTrain>>>();
- teacherTrains.ForEach(x =>
- {
- x.update.UnionWith(change.update);
- task.Add(client.GetContainer(Constant.TEAMModelOS, "Teacher").ReplaceItemAsync<TeacherTrain>(x, x.id, new PartitionKey($"TeacherTrain-{change.school}")));
- });
- await task.TaskPage(5);
- var unchange = change.tmdids.Except(teacherTrains.Select(x => x.id));
- if (unchange != null)
- {
- task.Clear();
- unchange.ToList().ForEach(x =>
- {
- TeacherTrain teacherTrain = new TeacherTrain
- {
- pk = "TeacherTrain",
- id = x,
- code = $"TeacherTrain-{change.school}",
- tmdid = x,
- school = change.school,
- update = new HashSet<string> { StatisticsService.TeacherAbility,
- StatisticsService.TeacherClass, StatisticsService.OfflineRecord }
- };
- teacherTrain.update.UnionWith(change.update);
- task.Add(client.GetContainer(Constant.TEAMModelOS, "Teacher").UpsertItemAsync<TeacherTrain>(teacherTrain, new PartitionKey($"TeacherTrain-{change.school}")));
- });
- await task.TaskPage(1);
- }
- }
- else
- {
- Area area = null;
- string sql = $"select value(c) from c where c.standard='{change.standard}'";
- await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Normal").GetItemQueryIterator<Area>(queryText: sql,
- requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Base-Area") }))
- {
- area = item;
- }
- AreaSetting setting = null;
- if (area != null)
- {
- try
- {
- //优先找校级
- setting = await client.GetContainer(Constant.TEAMModelOS, "School").ReadItemAsync<AreaSetting>(change.school, new PartitionKey("AreaSetting"));
- }
- catch (CosmosException)
- {
- try
- {
- setting = await client.GetContainer(Constant.TEAMModelOS, "Normal").ReadItemAsync<AreaSetting>(area.id, new PartitionKey("AreaSetting"));
- }
- catch (CosmosException)
- {
- setting = null;
- }
- }
- }
- if (setting == null)
- {
- setting = new AreaSetting
- {
- allTime = 50,
- classTime = 5,
- submitTime = 15,
- onlineTime = 20,
- offlineTime = 10,
- lessonMinutes = 45,
- };
- }
- List<Task<TeacherTrain>> task = new List<Task<TeacherTrain>>();
- teacherTrains.ForEach(x =>
- {
- x.update.UnionWith(change.update);
- task.Add(StatisticsService.StatisticsTeacher(x, setting, area, client, null));
- });
- await task.TaskPage(1);
- var unchange = change.tmdids.Except(teacherTrains.Select(x => x.id));
- if (unchange != null)
- {
- task.Clear();
- unchange.ToList().ForEach(x =>
- {
- task.Add(StatisticsService.StatisticsTeacher(new TeacherTrain
- {
- pk = "TeacherTrain",
- id = x,
- code = $"TeacherTrain-{change.school}",
- tmdid = x,
- school = change.school,
- update = new HashSet<string> { StatisticsService.TeacherAbility,
- StatisticsService.TeacherClass, StatisticsService.OfflineRecord }
- }, setting, area, client, null));
- });
- await task.TaskPage(1);
- }
- }
- }
- catch (CosmosException ex)
- {
- await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-研修数据变更,重新统计-TeacherTrainChange\n{msg}\n{ex.Message}\n{ex.StackTrace}CosmosException{ex.Status}", GroupNames.成都开发測試群組);
- }
- catch (Exception ex)
- {
- await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-研修数据变更,重新统计-TeacherTrainChange\n{msg}\n{ex.Message}\n{ex.StackTrace}", GroupNames.成都开发測試群組);
- }
- }
- /// <summary>
- /// 完善课程变更,StuListChange, originCode是学校编码 则表示名单是学校自定义名单,如果是tmdid则表示醍摩豆的私有名单,scope=school,private。
- /// </summary>
- /// <data msg>
- /// CourseChange
- ///// </data>
- /// <param name="msg"></param>
- /// <returns></returns>
- [Function("GroupChange")]
- public async Task GroupChangeFunc([ServiceBusTrigger("%Azure:ServiceBus:ActiveTask%", "group-change", Connection = "Azure:ServiceBus:ConnectionString")] string msg)
- {
- var client = _azureCosmos.GetCosmosClient();
- try
- {
- //await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-名单成员变更-GroupChange\n{msg}", GroupNames.成都开发測試群組);
- var jsonMsg = JsonDocument.Parse(msg);
- GroupChange groupChange = msg.ToObject<GroupChange>();
- //名单变动修改学生课程关联信息
- //await StuListService.FixStuCourse(client, stuListChange);
- //Vote投票 Survey问卷 Exam评测 Learn学习活动 Homework作业活动
- //名单变动修改学生问卷关联信息
- await ActivityService.FixActivity(client, _dingDing, groupChange, "Survey");
- //名单变动修改学生投票关联信息
- await ActivityService.FixActivity(client, _dingDing, groupChange, "Vote");
- //名单变动修改学生评测关联信息
- await ActivityService.FixActivity(client, _dingDing, groupChange, "Exam");
- //TODO学习活动
- //await FixActivity(client, stuListChange, "Learn");
- if (groupChange.type == null || !groupChange.type.Equals("research") || !groupChange.type.Equals("yxtrain") || !groupChange.type.Equals("activity"))
- {
- //课程名单变动修改学生课程关联信息
- await ActivityService.FixStuCourse(client, _dingDing, groupChange);
- //名单变动修改学生研修关联信息
- await ActivityService.FixActivity(client, _dingDing, groupChange, "Study");
- //名单变动修改学生简易评测关联信息
- await ActivityService.FixActivity(client, _dingDing, groupChange, "ExamLite");
- //名单变动修改学生作业活动信息
- await ActivityService.FixActivity(client, _dingDing, groupChange, "Homework");
- }
- }
- catch (Exception ex)
- {
- await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-GroupChange-GroupChange\n{ex.Message}\n{ex.StackTrace}\n{msg}", GroupNames.成都开发測試群組);
- }
- }
- [Function("ItemCond")]
- public async Task ItemCondFunc([ServiceBusTrigger("%Azure:ServiceBus:ItemCondQueue%", Connection = "Azure:ServiceBus:ConnectionString")] string msg)
- {
- try
- {
- var client = _azureCosmos.GetCosmosClient();
- var jsonMsg = JsonDocument.Parse(msg);
- List<ItemCondDto> itemCondDtos = msg.ToObject<List<ItemCondDto>>();
- foreach (var itemCondDto in itemCondDtos)
- {
- if (itemCondDto.scope.Equals("school"))
- {
- ItemCond itemCond = null;
- List<ItemInfo> items = new List<ItemInfo>();
- var queryslt = $"SELECT c.gradeIds,c.subjectId,c.periodId,c.type,c.level,c.field ,c.scope FROM c where c.periodId='{itemCondDto.filed}' and c.pid= null ";
- await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryIterator<ItemInfo>(queryText: queryslt, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Item-{itemCondDto.key}") }))
- {
- items.Add(item);
- }
- itemCond = new ItemCond()
- {
- id = $"{itemCondDto.filed}",
- code = $"ItemCond-{itemCondDto.key}",
- pk = "ItemCond",
- ttl = -1,
- count = items.Count,
- grades = new List<GradeCount>(),
- subjects = new List<SubjectItemCount>()
- };
- items.ForEach(z =>
- {
- if (!string.IsNullOrEmpty(z.type))
- {
- ItemService.CountItemCond(z, null, itemCond);
- }
- });
- await _azureRedis.GetRedisClient(8).HashSetAsync($"ItemCond:{itemCondDto.key}", $"{itemCondDto.filed}", itemCond.ToJsonString());
- }
- else
- {
- ItemCond itemCond = null;
- List<ItemInfo> items = new List<ItemInfo>();
- var queryslt = $"SELECT c.gradeIds,c.subjectId,c.periodId,c.type,c.level,c.field ,c.scope FROM c where c.pid= null ";
- await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Teacher").GetItemQueryIterator<ItemInfo>(queryText: queryslt, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Item-{itemCondDto.filed}") }))
- {
- items.Add(item);
- }
- itemCond = new ItemCond() { id = $"{itemCondDto.filed}", code = $"ItemCond", pk = "ItemCond", ttl = -1, count = items.Count };
- items.ForEach(z =>
- {
- if (!string.IsNullOrEmpty(z.type))
- {
- ItemService.CountItemCond(z, null, itemCond);
- }
- });
- await _azureRedis.GetRedisClient(8).HashSetAsync($"ItemCond:ItemCond", $"{itemCondDto.filed}", itemCond.ToJsonString());
- }
- }
- }
- catch (CosmosException ex)
- {
- await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-ServiceBus,ItemCond()\n{ex.Message}\n{ex.StackTrace}\n{msg}", GroupNames.醍摩豆服務運維群組);
- }
- catch (Exception ex)
- {
- await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-ServiceBus,ItemCond()\n{ex.Message}\n{ex.StackTrace}\n{msg}", GroupNames.醍摩豆服務運維群組);
- }
- }
- //更新產品一覽表
- [Function("Product")]
- public async Task ProductFunc([ServiceBusTrigger("%Azure:ServiceBus:ActiveTask%", "product", Connection = "Azure:ServiceBus:ConnectionString")] string msg, ILogger log)
- {
- try
- {
- var jsonMsg = JsonDocument.Parse(msg);
- jsonMsg.RootElement.TryGetProperty("method", out JsonElement method);
- jsonMsg.RootElement.TryGetProperty("schoolId", out JsonElement schoolId);
- jsonMsg.RootElement.TryGetProperty("prodCode", out JsonElement prodCode);
- jsonMsg.RootElement.TryGetProperty("prodId", out JsonElement prodId);
- var client = _azureCosmos.GetCosmosClient();
- string strQuery = string.Empty;
- //取得所有學校產品
- ////序號
- List<SchoolProductSumData> serialsProductSumOrg = new List<SchoolProductSumData>();
- strQuery = $"SELECT * FROM c WHERE c.dataType = 'serial'";
- await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryStreamIterator(queryText: strQuery, requestOptions: new QueryRequestOptions() { PartitionKey = new Azure.Cosmos.PartitionKey($"Product-{schoolId}") }))
- {
- using var json = await JsonDocument.ParseAsync(item.ContentStream);
- if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
- {
- foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
- {
- SchoolProductSerial serialInfo = obj.ToObject<SchoolProductSerial>();
- SchoolProductSumData serialProd = serialsProductSumOrg.Where(sp => sp.prodCode == serialInfo.prodCode).FirstOrDefault();
- if (serialProd == null)
- {
- SchoolProductSumData serialProdAdd = new SchoolProductSumData();
- serialProdAdd.prodCode = serialInfo.prodCode;
- serialProdAdd.ids.Add(serialInfo.id);
- serialProdAdd.avaliable = serialProdAdd.ids.Count;
- serialsProductSumOrg.Add(serialProdAdd);
- }
- else
- {
- if (!serialProd.ids.Contains(serialInfo.id))
- {
- serialProd.ids.Add(serialInfo.id);
- }
- serialProd.avaliable = serialProd.ids.Count;
- }
- }
- }
- }
- ////服務
- List<SchoolProductSumData> servicesProductSumOrg = new List<SchoolProductSumData>();
- long timestampToday = DateTimeOffset.UtcNow.AddSeconds(1).ToUnixTimeSeconds(); //比現實時間延遲1秒
- strQuery = $"SELECT * FROM c WHERE c.dataType = 'service' AND c.startDate <= {timestampToday} AND {timestampToday} <= c.endDate AND c.ttl < 0"; //在授權期間、ttl < 0 才取
- await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryStreamIterator(queryText: strQuery, requestOptions: new QueryRequestOptions() { PartitionKey = new Azure.Cosmos.PartitionKey($"Product-{schoolId}") }))
- {
- using var json = await JsonDocument.ParseAsync(item.ContentStream);
- if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
- {
- foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
- {
- SchoolProductService serviceInfo = obj.ToObject<SchoolProductService>();
- SchoolProductSumData serviceProd = servicesProductSumOrg.Where(sp => sp.prodCode == serviceInfo.prodCode).FirstOrDefault();
- if (serviceProd == null)
- {
- SchoolProductSumData serviceProdAdd = new SchoolProductSumData();
- serviceProdAdd.prodCode = serviceInfo.prodCode;
- serviceProdAdd.avaliable = 0;
- serviceProdAdd.ids.Add(serviceInfo.id);
- serviceProdAdd.avaliable += serviceInfo.number;
- servicesProductSumOrg.Add(serviceProdAdd);
- }
- else
- {
- if (!serviceProd.ids.Contains(serviceInfo.id))
- {
- serviceProd.ids.Add(serviceInfo.id);
- serviceProd.avaliable += serviceInfo.number;
- }
- }
- }
- }
- }
- ////服務產品特別對應項
- School school = await client.GetContainer(Constant.TEAMModelOS, "School").ReadItemAsync<School>($"{schoolId}", new PartitionKey("Base")); //學校基本資料取得
- bool updSchool = false; //是否變更學校基本資料
- int chgSchSizeCnt = 0; //變更學校空間的次數 若為0表示現時間點沒有任何空間可使用 => 回復學校空間為初始值
- int schoolDefaultSize = 1; //學校空間初始值:1
- if (!string.IsNullOrWhiteSpace(school.id))
- {
- if (servicesProductSumOrg.Count > 0)
- {
- foreach (SchoolProductSumData servicesProductSumOrgRow in servicesProductSumOrg)
- {
- //更新學校空間
- if (servicesProductSumOrgRow.prodCode.Equals("IPALJ6NY"))
- {
- school.size = (servicesProductSumOrgRow.avaliable < 1) ? 1 : servicesProductSumOrgRow.avaliable;
- await client.GetContainer(Constant.TEAMModelOS, "School").ReplaceItemAsync<School>(school, $"{schoolId}", new PartitionKey("Base"));
- updSchool = true;
- chgSchSizeCnt++;
- }
- }
- }
- if(chgSchSizeCnt.Equals(0) && !school.size.Equals(schoolDefaultSize))
- {
- school.size = schoolDefaultSize;
- //updSchool = true; //關於學校空間初始式樣未定,目前暫定:若需要Reset空間,則先維持原空間數不更動
- updSchool = false;
- }
- }
- //變更學校基本資料
- if(updSchool)
- {
- await client.GetContainer(Constant.TEAMModelOS, "School").ReplaceItemAsync<School>(school, $"{schoolId}", new PartitionKey("Base"));
- }
- ////硬體
- List<SchoolProductSumDataHard> hardsProductSumOrg = new List<SchoolProductSumDataHard>();
- strQuery = $"SELECT * FROM c WHERE c.dataType = 'hard'";
- await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryStreamIterator(queryText: strQuery, requestOptions: new QueryRequestOptions() { PartitionKey = new Azure.Cosmos.PartitionKey($"Product-{schoolId}") }))
- {
- using var json = await JsonDocument.ParseAsync(item.ContentStream);
- if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
- {
- foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
- {
- SchoolProductHard hardInfo = obj.ToObject<SchoolProductHard>();
- SchoolProductSumData hardProd = hardsProductSumOrg.Where(sp => sp.prodCode == hardInfo.prodCode).FirstOrDefault();
- if (hardProd == null)
- {
- SchoolProductSumDataHard hardProdAdd = new SchoolProductSumDataHard();
- hardProdAdd.prodCode = hardInfo.prodCode;
- hardProdAdd.model = hardInfo.model;
- hardProdAdd.ids.Add(hardInfo.id);
- hardProdAdd.avaliable = hardProdAdd.ids.Count;
- hardsProductSumOrg.Add(hardProdAdd);
- }
- else
- {
- if (!hardProd.ids.Contains(hardInfo.id))
- {
- hardProd.ids.Add(hardInfo.id);
- }
- hardProd.avaliable = hardProd.ids.Count;
- }
- }
- }
- }
- //更新學校產品一覽表
- SchoolProductSum prodSum = await client.GetContainer(Constant.TEAMModelOS, "School").ReadItemAsync<SchoolProductSum>(schoolId.ToString(), new PartitionKey($"ProductSum"));
- prodSum.serial = serialsProductSumOrg;
- prodSum.service = servicesProductSumOrg;
- prodSum.hard = hardsProductSumOrg;
- await client.GetContainer(Constant.TEAMModelOS, "School").ReplaceItemAsync<SchoolProductSum>(prodSum, prodSum.id, new PartitionKey($"{prodSum.code}"));
- }
- catch (CosmosException ex)
- {
- await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-ServiceBus,Product()\n{ex.Message}\n{ex.StackTrace}\n{msg}", GroupNames.醍摩豆服務運維群組);
- }
- catch (Exception ex)
- {
- await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-ServiceBus,Product()\n{ex.Message}\n{ex.StackTrace}\n{msg}", GroupNames.醍摩豆服務運維群組);
- }
- }
- /// <summary>
- /// 批量复制文件
- /// </summary>
- /// <param name="msg"></param>
- /// <returns></returns>
- [Function("CopyStandardFile")]
- public async Task BatchCopyBlobFunc([ServiceBusTrigger("%Azure:ServiceBus:ActiveTask%", "copy-standard-file", Connection = "Azure:ServiceBus:ConnectionString")] string msg)
- {
- try
- {
- //await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-Blob复制文件-CopyStandardFile\n{msg}", GroupNames.成都开发測試群組);
- var jsonMsg = JsonDocument.Parse(msg);
- BatchCopyFile bIBatchCopyFile = msg.ToObject<BatchCopyFile>();
- //批量复制文件
- var result = await BatchCopyFileService.CopyFile(_dingDing, _azureStorage, bIBatchCopyFile);
- if (result == 200)
- {
- //发送消息实体
- Notification notification = new Notification
- {
- hubName = "hita",
- type = "msg",
- from = $"BI:{_option.Location}:private",
- to = bIBatchCopyFile.tmdIds,
- label = $"{bIBatchCopyFile.codeKey}_finish",
- body = new { location = _option.Location, biz = $"{bIBatchCopyFile.codeKey}", tmdid = $"{bIBatchCopyFile.tmdid}", tmdname = $"{bIBatchCopyFile.tmdName}", status = 1, time = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds() }.ToJsonString(),
- expires = DateTimeOffset.UtcNow.AddDays(7).ToUnixTimeSeconds()
- };
- 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 = _option.Location;
- await _notificationService.SendNotification(clientID, clientSecret, location, url, notification); //站内发送消息
- }
- }
- catch (Exception ex)
- {
- await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-Blob复制文件-CopyStandardFile\n{ex.Message}\n{ex.StackTrace}\n{msg}", GroupNames.成都开发測試群組);
- }
- }
- /// <summary>
- /// 更新开课数据事件
- /// </summary>
- /// <param name="msg"></param>
- /// <returns></returns>
- [Function("LessonRecordEvent")]
- public async Task LessonRecordFunc([ServiceBusTrigger("%Azure:ServiceBus:ActiveTask%", "lesson-record-event", Connection = "Azure:ServiceBus:ConnectionString")] string msg)
- {
- JsonElement data = msg.ToObject<JsonElement>();
- string scope = "";
- string tmdid = "";
- string lessonId;
- string school;
- string tbname;
- string code;
- string blobname;
- List<LessonUpdate> updates = new List<LessonUpdate>();
- //更新课堂记录
- if (data.TryGetProperty("lesson_id", out JsonElement _lessonId) && !string.IsNullOrEmpty($"{_lessonId}"))
- {
- if (!data.TryGetProperty("tmdid", out JsonElement _tmdid)) return;
- if (!data.TryGetProperty("scope", out JsonElement _scope)) return;
- if (!data.TryGetProperty("grant_types", out JsonElement _grant_types)) return;
- data.TryGetProperty("school", out JsonElement _school);
- school = $"{_school}";
- scope = $"{_scope}";
- tmdid = $"{_tmdid}";
- lessonId = $"{_lessonId}";
- updates = _grant_types.ToObject<List<LessonUpdate>>();
- }//创建课堂记录
- else if (data.TryGetProperty("id", out JsonElement _id) && !string.IsNullOrEmpty($"{_id}")
- && data.TryGetProperty("tmdid", out JsonElement _tmdid) && !string.IsNullOrEmpty($"{_tmdid}")
- && data.TryGetProperty("scope", out JsonElement _scope) && !string.IsNullOrEmpty($"{_scope}"))
- {
- data.TryGetProperty("school", out JsonElement _school);
- school = $"{_school}";
- scope = $"{_scope}";
- tmdid = $"{_tmdid}";
- lessonId = $"{_id}";
- updates.Add(new LessonUpdate { grant_type = "create" });
- }//删除课堂记录
- else if (data.TryGetProperty("delete_id", out JsonElement _delete_id) && !string.IsNullOrEmpty($"{_delete_id}")
- && data.TryGetProperty("tmdid", out JsonElement _dtmdid) && !string.IsNullOrEmpty($"{_dtmdid}")
- && data.TryGetProperty("scope", out JsonElement _dscope) && !string.IsNullOrEmpty($"{_dscope}")
- && data.TryGetProperty("opt", out JsonElement _opt) && !string.IsNullOrEmpty($"{_opt}"))
- {
- data.TryGetProperty("school", out JsonElement _dschool);
- school = $"{_dschool}";
- if ($"{_opt}".Equals("delete"))
- {
- scope = $"{_dscope}";
- tmdid = $"{_dtmdid}";
- lessonId = $"{_delete_id}";
- updates.Add(new LessonUpdate { grant_type = "delete" });
- }
- else { return; }
- }
- else
- {
- return;
- }
- var client = _azureCosmos.GetCosmosClient();
- if ($"{scope}".Equals("school") && !string.IsNullOrEmpty($"{school}"))
- {
- blobname = $"{school}";
- code = $"LessonRecord-{school}";
- tbname = "School";
- }
- else if ($"{scope}".Equals("private"))
- {
- blobname = $"{tmdid}";
- code = $"LessonRecord-{tmdid}";
- tbname = "Teacher";
- }
- else
- {
- return;
- }
- LessonDis lessonDis = new LessonDis();
- List<LessonUpdate> msgs = new List<LessonUpdate>();
- try
- {
- LessonRecord oldlessonRecord = null;
- LessonRecord lessonRecord = null;
- Azure.Response response = await client.GetContainer(Constant.TEAMModelOS, tbname).ReadItemStreamAsync(lessonId, new PartitionKey(code));
- if (response.Status == 200)
- {
- var doc = JsonDocument.Parse(response.ContentStream);
- lessonRecord = doc.RootElement.ToObject<LessonRecord>();
- oldlessonRecord = doc.RootElement.ToObject<LessonRecord>();
- }
- else
- {
- lessonRecord = null;
- }
- bool isReplace = true;
- if (updates.IsNotEmpty())
- {
- foreach (LessonUpdate update in updates)
- {
- switch (update.grant_type)
- {
- //更新课堂时长
- case "up-duration":
- var duration = double.Parse($"{update.data}");
- lessonRecord.duration = duration;
- msgs.Add(update);
- 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)) {
- var durationFile = double.Parse($"{_duration}");
- if (duration < durationFile) {
- lessonRecord.duration = durationFile;
- }
- }
- 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.成都开发測試群組);
- }
- isReplace = true;
- break;
- //更新T分
- case "up-tScore":
- var tScore = int.Parse($"{update.data}");
- lessonRecord.tScore = tScore;
- msgs.Add(update);
- break;
- //更新课P分
- case "up-pScore":
- var pScore = int.Parse($"{update.data}");
- lessonRecord.pScore = pScore;
- msgs.Add(update);
- break;
- //更新 学生人数
- case "up-mCount":
- var mCount = int.Parse($"{update.data}");
- lessonRecord.mCount = mCount;
- msgs.Add(update);
- break;
- //更新 议课次数
- case "up-techCount":
- var techCount = int.Parse($"{update.data}");
- lessonRecord.mCount = techCount;
- msgs.Add(update);
- break;
- //更新 基础统计信息
- case "up-base":
- //如果有更新 则去读取/{_lessonId}/IES/base.json
- try
- {
- BlobDownloadResult baseblobDownload = await _azureStorage.GetBlobContainerClient(blobname).GetBlobClient($"/{_lessonId}/IES/base.json").DownloadContentAsync();
- LessonBase lessonBase = baseblobDownload.Content.ToObjectFromJson<LessonBase>();
- if (lessonBase != null)
- {
- lessonRecord.attendCount = lessonRecord.attendCount;
- lessonRecord.clientCount = lessonRecord.clientCount;
- lessonRecord.attendRate = lessonRecord.attendRate;
- lessonRecord.groupCount = lessonRecord.groupCount;
- lessonRecord.collateTaskCount = lessonRecord.collateTaskCount;
- lessonRecord.collateCount = lessonRecord.collateCount;
- lessonRecord.pushCount = lessonRecord.pushCount;
- lessonRecord.totalPoint = lessonRecord.totalPoint;
- lessonRecord.examQuizCount = lessonRecord.examQuizCount;
- lessonRecord.interactionCount = lessonRecord.interactionCount;
- lessonRecord.examPointRate = lessonRecord.examPointRate;
- lessonRecord.clientInteractionCount = lessonRecord.clientInteractionCount;
- lessonRecord.clientInteractionAverge = lessonRecord.clientInteractionAverge;
- }
- msgs.Add(update);
- }
- catch (RequestFailedException ex) when (ex.Status == 404)
- {
- msgs.Add(new LessonUpdate { grant_type = "up-base-404" });
- }
- catch (Exception ex)
- {
- await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}课程读取base.json,{_lessonId}\n{ex.Message}\n{ex.StackTrace}", GroupNames.成都开发測試群組);
- }
- break;
- //更新 时间线
- case "up-TimeLine":
- //BlobDownloadResult TimeLineblobDownload = await _azureStorage.GetBlobContainerClient(blobname).GetBlobClient($"/{_lessonId}/IES/TimeLine.json").DownloadContentAsync();
- //var timeline = TimeLineblobDownload.Content.ToObjectFromJson<List<LessonTimeLine>>();
- msgs.Add(update);
- break;
- //更新 课堂总览信息
- case "up-ActivityInfo":
- //BlobDownloadResult ActivityInfoblobDownload = await _azureStorage.GetBlobContainerClient(blobname).GetBlobClient($"/{_lessonId}/IES/ActivityInfo.json").DownloadContentAsync();
- //var activityInfos = ActivityInfoblobDownload.Content.ToObjectFromJson<List<LessonActivityInfo>>();
- msgs.Add(update);
- break;
- ///更新基础信息,名称科目,年级,分类等。
- case "up-baseinfo":
- if (updates.Count > 1)
- {
- isReplace = true;
- }
- else
- {
- isReplace = false;
- }
- msgs.Add(update);
- break;
- case "delete":
- try
- {
- await client.GetContainer(Constant.TEAMModelOS, tbname).DeleteItemAsync<LessonRecord>(lessonId, new PartitionKey(code));
- msgs.Add(update);
- }
- catch (CosmosException)
- {
- msgs.Add(update);
- }
- lessonRecord = null;
- isReplace = false;
- break;
- case "create":
- oldlessonRecord = null;
- //处理课堂选用的课程信息
- if (!string.IsNullOrEmpty(lessonRecord.courseId))
- {
- Course course = null;
- try
- {
- var cresponse = await client.GetContainer(Constant.TEAMModelOS, "School").ReadItemStreamAsync(lessonRecord.courseId, new PartitionKey($"Course-{lessonRecord.school}"));
- if (cresponse.Status == 200)
- {
- using var cJson = await JsonDocument.ParseAsync(cresponse.ContentStream);
- course = cJson.ToObject<Course>();
- }
- else
- {
- var sresponse = await client.GetContainer(Constant.TEAMModelOS, "Teacher").ReadItemStreamAsync(lessonRecord.courseId, new PartitionKey($"Course-{lessonRecord.tmdid}"));
- if (sresponse.Status == 200)
- {
- using var cJson = await JsonDocument.ParseAsync(sresponse.ContentStream);
- course = cJson.ToObject<Course>();
- }
- else
- {
- course = null;
- }
- }
- }
- catch (Exception ex) {
- await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-查询课程-CosmosDB异常{ex.Message}\n{ex.StackTrace}", GroupNames.成都开发測試群組);
- }
- /*catch (CosmosException ex) when (ex.Status != 404)
- {
- try
- {
- course = await client.GetContainer(Constant.TEAMModelOS, "Teacher").ReadItemAsync<Course>(lessonRecord.courseId, new PartitionKey($"Course-{lessonRecord.tmdid}"));
- }
- catch (CosmosException e) when (e.Status != 404)
- {
- course = null;
- }
- }*/
- if (course != null)
- {
- lessonRecord.periodId = course.period?.id;
- lessonRecord.subjectId = course.subject?.id;
- }
- }
- //处理课堂选用的名单
- if (lessonRecord.groupIds.IsNotEmpty())
- {
- 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))
- {
- try {
- School schoolObj = await client.GetContainer(Constant.TEAMModelOS, "School").ReadItemAsync<School>(lessonRecord.school, new PartitionKey("Base"));
- //年级算法
- var period = schoolObj.period.Find(x => x.id.Equals(lessonRecord.periodId));
- int? Count = period?.grades?.Count;
- if (Count.HasValue)
- {
- int Month = DateTimeOffset.UtcNow.Month;
- int Year = DateTimeOffset.UtcNow.Year;
- foreach (int year in groupLists.Select(x => x.year))
- {
- int grade;
- if (Month >= 1 && Month <= 6)
- {
- grade = (Year - year + 1) / Count.Value;
- }
- else
- {
- grade = (Year - year) / Count.Value;
- }
- grades.Add($"{grade}");
- }
- }
- } catch (CosmosException ex) when (ex.Status == 404) {
-
- }
- }
- lessonRecord.grade.AddRange(grades);
- }
- msgs.Add(update);
- break;
-
-
- default:
- break;
- }
- }
- //如果被删除则不能再被更新
- if (isReplace) {
- await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, tbname).ReplaceItemAsync<LessonRecord>(lessonRecord, lessonId, new PartitionKey(code));
- }
- //计算课堂更新前后的差值
- lessonDis = LessonService.DisLessonCount(oldlessonRecord, lessonRecord, lessonDis);
- await LessonService.FixLessonCount(client, _dingDing, lessonRecord, oldlessonRecord, lessonDis);
- }
- }
- catch (CosmosException e)
- {
- await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-更新课堂记录出错-CosmosDB异常{e.Message}\n{e.StackTrace}", GroupNames.成都开发測試群組);
- }
- catch (Exception ex)
- {
- await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-更新课堂记录出错\n{ex.Message}\n{ex.StackTrace}\n{data}\n{code}\n{updates}\n", GroupNames.成都开发測試群組);
- }
- }
- /// <summary>
- /// 完善课程变更
- /// </summary>
- /// <data msg>
- /// CourseChange
- ///// </data>
- /// <param name="msg"></param>
- /// <returns></returns>
- [Function("Course")]
- public async Task CourseFunc([ServiceBusTrigger("%Azure:ServiceBus:ActiveTask%", "course", Connection = "Azure:ServiceBus:ConnectionString")] string msg)
- {
- var client = _azureCosmos.GetCosmosClient();
- try
- {
- //await _dingDing.SendBotMsg($"ServiceBus,CourseChange:{msg}", GroupNames.醍摩豆服務運維群組);
- var jsonMsg = JsonDocument.Parse(msg);
- CourseChange courseChange = msg.ToObject<CourseChange>();
- if (courseChange == null)
- {
- return;
- }
- foreach (var cls in courseChange.addClass)
- {
- (List<RMember> tchList, List<RGroupList> classLists) = await GroupListService.GetStutmdidListids(_coreAPIHttpService, client, _dingDing, new List<string> { cls }, courseChange.school);
- var addStudentsCls = tchList.FindAll(x => x.type == 2);
- var addTmdidsCls = tchList.FindAll(x => x.type == 1);
- foreach (var stu in addStudentsCls)
- {
- try
- {
- ItemResponse<StuCourse> stuCourse = await client.GetContainer(Constant.TEAMModelOS, "Student").ReadItemAsync<StuCourse>(courseChange.id, new PartitionKey($"StuCourse-{courseChange.school}-{stu.id}"));
- if (!stuCourse.Value.classId.Contains(cls))
- {
- stuCourse.Value.classId.Add(cls);
- }
- await client.GetContainer(Constant.TEAMModelOS, "Student").ReplaceItemAsync<StuCourse>(stuCourse, courseChange.id, new PartitionKey($"StuCourse-{courseChange.school}-{stu.id}"));
- }
- catch (CosmosException ex)
- {
- if (ex.Response.Status == 404)
- {
- var course = new StuCourse
- {
- id = courseChange.id,
- scode = courseChange.code,
- name = courseChange.name,
- code = $"StuCourse-{courseChange.school}-{stu.id}",
- scope = courseChange.scope,
- school = courseChange.school,
- creatorId = courseChange.creatorId,
- classId = new List<string> { cls },
- pk = "StuCourse",
- createTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
- };
- await client.GetContainer(Constant.TEAMModelOS, "Student").CreateItemAsync(course, new PartitionKey(course.code));
- }
- else
- {
- await _dingDing.SendBotMsg($"OS,{ Environment.GetEnvironmentVariable("Option:Location")},CourseServiceBus -CosmosDB异常\n{ex.Message}{ex.StackTrace}", GroupNames.成都开发測試群組);
- }
- }
- }
- foreach (var tmd in addTmdidsCls)
- {
- try
- {
- ItemResponse<StuCourse> stuCourse = await client.GetContainer(Constant.TEAMModelOS, "Student").ReadItemAsync<StuCourse>(courseChange.id, new PartitionKey($"StuCourse-{tmd.id}"));
- if (!stuCourse.Value.classId.Contains(cls))
- {
- stuCourse.Value.classId.Add(cls);
- }
- await client.GetContainer(Constant.TEAMModelOS, "Student").ReplaceItemAsync<StuCourse>(stuCourse, courseChange.id, new PartitionKey($"StuCourse-{tmd.id}"));
- }
- catch (CosmosException ex)
- {
- if (ex.Response.Status == 404)
- {
- var course = new StuCourse
- {
- id = courseChange.id,
- scode = courseChange.code,
- name = courseChange.name,
- code = $"StuCourse-{tmd.id}",
- scope = courseChange.scope,
- school = courseChange.school,
- creatorId = courseChange.creatorId,
- classId = new List<string> { cls },
- pk = "StuCourse",
- createTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
- };
- await client.GetContainer(Constant.TEAMModelOS, "Student").CreateItemAsync(course, new PartitionKey(course.code));
- }
- else
- {
- await _dingDing.SendBotMsg($"OS,{ Environment.GetEnvironmentVariable("Option:Location")},CourseServiceBus -CosmosDB异常\n{ex.Message}{ex.StackTrace}", GroupNames.成都开发測試群組);
- }
- }
- }
- }
- foreach (var list in courseChange.addList)
- {
- (List<RMember> tchList, List<RGroupList> classLists) = await GroupListService.GetStutmdidListids(_coreAPIHttpService, client, _dingDing, new List<string> { list }, courseChange.school);
- var addStudentsCls = tchList.FindAll(x => x.type == 2);
- var addTmdidsCls = tchList.FindAll(x => x.type == 1);
- foreach (var stu in addStudentsCls)
- {
- try
- {
- ItemResponse<StuCourse> stuCourse = await client.GetContainer(Constant.TEAMModelOS, "Student").ReadItemAsync<StuCourse>(courseChange.id, new PartitionKey($"StuCourse-{stu.code}-{stu.id}"));
- if (!stuCourse.Value.stulist.Contains(list))
- {
- stuCourse.Value.stulist.Add(list);
- await client.GetContainer(Constant.TEAMModelOS, "Student").ReplaceItemAsync<StuCourse>(stuCourse, courseChange.id, new PartitionKey($"StuCourse-{stu.code}-{stu.id}"));
- }
- }
- catch (CosmosException ex)
- {
- if (ex.Response.Status == 404)
- {
- var course = new StuCourse
- {
- id = courseChange.id,
- scode = courseChange.code,
- name = courseChange.name,
- code = $"StuCourse-{courseChange.school}-{stu.id}",
- scope = courseChange.scope,
- school = courseChange.school,
- creatorId = courseChange.creatorId,
- stulist = new List<string> { list },
- pk = "StuCourse",
- createTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
- };
- await client.GetContainer(Constant.TEAMModelOS, "Student").CreateItemAsync(course, new PartitionKey(course.code));
- }
- else
- {
- await _dingDing.SendBotMsg($"OS,{ Environment.GetEnvironmentVariable("Option:Location")},CourseServiceBus -CosmosDB异常\n{ex.Message}{ex.StackTrace}", GroupNames.成都开发測試群組);
- }
- }
- }
- foreach (var tmd in addTmdidsCls)
- {
- try
- {
- ItemResponse<StuCourse> stuCourse = await client.GetContainer(Constant.TEAMModelOS, "Student").ReadItemAsync<StuCourse>(courseChange.id, new PartitionKey($"StuCourse-{tmd.id}"));
- if (!stuCourse.Value.stulist.Contains(list))
- {
- stuCourse.Value.stulist.Add(list);
- await client.GetContainer(Constant.TEAMModelOS, "Student").ReplaceItemAsync<StuCourse>(stuCourse, courseChange.id, new PartitionKey($"StuCourse-{tmd.id}"));
- }
- }
- catch (CosmosException ex)
- {
- if (ex.Response.Status == 404)
- {
- var course = new StuCourse
- {
- id = courseChange.id,
- scode = courseChange.code,
- name = courseChange.name,
- code = $"StuCourse-{tmd.id}",
- scope = courseChange.scope,
- school = courseChange.school,
- creatorId = courseChange.creatorId,
- stulist = new List<string> { list },
- pk = "StuCourse",
- createTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
- };
- await client.GetContainer(Constant.TEAMModelOS, "Student").CreateItemAsync(course, new PartitionKey(course.code));
- }
- else
- {
- await _dingDing.SendBotMsg($"OS,{ Environment.GetEnvironmentVariable("Option:Location")},CourseServiceBus -CosmosDB异常\n{ex.Message}{ex.StackTrace}", GroupNames.成都开发測試群組);
- }
- }
- }
- }
- foreach (var delCls in courseChange.delClass)
- {
- (List<RMember> tchList, List<RGroupList> classLists) = await GroupListService.GetStutmdidListids(_coreAPIHttpService, client, _dingDing, new List<string> { delCls }, courseChange.school);
- var delStudentsCls = tchList.FindAll(x => x.type == 2);
- var delTmdidsCls = tchList.FindAll(x => x.type == 1);
- foreach (var stu in delStudentsCls)
- {
- try
- {
- ItemResponse<StuCourse> stuCourse = await client.GetContainer(Constant.TEAMModelOS, "Student").ReadItemAsync<StuCourse>(courseChange.id, new PartitionKey($"StuCourse-{courseChange.school}-{stu.id}"));
- if (stuCourse.Value.classId.Contains(delCls))
- {
- stuCourse.Value.classId.Remove(delCls);
- }
- if (!stuCourse.Value.classId.IsNotEmpty() && !stuCourse.Value.stulist.IsNotEmpty())
- {
- //当两个列表都不存在时则直接删除
- await client.GetContainer(Constant.TEAMModelOS, "Student").DeleteItemAsync<StuCourse>(courseChange.id, new PartitionKey($"StuCourse-{courseChange.school}-{stu.id}"));
- }
- else
- {
- await client.GetContainer(Constant.TEAMModelOS, "Student").ReplaceItemAsync<StuCourse>(stuCourse, courseChange.id, new PartitionKey($"StuCourse-{courseChange.school}-{stu.id}"));
- }
- }
- catch (CosmosException ex)
- {
- await _dingDing.SendBotMsg($"OS,{ Environment.GetEnvironmentVariable("Option:Location")},CourseServiceBus -CosmosDB异常\n{ex.Message}{ex.StackTrace}", GroupNames.成都开发測試群組);
- }
- }
- foreach (var tmd in delTmdidsCls)
- {
- try
- {
- ItemResponse<StuCourse> stuCourse = await client.GetContainer(Constant.TEAMModelOS, "Student").ReadItemAsync<StuCourse>(courseChange.id, new PartitionKey($"StuCourse-{tmd.id}"));
- if (stuCourse.Value.classId.Contains(delCls))
- {
- stuCourse.Value.classId.Remove(delCls);
- }
- if (!stuCourse.Value.classId.IsNotEmpty() && !stuCourse.Value.stulist.IsNotEmpty())
- {
- //当两个列表都不存在时则直接删除
- await client.GetContainer(Constant.TEAMModelOS, "Student").DeleteItemAsync<StuCourse>(courseChange.id, new PartitionKey($"StuCourse-{tmd.id}"));
- }
- else
- {
- await client.GetContainer(Constant.TEAMModelOS, "Student").ReplaceItemAsync<StuCourse>(stuCourse, courseChange.id, new PartitionKey($"StuCourse-{tmd.id}"));
- }
- }
- catch (CosmosException ex)
- {
- await _dingDing.SendBotMsg($"OS,{ Environment.GetEnvironmentVariable("Option:Location")},CourseServiceBus -CosmosDB异常\n{ex.Message}{ex.StackTrace}", GroupNames.成都开发測試群組);
- }
- }
- }
- foreach (var delList in courseChange.delList)
- {
- (List<RMember> tchList, List<RGroupList> classLists) = await GroupListService.GetStutmdidListids(_coreAPIHttpService, client, _dingDing, new List<string> { delList }, courseChange.school);
- var delStudentsCls = tchList.FindAll(x => x.type == 2);
- var delTmdidsCls = tchList.FindAll(x => x.type == 1);
- foreach (var stu in delStudentsCls)
- {
- try
- {
- ItemResponse<StuCourse> stuCourse = await client.GetContainer(Constant.TEAMModelOS, "Student").ReadItemAsync<StuCourse>(courseChange.id, new PartitionKey($"StuCourse-{courseChange.school}-{stu.id}"));
- if (stuCourse.Value.stulist.Contains(delList))
- {
- stuCourse.Value.stulist.Remove(delList);
- }
- if (!stuCourse.Value.classId.IsNotEmpty() && !stuCourse.Value.stulist.IsNotEmpty())
- {
- //当两个列表都不存在时则直接删除
- await client.GetContainer(Constant.TEAMModelOS, "Student").DeleteItemAsync<StuCourse>(courseChange.id, new PartitionKey($"StuCourse-{courseChange.school}-{stu.id}"));
- }
- else
- {
- await client.GetContainer(Constant.TEAMModelOS, "Student").ReplaceItemAsync<StuCourse>(stuCourse, courseChange.id, new PartitionKey($"StuCourse-{courseChange.school}-{stu.id}"));
- }
- }
- catch (CosmosException ex)
- {
- continue;
- // await _dingDing.SendBotMsg($"OS,{ Environment.GetEnvironmentVariable("Option:Location")},CourseServiceBus -CosmosDB异常\n{ex.Message}{ex.StackTrace}", GroupNames.成都开发測試群組);
- }
- }
- foreach (var tmd in delTmdidsCls)
- {
- try
- {
- ItemResponse<StuCourse> stuCourse = await client.GetContainer(Constant.TEAMModelOS, "Student").ReadItemAsync<StuCourse>(courseChange.id, new PartitionKey($"StuCourse-{tmd.id}"));
- if (stuCourse.Value.stulist.Contains(delList))
- {
- stuCourse.Value.stulist.Remove(delList);
- }
- if (!stuCourse.Value.classId.IsNotEmpty() && !stuCourse.Value.stulist.IsNotEmpty())
- {
- //当两个列表都不存在时则直接删除
- await client.GetContainer(Constant.TEAMModelOS, "Student").DeleteItemAsync<StuCourse>(courseChange.id, new PartitionKey($"StuCourse-{tmd.id}"));
- }
- else
- {
- await client.GetContainer(Constant.TEAMModelOS, "Student").ReplaceItemAsync<StuCourse>(stuCourse, courseChange.id, new PartitionKey($"StuCourse-{tmd.id}"));
- }
- }
- catch (CosmosException ex)
- {
- await _dingDing.SendBotMsg($"OS,{ Environment.GetEnvironmentVariable("Option:Location")},CourseServiceBus -CosmosDB异常\n{ex.Message}{ex.StackTrace}", GroupNames.成都开发測試群組);
- }
- }
- }
- }
- catch (Exception ex)
- {
- await _dingDing.SendBotMsg($"OS,{ Environment.GetEnvironmentVariable("Option:Location")},CourseServiceBus -Course\n{ex.Message}{ex.StackTrace}", GroupNames.成都开发測試群組);
- }
- }
- }
- }
|