ActivityHttpTrigger.cs 26 KB

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