123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401 |
- 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;
- 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}", 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}", 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}", 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.Message}\n{e.Status}", 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.Message}\n{e.Status}", 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)
- {
- 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();
- 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.Message}\n{e.Status}", 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.Message}\n{e.Status}", 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");
- //名单变动修改学生研修关联信息
- await ActivityService.FixActivity(client, _dingDing, groupChange, "Study");
- //名单变动修改学生简易评测关联信息
- await ActivityService.FixActivity(client, _dingDing, groupChange, "ExamLite");
- //TODO学习活动
- //await FixActivity(client, stuListChange, "Learn");
- //名单变动修改学生作业活动信息
- await ActivityService.FixActivity(client, _dingDing, groupChange, "Homework");
- if (groupChange.type == null || !groupChange.type.Equals("research") || !groupChange.type.Equals("yxtrain") || !groupChange.type.Equals("activity"))
- {
- //课程名单变动修改学生课程关联信息
- await ActivityService.FixStuCourse(client, _dingDing, groupChange);
- }
- }
- 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;
- }
- }
- }
- }
- }
- ////服務產品特別對應項
- if (servicesProductSumOrg.Count > 0)
- {
- foreach (SchoolProductSumData servicesProductSumOrgRow in servicesProductSumOrg)
- {
- //更新學校空間
- if (servicesProductSumOrgRow.prodCode.Equals("IPALJ6NY"))
- {
- School school = await client.GetContainer(Constant.TEAMModelOS, "School").ReadItemAsync<School>($"{schoolId}", new PartitionKey("Base"));
- school.size = (servicesProductSumOrgRow.avaliable < 1) ? 1 : servicesProductSumOrgRow.avaliable;
- 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-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 ex)
- {
- 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.IsNullOrEmpty(lessonRecord.periodId))
- {
- School schoolObj = await client.GetContainer(Constant.TEAMModelOS, "School").ReadItemAsync<School>(lessonRecord.school, new PartitionKey("Base"));
- //年级算法
- int? Count = schoolObj.period.Find(x => x.id.Equals(lessonRecord.periodId)).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}");
- }
- }
- }
- 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", 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)
- {
- 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.成都开发測試群組);
- }
- }
- }
- }
|