123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373 |
- using System;
- using System.Collections;
- using System.Collections.Generic;
- using System.Dynamic;
- using System.IO;
- using System.Linq;
- using System.Net;
- using System.Text;
- using System.Text.Json;
- using System.Threading.Tasks;
- using Azure;
- using Microsoft.Azure.Cosmos;
- using Azure.Storage.Sas;
- using TEAMModelOS.SDK;
- using Microsoft.AspNetCore.Authorization;
- using Microsoft.AspNetCore.Cryptography.KeyDerivation;
- using Microsoft.AspNetCore.Mvc;
- using Microsoft.Extensions.Options;
- using TEAMModelOS.Filter;
- using TEAMModelOS.Models;
- using TEAMModelOS.SDK.DI;
- using TEAMModelOS.SDK.Extension;
- using TEAMModelOS.SDK.Models;
- using TEAMModelOS.SDK.Models.Cosmos;
- using TEAMModelOS.SDK.Models.Cosmos.Common;
- namespace TEAMModelOS.Controllers
- {
- [Route("school/notice")]
- [ApiController]
-
- public class NoticeController :ControllerBase
- {
- private readonly AzureCosmosFactory _azureCosmos;
- private readonly AzureStorageFactory _azureStorage;
- private readonly DingDing _dingDing;
- private readonly Option _option;
- public NoticeController(
- AzureCosmosFactory azureCosmos,
- AzureStorageFactory azureStorage,
- DingDing dingDing,
- IOptionsSnapshot<Option> option
- )
- {
- _azureCosmos = azureCosmos;
- _azureStorage = azureStorage;
- _dingDing = dingDing;
- _option = option?.Value;
- }
- /// <summary>
- /// 新增 或 修改
- /// </summary>
- /// <param name="request"></param>
- /// <returns></returns>
- [ProducesDefaultResponseType]
- [HttpPost("upsert")]
- [Authorize(Roles = "IES")]
- [AuthToken(Roles = "teacher,admin")]
- public async Task<IActionResult> Upsert(Notice request)
- {
- try
- {
- var (userid, _, _, school) = HttpContext.GetAuthTokenInfo();
- //新增
-
- var client = _azureCosmos.GetCosmosClient();
- if (request.scope.Equals("school") && (!string.IsNullOrEmpty(request.school)|| !string.IsNullOrEmpty(school)))
- {
- request.school = string.IsNullOrWhiteSpace(request.school) ? school : request.school;
- request.code = $"Notice-{request.school}";
- }
- else if (request.scope.Equals("private") && (!string.IsNullOrEmpty(request.creatorId)|| !string.IsNullOrEmpty(userid)))
- {
- request.creatorId = string.IsNullOrWhiteSpace(request.creatorId) ? userid : request.creatorId;
- request.code = $"Notice";
- }
- // request.code =$"Notice-{request.code}";
- request.pk = "Notice";
- request.ttl = -1;
- long now = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
- if (request.autoDelete) {
- int time = (int)(request.endTime - now) / 1000;
- if (time > 0) {
- request.ttl = time;
- }
- }
- request.createTime = now;
- request.creatorId = userid;
- //如果设置的时间是小于当前时间则立即发布
- if (request.startTime <= 0)
- {
- request.startTime = now;
- }
- if (request.publish == 1) {
- if (request.endTime <= request.startTime)
- {
- return BadRequest("结束时间必须大于开始时间");
- }
- }
- if (string.IsNullOrEmpty(request.id))
- {
- request.id = Guid.NewGuid().ToString();
-
- request = await client.GetContainer(Constant.TEAMModelOS,Constant.Common).CreateItemAsync(request, new PartitionKey($"{request.code}"));
- }
- else
- {
- var response = await client.GetContainer(Constant.TEAMModelOS, Constant.Common).ReadItemStreamAsync(request.id, new PartitionKey($"{request.code}"));
-
- if (response.StatusCode==System.Net.HttpStatusCode.OK)
- {
-
- request = await client.GetContainer(Constant.TEAMModelOS, Constant.Common).ReplaceItemAsync(request, request.id, new PartitionKey($"{request.code}"));
- }
- else
- {
- request = await client.GetContainer(Constant.TEAMModelOS, Constant.Common).CreateItemAsync(request, new PartitionKey($"{request.code}"));
- }
- }
- return Ok(new { vote = request });
- }
- catch (Exception e)
- {
- await _dingDing.SendBotMsg($"OS,{_option.Location},school/Notice/upsert()\n{e.Message}\n{e.StackTrace}\n{e .StackTrace}", GroupNames.醍摩豆服務運維群組);
- return BadRequest(e.StackTrace);
- }
- }
- /// <summary>
- ///
- /// </summary>
- /// <param name="request"></param>
- /// <returns></returns>
- [ProducesDefaultResponseType]
- [HttpPost("find")]
- [Authorize(Roles = "IES")]
- [AuthToken(Roles = "teacher,admin,student")]
- public async Task<IActionResult> Find(JsonElement request)
- {
- try
- {
- var (userid, _, _, school) = HttpContext.GetAuthTokenInfo();
- //必须有学校或者教师编码
- if (!request.TryGetProperty("code", out JsonElement code)) return BadRequest();
- if (!request.TryGetProperty("scope", out JsonElement scope)) return BadRequest();
- request.TryGetProperty("admin", out JsonElement admin);
- string stimestampsql = "";
- string etimestampsql = "";
- if (!$"{admin}".Equals("1"))
- {
- var stimestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
- if (request.TryGetProperty("stime", out JsonElement stime))
- {
- if (long.TryParse($"{stime}", out long data))
- {
- stimestamp = data;
- }
- }
- stimestampsql = $" and c.startTime <= {stimestamp} ";
- //默认当前时间
- var etimestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
- if (request.TryGetProperty("etime", out JsonElement etime))
- {
- if (long.TryParse($"{etime}", out long data))
- {
- etimestamp = data;
- }
- }
- etimestampsql = $" and c.endTime >= {etimestamp} ";
- }
- var publishsql = "";
- if (request.TryGetProperty("publish", out JsonElement publish))
- {
- if (!publish.ValueKind.Equals(JsonValueKind.Undefined) && !publish.ValueKind.Equals(JsonValueKind.Null) && publish.ValueKind.Equals(JsonValueKind.Number))
- {
- publishsql = $" and c.publish={publish} ";
- }
- }
- var creatorIdSql = "";
- if (request.TryGetProperty("creatorId", out JsonElement creatorId))
- {
- if (!publish.ValueKind.Equals(JsonValueKind.Undefined) && !publish.ValueKind.Equals(JsonValueKind.Null) && publish.ValueKind.Equals(JsonValueKind.String))
- {
- publishsql = $" and c.creatorId='{creatorId}' ";
- }
- }
- var typesql = "";
- if (request.TryGetProperty("type", out JsonElement type))
- {
- if (!type.ValueKind.Equals(JsonValueKind.Undefined) && !type.ValueKind.Equals(JsonValueKind.Null) && type.ValueKind.Equals(JsonValueKind.String))
- {
- typesql = $" and c.type='{type}' ";
- }
- }
- string joinSqlClasses = "";
- string andSqlClasses = "";
- if (request.TryGetProperty("classes", out JsonElement _classes))
- {
- if (_classes.ValueKind is JsonValueKind.Array)
- {
- List<string> subjects = _classes.ToObject<List<string>>();
- if (subjects.IsNotEmpty())
- {
- joinSqlClasses = " join A2 in c.classes ";
- List<string> sqlList = new List<string>();
- subjects.ForEach(x => { sqlList.Add($" '{x}' "); });
- string sql = string.Join(" , ", sqlList);
- andSqlClasses = $" and A2 in ({sql}) ";
- }
- }
- }
- List<Notice> notices = new List<Notice>();
- var client = _azureCosmos.GetCosmosClient();
- var query = $"select distinct value(c) from c {joinSqlClasses} where 1=1 {etimestampsql} {stimestampsql} {publishsql} {typesql} {andSqlClasses} {creatorIdSql} ";
- if ($"{scope}".Equals("school"))
- {
- await foreach (var item in client.GetContainer(Constant.TEAMModelOS, Constant.Common).GetItemQueryIteratorSql<Notice>(queryText: query,
- requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Notice-{code}") }))
- {
- notices.Add(item);
- }
- }
- else {
- await foreach (var item in client.GetContainer(Constant.TEAMModelOS, Constant.Common).GetItemQueryIteratorSql<Notice>(queryText: query,
- requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Notice") }))
- {
- notices.Add(item);
- }
- }
-
- return Ok(new { notices });
- }
- catch (Exception ex)
- {
- await _dingDing.SendBotMsg($"OS,{_option.Location},school/Notice/find()\n", GroupNames.醍摩豆服務運維群組);
- return BadRequest(ex.StackTrace);
- }
- }
- /// <summary>
- ///
- /// </summary>
- /// <param name="request"></param>
- /// <returns></returns>
- [ProducesDefaultResponseType]
- [HttpPost("find-by-student")]
- [Authorize(Roles = "IES")]
- [AuthToken(Roles = "teacher,admin,student")]
- public async Task<IActionResult> FindByStudent(JsonElement request)
- {
- try
- {
- object scope = null;
- HttpContext?.Items.TryGetValue("Scope", out scope);
- var (userid, _, _, school) = HttpContext.GetAuthTokenInfo();
- //必须有学校或者教师编码
- // if (!request.TryGetProperty("code", out JsonElement code)) return BadRequest();
-
- //string stimestampsql = "";
- //string etimestampsql = "";
- //var stimestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
- //if (request.TryGetProperty("stime", out JsonElement stime) && stime.ValueKind.Equals(JsonValueKind.Number))
- //{
- // if (long.TryParse($"{stime}", out long data))
- // {
- // stimestamp = data;
- // }
- //}
- //stimestampsql = $" and c.startTime <= {stimestamp} ";
- ////默认当前时间
- //var etimestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
- //if (request.TryGetProperty("etime", out JsonElement etime) && stime.ValueKind.Equals(JsonValueKind.Number))
- //{
- // if (long.TryParse($"{etime}", out long data))
- // {
- // etimestamp = data;
- // }
- //}
- //etimestampsql = $" and c.endTime >= {etimestamp} ";
- var publishsql = $" and c.publish=1 ";
- string joinSqlClasses = "";
- string andSqlClasses = "";
- if (request.TryGetProperty("classes", out JsonElement _classes))
- {
- if (_classes.ValueKind is JsonValueKind.Array)
- {
- List<string> subjects = _classes.ToObject<List<string>>();
- if (subjects.IsNotEmpty())
- {
- joinSqlClasses = " join A2 in c.classes ";
- List<string> sqlList = new List<string>();
- subjects.ForEach(x => { sqlList.Add($" '{x}' "); });
- string sql = string.Join(" , ", sqlList);
- andSqlClasses = $" and A2 in ({sql}) ";
- }
- }
- }
- else {
- return BadRequest();
- }
- List<Notice> notices = new List<Notice>();
- var client = _azureCosmos.GetCosmosClient();
- var query = $"select distinct value(c) from c {joinSqlClasses} where 1=1 {publishsql} {andSqlClasses} ";
- if ($"{scope}".Equals(Constant.ScopeTmdUser))
- {
- await foreach (var item in client.GetContainer(Constant.TEAMModelOS, Constant.Common).GetItemQueryIteratorSql<Notice>(queryText: query,
- requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Notice") }))
- {
- notices.Add(item);
- }
- }
- else {
- await foreach (var item in client.GetContainer(Constant.TEAMModelOS, Constant.Common).GetItemQueryIteratorSql<Notice>(queryText: query,
- requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Notice") }))
- {
- notices.Add(item);
- }
- if (!string.IsNullOrWhiteSpace(school)) {
- await foreach (var item in client.GetContainer(Constant.TEAMModelOS, Constant.Common).GetItemQueryIteratorSql<Notice>(queryText: query,
- requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Notice-{school}") }))
- {
- notices.Add(item);
- }
- }
- }
-
- return Ok(new { notices });
- }
- catch (Exception ex)
- {
- await _dingDing.SendBotMsg($"OS,{_option.Location},school/Notice/find()\n", GroupNames.醍摩豆服務運維群組);
- return BadRequest(ex.StackTrace);
- }
- }
- /// <summary>
- /// 删除
- /// </summary>
- /// <param name="request"></param>
- /// <returns></returns>
- [ProducesDefaultResponseType]
- [HttpPost("delete")]
- [AuthToken(Roles = "teacher,admin")]
- #if !DEBUG
- [Authorize(Roles = "IES")]
- #endif
- public async Task<IActionResult> Delete(JsonElement request) {
- try
- {
- // var (userid, _, _, school) = HttpContext.GetAuthTokenInfo();
- if (!request.TryGetProperty("id", out JsonElement id)) return BadRequest();
- if (!request.TryGetProperty("code", out JsonElement code)) return BadRequest();
- var client = _azureCosmos.GetCosmosClient();
- await client.GetContainer(Constant.TEAMModelOS, Constant.Common).DeleteItemStreamAsync(id.GetString(), new PartitionKey($"{code}"));
- return Ok(new { status = 200 });
- }
- catch (Exception e)
- {
- return BadRequest(e.StackTrace);
- }
- }
- }
- }
|