IESHttpTrigger.cs 51 KB

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