CommonController.cs 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448
  1. using Azure.Cosmos;
  2. using Microsoft.AspNetCore.Authorization;
  3. using Microsoft.AspNetCore.Http;
  4. using Microsoft.AspNetCore.Mvc;
  5. using Microsoft.Extensions.Options;
  6. using System;
  7. using System.Collections.Generic;
  8. using System.IO;
  9. using System.Linq;
  10. using System.Net.Http;
  11. using System.Net.Http.Json;
  12. using System.Text;
  13. using System.Text.Json;
  14. using System.Threading.Tasks;
  15. using TEAMModelOS.Filter;
  16. using TEAMModelOS.Models;
  17. using TEAMModelOS.SDK;
  18. using TEAMModelOS.SDK.DI;
  19. using TEAMModelOS.SDK.Extension;
  20. using TEAMModelOS.SDK.Models;
  21. using TEAMModelOS.SDK.Models.Cosmos.Common;
  22. using TEAMModelOS.SDK.Models.Service;
  23. namespace TEAMModelOS.Controllers.Common
  24. {
  25. [ProducesResponseType(StatusCodes.Status200OK)]
  26. [ProducesResponseType(StatusCodes.Status400BadRequest)]
  27. [Route("common")]
  28. [ApiController]
  29. public class CommonController : ControllerBase
  30. {
  31. private readonly AzureCosmosFactory _azureCosmos;
  32. private readonly SnowflakeId _snowflakeId;
  33. private readonly AzureServiceBusFactory _serviceBus;
  34. private readonly DingDing _dingDing;
  35. private readonly Option _option;
  36. private readonly AzureStorageFactory _azureStorage;
  37. private readonly IHttpClientFactory _clientFactory;
  38. private readonly CoreAPIHttpService _coreAPIHttpService;
  39. public CommonController(CoreAPIHttpService coreAPIHttpService, AzureCosmosFactory azureCosmos, AzureServiceBusFactory serviceBus, SnowflakeId snowflakeId, DingDing dingDing, IOptionsSnapshot<Option> option, AzureStorageFactory azureStorage, IHttpClientFactory clientFactory)
  40. {
  41. _azureCosmos = azureCosmos;
  42. _serviceBus = serviceBus;
  43. _snowflakeId = snowflakeId;
  44. _dingDing = dingDing;
  45. _option = option?.Value;
  46. _azureStorage = azureStorage;
  47. _clientFactory = clientFactory;
  48. _coreAPIHttpService = coreAPIHttpService;
  49. }
  50. [ProducesDefaultResponseType]
  51. [Authorize(Roles = "IES")]
  52. [AuthToken(Roles = "teacher,admin")]
  53. [HttpPost("count-activity")]
  54. public async Task<IActionResult> countActivity(JsonElement element)
  55. {
  56. try
  57. {
  58. List<string> keys = new List<string> { "Vote","Exam", "Survey","Homework","Learn" };
  59. var client = _azureCosmos.GetCosmosClient();
  60. element.TryGetProperty("code", out JsonElement code) ;
  61. element.TryGetProperty("tmdid", out JsonElement tmdid);
  62. Dictionary<string, int> countall = new Dictionary<string, int>();
  63. foreach (var key in keys) {
  64. string queryList = $"select count(1) as countschool from c where c.pk='{key}' ";
  65. if (code.ValueKind.Equals(JsonValueKind.String)) {
  66. var queryschool = $"select count(1) as countschool from c where c.pk='{key}' ";
  67. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Common").GetItemQueryStreamIterator(
  68. queryText: queryschool, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"{key}-{code}") }))
  69. {
  70. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  71. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  72. {
  73. foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
  74. {
  75. if (countall.ContainsKey(key.ToLower()))
  76. {
  77. countall[key.ToLower()] = countall[key.ToLower()] + obj.GetProperty("countprivate").GetInt32();
  78. }
  79. else
  80. {
  81. countall.Add(key.ToLower(), obj.GetProperty("countschool").GetInt32());
  82. }
  83. }
  84. }
  85. }
  86. }
  87. if (tmdid.ValueKind.Equals(JsonValueKind.String)) {
  88. var queryprivate = $"select count(1) as countprivate from c where c.pk='{key}' ";
  89. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Common").GetItemQueryStreamIterator(
  90. queryText: queryprivate, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"{key}-{tmdid}") }))
  91. {
  92. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  93. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  94. {
  95. foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
  96. {
  97. if (countall.ContainsKey(key.ToLower()))
  98. {
  99. countall[key.ToLower()] = countall[key.ToLower()] + obj.GetProperty("countprivate").GetInt32();
  100. }
  101. else
  102. {
  103. countall.Add(key.ToLower(), obj.GetProperty("countprivate").GetInt32());
  104. }
  105. }
  106. }
  107. }
  108. }
  109. }
  110. return Ok(new { countall });
  111. } catch (Exception ex) {
  112. await _dingDing.SendBotMsg($"OS,{_option.Location},common/count-activity\n{ex.Message}\n{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
  113. return BadRequest();
  114. }
  115. }
  116. /// <summary>
  117. /// 获取行政班接口
  118. /// </summary>
  119. /// <param name="element"></param>
  120. /// <returns></returns>
  121. //[ProducesDefaultResponseType]
  122. //[HttpPost("get-class-info")]
  123. //public async Task<IActionResult> GetClassInfo(JsonElement element)
  124. //{
  125. // try
  126. // {
  127. // var client = _azureCosmos.GetCosmosClient();
  128. // if (!element.TryGetProperty("classes", out JsonElement _classes)) return BadRequest();
  129. // if (!element.TryGetProperty("school", out JsonElement _school)) return BadRequest();
  130. // List<string> classes = _classes.ToObject<List<string>>();
  131. // var classInfos=await TriggerStuActivity.GetClassInfo(client, _dingDing, classes, $"{_school}");
  132. // return Ok(new { classInfos ,code = 200 });
  133. // }
  134. // catch (Exception ex)
  135. // {
  136. // await _dingDing.SendBotMsg($"OS,{_option.Location},common/get-class-info\n{ex.Message}\n{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
  137. // return BadRequest();
  138. // }
  139. //}
  140. //立即结束某个活动
  141. [ProducesDefaultResponseType]
  142. [Authorize(Roles = "IES")]
  143. [AuthToken(Roles = "teacher,admin")]
  144. [HttpPost("finish")]
  145. public async Task<IActionResult> finish(JsonElement element)
  146. {
  147. //var (id, school) = HttpContext.GetAuthTokenInfo();
  148. try
  149. {
  150. if (!element.TryGetProperty("id", out JsonElement id)) return BadRequest();
  151. if (!element.TryGetProperty("code", out JsonElement code)) return BadRequest();
  152. var client = _azureCosmos.GetCosmosClient();
  153. var data = await client.GetContainer(Constant.TEAMModelOS, "Common").ReadItemStreamAsync($"{id}", new Azure.Cosmos.PartitionKey($"{code}"));
  154. using var json = await JsonDocument.ParseAsync(data.ContentStream);
  155. long now = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
  156. Dictionary<string, object> dy = System.Text.Json.JsonSerializer.Deserialize<Dictionary<string, object>>(json.RootElement.ToString());
  157. dy["endTime"] = now;
  158. dy["progress"] = "finish";
  159. bool isScore = false;
  160. if (dy["pk"].ToString().Equals("Exam")) {
  161. List<PaperSimple> papers = dy["papers"].ToJsonString().ToObject<List<PaperSimple>>();
  162. var flag = papers.SelectMany(x => x.answers).ToList().Exists(c => c.Count == 0);
  163. if (!flag) {
  164. isScore = true;
  165. }
  166. }
  167. await client.GetContainer(Constant.TEAMModelOS, "Common").ReplaceItemAsync<Dictionary<string, object>>(dy, dy["id"].ToString(), new Azure.Cosmos.PartitionKey(dy["code"].ToString()));
  168. var httpClient = _clientFactory.CreateClient();
  169. var content = new { id = $"{id}", code = $"{code}" };
  170. await ActivityService.RefreshStuActivity(_coreAPIHttpService, client, _dingDing, $"{id}", $"{code}");
  171. return Ok(new { code=200, isScore });
  172. }
  173. catch (Exception ex)
  174. {
  175. await _dingDing.SendBotMsg($"OS,{_option.Location},common/finish\n{ex.Message}\n{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
  176. return BadRequest();
  177. }
  178. }
  179. /// <summary>
  180. /// 保存考试信息
  181. /// </summary>
  182. /// <param name="request"></param>
  183. /// <returns></returns>
  184. [ProducesDefaultResponseType]
  185. [AuthToken(Roles = "teacher,admin")]
  186. [HttpPost("update-end-time")]
  187. [Authorize(Roles = "IES")]
  188. public async Task<IActionResult> updateTime(JsonElement request)
  189. {
  190. if (!request.TryGetProperty("id", out JsonElement id)) return BadRequest();
  191. if (!request.TryGetProperty("code", out JsonElement code)) return BadRequest();
  192. //if (!request.TryGetProperty("type", out JsonElement type)) return BadRequest();
  193. try
  194. {
  195. var client = _azureCosmos.GetCosmosClient();
  196. var response = await client.GetContainer(Constant.TEAMModelOS, "Common").ReadItemStreamAsync(id.GetString(), new PartitionKey($"{code}"));
  197. if (response.Status == 200)
  198. {
  199. using var json = await JsonDocument.ParseAsync(response.ContentStream);
  200. //long now = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
  201. Dictionary<string, object> dy = System.Text.Json.JsonSerializer.Deserialize<Dictionary<string, object>>(json.RootElement.ToString());
  202. if (request.TryGetProperty("time", out JsonElement time))
  203. {
  204. dy["endTime"] = time.GetInt64();
  205. }
  206. if (request.TryGetProperty("name", out JsonElement name))
  207. {
  208. dy["name"] = name.GetString();
  209. }
  210. await client.GetContainer(Constant.TEAMModelOS, "Common").ReplaceItemAsync<Dictionary<string, object>>(dy, dy["id"].ToString(), new PartitionKey(dy["code"].ToString()));
  211. }
  212. return Ok(new { code = 200 });
  213. }
  214. catch (Exception e)
  215. {
  216. await _dingDing.SendBotMsg($"OS,{_option.Location},{code}/update-end-time()\n{e.Message}\n{e.StackTrace}\n", GroupNames.醍摩豆服務運維群組);
  217. }
  218. return Ok(new { id = id.GetString() });
  219. }
  220. //更新评测活动size
  221. [ProducesDefaultResponseType]
  222. [Authorize(Roles = "IES")]
  223. [AuthToken(Roles = "teacher,admin")]
  224. [HttpPost("exam-size")]
  225. public async Task<IActionResult> examSize(JsonElement element)
  226. {
  227. //var (id, school) = HttpContext.GetAuthTokenInfo();
  228. try
  229. {
  230. //if (!element.TryGetProperty("id", out JsonElement id)) return BadRequest();
  231. if (!element.TryGetProperty("code", out JsonElement code)) return BadRequest();
  232. var client = _azureCosmos.GetCosmosClient();
  233. List<ExamInfo> examInfo = new();
  234. List<Task<ItemResponse<ExamInfo>>> tasks = new();
  235. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Common").GetItemQueryIterator<ExamInfo>(queryText: $"select value(c) from c ", requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Exam-{code}") }))
  236. {
  237. examInfo.Add(item);
  238. }
  239. foreach (ExamInfo info in examInfo)
  240. {
  241. if (info.size == 0)
  242. {
  243. info.size = await _azureStorage.GetBlobContainerClient(info.school).GetBlobsSize($"exam/{info.id}");
  244. tasks.Add(client.GetContainer(Constant.TEAMModelOS, "Common").ReplaceItemAsync(info, info.id, new PartitionKey($"{info.code}")));
  245. }
  246. }
  247. await Task.WhenAll(tasks);
  248. return Ok();
  249. }
  250. catch (Exception ex)
  251. {
  252. await _dingDing.SendBotMsg($"OS,{_option.Location},common/exam-size\n{ex.Message}\n{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
  253. return BadRequest();
  254. }
  255. }
  256. //更新投票活动size
  257. [ProducesDefaultResponseType]
  258. [Authorize(Roles = "IES")]
  259. [AuthToken(Roles = "teacher,admin")]
  260. [HttpPost("vote-size")]
  261. public async Task<IActionResult> voteSize(JsonElement element)
  262. {
  263. //var (id, school) = HttpContext.GetAuthTokenInfo();
  264. try
  265. {
  266. //if (!element.TryGetProperty("id", out JsonElement id)) return BadRequest();
  267. if (!element.TryGetProperty("code", out JsonElement code)) return BadRequest();
  268. var client = _azureCosmos.GetCosmosClient();
  269. List<Vote> votes = new();
  270. List<Task<ItemResponse<Vote>>> tasks = new();
  271. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Common").GetItemQueryIterator<Vote>(queryText: $"select value(c) from c ", requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Vote-{code}") }))
  272. {
  273. votes.Add(item);
  274. }
  275. foreach (Vote vote in votes)
  276. {
  277. if (vote.size == 0)
  278. {
  279. vote.size = await _azureStorage.GetBlobContainerClient(vote.school).GetBlobsSize($"vote/{vote.id}");
  280. tasks.Add(client.GetContainer(Constant.TEAMModelOS, "Common").ReplaceItemAsync(vote, vote.id, new PartitionKey($"{vote.code}")));
  281. }
  282. }
  283. await Task.WhenAll(tasks);
  284. return Ok();
  285. }
  286. catch (Exception ex)
  287. {
  288. await _dingDing.SendBotMsg($"OS,{_option.Location},common/vote-size\n{ex.Message}\n{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
  289. return BadRequest();
  290. }
  291. }
  292. //更新问卷活动size
  293. [ProducesDefaultResponseType]
  294. [Authorize(Roles = "IES")]
  295. [AuthToken(Roles = "teacher,admin")]
  296. [HttpPost("survey-size")]
  297. public async Task<IActionResult> surveySize(JsonElement element)
  298. {
  299. try
  300. {
  301. //if (!element.TryGetProperty("id", out JsonElement id)) return BadRequest();
  302. if (!element.TryGetProperty("code", out JsonElement code)) return BadRequest();
  303. var client = _azureCosmos.GetCosmosClient();
  304. List<Survey> surveys = new();
  305. List<Task<ItemResponse<Survey>>> tasks = new();
  306. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Common").GetItemQueryIterator<Survey>(queryText: $"select value(c) from c ", requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Survey-{code}") }))
  307. {
  308. surveys.Add(item);
  309. }
  310. foreach (Survey survey in surveys)
  311. {
  312. if (survey.size == 0)
  313. {
  314. survey.size = await _azureStorage.GetBlobContainerClient(survey.school).GetBlobsSize($"vote/{survey.id}");
  315. tasks.Add(client.GetContainer(Constant.TEAMModelOS, "Common").ReplaceItemAsync(survey, survey.id, new PartitionKey($"{survey.code}")));
  316. }
  317. }
  318. await Task.WhenAll(tasks);
  319. return Ok();
  320. }
  321. catch (Exception ex)
  322. {
  323. await _dingDing.SendBotMsg($"OS,{_option.Location},common/survey-size\n{ex.Message}\n{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
  324. return BadRequest();
  325. }
  326. }
  327. //更新试题库size
  328. [ProducesDefaultResponseType]
  329. [Authorize(Roles = "IES")]
  330. [AuthToken(Roles = "teacher,admin")]
  331. [HttpPost("item-size")]
  332. public async Task<IActionResult> itemSize(JsonElement element)
  333. {
  334. try
  335. {
  336. //if (!element.TryGetProperty("id", out JsonElement id)) return BadRequest();
  337. if (!element.TryGetProperty("code", out JsonElement code)) return BadRequest();
  338. var client = _azureCosmos.GetCosmosClient();
  339. List<ItemInfo> items = new();
  340. List<Task<ItemResponse<ItemInfo>>> tasks = new();
  341. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryIterator<ItemInfo>(queryText: $"select value(c) from c ", requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Item-{code}") }))
  342. {
  343. items.Add(item);
  344. }
  345. foreach (ItemInfo info in items)
  346. {
  347. if (info.size == 0)
  348. {
  349. info.size = await _azureStorage.GetBlobContainerClient(code.ToString()).GetBlobsSize($"item/{info.id}");
  350. tasks.Add(client.GetContainer(Constant.TEAMModelOS, "School").ReplaceItemAsync(info, info.id, new PartitionKey($"{info.code}")));
  351. }
  352. }
  353. await Task.WhenAll(tasks);
  354. return Ok();
  355. }
  356. catch (Exception ex)
  357. {
  358. await _dingDing.SendBotMsg($"OS,{_option.Location},common/item-size\n{ex.Message}\n{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
  359. return BadRequest();
  360. }
  361. }
  362. //更新试卷库size
  363. [ProducesDefaultResponseType]
  364. [Authorize(Roles = "IES")]
  365. [AuthToken(Roles = "teacher,admin")]
  366. [HttpPost("paper-size")]
  367. public async Task<IActionResult> paperSize(JsonElement element)
  368. {
  369. try
  370. {
  371. //if (!element.TryGetProperty("id", out JsonElement id)) return BadRequest();
  372. if (!element.TryGetProperty("code", out JsonElement code)) return BadRequest();
  373. var client = _azureCosmos.GetCosmosClient();
  374. List<Paper> papers = new();
  375. List<Task<ItemResponse<Paper>>> tasks = new();
  376. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryIterator<Paper>(queryText: $"select value(c) from c ", requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Paper-{code}") }))
  377. {
  378. papers.Add(item);
  379. }
  380. foreach (Paper paper in papers)
  381. {
  382. if (paper.size == 0)
  383. {
  384. paper.size = await _azureStorage.GetBlobContainerClient(code.ToString()).GetBlobsSize($"paper/{paper.name}");
  385. tasks.Add(client.GetContainer(Constant.TEAMModelOS, "School").ReplaceItemAsync(paper, paper.id, new PartitionKey($"{paper.code}")));
  386. }
  387. }
  388. await Task.WhenAll(tasks);
  389. return Ok();
  390. }
  391. catch (Exception ex)
  392. {
  393. await _dingDing.SendBotMsg($"OS,{_option.Location},common/paper-size\n{ex.Message}\n{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
  394. return BadRequest();
  395. }
  396. }
  397. /// <summary>
  398. ///
  399. /// </summary>
  400. /// <param name="element"></param>
  401. /// <returns></returns>
  402. [ProducesDefaultResponseType]
  403. [Authorize(Roles = "IES")]
  404. [AuthToken(Roles = "teacher,admin,student")]
  405. [HttpPost("delete-activity")]
  406. public async Task<IActionResult> DeleteActivity(JsonElement element) {
  407. try {
  408. if (!element.TryGetProperty("id", out JsonElement id)) return BadRequest();
  409. if (!element.TryGetProperty("code", out JsonElement code)) return BadRequest();
  410. if (!element.TryGetProperty("role", out JsonElement role)) return BadRequest();
  411. var client = _azureCosmos.GetCosmosClient();
  412. if (role.ValueKind.Equals(JsonValueKind.String))
  413. {
  414. if (role.GetString().Equals("teacher") || role.GetString().Equals("admin"))
  415. {
  416. await client.GetContainer(Constant.TEAMModelOS, "Student").DeleteItemAsync<StuActivity>($"{id}", new PartitionKey($"{code}"));
  417. }
  418. else if (role.GetString().Equals("student"))
  419. {
  420. await client.GetContainer(Constant.TEAMModelOS, "Student").DeleteItemAsync<StuActivity>($"{id}", new PartitionKey($"{code}"));
  421. }
  422. else
  423. {
  424. return Ok(new { status = 500 });
  425. }
  426. }
  427. else {
  428. return Ok(new { status = 500 });
  429. }
  430. return Ok(new { status = 200 });
  431. } catch (Exception ex) {
  432. await _dingDing.SendBotMsg($"OS,{_option.Location},common/delete-activity\n{ex.Message}\n{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
  433. return Ok(new { status = 500 });
  434. }
  435. }
  436. }
  437. }