123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417 |
- using Microsoft.AspNetCore.Mvc;
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Threading.Tasks;
- using TEAMModelOS.Models;
- using TEAMModelOS.SDK.DI;
- using System.Text.Json;
- using TEAMModelOS.SDK.Helper.Common.StringHelper;
- using TEAMModelOS.SDK.Models;
- using Microsoft.AspNetCore.Http;
- using TEAMModelOS.SDK.Extension;
- using Azure.Cosmos;
- using Microsoft.AspNetCore.Authentication;
- using System.Text;
- using TEAMModelOS.SDK.DI.AzureCosmos.Inner;
- using Microsoft.Extensions.Options;
- using TEAMModelOS.Filter;
- using HTEXLib.COMM.Helpers;
- using Microsoft.AspNetCore.Authorization;
- using TEAMModelOS.SDK;
- using static TEAMModelOS.SDK.ValidatorHelper;
- using System.ComponentModel.DataAnnotations;
- namespace TEAMModelOS.Controllers
- {
- [ProducesResponseType(StatusCodes.Status200OK)]
- [ProducesResponseType(StatusCodes.Status400BadRequest)]
- [Route("knowledges")]
- [ApiController]
- public class KnowledgesController : ControllerBase
- {
- private readonly SnowflakeId _snowflakeId;
- private readonly AzureCosmosFactory _azureCosmos;
- private readonly DingDing _dingDing;
- private readonly Option _option;
- private readonly AzureRedisFactory _azureRedis;
- private readonly HttpTrigger _httpTrigger;
- public KnowledgesController(HttpTrigger httpTrigger, AzureCosmosFactory azureCosmos, SnowflakeId snowflakeId, DingDing dingDing, IOptionsSnapshot<Option> option, AzureRedisFactory azureRedis)
- {
- _azureCosmos = azureCosmos;
- _snowflakeId = snowflakeId;
- _dingDing = dingDing;
- _option = option?.Value;
- _azureRedis = azureRedis;
- _httpTrigger = httpTrigger;
- }
- /**
- *
- {
- "periodId": "ca484aa8-e7b5-4a7c-8ef3-bd9e7b7d4fp2",
- "subjectId":"ac73f07d-2cc8-4174-85ae-b39cc5b6beef",
- "scope":"school",
- "owner":"hbcn",
- "points": [
- "一元一次方程","二元一次方程","一元二次方程","直线方程","三元一次方程","鸡兔同笼问题","微积分方程","函数有界性","函数单调性","函数奇偶性","函数周期性","函数连续性","函数凹凸性",
- "常函数","一次函数","二次函数","三次函数","四次函数","五次函数","幂函数","指数函数","对数函数","三角函数","反三角函数","常数函数",
- "正弦函数","余弦函数","正切函数","余切函数","正割函数","余割函数","正矢函数","余矢函数","半正矢函数","半余矢函数","外正割函数","外余割函数"
- ],
- "blocks":[
- {
- "name": "方程式" ,
- "points":["一元一次方程","二元一次方程","一元二次方程","直线方程","三元一次方程","鸡兔同笼问题","微积分方程"]
- },
- {
- "name": "函数的特性" ,
- "points": ["函数有界性","函数单调性","函数奇偶性","函数周期性","函数连续性","函数凹凸性"]
- },
- {
- "name": "多项式函数" ,
- "points": ["常函数","一次函数","二次函数","三次函数","四次函数","五次函数"]
- },
- {
- "name": "基本初等函数" ,
- "points": ["幂函数","指数函数","对数函数","三角函数","反三角函数","常数函数"]
- },
- {
- "name": "三角函数" ,
- "points":["正弦函数","余弦函数","正切函数","余切函数","正割函数","余割函数","正矢函数","余矢函数","半正矢函数","半余矢函数","外正割函数","外余割函数"]
- }
- ]
- }
- */
- [ProducesDefaultResponseType]
- [HttpPost("upsert")]
- [Authorize(Roles = "IES")]
- [AuthToken(Roles = "admin", Permissions = "knowledge-upd")]
- public async Task<IActionResult> Upsert(Knowledge knowledge)
- {
- var client = _azureCosmos.GetCosmosClient();
- knowledge.code = $"Knowledge-{knowledge.owner}-{knowledge.subjectId}";
- StringBuilder sql = new StringBuilder($"select value(c) from c where c.periodId = '{knowledge.periodId}'");
- Knowledge old = null;
- await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryIterator<Knowledge>(queryText: sql.ToString(), requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"{ knowledge.code}") }))
- {
- old = item;
- break;
- }
- if (old != null)
- {
- knowledge.id = old.id;
- knowledge = await client.GetContainer(Constant.TEAMModelOS, "School").ReplaceItemAsync(knowledge, old.id, new PartitionKey($"{knowledge.code}"));
- }
- else
- {
- knowledge.id = Guid.NewGuid().ToString();
- knowledge = await client.GetContainer(Constant.TEAMModelOS, "School").CreateItemAsync(knowledge, new PartitionKey($"{knowledge.code}"));
- }
- var count = new { pcount = knowledge.points != null ? knowledge.points.Count : 0, bcount = knowledge.blocks != null ? knowledge.blocks.Count : 0 };
- //处理知识点,知识块计数问题
- await _azureRedis.GetRedisClient(8).HashSetAsync($"Knowledge:Count:{knowledge.owner}-{knowledge.subjectId}", knowledge.periodId, count.ToJsonString());
- return Ok(knowledge);
- }
- [ProducesDefaultResponseType]
- [HttpPost("upsert-knowledge")]
- [Authorize(Roles = "IES")]
- [AuthToken(Roles = "admin", Permissions = "knowledge-upd")]
- public async Task<IActionResult> UpsertKnowledge(JsonElement json)
- {
- if (!json.TryGetProperty("school", out JsonElement school)) return BadRequest();
- Knowledge knowledge = json.GetProperty("knowledge").ToObject<Knowledge>();
- List<OldNew> old_new = null;
- if (json.TryGetProperty("old_new", out JsonElement _old_new))
- {
- old_new = _old_new.ToObject<List<OldNew>>();
- }
- ValidResult validResult = knowledge.IsValid();
- if (!validResult.isVaild)
- {
- return BadRequest(validResult);
- }
- var client = _azureCosmos.GetCosmosClient();
- knowledge.code = $"Knowledge-{knowledge.owner}-{knowledge.subjectId}";
- StringBuilder sql = new StringBuilder($"select value(c) from c where c.periodId = '{knowledge.periodId}'");
- Knowledge old = null;
- await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryIterator<Knowledge>(queryText: sql.ToString(), requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"{ knowledge.code}") }))
- {
- old = item;
- break;
- }
- if (old != null)
- {
- knowledge.id = old.id;
- knowledge = await client.GetContainer(Constant.TEAMModelOS, "School").ReplaceItemAsync(knowledge, old.id, new PartitionKey($"{knowledge.code}"));
- }
- else
- {
- knowledge.id = Guid.NewGuid().ToString();
- knowledge = await client.GetContainer(Constant.TEAMModelOS, "School").CreateItemAsync(knowledge, new PartitionKey($"{knowledge.code}"));
- }
- var count = new { pcount = knowledge.points != null ? knowledge.points.Count : 0, bcount = knowledge.blocks != null ? knowledge.blocks.Count : 0 };
- //处理知识点,知识块计数问题
- await _azureRedis.GetRedisClient(8).HashSetAsync($"Knowledge:Count:{knowledge.owner}-{knowledge.subjectId}", knowledge.periodId, count.ToJsonString());
- if (old_new.IsNotEmpty() && old != null && knowledge != null)
- {
- var _old = old_new.Select(x => x._old).ToList();
- var notinold = _old.Except(old.points);
- if (notinold != null && notinold.Count() > 0)
- {
- return BadRequest($"{notinold.ToJsonString()} 不存在原来的知识点中");
- }
- var _new = old_new.Select(x => x._new).Where(z => !string.IsNullOrEmpty(z));
- if (_new != null && _new.Count() > 0)
- {
- var notinnew = _new.Except(knowledge.points);
- if (notinnew != null && notinnew.Count() > 0)
- {
- return BadRequest($"{notinnew.ToJsonString()} 不存在新的知识点中");
- }
- }
- _ = _httpTrigger.RequestHttpTrigger(new { old_new = old_new, school = $"{school}" }, _option.Location, "knowledge-change");
- }
- return Ok(knowledge);
- }
- /// <summary>
- ///
- /// "periodId": "ca484aa8-e7b5-4a7c-8ef3-bd9e7b7d4fp2",
- /// "subjectId":"ac73f07d-2cc8-4174-85ae-b39cc5b6beef",
- /// "owner":"hbcn",
- /// "points":["11111"]
- /// </summary>
- /// <param name="knowledge"></param>
- /// <returns></returns>
- [ProducesDefaultResponseType]
- [HttpPost("item-import")]
- [Authorize(Roles = "IES")]
- [AuthToken(Roles = "admin", Permissions = "knowledge-upd")]
- public async Task<IActionResult> ItemImport(Knowledge dto)
- {
- var client = _azureCosmos.GetCosmosClient();
- dto.code = $"Knowledge-{dto.owner}-{dto.subjectId}";
- StringBuilder sql = new StringBuilder($"select value(c) from c where c.periodId = '{dto.periodId}'");
- Knowledge knowledge = null;
- await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryIterator<Knowledge>(
- queryText: sql.ToString(), requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"{ dto.code}") }))
- {
- knowledge = item;
- break;
- }
- if (knowledge != null)
- {
- var notin = dto.points.Where(x => !knowledge.points.Any(y => y.Equals(x))).ToList();
- if (notin.IsNotEmpty())
- {
- knowledge.points.AddRange(notin);
- knowledge = await client.GetContainer(Constant.TEAMModelOS, "School").ReplaceItemAsync(knowledge, knowledge.id, new PartitionKey($"{knowledge.code}"));
- }
- }
- else
- {
- knowledge = dto;
- knowledge.id = Guid.NewGuid().ToString();
- knowledge.points = dto.points;
- knowledge = await client.GetContainer(Constant.TEAMModelOS, "School").CreateItemAsync(knowledge, new PartitionKey($"{knowledge.code}"));
- }
- var count = new { pcount = knowledge.points != null ? knowledge.points.Count : 0, bcount = knowledge.blocks != null ? knowledge.blocks.Count : 0 };
- //处理知识点,知识块计数问题
- await _azureRedis.GetRedisClient(8).HashSetAsync($"Knowledge:Count:{knowledge.owner}-{knowledge.subjectId}", knowledge.periodId, count.ToJsonString());
- return Ok(new { knowledge });
- }
- /// <summary>
- /**
-
- {
- !"hbcn-ac73f07d-2cc8-4174-85ae-b39cc5b6beef":"ca484aa8-e7b5-4a7c-8ef3-bd9e7b7d4fp2",
- }
-
- 单个Item查询一个学校某个科目知识点,知识块数量,如果需要确定某一个学段,则需要加学段。
- **/
- /// </summary>
- /// <param name="request"></param>
- /// <returns></returns>
- [ProducesDefaultResponseType]
- [HttpPost("find-count")]
- [AuthToken(Roles = "teacher,admin,student", Permissions = "knowledge-read,knowledge-upd")]
- public async Task<IActionResult> FindCount(Dictionary<string, string> request)
- {
- var (userid, _, _, school) = HttpContext.GetAuthTokenInfo();
- List<dynamic> datas = new List<dynamic>();
- foreach (var kp in request)
- {
- var countPoint = 0;
- var countBlock = 0;
- if (!string.IsNullOrWhiteSpace(kp.Value))
- {
- var value = await _azureRedis.GetRedisClient(8).HashGetAsync($"Knowledge:Count:{kp.Key}", kp.Value);
- if (value != default && !value.IsNullOrEmpty)
- {
- JsonElement record = value.ToString().ToObject<JsonElement>();
- if (record.TryGetProperty("pcount", out JsonElement pcout))
- {
- int.TryParse($"{pcout}", out countPoint);
- }
- if (record.TryGetProperty("bcount", out JsonElement bcout))
- {
- int.TryParse($"{bcout}", out countBlock);
- }
- if (countPoint == 0)
- {
- }
- }
- }
- else
- {
- var values = await _azureRedis.GetRedisClient(8).HashGetAllAsync($"Knowledge:Count:{kp.Key}");
- if (values != null)
- {
- foreach (var value in values)
- {
- JsonElement record = value.ToString().ToObject<JsonElement>();
- if (record.TryGetProperty("pcount", out JsonElement pcout))
- {
- if (int.TryParse($"{pcout}", out int countP))
- {
- countPoint = countPoint + countP;
- }
- }
- if (record.TryGetProperty("bcount", out JsonElement bcout))
- {
- if (int.TryParse($"{bcout}", out int countB))
- {
- countBlock = countBlock + countB;
- }
- }
- }
- }
- }
- datas.Add(new { key = kp.Key, countPoint, countBlock });
- }
- return Ok(new { datas });
- }
- /**
- * {
- ?"periodId": "ca484aa8-e7b5-4a7c-8ef3-bd9e7b7d4fp2",
- !"subjectId": "ac73f07d-2cc8-4174-85ae-b39cc5b6beef",
- !"school_code": "hbcn"
- }
- **/
- [ProducesDefaultResponseType]
- [HttpPost("find")]
- [AuthToken(Roles = "teacher,admin,student", Permissions = "knowledge-read,knowledge-upd")]
- public async Task<IActionResult> Find(JsonElement request)
- {
- var client = _azureCosmos.GetCosmosClient();
- request.TryGetProperty("periodId", out JsonElement periodId);
- if (!request.TryGetProperty("subjectId", out JsonElement subjectId)) return BadRequest();
- if (!request.TryGetProperty("school_code", out JsonElement school_code)) return BadRequest();
- string code = $"Knowledge-{school_code}-{subjectId}";
- StringBuilder sql = new StringBuilder($"select value(c) from c");
- if (periodId.ValueKind.Equals(JsonValueKind.String))
- {
- sql.Append($" where c.periodId = '{periodId}'");
- }
- List<Knowledge> knowledges = new List<Knowledge>();
- await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryIterator<Knowledge>(queryText: sql.ToString(), requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"{code}") }))
- {
- knowledges.Add(item);
- }
- return Ok(knowledges);
- }
- }
- }
- using Newtonsoft.Json.Linq;
- using System;
- using System.Collections.Generic;
- using System.ComponentModel;
- using System.Net.Http;
- using System.Reflection;
- using System.Text;
- using System.Threading.Tasks;
- using System.Security.Cryptography;
- using System.Net.Http.Json;
- using System.Text.Json;
- using System.IO;
- using TEAMModelOS.SDK.Extension;
- using System.Net;
- namespace TEAMModelOS.SDK.DI
- {
- public class HttpTrigger
- {
- private readonly HttpClient _httpClient;
- public HttpTrigger(HttpClient httpClient)
- {
- _httpClient = httpClient;
- }
- // <summary>
- /// 请求信息
- /// </summary>
- /// <param name="robotUrl">釘釘Robot發送Url</param>
- /// <param name="secret">加簽密鑰</param>
- /// <param name="msg">發送訊息</param>
- /// <returns></returns>
- public async Task<(int status, string json)> RequestHttpTrigger(object data, string location, string url)
- {
- var keys = HttpTriggerUrl.HttpTrigger地址.GetDescriptionText().Split(',');
- string domain = "";
- if (location.Equals("China-Dep"))
- {
- domain = keys[1];
- }
- else if (location.Equals("China-Test"))
- {
- domain = keys[1];
- }
- else if (location.Equals("China"))
- {
- domain = keys[2];
- }
- else if (location.Equals("Global-Dep"))
- {
- domain = keys[4];
- }
- else if (location.Equals("Global-Test"))
- {
- domain = keys[4];
- }
- else if (location.Equals("Global"))
- {
- domain = keys[5];
- }
- string link = domain.Contains("localhost") ? $"http://{domain}/api/{url}" : $"http://{domain}/api/{url}";
- HttpContent httpContent = new StringContent(data.ToJsonString());
- HttpResponseMessage responseMessage = await _httpClient.PostAsync(link, httpContent);
- if (responseMessage.StatusCode == HttpStatusCode.OK)
- {
- string Content = await responseMessage.Content.ReadAsStringAsync();
- Content.ToObject<JsonElement>().TryGetProperty("data", out JsonElement content);
- return (200, $"{content}");
- }
- else
- {
- string Content = await responseMessage.Content?.ReadAsStringAsync();
- return (500, Content);
- }
- }
- }
- public enum HttpTriggerUrl
- {
- [Description("localhost:7071,teammodelosfunction-test.chinacloudsites.cn,teammodelosfunction.chinacloudsites.cn,teammodelosfunction.chinacloudsites.cn,teammodelosfunction.chinacloudsites.cn")]
- HttpTrigger地址,
- }
- }
|