ActivityHttpTrigger.cs 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561
  1. using System;
  2. using System.IO;
  3. using System.Threading.Tasks;
  4. using Microsoft.AspNetCore.Mvc;
  5. using Microsoft.Azure.WebJobs;
  6. using Microsoft.Azure.WebJobs.Extensions.Http;
  7. using Microsoft.AspNetCore.Http;
  8. using Microsoft.Extensions.Logging;
  9. using TEAMModelOS.SDK.DI;
  10. using Azure.Cosmos;
  11. using System.Text.Json;
  12. using System.Collections.Generic;
  13. using TEAMModelOS.SDK.Models;
  14. using TEAMModelOS.SDK.Extension;
  15. using TEAMModelOS.SDK.Helper.Common.CollectionHelper;
  16. using TEAMModelOS.SDK.Models.Cosmos;
  17. using TEAMModelOS.SDK.Models.Cosmos.Common;
  18. using TEAMModelOS.TEAMModelFunction;
  19. namespace TEAMModelFunction
  20. {
  21. public class ActivityHttpTrigger
  22. {
  23. private readonly AzureCosmosFactory _azureCosmos;
  24. private readonly DingDing _dingDing;
  25. private readonly AzureStorageFactory _azureStorage;
  26. private readonly AzureRedisFactory _azureRedis;
  27. public ActivityHttpTrigger(AzureCosmosFactory azureCosmos, DingDing dingDing, AzureStorageFactory azureStorage
  28. , AzureRedisFactory azureRedis)
  29. {
  30. _azureCosmos = azureCosmos;
  31. _dingDing = dingDing;
  32. _azureStorage = azureStorage;
  33. _azureRedis = azureRedis;
  34. }
  35. /// <summary>
  36. /// 修复已存在的课程且未初始化学生课程列表的业务。
  37. /// </summary>
  38. /// <param name="req"></param>
  39. /// <param name="log"></param>
  40. /// <returns></returns>
  41. [FunctionName("fix-stu-course")]
  42. public async Task<IActionResult> StuCourse([HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = null)] HttpRequest req, ILogger log)
  43. {
  44. log.LogInformation("fix-stu-course...");
  45. string originCode = await new StreamReader(req.Body).ReadToEndAsync();
  46. List<Course> courses = new List<Course>();
  47. var client = _azureCosmos.GetCosmosClient();
  48. var query = $"select * from c ";
  49. await foreach (var item in client.GetContainer("TEAMModelOS", "School").GetItemQueryIterator<Course>(queryText: query,
  50. requestOptions: new QueryRequestOptions() { PartitionKey = new Azure.Cosmos.PartitionKey($"Course-{originCode}") }))
  51. {
  52. courses.Add(item);
  53. }
  54. await foreach (var item in client.GetContainer("TEAMModelOS", "Teacher").GetItemQueryIterator<Course>(queryText: query,
  55. requestOptions: new QueryRequestOptions() { PartitionKey = new Azure.Cosmos.PartitionKey($"Course-{originCode}") }))
  56. {
  57. courses.Add(item);
  58. }
  59. //2.获取课程的id 并尝试添加或移除对应的学生课程记录StuCourse。
  60. foreach (var course in courses)
  61. {
  62. if (course.schedule.IsNotEmpty())
  63. {
  64. foreach (var sc in course.schedule)
  65. {
  66. if (!string.IsNullOrEmpty(sc.stulist))
  67. {
  68. (List<string> tmdids, List<Students> studentss) = await TriggerStuActivity.GetStuList(client, _dingDing, new List<string>() { sc.stulist }, course.school);
  69. foreach (var addStu in studentss)
  70. {
  71. var stuCourse = new StuCourse
  72. {
  73. id = course.id,
  74. scode = course.code,
  75. name = course.name,
  76. code = $"StuCourse-{course.school}-{addStu.id}",
  77. scope = course.scope,
  78. school = course.school,
  79. creatorId = course.creatorId,
  80. pk = "StuCourse"
  81. };
  82. await client.GetContainer("TEAMModelOS", "Student").UpsertItemAsync(stuCourse, new PartitionKey(stuCourse.code));
  83. }
  84. foreach (var addTmd in tmdids)
  85. {
  86. var tmdCourse = new StuCourse
  87. {
  88. id = course.id,
  89. scode = course.code,
  90. name = course.name,
  91. code = $"StuCourse-{addTmd}",
  92. scope = course.scope,
  93. //school = courseChange.school,
  94. creatorId = course.creatorId,
  95. pk = "StuCourse"
  96. };
  97. await client.GetContainer("TEAMModelOS", "Teacher").UpsertItemAsync(tmdCourse, new PartitionKey(tmdCourse.code));
  98. }
  99. }
  100. }
  101. }
  102. }
  103. return new OkObjectResult(new { });
  104. }
  105. /// <summary>
  106. /// 设置评测未初始化学生列表的
  107. /// </summary>
  108. /// <param name="req"></param>
  109. /// <param name="log"></param>
  110. /// <returns></returns>
  111. [FunctionName("fix-exam-activity")]
  112. public async Task<IActionResult> ExamActivity([HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = null)] HttpRequest req,ILogger log)
  113. {
  114. log.LogInformation("fix-exam-activity...");
  115. string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
  116. List<string> datas = JsonSerializer.Deserialize<List<string>>(requestBody);
  117. var client = _azureCosmos.GetCosmosClient();
  118. var query = $"select * from c ";
  119. foreach (string data in datas) {
  120. List<ExamInfo> exams = new List<ExamInfo>();
  121. await foreach (var item in client.GetContainer("TEAMModelOS", "Common").GetItemQueryStreamIterator(
  122. queryText: query, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Exam-{data}") }))
  123. {
  124. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  125. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  126. {
  127. foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
  128. {
  129. exams.Add(obj.ToObject<ExamInfo>());
  130. }
  131. }
  132. }
  133. log.LogInformation($"{exams.ToJsonString()}");
  134. foreach (var info in exams)
  135. {
  136. if (!info.classes.IsNotEmpty())
  137. {
  138. continue;
  139. }
  140. List<string> sub = new List<string>();
  141. foreach (ExamSubject subject in info.subjects)
  142. {
  143. sub.Add(subject.id);
  144. }
  145. (List<string> tmdids, List<Students> studentss) = await TriggerStuActivity.GetStuList(client, _dingDing, info.classes, info.school);
  146. List<StuActivity> stuActivities = new List<StuActivity>();
  147. List<StuActivity> tmdActivities = new List<StuActivity>();
  148. if (tmdids.IsNotEmpty())
  149. {
  150. tmdids.ForEach(x => {
  151. tmdActivities.Add(new StuActivity
  152. {
  153. pk = "Activity",
  154. id = info.id,
  155. code = $"Activity-{x}",
  156. type = "exam",
  157. name = info.name,
  158. startTime = info.startTime,
  159. endTime = info.endTime,
  160. scode = info.code,
  161. scope = info.scope,
  162. school = info.school,
  163. creatorId = info.creatorId,
  164. subjects = sub,
  165. blob = null,
  166. owner = info.owner
  167. });
  168. });
  169. }
  170. if (studentss.IsNotEmpty())
  171. {
  172. studentss.ForEach(x => {
  173. stuActivities.Add(new StuActivity
  174. {
  175. pk = "Activity",
  176. id = info.id,
  177. code = $"Activity-{info.school}-{x.id}",
  178. type = "exam",
  179. name = info.name,
  180. startTime = info.startTime,
  181. endTime = info.endTime,
  182. scode = info.code,
  183. scope = info.scope,
  184. school = info.school,
  185. creatorId = info.creatorId,
  186. subjects = sub,
  187. blob=null,
  188. owner = info.owner
  189. });
  190. });
  191. }
  192. await TriggerStuActivity.SaveStuActivity(client, _dingDing, stuActivities, tmdActivities);
  193. }
  194. }
  195. return new OkObjectResult(new { });
  196. }
  197. /// <summary>
  198. /// 设置投票未初始化学生列表的业务
  199. /// </summary>
  200. /// <param name="req"></param>
  201. /// <param name="log"></param>
  202. /// <returns></returns>
  203. [FunctionName("fix-vote-activity")]
  204. public async Task<IActionResult> VoteActivity(
  205. [HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequest req,
  206. ILogger log)
  207. {
  208. log.LogInformation("fix-vote-activity...");
  209. string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
  210. List<string> datas = JsonSerializer.Deserialize<List<string>>(requestBody);
  211. var client = _azureCosmos.GetCosmosClient();
  212. var query = $"select * from c ";
  213. foreach (string data in datas)
  214. {
  215. List<Vote> votes = new List<Vote>();
  216. await foreach (var item in client.GetContainer("TEAMModelOS", "Common").GetItemQueryStreamIterator(
  217. queryText: query, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Vote-{data}") }))
  218. {
  219. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  220. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  221. {
  222. foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
  223. {
  224. votes.Add(obj.ToObject<Vote>());
  225. }
  226. }
  227. }
  228. log.LogInformation($"{votes.ToJsonString()}");
  229. foreach (var info in votes)
  230. {
  231. if (!info.classes.IsNotEmpty())
  232. {
  233. continue;
  234. }
  235. (List<string> tmdids, List<Students> studentss) = await TriggerStuActivity.GetStuList(client, _dingDing, info.classes, info.school);
  236. List<StuActivity> stuActivities = new List<StuActivity>();
  237. List<StuActivity> tmdActivities = new List<StuActivity>();
  238. if (tmdids.IsNotEmpty())
  239. {
  240. tmdids.ForEach(x => {
  241. tmdActivities.Add(new StuActivity
  242. {
  243. pk = "Activity",
  244. id = info.id,
  245. code = $"Activity-{x}",
  246. type = "vote",
  247. name = info.name,
  248. startTime = info.startTime,
  249. endTime = info.endTime,
  250. scode = info.code,
  251. scope = info.scope,
  252. school = info.school,
  253. creatorId = info.creatorId,
  254. subjects = new List<string>() { "" },
  255. blob = null,
  256. owner = info.owner
  257. });
  258. });
  259. }
  260. if (studentss.IsNotEmpty())
  261. {
  262. studentss.ForEach(x => {
  263. stuActivities.Add(new StuActivity
  264. {
  265. pk = "Activity",
  266. id = info.id,
  267. code = $"Activity-{info.school}-{x.id}",
  268. type = "vote",
  269. name = info.name,
  270. startTime = info.startTime,
  271. endTime = info.endTime,
  272. scode = info.code,
  273. scope = info.scope,
  274. school = info.school,
  275. creatorId = info.creatorId,
  276. subjects = new List<string>() { "" },
  277. blob = null,
  278. owner = info.owner
  279. });
  280. });
  281. }
  282. await TriggerStuActivity.SaveStuActivity(client, _dingDing, stuActivities, tmdActivities);
  283. }
  284. }
  285. return new OkObjectResult(new { });
  286. }
  287. /// <summary>
  288. /// 设置问卷调查未初始化学生列表的业务
  289. /// </summary>
  290. /// <param name="req"></param>
  291. /// <param name="log"></param>
  292. /// <returns></returns>
  293. [FunctionName("fix-survey-activity")]
  294. public async Task<IActionResult> SurveyActivity(
  295. [HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequest req,
  296. ILogger log)
  297. {
  298. log.LogInformation("fix-survey-activity...");
  299. string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
  300. List<string> datas = JsonSerializer.Deserialize<List<string>>(requestBody);
  301. var client = _azureCosmos.GetCosmosClient();
  302. var query = $"select * from c ";
  303. foreach (string data in datas)
  304. {
  305. List<Survey> surveys = new List<Survey>();
  306. await foreach (var item in client.GetContainer("TEAMModelOS", "Common").GetItemQueryStreamIterator(
  307. queryText: query, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Survey-{data}") }))
  308. {
  309. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  310. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  311. {
  312. foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
  313. {
  314. surveys.Add(obj.ToObject<Survey>());
  315. }
  316. }
  317. }
  318. log.LogInformation($"{surveys.ToJsonString()}");
  319. foreach (var info in surveys)
  320. {
  321. if (!info.classes.IsNotEmpty())
  322. {
  323. continue;
  324. }
  325. (List<string> tmdids, List<Students> studentss) = await TriggerStuActivity.GetStuList(client, _dingDing, info.classes, info.school);
  326. List<StuActivity> stuActivities = new List<StuActivity>();
  327. List<StuActivity> tmdActivities = new List<StuActivity>();
  328. if (tmdids.IsNotEmpty())
  329. {
  330. tmdids.ForEach(x => {
  331. tmdActivities.Add(new StuActivity
  332. {
  333. pk = "Activity",
  334. id = info.id,
  335. code = $"Activity-{x}",
  336. type = "survey",
  337. name = info.name,
  338. startTime = info.startTime,
  339. endTime = info.endTime,
  340. scode = info.code,
  341. scope = info.scope,
  342. school = info.school,
  343. creatorId = info.creatorId,
  344. subjects = new List<string>() { "" },
  345. blob = info.blob,
  346. owner=info.owner
  347. });
  348. });
  349. }
  350. if (studentss.IsNotEmpty())
  351. {
  352. studentss.ForEach(x => {
  353. stuActivities.Add(new StuActivity
  354. {
  355. pk = "Activity",
  356. id = info.id,
  357. code = $"Activity-{info.school}-{x.id}",
  358. type = "survey",
  359. name = info.name,
  360. startTime = info.startTime,
  361. endTime = info.endTime,
  362. scode = info.code,
  363. scope = info.scope,
  364. school = info.school,
  365. creatorId = info.creatorId,
  366. subjects = new List<string>() { "" },
  367. blob=info.blob,
  368. owner = info.owner
  369. });
  370. });
  371. }
  372. await TriggerStuActivity.SaveStuActivity(client, _dingDing, stuActivities, tmdActivities);
  373. }
  374. }
  375. return new OkObjectResult(new { });
  376. }
  377. /// <summary>
  378. //获取题目摘要信息
  379. /// </summary>
  380. /// <param name="request"></param>
  381. /// <returns></returns>
  382. [ProducesDefaultResponseType]
  383. //[AuthToken(Roles = "teacher")]
  384. [FunctionName("fix-itemcond")]
  385. public async Task<IActionResult> FixItemCond(
  386. [HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequest req,
  387. ILogger log)
  388. {
  389. var client = _azureCosmos.GetCosmosClient();
  390. //List<ItemInfo> items = new List<ItemInfo>();
  391. var queryslt = $"SELECT value(c) FROM c ";
  392. ItemCond cond = new ItemCond();
  393. await foreach (var item in client.GetContainer("TEAMModelOS", "School").GetItemQueryIterator<ItemInfo>(queryText: queryslt, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Item-hbcn") }))
  394. {
  395. ItemService.CountItemCond(item,null,cond);
  396. //items.Add(item);
  397. }
  398. return new OkObjectResult(new { cond });
  399. }
  400. /// <summary>
  401. /// 设置问卷调查未初始化学生列表的业务
  402. /// </summary>
  403. /// <param name="req"></param>
  404. /// <param name="log"></param>
  405. /// <returns></returns>
  406. [FunctionName("refresh-stu-activity")]
  407. public async Task<IActionResult> RefreshStuActivity(
  408. [HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequest req,
  409. ILogger log)
  410. {
  411. string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
  412. dynamic json = JsonSerializer.Deserialize<dynamic>(requestBody);
  413. string id = json.id;
  414. string code = json.code;
  415. if (string.IsNullOrEmpty(id) || string.IsNullOrEmpty(code)) {
  416. return new BadRequestResult();
  417. }
  418. var client = _azureCosmos.GetCosmosClient();
  419. // var query = $"SELECT distinct c.owner, c.id,c.code, c.classes,c.subjects,c.progress,c.scope,c.startTime,c.school,c.creatorId,c.name,c.pk ,c.endTime FROM c join A1 in c.classes where c.pk='{type}' and A1 in('{stuListChange.listid}') ";
  420. MQActivity activity = null;
  421. try {
  422. var aactivity= await client.GetContainer("TEAMModelOS", "Common").ReadItemStreamAsync(id, new Azure.Cosmos.PartitionKey(code));
  423. using var da = await JsonDocument.ParseAsync(aactivity.ContentStream);
  424. activity = da.ToObject<MQActivity>();
  425. } catch (Exception ex) {
  426. }
  427. if (activity != null)
  428. {
  429. (List<string> tmdids, List<Students> students) = await TriggerStuActivity.GetStuList(client, _dingDing, activity.classes, activity.school);
  430. if (tmdids.IsNotEmpty())
  431. {
  432. foreach (string tmdid in tmdids)
  433. {
  434. var stucourse = new StuActivity
  435. {
  436. id = activity.id,
  437. scode = activity.code,
  438. name = activity.name,
  439. code = $"Activity-{tmdid}",
  440. scope = activity.scope,
  441. school = activity.school,
  442. creatorId = activity.creatorId,
  443. pk = "Activity",
  444. type = activity.pk,
  445. subjects = activity.pk.ToLower().Equals("exam") && activity.subjects.IsNotEmpty() ? new List<string>() { activity.subjects[0].id } : new List<string>() { "" },
  446. startTime = activity.startTime,
  447. endTime = activity.endTime,
  448. blob = activity.blob,
  449. owner = activity.owner
  450. };
  451. await client.GetContainer("TEAMModelOS", "Teacher").UpsertItemAsync(stucourse, new PartitionKey(stucourse.code));
  452. }
  453. }
  454. if (students.IsNotEmpty())
  455. {
  456. foreach (Students student in students)
  457. {
  458. var stucourse = new StuActivity
  459. {
  460. id = activity.id,
  461. scode = activity.code,
  462. name = activity.name,
  463. code = $"Activity-{activity.school}-{student.id}",
  464. scope = activity.scope,
  465. school = activity.school,
  466. creatorId = activity.creatorId,
  467. pk = "Activity",
  468. type = activity.pk,
  469. subjects = activity.pk.ToLower().Equals("exam") && activity.subjects.IsNotEmpty() ? new List<string>() { activity.subjects[0].id } : new List<string>() { "" },
  470. startTime = activity.startTime,
  471. endTime = activity.endTime,
  472. blob = activity.blob,
  473. owner = activity.owner
  474. };
  475. await client.GetContainer("TEAMModelOS", "Student").UpsertItemAsync(stucourse, new PartitionKey(stucourse.code));
  476. }
  477. }
  478. return new OkObjectResult(new { code = 200 });
  479. }
  480. else {
  481. return new BadRequestResult();
  482. }
  483. }
  484. /// <summary>
  485. ///获取单个目录的大小,用于获取评测,试题,试卷,问卷,投票等 文件层级超过两层的文件。
  486. ///例如 /exam/uuid/xxx /item/uuid/xxx /paper/uuid/xxx /vote/uuid/xxx /suervy/uuid/xxx
  487. /// {"name":"hbcn","/item/uuid/xxx"}
  488. /// </summary>
  489. /// <param name="req"></param>
  490. /// <param name="log"></param>
  491. /// <returns></returns>
  492. [FunctionName("get-prefixsize")]
  493. public async Task<IActionResult> GetPrefixsize(
  494. [HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequest req,
  495. ILogger log)
  496. {
  497. try {
  498. string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
  499. var data = System.Text.Json.JsonSerializer.Deserialize<JsonElement>(requestBody);
  500. if (data.TryGetProperty("name", out JsonElement name) && data.TryGetProperty("root", out JsonElement root))
  501. {
  502. var size = await _azureStorage.GetBlobContainerClient($"{name}").GetBlobsSize($"{root}");
  503. return new OkObjectResult(new { size = size });
  504. }
  505. else
  506. {
  507. return new BadRequestResult();
  508. }
  509. } catch (Exception ex) {
  510. await _dingDing.SendBotMsg($"TEAMModelFunction,ActivityHttpTrigger,get-prefixsize()\n{ex.Message}", GroupNames.醍摩豆服務運維群組);
  511. return new BadRequestResult();
  512. }
  513. }
  514. /// <summary>
  515. ///获取多个blob路径的文件大小
  516. /// {"name":"hbcn","blobs":["/paper/uuid/xxx.json","/paper/uuid/aaa.json"]}
  517. /// </summary>
  518. /// <param name="req"></param>
  519. /// <param name="log"></param>
  520. /// <returns></returns>
  521. [FunctionName("get-blobsize")]
  522. public async Task<IActionResult> GetBlobsize(
  523. [HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequest req,
  524. ILogger log)
  525. {
  526. try {
  527. string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
  528. var data = System.Text.Json.JsonSerializer.Deserialize<JsonElement>(requestBody);
  529. if (data.TryGetProperty("name", out JsonElement name) && data.TryGetProperty("blobs", out JsonElement blob))
  530. {
  531. List<string> blobs = JsonSerializer.Deserialize<List<string>>(blob.ToJsonString());
  532. var size= await _azureStorage.GetBlobContainerClient($"{name}").GetBlobsSize(blobs);
  533. return new OkObjectResult(new { size = size });
  534. }
  535. else {
  536. return new BadRequestResult();
  537. }
  538. } catch (Exception ex)
  539. {
  540. await _dingDing.SendBotMsg($"TEAMModelFunction,ActivityHttpTrigger,get-blobsize()\n{ex.Message}", GroupNames.醍摩豆服務運維群組);
  541. return new BadRequestResult();
  542. }
  543. }
  544. }
  545. }