TestController.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289
  1. using Azure.Cosmos;
  2. using Microsoft.AspNetCore.Http;
  3. using Microsoft.AspNetCore.Mvc;
  4. using Newtonsoft.Json;
  5. using StackExchange.Redis;
  6. using System;
  7. using System.Collections.Generic;
  8. using System.IO;
  9. using System.Linq;
  10. using System.Net;
  11. using System.Net.Http;
  12. using System.Net.Http.Json;
  13. using System.Text;
  14. using System.Text.Json;
  15. using System.Threading.Tasks;
  16. using TEAMModelOS.SDK.DI;
  17. using TEAMModelOS.SDK.Extension;
  18. using TEAMModelOS.SDK.Models;
  19. using TEAMModelOS.SDK.Models.Cosmos.Common;
  20. using TEAMModelOS.Services.Common;
  21. namespace TEAMModelOS.Controllers
  22. {
  23. [Route("test")]
  24. [ApiController]
  25. public class TestController :ControllerBase
  26. {
  27. private readonly AzureStorageFactory _azureStorage;
  28. private readonly AzureRedisFactory _azureRedis;
  29. private readonly AzureCosmosFactory _azureCosmos;
  30. private readonly DingDing _dingDing;
  31. public TestController(AzureCosmosFactory azureCosmos, AzureRedisFactory azureRedis, AzureStorageFactory azureStorage, DingDing dingDing) {
  32. _azureCosmos = azureCosmos;
  33. _azureRedis = azureRedis;
  34. _azureStorage = azureStorage;
  35. _dingDing = dingDing;
  36. }
  37. /// <summary>
  38. /// 测试blob多线程写入同一个文件
  39. /// </summary>
  40. /// <returns></returns>
  41. [ProducesDefaultResponseType]
  42. [HttpPost("blobroot")]
  43. public async Task<IActionResult> MultipleBlob(JsonElement jsonMsg) {
  44. if (jsonMsg.TryGetProperty("name", out JsonElement name) && name.ValueKind == JsonValueKind.String
  45. && jsonMsg.TryGetProperty("root", out JsonElement root) && root.ValueKind == JsonValueKind.String)
  46. {
  47. List<Dictionary<string, double?>> list = new List<Dictionary<string, double?>>();
  48. string u = System.Web.HttpUtility.UrlDecode($"{root}", Encoding.UTF8).Split("/")[0];
  49. var client = _azureStorage.GetBlobContainerClient($"{name}");
  50. var size = await client.GetBlobsSize(u);
  51. await _azureRedis.GetRedisClient(8).SortedSetRemoveAsync($"Blob:Catalog:{name}", u);
  52. await _azureRedis.GetRedisClient(8).SortedSetIncrementAsync($"Blob:Catalog:{name}", u, size.HasValue ? size.Value : 0);
  53. var scores = await _azureRedis.GetRedisClient(8).SortedSetRangeByRankWithScoresAsync($"Blob:Catalog:{name}");
  54. double blobsize = 0;
  55. if (scores != default && scores != null)
  56. {
  57. foreach (var score in scores)
  58. {
  59. blobsize = blobsize + score.Score;
  60. list.Add(new Dictionary<string, double?>() { { score.Element.ToString(), score.Score } });
  61. }
  62. }
  63. await _azureRedis.GetRedisClient(8).HashSetAsync($"Blob:Record", new RedisValue($"{name}"), new RedisValue($"{blobsize}"));
  64. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-ServiceBus,Blob() 容器:{name}使用:{root},文件分类:{list.ToJsonString()}",
  65. GroupNames.成都开发測試群組);
  66. return Ok(list);
  67. }
  68. else {
  69. return Ok();
  70. }
  71. }
  72. private async Task<int> SendNotification( )
  73. {
  74. HttpClient _httpClient = new HttpClient();
  75. // _httpClient.DefaultRequestHeaders.Add("Authorization", $"Bearer {token.AccessToken}");
  76. var pa = new { grant_type = "device", client_id= "9794e418-c4ef-4fd5-a42d-accaa2d96d6e" , client_secret = "ruL?I79h0w1AZaZXtBaZeZuQLQXLa=:-" };
  77. HttpResponseMessage responseMessage = await _httpClient.PostAsJsonAsync("https://api2-rc.teammodel.net/oauth2/token", pa);
  78. if (responseMessage.StatusCode == HttpStatusCode.OK)
  79. {
  80. return 200;
  81. }
  82. else if (responseMessage.StatusCode == HttpStatusCode.Unauthorized)
  83. {
  84. return 401;
  85. }
  86. else
  87. {
  88. return 500;
  89. }
  90. }
  91. /// <summary>
  92. /// 测试redis通配符
  93. /// </summary>
  94. /// <param name="request"></param>
  95. /// <returns></returns>
  96. [ProducesDefaultResponseType]
  97. [HttpGet("test-delete-read")]
  98. public async Task<IActionResult> TestDelete() {
  99. foreach (var cnt in _azureStorage.GetBlobServiceClient().GetBlobContainers()) {
  100. Console.WriteLine(cnt.Name);
  101. }
  102. await SendNotification();
  103. var client = _azureCosmos.GetCosmosClient();
  104. string aaa = "0";
  105. try {
  106. ItemResponse<Student> a = await client.GetContainer(Constant.TEAMModelOS, "Student").DeleteItemAsync<Student>("1111111", new PartitionKey($"Course-111111"));
  107. Ok(a.GetRawResponse().Status);
  108. } catch (CosmosException ex) {
  109. if (ex.Response.Status == 404) {
  110. aaa = "404";
  111. }
  112. }
  113. try
  114. {
  115. ItemResponse<Student> a = await client.GetContainer(Constant.TEAMModelOS, "Student").ReadItemAsync<Student>("1111111", new PartitionKey($"Course-111111"));
  116. Ok(a.GetRawResponse().Status);
  117. }
  118. catch (CosmosException ex)
  119. {
  120. if (ex.Response.Status == 404)
  121. {
  122. aaa = aaa+ " 404";
  123. }
  124. }
  125. try
  126. {
  127. var a = await client.GetContainer(Constant.TEAMModelOS, "Student").DeleteItemStreamAsync("1111111", new PartitionKey($"Course-111111"));
  128. Ok(a.Status);
  129. }
  130. catch (CosmosException ex)
  131. {
  132. if (ex.Response.Status == 404)
  133. {
  134. aaa = "404";
  135. }
  136. }
  137. try
  138. {
  139. var a = await client.GetContainer(Constant.TEAMModelOS, "Student").ReadItemStreamAsync("1111111", new PartitionKey($"Course-111111"));
  140. Ok(a.Status);
  141. }
  142. catch (CosmosException ex)
  143. {
  144. if (ex.Response.Status == 404)
  145. {
  146. aaa = aaa + " 404";
  147. }
  148. }
  149. return Ok(new { aaa });
  150. }
  151. /// <summary>
  152. /// 测试redis通配符
  153. /// </summary>
  154. /// <param name="request"></param>
  155. /// <returns></returns>
  156. [ProducesDefaultResponseType]
  157. [HttpGet("test-redis")]
  158. public async Task<IActionResult> TestRedis( ) {
  159. try
  160. {
  161. var client = _azureCosmos.GetCosmosClient();
  162. List<ItemInfo> items = new List<ItemInfo>();
  163. var queryslt = $"SELECT value(c) FROM c where c.pid = null ";
  164. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryIterator<ItemInfo>(queryText: queryslt, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Item-hbcn") }))
  165. {
  166. items.Add(item);
  167. }
  168. List<ItemCond> itemConds = new List<ItemCond>();
  169. items.GroupBy(x => x.periodId).Select(y => new { key = y.Key, list = y.ToList() }).ToList().ForEach(z => {
  170. ItemCond cond = new ItemCond() { id = z.key, code = $"ItemCond-hbcn", pk = "ItemCond", ttl = -1, count = z.list.Count, grades = new List<GradeCount>(), subjects = new List<SubjectCount>() };
  171. z.list.ForEach(y => {
  172. ItemService.CountItemCond(y, null, cond);
  173. });
  174. itemConds.Add(cond);
  175. });
  176. itemConds.ForEach(async cond =>
  177. {
  178. await client.GetContainer(Constant.TEAMModelOS, "School").UpsertItemAsync<ItemCond>(cond, new PartitionKey(cond.code));
  179. });
  180. return Ok(new { itemConds });
  181. }
  182. catch (Exception ex) { await _dingDing.SendBotMsg($"TEAMModelFunction,ActivityHttpTrigger,fix-itemcond()\n{ex.Message}{ex.StackTrace}", GroupNames.醍摩豆服務運維群組); }
  183. return Ok(new { });
  184. }
  185. /// <summary>
  186. /// 删除
  187. /// </summary>
  188. /// <param name="request"></param>
  189. /// <returns></returns>
  190. [ProducesDefaultResponseType]
  191. //[AuthToken(Roles = "teacher")]
  192. [HttpPost("fix-blob-content")]
  193. public async Task<IActionResult> FixBlobContent(JsonElement request)
  194. {
  195. try
  196. {
  197. if (!request.TryGetProperty("name", out JsonElement name)) return BadRequest();
  198. if (!request.TryGetProperty("scope", out JsonElement _scope)) return BadRequest();
  199. var client = _azureCosmos.GetCosmosClient();
  200. List<string> prefixs = new List<string>() { "audio", "doc", "image", "other", "res", "video", "thum" };
  201. var ContainerClient = _azureStorage.GetBlobContainerClient($"{name}");
  202. string scope = "private";
  203. scope = $"{_scope}";
  204. var tb = "Teacher";
  205. if (scope != "private")
  206. {
  207. tb = "School";
  208. }
  209. long now = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
  210. foreach (var prefix in prefixs)
  211. {
  212. List<string> items = await ContainerClient.List(prefix);
  213. foreach (var item in items)
  214. {
  215. var urlsSize = await ContainerClient.GetBlobsSize(item);
  216. Bloblog bloblog = new Bloblog { id = Guid.NewGuid().ToString(), code = $"Bloblog-{name}", pk = "Bloblog", time = now, size = urlsSize != null && urlsSize.HasValue ? urlsSize.Value : 0, type = prefix };
  217. await client.GetContainer(Constant.TEAMModelOS, tb).UpsertItemAsync(bloblog, new Azure.Cosmos.PartitionKey(bloblog.code)) ;
  218. }
  219. }
  220. return new OkObjectResult(new { });
  221. }
  222. catch (Exception ex)
  223. {
  224. await _dingDing.SendBotMsg($"TEAMModelFunction,ActivityHttpTrigger,fix-blob-content()\n{ex.Message}{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
  225. return new BadRequestResult();
  226. }
  227. }
  228. /// <summary>
  229. /// 删除
  230. /// </summary>
  231. /// <param name="request"></param>
  232. /// <returns></returns>
  233. [ProducesDefaultResponseType]
  234. //[AuthToken(Roles = "teacher")]
  235. [HttpPost("delete")]
  236. public async Task<IActionResult> Delete(JsonElement request)
  237. {
  238. try
  239. {
  240. var client = _azureCosmos.GetCosmosClient();
  241. var query = $"select c.id ,c.code from c where c.pk='StuCourse' ";
  242. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Teacher").GetItemQueryIterator<IdCode>(queryText: query))
  243. {
  244. await client.GetContainer(Constant.TEAMModelOS, "Teacher").DeleteItemStreamAsync(item.id, new PartitionKey(item.code));
  245. }
  246. return Ok(new { code = 1 });
  247. }
  248. catch (Exception e)
  249. {
  250. return BadRequest(e.StackTrace);
  251. }
  252. }
  253. }
  254. public class IdCode
  255. {
  256. public string id { get; set; }
  257. public string code { get; set; }
  258. }
  259. }