123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361 |
- using Azure.Cosmos;
- using Microsoft.AspNetCore.Http;
- using Microsoft.AspNetCore.Mvc;
- using Microsoft.Extensions.Options;
- using System;
- using System.Collections.Generic;
- using System.IO;
- using System.Linq;
- using System.Net.Http;
- using System.Net.Http.Json;
- using System.Text;
- using System.Text.Json;
- using System.Threading.Tasks;
- using TEAMModelOS.Filter;
- using TEAMModelOS.Models;
- using TEAMModelOS.SDK.DI;
- using TEAMModelOS.SDK.Models;
- using TEAMModelOS.SDK.Models.Cosmos.Common;
- namespace TEAMModelOS.Controllers.Common
- {
- [ProducesResponseType(StatusCodes.Status200OK)]
- [ProducesResponseType(StatusCodes.Status400BadRequest)]
- //[Authorize(Roles = "IES5")
- [Route("common")]
- [ApiController]
- public class CommonController : ControllerBase
- {
- private readonly AzureCosmosFactory _azureCosmos;
- private readonly SnowflakeId _snowflakeId;
- private readonly AzureServiceBusFactory _serviceBus;
- private readonly DingDing _dingDing;
- private readonly Option _option;
- private readonly AzureStorageFactory _azureStorage;
- private readonly IHttpClientFactory _clientFactory;
- public CommonController(AzureCosmosFactory azureCosmos, AzureServiceBusFactory serviceBus, SnowflakeId snowflakeId, DingDing dingDing, IOptionsSnapshot<Option> option, AzureStorageFactory azureStorage, IHttpClientFactory clientFactory)
- {
- _azureCosmos = azureCosmos;
- _serviceBus = serviceBus;
- _snowflakeId = snowflakeId;
- _dingDing = dingDing;
- _option = option?.Value;
- _azureStorage = azureStorage;
- _clientFactory = clientFactory;
- }
- //立即结束某个活动
- [ProducesDefaultResponseType]
- // [AuthToken(Roles = "teacher,admin")]
- [HttpPost("count-activity")]
- public async Task<IActionResult> countActivity(JsonElement element)
- {
- try
- {
- List<string> keys = new List<string> { "Vote","Exam", "Survey","Homework","Learn" };
- var client = _azureCosmos.GetCosmosClient();
- element.TryGetProperty("code", out JsonElement code) ;
- element.TryGetProperty("tmdid", out JsonElement tmdid);
- Dictionary<string, int> countall = new Dictionary<string, int>();
- foreach (var key in keys) {
- string queryList = $"select count(1) as countschool from c where c.pk='{key}' ";
- if (code.ValueKind.Equals(JsonValueKind.String)) {
- var queryschool = $"select count(1) as countschool from c where c.pk='{key}' ";
- await foreach (var item in client.GetContainer("TEAMModelOS", "Common").GetItemQueryStreamIterator(
- queryText: queryschool, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"{key}-{code}") }))
- {
- using var json = await JsonDocument.ParseAsync(item.ContentStream);
- if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
- {
- foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
- {
- if (countall.ContainsKey(key.ToLower()))
- {
- countall[key.ToLower()] = countall[key.ToLower()] + obj.GetProperty("countprivate").GetInt32();
- }
- else
- {
- countall.Add(key.ToLower(), obj.GetProperty("countschool").GetInt32());
- }
- }
- }
- }
- }
- if (tmdid.ValueKind.Equals(JsonValueKind.String)) {
- var queryprivate = $"select count(1) as countprivate from c where c.pk='{key}' ";
- await foreach (var item in client.GetContainer("TEAMModelOS", "Common").GetItemQueryStreamIterator(
- queryText: queryprivate, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"{key}-{tmdid}") }))
- {
- using var json = await JsonDocument.ParseAsync(item.ContentStream);
- if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
- {
- foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
- {
- if (countall.ContainsKey(key.ToLower()))
- {
- countall[key.ToLower()] = countall[key.ToLower()] + obj.GetProperty("countprivate").GetInt32();
- }
- else
- {
- countall.Add(key.ToLower(), obj.GetProperty("countprivate").GetInt32());
- }
- }
- }
- }
- }
- }
- return Ok(new { countall });
- } catch (Exception ex) {
- await _dingDing.SendBotMsg($"OS,{_option.Location},common/count-activity\n{ex.Message}{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
- return BadRequest();
- }
- }
- //立即结束某个活动
- [ProducesDefaultResponseType]
- [AuthToken(Roles = "teacher,admin")]
- [HttpPost("finish")]
- public async Task<IActionResult> finish(JsonElement element)
- {
- //var (id, school) = HttpContext.GetAuthTokenInfo();
- try
- {
- if (!element.TryGetProperty("id", out JsonElement id)) return BadRequest();
- if (!element.TryGetProperty("code", out JsonElement code)) return BadRequest();
- var client = _azureCosmos.GetCosmosClient();
- var data = await client.GetContainer("TEAMModelOS", "Common").ReadItemStreamAsync($"{id}", new Azure.Cosmos.PartitionKey($"{code}"));
- using var json = await JsonDocument.ParseAsync(data.ContentStream);
- long now = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
- Dictionary<string, object> dy = System.Text.Json.JsonSerializer.Deserialize<Dictionary<string, object>>(json.RootElement.ToString());
- dy["endTime"] = now;
- dy["progress"] = "finish";
- await client.GetContainer("TEAMModelOS", "Common").ReplaceItemAsync<Dictionary<string, object>>(dy, dy["id"].ToString(), new Azure.Cosmos.PartitionKey(dy["code"].ToString()));
- var httpClient = _clientFactory.CreateClient();
- var content = new { id = $"{id}", code = $"{code}" };
- var response = await httpClient.PostAsJsonAsync($"{_option.HttpTrigger }refresh-stu-activity", content);
- return Ok(await JsonDocument.ParseAsync(await response.Content.ReadAsStreamAsync()));
- }
- catch (Exception ex)
- {
- await _dingDing.SendBotMsg($"OS,{_option.Location},common/finish\n{ex.Message}{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
- return BadRequest();
- }
- }
- //更新评测活动size
- [ProducesDefaultResponseType]
- //[AuthToken(Roles = "teacher,admin")]
- [HttpPost("exam-size")]
- public async Task<IActionResult> examSize(JsonElement element)
- {
- //var (id, school) = HttpContext.GetAuthTokenInfo();
- try
- {
- //if (!element.TryGetProperty("id", out JsonElement id)) return BadRequest();
- if (!element.TryGetProperty("code", out JsonElement code)) return BadRequest();
- var client = _azureCosmos.GetCosmosClient();
- List<ExamInfo> examInfo = new();
- List<Task<ItemResponse<ExamInfo>>> tasks = new();
- await foreach (var item in client.GetContainer("TEAMModelOS", "Common").GetItemQueryIterator<ExamInfo>(queryText: $"select value(c) from c ", requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Exam-{code}") }))
- {
- examInfo.Add(item);
- }
- foreach (ExamInfo info in examInfo)
- {
- if (info.size == 0)
- {
- info.size = await _azureStorage.GetBlobContainerClient(info.school).GetBlobsSize($"exam/{info.id}");
- tasks.Add(client.GetContainer("TEAMModelOS", "Common").ReplaceItemAsync(info, info.id, new PartitionKey($"{info.code}")));
- }
- }
- await Task.WhenAll(tasks);
- return Ok();
- }
- catch (Exception ex)
- {
- await _dingDing.SendBotMsg($"OS,{_option.Location},common/exam-size\n{ex.Message}{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
- return BadRequest();
- }
- }
- //更新投票活动size
- [ProducesDefaultResponseType]
- //[AuthToken(Roles = "teacher,admin")]
- [HttpPost("vote-size")]
- public async Task<IActionResult> voteSize(JsonElement element)
- {
- //var (id, school) = HttpContext.GetAuthTokenInfo();
- try
- {
- //if (!element.TryGetProperty("id", out JsonElement id)) return BadRequest();
- if (!element.TryGetProperty("code", out JsonElement code)) return BadRequest();
- var client = _azureCosmos.GetCosmosClient();
- List<Vote> votes = new();
- List<Task<ItemResponse<Vote>>> tasks = new();
- await foreach (var item in client.GetContainer("TEAMModelOS", "Common").GetItemQueryIterator<Vote>(queryText: $"select value(c) from c ", requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Vote-{code}") }))
- {
- votes.Add(item);
- }
- foreach (Vote vote in votes)
- {
- if (vote.size == 0)
- {
- vote.size = await _azureStorage.GetBlobContainerClient(vote.school).GetBlobsSize($"vote/{vote.id}");
- tasks.Add(client.GetContainer("TEAMModelOS", "Common").ReplaceItemAsync(vote, vote.id, new PartitionKey($"{vote.code}")));
- }
- }
- await Task.WhenAll(tasks);
- return Ok();
- }
- catch (Exception ex)
- {
- await _dingDing.SendBotMsg($"OS,{_option.Location},common/vote-size\n{ex.Message}{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
- return BadRequest();
- }
- }
- //更新问卷活动size
- [ProducesDefaultResponseType]
- //[AuthToken(Roles = "teacher,admin")]
- [HttpPost("survey-size")]
- public async Task<IActionResult> surveySize(JsonElement element)
- {
- try
- {
- //if (!element.TryGetProperty("id", out JsonElement id)) return BadRequest();
- if (!element.TryGetProperty("code", out JsonElement code)) return BadRequest();
- var client = _azureCosmos.GetCosmosClient();
- List<Survey> surveys = new();
- List<Task<ItemResponse<Survey>>> tasks = new();
- await foreach (var item in client.GetContainer("TEAMModelOS", "Common").GetItemQueryIterator<Survey>(queryText: $"select value(c) from c ", requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Survey-{code}") }))
- {
- surveys.Add(item);
- }
- foreach (Survey survey in surveys)
- {
- if (survey.size == 0)
- {
- survey.size = await _azureStorage.GetBlobContainerClient(survey.school).GetBlobsSize($"vote/{survey.id}");
- tasks.Add(client.GetContainer("TEAMModelOS", "Common").ReplaceItemAsync(survey, survey.id, new PartitionKey($"{survey.code}")));
- }
- }
- await Task.WhenAll(tasks);
- return Ok();
- }
- catch (Exception ex)
- {
- await _dingDing.SendBotMsg($"OS,{_option.Location},common/survey-size\n{ex.Message}{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
- return BadRequest();
- }
- }
- //更新试题库size
- [ProducesDefaultResponseType]
- //[AuthToken(Roles = "teacher,admin")]
- [HttpPost("item-size")]
- public async Task<IActionResult> itemSize(JsonElement element)
- {
- try
- {
- //if (!element.TryGetProperty("id", out JsonElement id)) return BadRequest();
- if (!element.TryGetProperty("code", out JsonElement code)) return BadRequest();
- var client = _azureCosmos.GetCosmosClient();
- List<ItemInfo> items = new();
- List<Task<ItemResponse<ItemInfo>>> tasks = new();
- await foreach (var item in client.GetContainer("TEAMModelOS", "School").GetItemQueryIterator<ItemInfo>(queryText: $"select value(c) from c ", requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Item-{code}") }))
- {
- items.Add(item);
- }
- foreach (ItemInfo info in items)
- {
- if (info.size == 0)
- {
- info.size = await _azureStorage.GetBlobContainerClient(code.ToString()).GetBlobsSize($"item/{info.id}");
- tasks.Add(client.GetContainer("TEAMModelOS", "School").ReplaceItemAsync(info, info.id, new PartitionKey($"{info.code}")));
- }
- }
- await Task.WhenAll(tasks);
- return Ok();
- }
- catch (Exception ex)
- {
- await _dingDing.SendBotMsg($"OS,{_option.Location},common/item-size\n{ex.Message}{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
- return BadRequest();
- }
- }
- //更新试卷库size
- [ProducesDefaultResponseType]
- //[AuthToken(Roles = "teacher,admin")]
- [HttpPost("paper-size")]
- public async Task<IActionResult> paperSize(JsonElement element)
- {
- try
- {
- //if (!element.TryGetProperty("id", out JsonElement id)) return BadRequest();
- if (!element.TryGetProperty("code", out JsonElement code)) return BadRequest();
- var client = _azureCosmos.GetCosmosClient();
- List<Paper> papers = new();
- List<Task<ItemResponse<Paper>>> tasks = new();
- await foreach (var item in client.GetContainer("TEAMModelOS", "School").GetItemQueryIterator<Paper>(queryText: $"select value(c) from c ", requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Paper-{code}") }))
- {
- papers.Add(item);
- }
- foreach (Paper paper in papers)
- {
- if (paper.size == 0)
- {
- paper.size = await _azureStorage.GetBlobContainerClient(code.ToString()).GetBlobsSize($"paper/{paper.name}");
- tasks.Add(client.GetContainer("TEAMModelOS", "School").ReplaceItemAsync(paper, paper.id, new PartitionKey($"{paper.code}")));
- }
- }
- await Task.WhenAll(tasks);
- return Ok();
- }
- catch (Exception ex)
- {
- await _dingDing.SendBotMsg($"OS,{_option.Location},common/paper-size\n{ex.Message}{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
- return BadRequest();
- }
- }
- /// <summary>
- ///
- /// </summary>
- /// <param name="element"></param>
- /// <returns></returns>
- [ProducesDefaultResponseType]
- [HttpPost("delete-activity")]
- [AuthToken(Roles = "teacher,admin,student")]
- public async Task<IActionResult> DeleteActivity(JsonElement element) {
- try {
- if (!element.TryGetProperty("id", out JsonElement id)) return BadRequest();
- if (!element.TryGetProperty("code", out JsonElement code)) return BadRequest();
- if (!element.TryGetProperty("role", out JsonElement role)) return BadRequest();
- var client = _azureCosmos.GetCosmosClient();
- if (role.ValueKind.Equals(JsonValueKind.String))
- {
- if (role.GetString().Equals("teacher") || role.GetString().Equals("admin"))
- {
- await client.GetContainer("TEAMModelOS", "Teacher").DeleteItemAsync<StuActivity>($"{id}", new PartitionKey($"{code}"));
- }
- else if (role.GetString().Equals("student"))
- {
- await client.GetContainer("TEAMModelOS", "Student").DeleteItemAsync<StuActivity>($"{id}", new PartitionKey($"{code}"));
- }
- else
- {
- return Ok(new { status = 500 });
- }
- }
- else {
- return Ok(new { status = 500 });
- }
- return Ok(new { status = 200 });
- } catch (Exception ex) {
- await _dingDing.SendBotMsg($"OS,{_option.Location},common/delete-activity\n{ex.Message}{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
- return Ok(new { status = 500 });
- }
- }
- }
- }
|