IESHttpTrigger.cs 55 KB

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