123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350 |
- using Azure.Cosmos;
- using Microsoft.AspNetCore.Authorization;
- using Microsoft.AspNetCore.Http;
- using Microsoft.AspNetCore.Mvc;
- using Microsoft.Extensions.Configuration;
- using Microsoft.Extensions.Options;
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Net;
- using System.Text.Json;
- using System.Threading.Tasks;
- using TEAMModelOS.Models;
- using TEAMModelOS.SDK.DI;
- using TEAMModelOS.SDK.Extension;
- using TEAMModelOS.SDK.Models;
- namespace TEAMModelOS.Controllers.Common
- {
- [ProducesResponseType(StatusCodes.Status200OK)]
- [ProducesResponseType(StatusCodes.Status400BadRequest)]
-
- [Route("common/work")]
- [ApiController]
- public class WorkController : 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 AzureRedisFactory _azureRedis;
- public IConfiguration _configuration { get; set; }
- public WorkController(AzureCosmosFactory azureCosmos, AzureServiceBusFactory serviceBus, SnowflakeId snowflakeId, DingDing dingDing,
- IOptionsSnapshot<Option> option, AzureStorageFactory azureStorage, AzureRedisFactory azureRedis, IConfiguration configuration)
- {
- _azureCosmos = azureCosmos;
- _serviceBus = serviceBus;
- _snowflakeId = snowflakeId;
- _dingDing = dingDing;
- _option = option?.Value;
- _azureStorage = azureStorage;
- _azureRedis = azureRedis;
- _configuration = configuration;
- }
- /// <summary>
- /// 保存评测信息
- /// </summary>
- /// <param name="request"></param>
- /// <returns></returns>
- [ProducesDefaultResponseType]
- //[AuthToken(Roles = "teacher,admin")]
- [HttpPost("save")]
- [Authorize(Roles = "IES")]
- public async Task<IActionResult> Save(JsonElement request)
- {
- try
- {
- var client = _azureCosmos.GetCosmosClient();
- Homework work = request.ToObject<Homework>();
- work.owner = "school";
- try
- {
- work.ttl = -1;
- work.code = "Homework-" + work.school;
- long now = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
- work.createTime = now;
- if (work.startTime > now)
- {
- work.progress = "pending";
- }
- else
- {
- work.progress = "going";
- }
- if (string.IsNullOrEmpty(work.id))
- {
- work.id = Guid.NewGuid().ToString();
- await client.GetContainer("TEAMModelOS", "Common").CreateItemAsync(work, new PartitionKey($"{work.code}"));
- }
- else
- {
- await client.GetContainer("TEAMModelOS", "Common").UpsertItemAsync(work, new PartitionKey($"{work.code}"));
- }
- }
- catch (Exception e)
- {
- await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-saveMore\n{e.Message}{e.StackTrace}", GroupNames.醍摩豆服務運維群組);
- }
- return Ok(new { work.id, code = (int)HttpStatusCode.OK });
- }
- catch (Exception ex)
- {
- await _dingDing.SendBotMsg($"OS,{_option.Location},Homework/save()\n{ex.Message}", GroupNames.醍摩豆服務運維群組);
- return BadRequest();
- }
- }
- /// <summary>
- /// 上传作答
- /// </summary>
- /// <param name="request"></param>
- /// <returns></returns>
- [ProducesDefaultResponseType]
- [Authorize(Roles = "IES")]
- //[AuthToken(Roles = "teacher,admin")]
- [HttpPost("record-in")]
- public async Task<IActionResult> RecordIn(JsonElement request)
- {
- try
- {
- if (!request.TryGetProperty("id", out JsonElement id)) return BadRequest();
- if (!request.TryGetProperty("code", out JsonElement code)) return BadRequest();
- if (!request.TryGetProperty("tId", out JsonElement tId)) return BadRequest();
- if (!request.TryGetProperty("ans", out JsonElement ans)) return BadRequest();
- var client = _azureCosmos.GetCosmosClient();
- //List<List<string>> answer = ans.ToObject<List<List<string>>>();
- long now = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
- var response = await client.GetContainer("TEAMModelOS", "Common").ReadItemStreamAsync(id.ToString(), new PartitionKey($"Homework-{code}"));
- if (response.Status == (int)HttpStatusCode.OK)
- {
- var json = await JsonDocument.ParseAsync(response.ContentStream);
- Homework work = json.ToObject<Homework>();
- //List<List<string>> standard = work.items.answers;
- bool flag = work.teachers.Exists(s => s.id.Equals(tId.GetString()));
- List<string> ids = work.teachers.Select(e => e.id).ToList();
- int index = ids.IndexOf(tId.GetString());
- if (flag)
- {
- foreach (var record in work.teachers)
- {
- if (record.id.Equals(tId.GetString()))
- {
- record.hw = ans.GetString();
- record.hwTime = now;
- }
- }
- }
- else {
- Submits submits = new();
- submits.id = tId.GetString();
- submits.hw = ans.GetString();
- submits.hwTime = now;
- work.teachers.Add(submits);
- }
- await client.GetContainer("TEAMModelOS", "Common").ReplaceItemAsync(work, work.id, new PartitionKey($"{work.code}"));
- }
- else
- {
- return Ok(new { code = HttpStatusCode.NotFound });
- }
- return Ok(new { code = HttpStatusCode.OK });
- }
- catch (Exception ex)
- {
- await _dingDing.SendBotMsg($"OS,{_option.Location},Homework/record-in()\n{ex.Message}", GroupNames.醍摩豆服務運維群組);
- return BadRequest();
- }
- }
- [ProducesDefaultResponseType]
- [Authorize(Roles = "IES")]
- //[AuthToken(Roles = "teacher")]
- [HttpPost("delete")]
- public async Task<IActionResult> Delete(JsonElement request)
- {
- try
- {
- if (!request.TryGetProperty("id", out JsonElement id)) return BadRequest();
- if (!request.TryGetProperty("code", out JsonElement code)) return BadRequest();
- var client = _azureCosmos.GetCosmosClient();
- var response = await client.GetContainer("TEAMModelOS", "Common").DeleteItemStreamAsync(id.ToString(), new PartitionKey($"Homework-{code}"));
- return Ok(new { id, code = response.Status });
- }
- catch (Exception e)
- {
- await _dingDing.SendBotMsg($"OS,{_option.Location},Homework/delete()\n{e.Message}", GroupNames.醍摩豆服務運維群組);
- return BadRequest();
- }
- }
- /// <param name="request"></param>
- /// <returns></returns>
- [ProducesDefaultResponseType]
- [Authorize(Roles = "IES")]
- //[AuthToken(Roles = "teacher")]
- [HttpPost("find")]
- public async Task<IActionResult> Find(JsonElement requert)
- {
- try
- {
- if (!requert.TryGetProperty("code", out JsonElement code)) return BadRequest();
- var client = _azureCosmos.GetCosmosClient();
- var query = $"select c.id,c.name,c.createTime,c.startTime,c.endTime,c.allowSupply,c.allowComment from c where (c.status<>404 or IS_DEFINED(c.status) = false ) ";
- string continuationToken = string.Empty;
- string token = default;
- //是否需要进行分页查询,默认不分页
- bool iscontinuation = false;
- if (requert.TryGetProperty("token", out JsonElement token_1))
- {
- token = token_1.GetString();
- iscontinuation = true;
- };
- //默认不指定返回大小
- int? topcout = null;
- if (requert.TryGetProperty("count", out JsonElement jcount))
- {
- if (!jcount.ValueKind.Equals(JsonValueKind.Undefined) && !jcount.ValueKind.Equals(JsonValueKind.Null) && jcount.TryGetInt32(out int data))
- {
- topcout = data;
- }
- }
- List<object> works = new();
- await foreach (var item in client.GetContainer("TEAMModelOS", "Common").GetItemQueryStreamIterator(queryText: query, continuationToken: token, requestOptions: new QueryRequestOptions() { MaxItemCount = topcout, PartitionKey = new PartitionKey($"Homework-{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())
- {
- works.Add(obj.ToObject<object>());
- }
- }
- if (iscontinuation)
- {
- continuationToken = item.GetContinuationToken();
- break;
- }
- }
- return Ok(new { works });
- }
- catch (Exception e)
- {
- await _dingDing.SendBotMsg($"OS,{_option.Location},Homework/find()\n{e.Message}", GroupNames.醍摩豆服務運維群組);
- return BadRequest();
- }
- }
- [ProducesDefaultResponseType]
- [Authorize(Roles = "IES")]
- //[AuthToken(Roles = "teacher")]
- [HttpPost("find-summary")]
- public async Task<IActionResult> FindSummary(JsonElement requert)
- {
- try
- {
- if (!requert.TryGetProperty("id", out JsonElement id)) return BadRequest();
- if (!requert.TryGetProperty("code", out JsonElement code)) return BadRequest();
- var client = _azureCosmos.GetCosmosClient();
- List<Homework> works = new();
- await foreach (var item in client.GetContainer("TEAMModelOS", "Common").GetItemQueryIterator<Homework>(queryText: $"select value(c) from c where (c.status<>404 or IS_DEFINED(c.status) = false ) and c.id = '{id}'", requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Homework-{code}") }))
- {
- works.Add(item);
- }
- return Ok(new { works });
- }
- catch (Exception e)
- {
- await _dingDing.SendBotMsg($"OS,{_option.Location},Homework/FindSummary()\n{e.Message}", GroupNames.醍摩豆服務運維群組);
- return BadRequest();
- }
- }
- /// <param name="request"></param>
- /// <returns></returns>
- [ProducesDefaultResponseType]
- [Authorize(Roles = "IES")]
- //[AuthToken(Roles = "teacher")]
- [HttpPost("find-by-teacher")]
- public async Task<IActionResult> FindByTeacher(JsonElement requert)
- {
- try
- {
- if (!requert.TryGetProperty("code", out JsonElement code)) return BadRequest();
- if (!requert.TryGetProperty("tId", out JsonElement tId)) return BadRequest();
- var client = _azureCosmos.GetCosmosClient();
- var query = $"select c.id,c.name,c.createTime,A0.time from c join A0 in c.teachers where (c.status<>404 or IS_DEFINED(c.status) = false ) and A0.id = '{tId}'";
- List<object> works = new();
- await foreach (var item in client.GetContainer("TEAMModelOS", "Common").GetItemQueryStreamIterator(queryText: query, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Homework-{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())
- {
- works.Add(obj.ToObject<object>());
- }
- }
- }
- return Ok(new { works });
- }
- catch (Exception e)
- {
- await _dingDing.SendBotMsg($"OS,{_option.Location},Homework/find-by-teacher()\n{e.Message}", GroupNames.醍摩豆服務運維群組);
- return BadRequest();
- }
- }
- [ProducesDefaultResponseType]
- [Authorize(Roles = "IES")]
- //[AuthToken(Roles = "teacher")]
- [HttpPost("find-summary-by-teacher")]
- public async Task<IActionResult> FindSummaryByTeacher(JsonElement requert)
- {
- try
- {
- if (!requert.TryGetProperty("id", out JsonElement id)) return BadRequest();
- if (!requert.TryGetProperty("code", out JsonElement code)) return BadRequest();
- if (!requert.TryGetProperty("tId", out JsonElement tId)) return BadRequest();
- var client = _azureCosmos.GetCosmosClient();
- List<object> works = new();
- await foreach (var item in client.GetContainer("TEAMModelOS", "Common").GetItemQueryStreamIterator(queryText: $"select value(c) from c join A0 in c.teachers where (c.status<>404 or IS_DEFINED(c.status) = false ) and A0.id = '{tId}' and c.id = '{id}'", requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Homework-{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())
- {
- works.Add(obj.ToObject<object>());
- }
- }
- }
- return Ok(new { works });
- }
- catch (Exception e)
- {
- await _dingDing.SendBotMsg($"OS,{_option.Location},Homework/find-summary-by-teacher()\n{e.Message}", GroupNames.醍摩豆服務運維群組);
- return BadRequest();
- }
- }
- }
- }
|