IESHttpTrigger.cs 55 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986
  1. using Microsoft.AspNetCore.Http;
  2. using Microsoft.AspNetCore.Mvc;
  3. using Microsoft.Azure.Functions.Worker;
  4. using Microsoft.Extensions.Configuration;
  5. using Microsoft.Extensions.Logging;
  6. using TEAMModelOS.Function.DI;
  7. using TEAMModelOS.SDK.DI;
  8. using TEAMModelOS.SDK;
  9. using TEAMModelOS.Models;
  10. using Microsoft.Extensions.Options;
  11. using System.Net;
  12. using System.Text.Json;
  13. using System.Reflection;
  14. using HTEXLib.COMM.Helpers;
  15. using StackExchange.Redis;
  16. using static TEAMModelOS.SDK.Services.BlobService;
  17. using TEAMModelOS.SDK.Models;
  18. using Azure.Cosmos;
  19. using TEAMModelOS.SDK.Extension;
  20. using System.Dynamic;
  21. using Azure.Storage.Blobs.Models;
  22. using TEAMModelOS.SDK.Models.Table;
  23. namespace TEAMModelOS.Function
  24. {
  25. public class IESHttpTrigger
  26. {
  27. private readonly ILogger<IESHttpTrigger> _logger;
  28. private readonly AzureCosmosFactory _azureCosmos;
  29. private readonly DingDing _dingDing;
  30. private readonly AzureStorageFactory _azureStorage;
  31. private readonly AzureRedisFactory _azureRedis;
  32. private readonly IHttpClientFactory _httpClient;
  33. private readonly Option? _option;
  34. private readonly CoreAPIHttpService _coreAPIHttpService;
  35. private readonly IConfiguration _configuration;
  36. private readonly BackgroundWorkerQueue _backgroundWorkerQueue;
  37. public IESHttpTrigger(ILogger<IESHttpTrigger> logger, AzureCosmosFactory azureCosmos, DingDing dingDing, CoreAPIHttpService coreAPIHttpService, AzureStorageFactory azureStorage , AzureRedisFactory azureRedis, IHttpClientFactory httpClient, IOptionsSnapshot<Option> option,
  38. IConfiguration configuration, BackgroundWorkerQueue backgroundWorkerQueue)
  39. {
  40. _logger = logger;
  41. _azureCosmos = azureCosmos;
  42. _dingDing = dingDing;
  43. _azureStorage = azureStorage;
  44. _azureRedis = azureRedis;
  45. _httpClient = httpClient;
  46. _coreAPIHttpService = coreAPIHttpService;
  47. _option = option?.Value;
  48. _configuration = configuration;
  49. _backgroundWorkerQueue = backgroundWorkerQueue;
  50. }
  51. [Function("upsert-student-portrait")]
  52. public async Task<IActionResult> UpsertStudentPortrait([HttpTrigger(AuthorizationLevel.Anonymous, "post",Route =null )] HttpRequest req)
  53. {
  54. _logger.LogInformation("C# HTTP trigger function processed a request.");
  55. string data = await new StreamReader(req.Body).ReadToEndAsync();
  56. var json = JsonDocument.Parse(data).RootElement;
  57. //var response = req.CreateResponse(HttpStatusCode.OK);
  58. var responseData = await OpenApiService.UpsertStudentPortrait(_azureCosmos, _dingDing, _azureRedis, json);
  59. // await response.WriteAsJsonAsync(new { data = responseData });
  60. // return new OkObjectResult("Welcome to Azure Functions!");
  61. return new OkObjectResult(new { data = responseData });
  62. }
  63. [Function("system-info-function")]
  64. public async Task<IActionResult> SystemInfo([HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = null)] HttpRequest req)
  65. {
  66. _logger.LogInformation("C# HTTP trigger function processed a request.");
  67. Type attr = this.GetType();
  68. string currentDirectory = Path.GetDirectoryName(attr.Assembly.Location);
  69. Assembly assembly = Assembly.LoadFrom($"{currentDirectory}\\TEAMModelOS.FunctionV4.dll");
  70. var description = assembly.GetCustomAttribute<AssemblyDescriptionAttribute>().Description;
  71. //var v1 = Assembly.GetEntryAssembly().GetName().Version;
  72. //var v2 = Assembly.GetEntryAssembly().GetCustomAttribute<AssemblyFileVersionAttribute>().Version;
  73. // var description = Assembly.GetEntryAssembly().GetCustomAttribute<AssemblyDescriptionAttribute>().Description;
  74. var version = Assembly.GetEntryAssembly().GetCustomAttribute<AssemblyFileVersionAttribute>().Version;
  75. long nowtime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
  76. //Console.WriteLine($"Assembly.GetEntryAssembly().GetName().Version: " +
  77. // $"{Assembly.GetEntryAssembly().GetName().Version}");5.2107.12.1
  78. //Console.WriteLine($"Assembly.GetEntryAssembly().GetCustomAttribute<AssemblyFileVersionAttribute>().Version:" +
  79. // $"{Assembly.GetEntryAssembly().GetCustomAttribute<AssemblyFileVersionAttribute>().Version}");5.2107.12.1
  80. //Console.WriteLine($"Assembly.GetEntryAssembly().GetCustomAttribute<AssemblyInformationalVersionAttribute>().InformationalVersion:" +
  81. // $"{Assembly.GetEntryAssembly().GetCustomAttribute<AssemblyInformationalVersionAttribute>().InformationalVersion}");5.2107.12
  82. return new OkObjectResult(new { version, description, nowtime });
  83. }
  84. [Function("surplus-space-notify")]
  85. public IActionResult SurplusSpaceNotify([HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = null)] HttpRequest req)
  86. {
  87. string msg = "";
  88. _backgroundWorkerQueue.QueueBackgroundWorkItem(async token =>
  89. {
  90. try
  91. {
  92. string data = await new StreamReader(req.Body).ReadToEndAsync();
  93. var json = JsonDocument.Parse(data).RootElement;
  94. json.TryGetProperty("name", out JsonElement _name);
  95. json.TryGetProperty("scope", out JsonElement _scope);
  96. json.TryGetProperty("percent", out JsonElement _percent);
  97. double percent = _percent.GetDouble();
  98. string name = _name.ToString();
  99. string scope = _scope.ToString();
  100. int tag = 11;
  101. if (percent <= 10 && percent > 5)
  102. {
  103. tag = 10;
  104. }
  105. else if (percent <= 5 && percent > 0)
  106. {
  107. tag = 5;
  108. }
  109. else if (percent <= 0)
  110. {
  111. tag = 0;
  112. }
  113. List<IdNameCode> ids = new List<IdNameCode>();
  114. Teacher teacher = null;
  115. School school = null;
  116. if (scope.Equals("school", StringComparison.OrdinalIgnoreCase))
  117. {
  118. school = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.School).ReadItemAsync<School>(name, new PartitionKey("Base"));
  119. string sql = $"select value c from c where c.code='Teacher-{name}' and c.status='join' and array_contains(c.roles,'admin') ";
  120. List<SchoolTeacher> adminTeachers = new List<SchoolTeacher>();
  121. await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.School)
  122. .GetItemQueryIterator<SchoolTeacher>(queryText: sql, requestOptions: new QueryRequestOptions { PartitionKey = new PartitionKey($"Teacher-{name}") }))
  123. {
  124. adminTeachers.Add(item);
  125. }
  126. if (adminTeachers.IsNotEmpty())
  127. {
  128. string sqlAdmin = $"select c.id,c.lang as code ,c.name from c where c.id in ({string.Join(",", adminTeachers.Select(z => $"'{z.id}'"))}) ";
  129. await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.Teacher)
  130. .GetItemQueryIterator<IdNameCode>(queryText: sqlAdmin, requestOptions: new QueryRequestOptions { PartitionKey = new PartitionKey($"Base") }))
  131. {
  132. ids.Add(item);
  133. }
  134. }
  135. }
  136. else
  137. {
  138. teacher= await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.Teacher).ReadItemAsync<Teacher>(name, new PartitionKey("Base"));
  139. ids.Add(new IdNameCode
  140. {
  141. id = teacher.id,
  142. name = teacher.name,
  143. code = teacher.lang
  144. });
  145. }
  146. //如果已经扩容请忽略此通知!
  147. string key = scope.Equals("school", StringComparison.OrdinalIgnoreCase) ? $"Blob:Space:School:Notify:{name}" : $"Blob:Space:Private:Notify:{name}";
  148. foreach (var idnamecode in ids)
  149. {
  150. string filed = $"{idnamecode.id}-{tag}";
  151. BlobSpaceNotify? blobSpaceNotify = null;
  152. RedisValue value = await _azureRedis.GetRedisClient(8).HashGetAsync(key, filed);
  153. if (value != default && !value.IsNullOrEmpty)
  154. {
  155. blobSpaceNotify = value.ToString().ToObject<BlobSpaceNotify>();
  156. }
  157. if (tag < 11)
  158. {
  159. if (blobSpaceNotify == null)
  160. {
  161. if ("school".Equals(scope, StringComparison.OrdinalIgnoreCase))
  162. {
  163. _coreAPIHttpService.PushNotify(new List<IdNameCode> { idnamecode }, $"blob-space-school-notify", Constant.NotifyType_IES5_Management,
  164. new Dictionary<string, object> { { "tmdname", idnamecode.name }, { "schoolName", school.name }, { "percent", $"{tag}" }, { "schoolId", $"{school.id}" }, { "tmdid", idnamecode.id } },
  165. $"{Environment.GetEnvironmentVariable("Option:Location")}", _configuration, _dingDing, "");
  166. }
  167. else
  168. {
  169. _coreAPIHttpService.PushNotify(new List<IdNameCode> { idnamecode }, $"blob-space-private-notify", Constant.NotifyType_IES5_Management,
  170. new Dictionary<string, object> { { "tmdname", idnamecode.name }, { "percent", $"{tag}" }, { "tmdid", idnamecode.id } },
  171. $"{Environment.GetEnvironmentVariable("Option:Location")}", _configuration, _dingDing, "");
  172. }
  173. blobSpaceNotify = new BlobSpaceNotify { id = idnamecode.id, tag = tag, containerName = name, scope = scope, notifyIndex = Guid.NewGuid().ToString() };
  174. await _azureRedis.GetRedisClient(8).HashSetAsync(key, filed, blobSpaceNotify.ToJsonString());
  175. await _azureRedis.GetRedisClient(8).KeyExpireAsync(key, new TimeSpan(hours: 7*24, minutes: 0, seconds: 0));
  176. }
  177. else
  178. {
  179. //已经发送过的不在提交
  180. }
  181. }
  182. else
  183. {
  184. if (blobSpaceNotify != null)
  185. {
  186. //撤销
  187. var index = blobSpaceNotify.notifyIndex;
  188. await _azureRedis.GetRedisClient(8).HashDeleteAsync(key, filed);
  189. _coreAPIHttpService.CancelNotify(index, $"{Environment.GetEnvironmentVariable("Option:Location")}", _configuration);
  190. }
  191. }
  192. }
  193. }
  194. catch (Exception ex)
  195. {
  196. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")},空间不足,通知发送处理异常{ex.Message}\n{ex.StackTrace}", GroupNames.成都开发測試群組);
  197. }
  198. });
  199. return new OkObjectResult(new { msg });
  200. }
  201. [Function("area-artsetting-change")]
  202. public async Task<IActionResult> AreaArtSettingChange([HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = null)] HttpRequest req)
  203. {
  204. string msg = "";
  205. try
  206. {
  207. string data = await new StreamReader(req.Body).ReadToEndAsync();
  208. var json = JsonDocument.Parse(data).RootElement;
  209. json.TryGetProperty("areaId", out JsonElement _areaId);
  210. string schoolSQL = $"select value c from c where c.areaId='{_areaId}'";
  211. List<School> schools = new List<School>();
  212. await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.School)
  213. .GetItemQueryIterator<School>(queryText: schoolSQL, requestOptions: new QueryRequestOptions { PartitionKey = new PartitionKey($"Base") }))
  214. {
  215. schools.Add(item);
  216. }
  217. ArtSetting artSetting = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.Normal).ReadItemAsync<ArtSetting>($"{_areaId}", new PartitionKey("ArtSetting"));
  218. foreach (var school in schools)
  219. {
  220. msg = school.ToJsonString();
  221. List<Period> periods = new List<Period>();
  222. var hastype_period = school.period.Where(p => !string.IsNullOrWhiteSpace(p.periodType));
  223. if (hastype_period.Any())
  224. {
  225. periods.AddRange(hastype_period);
  226. }
  227. var nottype_period = school.period.Where(p => string.IsNullOrWhiteSpace(p.periodType));
  228. if (nottype_period!=null && nottype_period.Count()>0)
  229. {
  230. foreach (var period in nottype_period)
  231. {
  232. if (period.name.Contains("小学"))
  233. {
  234. period.periodType= "primary";
  235. }
  236. if (period.name.Contains("初中"))
  237. {
  238. period.periodType = "junior";
  239. }
  240. if (period.name.Contains("高中"))
  241. {
  242. period.periodType = "senior";
  243. }
  244. if (string.IsNullOrWhiteSpace(period.periodType) && school.period.Count == 1)
  245. {
  246. if (school.name.Contains("小学"))
  247. {
  248. period.periodType = "primary";
  249. }
  250. if (school.name.Contains("初中"))
  251. {
  252. period.periodType = "junior";
  253. }
  254. if (school.name.Contains("高中"))
  255. {
  256. period.periodType = "senior";
  257. }
  258. }
  259. if (!string.IsNullOrWhiteSpace(period.periodType))
  260. {
  261. periods.Add(period);
  262. }
  263. }
  264. }
  265. foreach (var period in periods)
  266. {
  267. var dimension = artSetting.dimensions.FindAll(x => x.type.Intersect(new List<string> { period.periodType }).Any());
  268. var bindIds = period.subjects.Where(s => !string.IsNullOrWhiteSpace(s.bindId)).Select(x => x.bindId);
  269. //该学段未同步学科的。
  270. var unBindIds = dimension.Where(z => !string.IsNullOrWhiteSpace(z.subjectBind)).Select(x => x.subjectBind).ToHashSet().Except(bindIds);
  271. if (unBindIds.Any() && unBindIds.Count()>0)
  272. {
  273. //尝试寻找同名学科且没有设置bindId的
  274. foreach (var unBindId in unBindIds)
  275. {
  276. var subjects = artSetting.dimensions.FindAll(d => !string.IsNullOrWhiteSpace(d.subjectBind) && !string.IsNullOrWhiteSpace(d.subject) && d.subjectBind.Equals(unBindId))?.Select(m => m.subject);
  277. if (subjects != null)
  278. {
  279. foreach (var subject in subjects)
  280. {
  281. //获取同名学科,且没绑定的
  282. var sub = period.subjects.FindAll(sub => sub.name.Contains(subject) && string.IsNullOrWhiteSpace(sub.bindId));
  283. if (sub.IsNotEmpty())
  284. {
  285. sub[0].bindId = unBindId;
  286. }
  287. else
  288. {
  289. period.subjects.Add(new Subject { id = Guid.NewGuid().ToString(), name = subject, bindId = unBindId, type = 1 });
  290. }
  291. break;
  292. }
  293. }
  294. }
  295. }
  296. var period_subjects = period.subjects.Where(s => !string.IsNullOrWhiteSpace(s.bindId));
  297. foreach (var subject in period_subjects)
  298. {
  299. var dim = dimension.Where(x => x.subjectBind.Equals(subject.bindId));
  300. if (dim.Any())
  301. {
  302. Knowledge old = null;
  303. string sql = $"select value(c) from c where c.periodId = '{period.id}'";
  304. string pk = $"Knowledge-{school.id}-{subject.id}";
  305. await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "School").
  306. GetItemQueryIterator<Knowledge>(queryText: sql, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey(pk) }))
  307. {
  308. old = item;
  309. break;
  310. }
  311. //同步知识块。
  312. if (old != null)
  313. {
  314. bool change = false;
  315. //如果之前的是1 来源于区级,后面因区级删除,应该还原为0。
  316. var oldBlocks = old.blocks.Select(x => x.name).ToHashSet();
  317. var dimBlocks = dim.SelectMany(d => d.blocks);
  318. //增加的
  319. var addBlocks = dimBlocks.Except(oldBlocks);
  320. //减少的
  321. var cutBlocks = oldBlocks.Except(dimBlocks);
  322. foreach (var add in addBlocks)
  323. {
  324. old.blocks.Add(new Block { name = add, source = 1 });
  325. change = true;
  326. }
  327. //减少的还原为0
  328. if (cutBlocks.Any())
  329. {
  330. old.blocks.ForEach(ob => {
  331. if (cutBlocks.Contains(ob.name))
  332. {
  333. ob.source = 0;
  334. change = true;
  335. }
  336. });
  337. }
  338. foreach (var db in dimBlocks)
  339. {
  340. old.blocks.ForEach(ob => {
  341. if (db.Equals(ob.name))
  342. {
  343. ob.source = 1;
  344. change = true;
  345. }
  346. });
  347. }
  348. if (change)
  349. {
  350. await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.School).ReplaceItemAsync(old, old.id, new PartitionKey(old.code));
  351. }
  352. var count = new { pcount = old.points != null ? old.points.Count : 0, bcount = old.blocks != null ? old.blocks.Count : 0 };
  353. //处理知识点,知识块计数问题
  354. await _azureRedis.GetRedisClient(8).HashSetAsync($"Knowledge:Count:{old.owner}-{old.subjectId}", old.periodId, count.ToJsonString());
  355. }
  356. else
  357. {
  358. var blocks = dim.SelectMany(x => x.blocks).Select(bs => new Block { name = bs, source = 1 });
  359. if (blocks.Any())
  360. {
  361. var _new = new Knowledge
  362. {
  363. id = Guid.NewGuid().ToString(),
  364. pk = "Knowledge",
  365. code = pk,
  366. owner = school.id,
  367. periodId = period.id,
  368. subjectId = subject.id,
  369. blocks = blocks.ToList()
  370. };
  371. await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.School).CreateItemAsync(_new, new PartitionKey(_new.code));
  372. var count = new { pcount = _new.points != null ? _new.points.Count : 0, bcount = _new.blocks != null ? _new.blocks.Count : 0 };
  373. //处理知识点,知识块计数问题
  374. await _azureRedis.GetRedisClient(8).HashSetAsync($"Knowledge:Count:{_new.owner}-{_new.subjectId}", _new.periodId, count.ToJsonString());
  375. }
  376. }
  377. }
  378. }
  379. }
  380. await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.School).ReplaceItemAsync(school, school.id, new PartitionKey(school.code));
  381. }
  382. }
  383. catch (Exception ex)
  384. {
  385. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")},area-artsetting-change,{ex.Message}\n{ex.StackTrace}\n{msg}", GroupNames.醍摩豆服務運維群組);
  386. }
  387. return new OkObjectResult(new { });
  388. }
  389. [Function("graduate-change")]
  390. public async Task<IActionResult> GraduateChange([HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = null)] HttpRequest req)
  391. {
  392. dynamic jsondata = new ExpandoObject();
  393. try
  394. {
  395. string data = await new StreamReader(req.Body).ReadToEndAsync();
  396. var json = JsonDocument.Parse(data).RootElement;
  397. jsondata = json;
  398. //await _dingDing.SendBotMsg( "毕业状态变更:"+json.ToJsonString(), GroupNames.成都开发測試群組);
  399. string schoolId = null;
  400. if (json.TryGetProperty("schoolId", out JsonElement _schoolId))
  401. {
  402. schoolId = $"{_schoolId}";
  403. }
  404. if (string.IsNullOrEmpty(schoolId))
  405. {
  406. return new OkObjectResult(new { });
  407. }
  408. //计算毕业的
  409. if (json.TryGetProperty("graduate_classes", out JsonElement _graduate_classes))
  410. {
  411. List<Class> graduate_classes = _graduate_classes.ToObject<List<Class>>();
  412. if (graduate_classes.IsNotEmpty())
  413. {
  414. var ids = graduate_classes.Where(x => !string.IsNullOrWhiteSpace(x.id)).Select(x => $"'{x.id}'");
  415. List<Student> students = new List<Student>();
  416. string sql = $"select value c from c where (c.graduate = 0 or IS_DEFINED(c.graduate) = false) and c.classId in ({string.Join(",", ids)})";
  417. await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.Student)
  418. .GetItemQueryIterator<Student>(queryText: sql, requestOptions: new QueryRequestOptions { PartitionKey = new PartitionKey($"Base-{schoolId}") }))
  419. {
  420. item.graduate = 1;
  421. students.Add(item);
  422. }
  423. foreach (var item in students)
  424. {
  425. item.graduate = 1;
  426. await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.Student).ReplaceItemAsync<Student>(item, item.id, new PartitionKey($"Base-{schoolId}"));
  427. }
  428. foreach (var item in graduate_classes)
  429. {
  430. item.graduate = 1;
  431. await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.School).ReplaceItemAsync<Class>(item, item.id, new PartitionKey($"Class-{schoolId}"));
  432. }
  433. }
  434. }
  435. //未毕业的
  436. if (json.TryGetProperty("cancel_graduate_classes", out JsonElement _cancel_graduate_classes))
  437. {
  438. List<Class> cancel_graduate_classes = _cancel_graduate_classes.ToObject<List<Class>>();
  439. if (cancel_graduate_classes.IsNotEmpty())
  440. {
  441. var ids = cancel_graduate_classes.Where(x => !string.IsNullOrWhiteSpace(x.id)).Select(x => $"'{x.id}'");
  442. List<Student> students = new List<Student>();
  443. string sql = $"select value c from c where c.graduate =1 and c.classId in ({string.Join(",", ids)})";
  444. await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.Student)
  445. .GetItemQueryIterator<Student>(queryText: sql, requestOptions: new QueryRequestOptions { PartitionKey = new PartitionKey($"Base-{schoolId}") }))
  446. {
  447. item.graduate = 0;
  448. students.Add(item);
  449. }
  450. foreach (var item in students)
  451. {
  452. item.graduate = 0;
  453. await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.Student).ReplaceItemAsync<Student>(item, item.id, new PartitionKey($"Base-{schoolId}"));
  454. }
  455. foreach (var item in cancel_graduate_classes)
  456. {
  457. item.graduate = 0;
  458. await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.School).ReplaceItemAsync<Class>(item, item.id, new PartitionKey($"Class-{schoolId}"));
  459. }
  460. }
  461. }
  462. }
  463. catch (Exception ex)
  464. {
  465. await _dingDing.SendBotMsg($"graduate-change,{ex.Message}\n{ex.StackTrace}\n{jsondata.ToJsonString()}", GroupNames.醍摩豆服務運維群組);
  466. }
  467. return new OkObjectResult(new { });
  468. }
  469. [Function("lesson-tag-change")]
  470. public async Task<IActionResult> LessonTagChange([HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = null)] HttpRequest req)
  471. {
  472. string data = await new StreamReader(req.Body).ReadToEndAsync();
  473. var json = JsonDocument.Parse(data).RootElement;
  474. List<TagOldNew> old_new = null;
  475. string school = null;
  476. if (json.TryGetProperty("school", out JsonElement _school))
  477. {
  478. school = _school.GetString();
  479. }
  480. if (json.TryGetProperty("old_new", out JsonElement _old_new))
  481. {
  482. old_new = _old_new.ToObject<List<TagOldNew>>();
  483. }
  484. if (old_new.IsNotEmpty() && !string.IsNullOrWhiteSpace(school))
  485. {
  486. foreach (var on in old_new)
  487. {
  488. List<LessonRecord> lessonRecords = new List<LessonRecord>();
  489. string sql = $"select value(c) from c where array_contains(c.category,'{on._old}') ";
  490. await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "School").GetItemQueryIterator<LessonRecord>
  491. (queryText: sql.ToString(), requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"LessonRecord-{_school}") }))
  492. {
  493. lessonRecords.Add(item);
  494. }
  495. lessonRecords.ForEach(item =>
  496. {
  497. //修改标签
  498. if (!string.IsNullOrWhiteSpace(on._new))
  499. {
  500. for (int i = 0; i < item.category.Count; i++)
  501. {
  502. if (item.category[i].Equals(on._old))
  503. {
  504. item.category[i] = on._new;
  505. }
  506. }
  507. }
  508. else
  509. {
  510. //表示删除标签
  511. item.category.RemoveAll(x => x.Equals(on._old));
  512. }
  513. });
  514. foreach (var item in lessonRecords)
  515. {
  516. await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "School").ReplaceItemAsync(item, item.id, new PartitionKey(item.code));
  517. }
  518. }
  519. }
  520. return new OkObjectResult(new { data= json});
  521. }
  522. [Function("knowledge-change")]
  523. public async Task<IActionResult> KnowledgeChange([HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = null)] HttpRequest req)
  524. {
  525. string data = await new StreamReader(req.Body).ReadToEndAsync();
  526. var json = JsonDocument.Parse(data).RootElement;
  527. List<TagOldNew> old_new = null;
  528. string school = null;
  529. if (json.TryGetProperty("school", out JsonElement _school))
  530. {
  531. school = _school.GetString();
  532. }
  533. if (json.TryGetProperty("old_new", out JsonElement _old_new))
  534. {
  535. old_new = _old_new.ToObject<List<TagOldNew>>();
  536. }
  537. if (old_new.IsNotEmpty() && !string.IsNullOrWhiteSpace(school))
  538. {
  539. foreach (var on in old_new)
  540. {
  541. List<ItemInfo> items = new List<ItemInfo>();
  542. string sql = $"select value(c) from c where array_contains(c.knowledge,'{on._old}') ";
  543. await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "School").GetItemQueryIterator<ItemInfo>
  544. (queryText: sql.ToString(), requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Item-{_school}") }))
  545. {
  546. items.Add(item);
  547. }
  548. items.ForEach(item =>
  549. {
  550. //修改知识点
  551. if (!string.IsNullOrEmpty(on._new))
  552. {
  553. for (int i = 0; i < item.knowledge.Count; i++)
  554. {
  555. if (item.knowledge[i].Equals(on._old))
  556. {
  557. item.knowledge[i] = on._new;
  558. }
  559. }
  560. }
  561. else
  562. {
  563. //表示删除知识点
  564. item.knowledge.RemoveAll(x => x.Equals(on._old));
  565. }
  566. });
  567. foreach (var item in items)
  568. {
  569. ItemBlob itemBlob = null;
  570. try
  571. {
  572. BlobDownloadInfo blobDownloadResult = await _azureStorage.GetBlobContainerClient($"{school}").GetBlobClient($"/item/{item.id}/{item.id}.json").DownloadAsync();
  573. if (blobDownloadResult != null)
  574. {
  575. var blob = JsonDocument.Parse(blobDownloadResult.Content);
  576. itemBlob = blob.RootElement.ToObject<ItemBlob>();
  577. itemBlob.exercise.knowledge = item.knowledge;
  578. await _azureStorage.GetBlobContainerClient($"{school}").UploadFileByContainer(itemBlob.ToJsonString(), "item", $"{item.id}/{item.id}.json", true);
  579. }
  580. }
  581. catch (Exception ex)
  582. {
  583. itemBlob = null;
  584. }
  585. await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "School").ReplaceItemAsync(item, item.id, new PartitionKey(item.code));
  586. }
  587. }
  588. }
  589. return new OkObjectResult(new {data=json });
  590. }
  591. [Function("online-record")]
  592. public async Task<IActionResult> OnlineRecord([HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = null)] HttpRequest req)
  593. {
  594. // return new OkObjectResult(new { });
  595. string data = await new StreamReader(req.Body).ReadToEndAsync();
  596. var json = JsonDocument.Parse(data).RootElement;
  597. try
  598. {
  599. string school = null;
  600. string scope = null;
  601. string id = null;
  602. string ip = null;
  603. int expire = 1;
  604. if (json.TryGetProperty("school", out JsonElement _school))
  605. school = _school.GetString();
  606. if (json.TryGetProperty("scope", out JsonElement _scope))
  607. scope = _scope.GetString();
  608. if (json.TryGetProperty("id", out JsonElement _id))
  609. id = _id.GetString();
  610. if (json.TryGetProperty("ip", out JsonElement _ip))
  611. ip = _ip.GetString();
  612. if (json.TryGetProperty("expire", out JsonElement _expire))
  613. expire = _expire.GetInt32();
  614. var table = _azureStorage.GetCloudTableClient().GetTableReference("IESLogin");
  615. var cosmosClient = _azureCosmos.GetCosmosClient();
  616. DateTimeOffset dateTime = DateTimeOffset.UtcNow;
  617. var dateHour = dateTime.ToString("yyyyMMddHH"); //获取当天的小时
  618. var dateDay = dateTime.ToString("yyyyMMdd"); //获取当天的日期
  619. var dateMonth = dateTime.ToString("yyyyMM");//获取当月的日期
  620. var currentHour = dateTime.Hour; //当前小时
  621. var currentDay = dateTime.Day; //当前天
  622. long Expire = dateTime.AddHours(expire).ToUnixTimeMilliseconds(); //token到期时间
  623. long now = dateTime.ToUnixTimeMilliseconds(); //当前时间戳
  624. DateTime hour = DateTime.UtcNow.AddHours(25); //25小时到期
  625. DateTime month = DateTime.UtcNow.AddDays(32); //一个月到期
  626. var delTbHour = dateTime.AddHours(-168).ToString("yyyyMMddHH"); //168小时前
  627. var delTbDay = dateTime.AddDays(-180).ToString("yyyyMMdd"); //180天前
  628. switch (scope)
  629. {
  630. case "teacher":
  631. try
  632. {
  633. //Teacher teacher = await cosmosClient.GetContainer("TEAMModelOS", "Teacher").ReadItemAsync<Teacher>(id, new PartitionKey("Base"));
  634. //teacher.loginInfos = new List<LoginInfo>() { new LoginInfo { expire = Expire, ip = ip, time = now } };
  635. //await cosmosClient.GetContainer("TEAMModelOS", "Teacher").ReplaceItemAsync<Teacher>(teacher, teacher.id, new PartitionKey("Base"));
  636. }
  637. catch { }
  638. break;
  639. case "student":
  640. try
  641. {
  642. // Student student = await cosmosClient.GetContainer("TEAMModelOS", Constant.Student).ReadItemAsync<Student>(id, new PartitionKey($"Base-{school}"));
  643. //student.loginInfos = new List<LoginInfo>() { new LoginInfo { expire = Expire, ip = ip, time = now } };
  644. //await cosmosClient.GetContainer("TEAMModelOS", Constant.Student).ReplaceItemAsync<Student>(student, student.id, new PartitionKey($"Base-{school}"));
  645. string key = $"Login:School:{school}:student-day:{dateDay}";
  646. //记录一个学校每天每个学生登录的次数
  647. await _azureRedis.GetRedisClient(8).SortedSetIncrementAsync(key, id, 1);
  648. //获取key到期的时间
  649. await _azureRedis.GetRedisClient(8).KeyExpireAsync(key, hour); //设置到期时间25小时
  650. }
  651. catch (Exception ex) { await _dingDing.SendBotMsg($"{ex.Message}{ex.StackTrace}", GroupNames.成都开发測試群組); }
  652. break;
  653. case "tmduser":
  654. try
  655. {
  656. //TmdUser tmdUser = await cosmosClient.GetContainer("TEAMModelOS", Constant.Student).ReadItemAsync<TmdUser>(id, new PartitionKey("Base"));
  657. //tmdUser.loginInfos = new List<LoginInfo>() { new LoginInfo { expire = Expire, ip = ip, time = now } };
  658. //await cosmosClient.GetContainer("TEAMModelOS", Constant.Student).ReplaceItemAsync<TmdUser>(tmdUser, tmdUser.id, new PartitionKey("Base"));
  659. }
  660. catch { }
  661. break;
  662. }
  663. //天
  664. SortedSetEntry[] dayCnt = null;
  665. //月
  666. SortedSetEntry[] monthCnt = null;
  667. try
  668. {
  669. await _azureRedis.GetRedisClient(8).SortedSetIncrementAsync($"Login:IES:{scope}:{dateDay}", $"{currentHour}", 1);//一天24小时 小时为单位
  670. await _azureRedis.GetRedisClient(8).SortedSetIncrementAsync($"Login:IES:{scope}:{dateMonth}", $"{currentDay}", 1); //一天的累计 天为单位
  671. var resDay = await _azureRedis.GetRedisClient(8).KeyTimeToLiveAsync($"Login:IES:{scope}:{dateDay}");
  672. if (resDay == null)
  673. await _azureRedis.GetRedisClient(8).KeyExpireAsync($"Login:IES:{scope}:{dateDay}", hour); //设置到期时间
  674. var rspMonth = await _azureRedis.GetRedisClient(8).KeyTimeToLiveAsync($"Login:IES:{scope}:{dateMonth}");
  675. if (rspMonth == null)
  676. await _azureRedis.GetRedisClient(8).KeyExpireAsync($"Login:IES:{scope}:{dateMonth}", month); //设置到期时间
  677. //保存当前小时统计
  678. dayCnt = _azureRedis.GetRedisClient(8).SortedSetRangeByScoreWithScores($"Login:IES:{scope}:{dateDay}");
  679. //保存当前的统计数据
  680. monthCnt = _azureRedis.GetRedisClient(8).SortedSetRangeByScoreWithScores($"Login:IES:{scope}:{dateMonth}");
  681. }
  682. catch { }
  683. if (dayCnt != null && dayCnt.Length > 0)
  684. {
  685. List<HourLogin> hourLogins = new();
  686. foreach (var dCnt in dayCnt)
  687. {
  688. if (((int)dCnt.Element) == currentHour)
  689. {
  690. var tphourLogins = await table.QueryWhereString<HourLogin>($"PartitionKey eq 'HourLogin' and RowKey eq '{dateHour}'");
  691. if (tphourLogins.Count > 0)
  692. {
  693. foreach (var hourLogin in tphourLogins)
  694. {
  695. if (scope.Equals("teacher"))
  696. hourLogin.Teacher = (int)dCnt.Score;
  697. else if (scope.Equals("student"))
  698. hourLogin.Student = (int)dCnt.Score;
  699. else
  700. hourLogin.TmdUser = (int)dCnt.Score;
  701. hourLogins.Add(hourLogin);
  702. }
  703. }
  704. else
  705. {
  706. HourLogin hourLogin = new() { PartitionKey = $"HourLogin", RowKey = dateHour, Hour = currentHour };
  707. if (scope.Equals("teacher"))
  708. {
  709. hourLogin.Teacher = 1;
  710. hourLogin.Student = 0;
  711. hourLogin.TmdUser = 0;
  712. }
  713. else if (scope.Equals("student"))
  714. {
  715. hourLogin.Teacher = 0;
  716. hourLogin.Student = 1;
  717. hourLogin.TmdUser = 0;
  718. }
  719. else
  720. {
  721. hourLogin.Teacher = 0;
  722. hourLogin.Student = 0;
  723. hourLogin.TmdUser = 1;
  724. }
  725. hourLogins.Add(hourLogin);
  726. }
  727. }
  728. }
  729. await table.SaveOrUpdateAll(hourLogins); //保存和更新保存当前小时登录次数
  730. }
  731. if (monthCnt != null && monthCnt.Length > 0)
  732. {
  733. List<DayLogin> dayLogins = new();
  734. foreach (var mCnt in monthCnt)
  735. {
  736. if (((int)mCnt.Element) == currentDay)
  737. {
  738. //保存当天的峰值
  739. var tbDays = await table.QueryWhereString<DayLogin>($"PartitionKey eq 'DayLogin' and RowKey eq '{dateDay}'");
  740. if (tbDays.Count > 0)
  741. {
  742. foreach (var dayLogin in tbDays)
  743. {
  744. if (scope.Equals("teacher"))
  745. dayLogin.Teacher = (int)mCnt.Score;
  746. else if (scope.Equals("student"))
  747. dayLogin.Student = (int)mCnt.Score;
  748. else
  749. dayLogin.TmdUser = (int)mCnt.Score;
  750. dayLogins.Add(dayLogin);
  751. }
  752. }
  753. else
  754. {
  755. //保存当月每天的峰值
  756. DayLogin dayLogin = new() { PartitionKey = $"DayLogin", RowKey = dateDay, Day = currentDay };
  757. if (scope.Equals("teacher"))
  758. {
  759. dayLogin.Teacher = 1;
  760. dayLogin.Student = 0;
  761. dayLogin.TmdUser = 0;
  762. }
  763. else if (scope.Equals("student"))
  764. {
  765. dayLogin.Teacher = 0;
  766. dayLogin.Student = 1;
  767. dayLogin.TmdUser = 0;
  768. }
  769. else
  770. {
  771. dayLogin.Teacher = 0;
  772. dayLogin.Student = 0;
  773. dayLogin.TmdUser = 1;
  774. }
  775. dayLogins.Add(dayLogin);
  776. }
  777. }
  778. }
  779. await table.SaveOrUpdateAll(dayLogins);// 保存当月每天在线数据
  780. }
  781. string tbHourSql = $"PartitionKey eq 'HourLogin' and RowKey le '{delTbHour}'";
  782. string tbDaySql = $"PartitionKey eq 'DayLogin' and RowKey le '{delTbDay}'";
  783. try
  784. {
  785. await table.DeleteStringWhere<HourLogin>(rowKey: tbHourSql); //删除168小时前的数据
  786. await table.DeleteStringWhere<DayLogin>(rowKey: tbDaySql); //删除180天前的数据
  787. }
  788. catch { }
  789. if (!string.IsNullOrWhiteSpace(school))
  790. {
  791. //天
  792. SortedSetEntry[] scDayCnt = null;
  793. //月
  794. SortedSetEntry[] scMonthCnt = null;
  795. try
  796. {
  797. await _azureRedis.GetRedisClient(8).SortedSetIncrementAsync($"Login:School:{school}:{scope}:{dateDay}", $"{currentHour}", 1);//当天当前小时在线人加1
  798. await _azureRedis.GetRedisClient(8).SortedSetIncrementAsync($"Login:School:{school}:{scope}:{dateMonth}", $"{currentDay}", 1); //当天的在线加1
  799. var reScDay = await _azureRedis.GetRedisClient(8).KeyTimeToLiveAsync($"Login:School:{school}:{scope}:{dateDay}");
  800. if (reScDay == null)
  801. await _azureRedis.GetRedisClient(8).KeyExpireAsync($"Login:School:{school}:{scope}:{dateDay}", hour); //设置到期时间
  802. var reScMonth = await _azureRedis.GetRedisClient(8).KeyTimeToLiveAsync($"Login:School:{school}:{scope}:{dateMonth}");
  803. if (reScMonth == null)
  804. await _azureRedis.GetRedisClient(8).KeyExpireAsync($"Login:School:{school}:{scope}:{dateMonth}", month); //设置到期时间
  805. //保存学校当天每小时的
  806. scDayCnt = _azureRedis.GetRedisClient(8).SortedSetRangeByScoreWithScores($"Login:School:{school}:{scope}:{dateDay}");
  807. //学校天峰值
  808. scMonthCnt = _azureRedis.GetRedisClient(8).SortedSetRangeByScoreWithScores($"Login:School:{school}:{scope}:{dateMonth}");
  809. }
  810. catch { }
  811. if (scDayCnt != null && scDayCnt.Length > 0)
  812. {
  813. List<HourLoginSchool> hourLoginSchools = new();
  814. foreach (var scDCnt in scDayCnt)
  815. {
  816. if (((int)scDCnt.Element) == currentHour)
  817. {
  818. var tmpHour = await table.QueryWhereString<HourLoginSchool>($"PartitionKey eq 'HourLogin-{school}' and RowKey eq '{dateHour}'");
  819. if (tmpHour.Count > 0)
  820. {
  821. foreach (var hLoginSc in tmpHour)
  822. {
  823. if (scope.Equals("teacher"))
  824. hLoginSc.Teacher = (int)scDCnt.Score;
  825. else if (scope.Equals("student"))
  826. hLoginSc.Student = (int)scDCnt.Score;
  827. else
  828. hLoginSc.TmdUser = (int)scDCnt.Score;
  829. hourLoginSchools.Add(hLoginSc);
  830. }
  831. }
  832. else
  833. {
  834. //学校小时峰值
  835. HourLoginSchool hourLoginSc = new() { PartitionKey = $"HourLogin-{school}", RowKey = dateHour, Hour = currentHour, School = school };
  836. if (scope.Equals("teacher"))
  837. {
  838. hourLoginSc.Teacher = 1;
  839. hourLoginSc.Student = 0;
  840. hourLoginSc.TmdUser = 0;
  841. }
  842. else if (scope.Equals("student"))
  843. {
  844. hourLoginSc.Teacher = 0;
  845. hourLoginSc.Student = 1;
  846. hourLoginSc.TmdUser = 0;
  847. }
  848. else
  849. {
  850. hourLoginSc.Teacher = 0;
  851. hourLoginSc.Student = 0;
  852. hourLoginSc.TmdUser = 1;
  853. }
  854. hourLoginSchools.Add(hourLoginSc);
  855. }
  856. }
  857. }
  858. await table.SaveOrUpdateAll(hourLoginSchools);
  859. }
  860. if (scMonthCnt != null && scMonthCnt.Length > 0)
  861. {
  862. List<DayLoginSchool> DayLoginSchools = new();
  863. foreach (var scMCnt in scMonthCnt)
  864. {
  865. if (((int)scMCnt.Element) == currentDay)
  866. {
  867. var tempDays = await table.QueryWhereString<DayLoginSchool>($"PartitionKey eq 'DayLogin-{school}' and RowKey eq '{dateDay}'");
  868. if (tempDays.Count > 0)
  869. {
  870. foreach (var dLoginSc in tempDays)
  871. {
  872. if (scope.Equals("teacher"))
  873. dLoginSc.Teacher = (int)scMCnt.Score;
  874. else if (scope.Equals("student"))
  875. dLoginSc.Student = (int)scMCnt.Score;
  876. else
  877. dLoginSc.TmdUser = (int)scMCnt.Score;
  878. DayLoginSchools.Add(dLoginSc);
  879. }
  880. }
  881. else
  882. {
  883. //学校天峰值
  884. DayLoginSchool dayLoginSc = new() { PartitionKey = $"DayLogin-{school}", RowKey = dateDay, Day = currentDay, School = school };
  885. if (scope.Equals("teacher"))
  886. {
  887. dayLoginSc.Teacher = 1;
  888. dayLoginSc.Student = 0;
  889. dayLoginSc.TmdUser = 0;
  890. }
  891. else if (scope.Equals("student"))
  892. {
  893. dayLoginSc.Teacher = 0;
  894. dayLoginSc.Student = 1;
  895. dayLoginSc.TmdUser = 0;
  896. }
  897. else
  898. {
  899. dayLoginSc.Teacher = 0;
  900. dayLoginSc.Student = 0;
  901. dayLoginSc.TmdUser = 1;
  902. }
  903. DayLoginSchools.Add(dayLoginSc);
  904. }
  905. }
  906. }
  907. await table.SaveOrUpdateAll(DayLoginSchools);//保存学校当月在线数据
  908. }
  909. string tbScHourSql = $"PartitionKey eq 'HourLogin-{school}' and RowKey le '{delTbHour}'";
  910. List<HourLogin> scHourLog = await table.QueryWhereString<HourLogin>(tbScHourSql);
  911. if (scHourLog.Count > 0)
  912. try
  913. {
  914. //await table.DeleteStringWhere<HourLogin>(tbScHourSql); //删除学校168小时前的数据
  915. await table.DeleteAll(scHourLog);
  916. }
  917. catch { }
  918. string tbScDaySql = $"PartitionKey eq 'DayLogin-{school}' and RowKey le '{delTbDay}'";
  919. List<DayLogin> scDayLog = await table.QueryWhereString<DayLogin>(tbScDaySql);
  920. if (scDayLog.Count > 0)
  921. try
  922. {
  923. //await table.DeleteStringWhere<DayLogin>(tbScDaySql); //删除学校180天前的数据
  924. await table.DeleteAll(scDayLog);
  925. }
  926. catch { }
  927. }
  928. return new OkObjectResult(new { data=json});
  929. }
  930. catch (Exception ex)
  931. {
  932. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-online-record 人数记录异常{ex.Message}\n{ex.StackTrace}", GroupNames.成都开发測試群組);
  933. return new OkObjectResult(new { data = json });
  934. }
  935. }
  936. }
  937. }