TestController.cs 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597
  1. using Azure.Cosmos;
  2. using Azure.Messaging.ServiceBus;
  3. using Azure.Storage.Blobs.Models;
  4. using HTEXLib.COMM.Helpers;
  5. using HTEXLib.Helpers.ShapeHelpers;
  6. using Microsoft.AspNetCore.Hosting;
  7. using Microsoft.AspNetCore.Http;
  8. using Microsoft.AspNetCore.Mvc;
  9. using Microsoft.Extensions.Configuration;
  10. using Microsoft.International.Converters.PinYinConverter;
  11. using Microsoft.International.Converters.TraditionalChineseToSimplifiedConverter;
  12. using Newtonsoft.Json;
  13. using StackExchange.Redis;
  14. using System;
  15. using System.Collections.Generic;
  16. using System.IO;
  17. using System.Linq;
  18. using System.Net;
  19. using System.Net.Http;
  20. using System.Net.Http.Json;
  21. using System.Text;
  22. using System.Text.Json;
  23. using System.Text.RegularExpressions;
  24. using System.Threading.Tasks;
  25. using TEAMModelOS.SDK;
  26. using TEAMModelOS.SDK.DI;
  27. using TEAMModelOS.SDK.Extension;
  28. using TEAMModelOS.SDK.Models;
  29. using TEAMModelOS.SDK.Models.Cosmos.Common;
  30. using TEAMModelOS.Services.Common;
  31. using static TEAMModelOS.SDK.Models.Teacher;
  32. using static TEAMModelOS.SDK.SchoolService;
  33. namespace TEAMModelOS.Controllers
  34. {
  35. [Route("test")]
  36. [ApiController]
  37. public class TestController : ControllerBase
  38. {
  39. private readonly HttpClient _httpClient;
  40. public IWebHostEnvironment _environment { get; set; }
  41. private readonly AzureStorageFactory _azureStorage;
  42. private readonly AzureRedisFactory _azureRedis;
  43. private readonly AzureCosmosFactory _azureCosmos;
  44. private readonly DingDing _dingDing;
  45. private readonly AzureServiceBusFactory _serviceBus;
  46. public IConfiguration _configuration { get; set; }
  47. public TestController(HttpClient httpClient,IWebHostEnvironment environment, AzureCosmosFactory azureCosmos, AzureRedisFactory azureRedis, AzureStorageFactory azureStorage, IConfiguration configuration, AzureServiceBusFactory serviceBus, DingDing dingDing)
  48. {
  49. _azureCosmos = azureCosmos;
  50. _azureRedis = azureRedis;
  51. _azureStorage = azureStorage;
  52. _dingDing = dingDing;
  53. _serviceBus = serviceBus; _configuration = configuration;
  54. _environment = environment;
  55. _httpClient= httpClient;
  56. }
  57. /*
  58. [
  59. {"method":"台北市","params":{"CountryId":"TW","CityId":"30"}},1
  60. {"method":"新北市","params":{"CountryId":"TW","CityId":"01"}},1
  61. {"method":"桃园市","params":{"CountryId":"TW","CityId":"03"}},1
  62. {"method":"台中市","params":{"CountryId":"TW","CityId":"66"}},1
  63. {"method":"台南市","params":{"CountryId":"TW","CityId":"67"}},1
  64. {"method":"高雄市","params":{"CountryId":"TW","CityId":"64"}},1
  65. {"method":"基隆市","params":{"CountryId":"TW","CityId":"17"}},1
  66. {"method":"新竹市","params":{"CountryId":"TW","CityId":"18"}},1
  67. {"method":"嘉义市","params":{"CountryId":"TW","CityId":"20"}},1
  68. {"method":"新竹县","params":{"CountryId":"TW","CityId":"04"}},1
  69. {"method":"苗栗县","params":{"CountryId":"TW","CityId":"05"}},1
  70. {"method":"彰化县","params":{"CountryId":"TW","CityId":"07"}},1
  71. {"method":"南投县","params":{"CountryId":"TW","CityId":"08"}},1
  72. {"method":"云林县","params":{"CountryId":"TW","CityId":"09"}},1
  73. {"method":"嘉义县","params":{"CountryId":"TW","CityId":"10"}},1
  74. {"method":"屏东县","params":{"CountryId":"TW","CityId":"13"}},1
  75. {"method":"宜兰县","params":{"CountryId":"TW","CityId":"02"}},1
  76. {"method":"花莲县","params":{"CountryId":"TW","CityId":"15"}},1
  77. {"method":"台东县","params":{"CountryId":"TW","CityId":"14"}},1
  78. {"method":"澎湖县","params":{"CountryId":"TW","CityId":"16"}},1
  79. {"method":"金门县","params":{"CountryId":"TW","CityId":"71"}},
  80. {"method":"连江县","params":{"CountryId":"TW","CityId":"72"}}
  81. ]
  82. */
  83. /// <summary>
  84. /// 测试blob多线程写入同一个文件
  85. /// </summary>
  86. /// <returns></returns>
  87. [ProducesDefaultResponseType]
  88. [HttpPost("get-schools")]
  89. public async Task<IActionResult> GetSchools(JsonElement json) {
  90. string msg = "{\"standard\":\"standard3\",\"tmdids\":[\"1635136038\"],\"school\":\"pbjyey\",\"update\":[\"TeacherAbility\"],\"statistics\":0}";
  91. try
  92. {
  93. // await _dingDing.SendBotMsg($"teacher-train-change\n{msg}",GroupNames.成都开发測試群組);
  94. TeacherTrainChange change = msg.ToObject<TeacherTrainChange>();
  95. var client = _azureCosmos.GetCosmosClient();
  96. string insql = $"where c.id in ({string.Join(",", change.tmdids.Select(x => $"'{x}'"))})";
  97. string selsql = $"select value(c) from c {insql} ";
  98. List<TeacherTrain> teacherTrains = new List<TeacherTrain>();
  99. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Teacher").GetItemQueryIterator<TeacherTrain>(queryText: selsql,
  100. requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"TeacherTrain-{change.school}") }))
  101. {
  102. teacherTrains.Add(item);
  103. }
  104. if (change.statistics != 1)
  105. {
  106. List<Task<ItemResponse<TeacherTrain>>> task = new List<Task<ItemResponse<TeacherTrain>>>();
  107. teacherTrains.ForEach(x =>
  108. {
  109. x.update.UnionWith(change.update);
  110. task.Add(client.GetContainer(Constant.TEAMModelOS, "Teacher").ReplaceItemAsync<TeacherTrain>(x, x.id, new PartitionKey($"TeacherTrain-{change.school}")));
  111. });
  112. await task.TaskPage(5);
  113. var unchange = change.tmdids.Except(teacherTrains.Select(x => x.id));
  114. if (unchange != null)
  115. {
  116. task.Clear();
  117. unchange.ToList().ForEach(x =>
  118. {
  119. TeacherTrain teacherTrain = new TeacherTrain
  120. {
  121. pk = "TeacherTrain",
  122. id = x,
  123. code = $"TeacherTrain-{change.school}",
  124. tmdid = x,
  125. school = change.school,
  126. update = new HashSet<string> { StatisticsService.TeacherAbility,
  127. StatisticsService.TeacherClass, StatisticsService.OfflineRecord }
  128. };
  129. teacherTrain.update.UnionWith(change.update);
  130. task.Add(client.GetContainer(Constant.TEAMModelOS, "Teacher").UpsertItemAsync<TeacherTrain>(teacherTrain, new PartitionKey($"TeacherTrain-{change.school}")));
  131. });
  132. await task.TaskPage(1);
  133. }
  134. }
  135. else
  136. {
  137. Area area = null;
  138. string sql = $"select value(c) from c where c.standard='{change.standard}'";
  139. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Normal").GetItemQueryIterator<Area>(queryText: sql,
  140. requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Base-Area") }))
  141. {
  142. area = item;
  143. }
  144. AreaSetting setting = null;
  145. if (area != null)
  146. {
  147. try
  148. {
  149. //优先找校级
  150. setting = await client.GetContainer(Constant.TEAMModelOS, "School").ReadItemAsync<AreaSetting>(change.school, new PartitionKey("AreaSetting"));
  151. }
  152. catch (CosmosException)
  153. {
  154. try
  155. {
  156. setting = await client.GetContainer(Constant.TEAMModelOS, "Normal").ReadItemAsync<AreaSetting>(area.id, new PartitionKey("AreaSetting"));
  157. }
  158. catch (CosmosException)
  159. {
  160. setting = null;
  161. }
  162. }
  163. }
  164. if (setting == null)
  165. {
  166. setting = new AreaSetting
  167. {
  168. allTime = 50,
  169. classTime = 5,
  170. submitTime = 15,
  171. onlineTime = 20,
  172. offlineTime = 10,
  173. lessonMinutes = 45,
  174. };
  175. }
  176. List<Task<TeacherTrain>> task = new List<Task<TeacherTrain>>();
  177. teacherTrains.ForEach(x =>
  178. {
  179. x.update.UnionWith(change.update);
  180. task.Add(StatisticsService.StatisticsTeacher(x, setting, area, client, null));
  181. });
  182. await task.TaskPage(1);
  183. var unchange = change.tmdids.Except(teacherTrains.Select(x => x.id));
  184. if (unchange != null)
  185. {
  186. task.Clear();
  187. unchange.ToList().ForEach(x =>
  188. {
  189. task.Add(StatisticsService.StatisticsTeacher(new TeacherTrain
  190. {
  191. pk = "TeacherTrain",
  192. id = x,
  193. code = $"TeacherTrain-{change.school}",
  194. tmdid = x,
  195. school = change.school,
  196. update = new HashSet<string> { StatisticsService.TeacherAbility,
  197. StatisticsService.TeacherClass, StatisticsService.OfflineRecord }
  198. }, setting, area, client, null));
  199. });
  200. await task.TaskPage(1);
  201. }
  202. }
  203. }
  204. catch (CosmosException ex)
  205. {
  206. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-研修数据变更,重新统计-TeacherTrainChange\n{msg}\n{ex.Message}\n{ex.StackTrace}CosmosException{ex.Status}", GroupNames.成都开发測試群組);
  207. }
  208. catch (Exception ex)
  209. {
  210. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-研修数据变更,重新统计-TeacherTrainChange\n{msg}\n{ex.Message}\n{ex.StackTrace}", GroupNames.成都开发測試群組);
  211. }
  212. /*
  213. string path = $"{_environment.ContentRootPath}/JsonFile/Core/city.json";
  214. StreamReader streamReader = new StreamReader(new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite), Encoding.UTF8);
  215. StringBuilder stringBuilder = new StringBuilder();
  216. string text;
  217. while ((text = streamReader.ReadLine()) != null)
  218. {
  219. stringBuilder.Append(text.ToString());
  220. }
  221. streamReader.Close();
  222. string input = stringBuilder.ToString();
  223. List<string> region = new List<string>() {
  224. "110000", "110100", "110200",
  225. "120000", "120100", "120200",
  226. "310000", "310100", "310200",
  227. "500000", "500100", "810100",
  228. "810200", "810300", "820100",
  229. "820200", "820300"
  230. };
  231. List<string> cityids = new List<string>() {
  232. "30","01","03","66","67","64","17","18","20","04","05","07","08","09","10","13","02","15","14","16","71","72"
  233. };
  234. Dictionary<string, List<CodeName>> regions = input.ToObject<Dictionary<string, List<CodeName>>>();
  235. List<List<string>> datas = new List<List<string>>() { region };
  236. foreach (var r in regions)
  237. {
  238. if (!region.Contains(r.Key) && !r.Key.StartsWith("71"))
  239. {
  240. datas.Add(r.Value.Select(x => x.code).ToList());
  241. }
  242. }
  243. List<Task<List<SchoolInfo>>> tasks = new List<Task<List<SchoolInfo>>>();
  244. //datas.ForEach(x =>
  245. //{
  246. // tasks.Add(GetSchoolAsync(x));
  247. //});
  248. List<SchoolInfo> schoolInfos = new List<SchoolInfo>();
  249. //var schools = await Task.WhenAll(tasks);
  250. //var schools =await GetSchoolAsync(cityids);
  251. // schoolInfos.AddRange(schools);
  252. //foreach (var schs in schools)
  253. //{
  254. // schoolInfos.AddRange(schs);
  255. //}
  256. List<string> nodatas = new List<string>();
  257. foreach (var data in datas) {
  258. (List<SchoolInfo> schoolIn, List<string> nodata) = await GetSchoolAsync(data);
  259. schoolInfos.AddRange(schoolIn);
  260. nodatas.AddRange(nodata);
  261. }
  262. await _dingDing.SendBotMsg($"os,test,{nodatas.ToJsonString()}", GroupNames.成都开发測試群組);
  263. return Ok(schoolInfos);
  264. */
  265. return Ok();
  266. }
  267. public async Task<(List<SchoolInfo> schoolInfos,List<string> nodata)> GetSchoolAsync(List<string> regions) {
  268. List < SchoolInfo > schools= new List<SchoolInfo>();
  269. List<string> nodata = new List<string>();
  270. foreach (var region in regions) {
  271. Dictionary<string, object> data = new Dictionary<string, object>();
  272. data.Add("method", "api/School/getSchool");
  273. data.Add("params", new { CountryId = "CN", CityId = region });
  274. HttpResponseMessage responseMessage = await _httpClient.PostAsJsonAsync("https://contest.teammodel.cn/api/School/getSchool", data);
  275. if (responseMessage.StatusCode == HttpStatusCode.OK)
  276. {
  277. string Content = await responseMessage.Content.ReadAsStringAsync();
  278. try {
  279. Content.ToObject<JsonElement>().TryGetProperty("result", out JsonElement content);
  280. if (content.ValueKind.Equals(JsonValueKind.Object) && content.TryGetProperty("data", out JsonElement _data))
  281. {
  282. if (_data.ValueKind.Equals(JsonValueKind.Array))
  283. {
  284. List<SchoolInfo> infos = _data.ToObject<List<SchoolInfo>>();
  285. if (infos.IsNotEmpty())
  286. {
  287. schools.AddRange(infos.Where(x => x.name != null && x.cityName != null).ToList());
  288. }
  289. }
  290. else {
  291. nodata.Add(data.ToJsonString());
  292. continue;
  293. }
  294. }
  295. else { nodata.Add(data.ToJsonString());
  296. continue; }
  297. } catch (Exception ex) {
  298. nodata.Add(data.ToJsonString());
  299. throw new Exception(ex.Message,ex.InnerException);
  300. }
  301. }
  302. }
  303. return (schools, nodata);
  304. }
  305. public class SchoolInfo
  306. {
  307. public string typeName { get; set; }
  308. public string provinceName { get; set; }
  309. public string provinceId { get; set; }
  310. public string id { get; set; }
  311. public string name { get; set; }
  312. public string cityId { get; set; }
  313. public string cityName { get; set; }
  314. public string address { get; set; }
  315. }
  316. public class CodeName
  317. {
  318. public string code { get; set; }
  319. public string name { get; set; }
  320. }
  321. /// <summary>
  322. /// 测试blob多线程写入同一个文件
  323. /// </summary>
  324. /// <returns></returns>
  325. [ProducesDefaultResponseType]
  326. [HttpPost("generate-school-codes")]
  327. public async Task<IActionResult> GenerateSchoolCodes(JsonElement json)
  328. {
  329. List<SchoolData> schoolss = json.GetProperty("schools").ToObject<List<SchoolData>>();
  330. dynamic data = await SchoolService.GenerateSchoolCode(schoolss, _dingDing, _environment);
  331. return Ok(data);
  332. }
  333. /// <summary>
  334. /// 测试blob多线程写入同一个文件
  335. /// </summary>
  336. /// <returns></returns>
  337. [ProducesDefaultResponseType]
  338. [HttpPost("blobroot")]
  339. public async Task<IActionResult> MultipleBlob(JsonElement jsonMsg)
  340. {
  341. if (jsonMsg.TryGetProperty("name", out JsonElement name) && name.ValueKind == JsonValueKind.String
  342. && jsonMsg.TryGetProperty("root", out JsonElement root) && root.ValueKind == JsonValueKind.String)
  343. {
  344. List<Dictionary<string, double?>> list = new List<Dictionary<string, double?>>();
  345. string u = System.Web.HttpUtility.UrlDecode($"{root}", Encoding.UTF8).Split("/")[0];
  346. var client = _azureStorage.GetBlobContainerClient($"{name}");
  347. var size = await client.GetBlobsSize(u);
  348. await _azureRedis.GetRedisClient(8).SortedSetRemoveAsync($"Blob:Catalog:{name}", u);
  349. await _azureRedis.GetRedisClient(8).SortedSetIncrementAsync($"Blob:Catalog:{name}", u, size.HasValue ? size.Value : 0);
  350. var scores = await _azureRedis.GetRedisClient(8).SortedSetRangeByRankWithScoresAsync($"Blob:Catalog:{name}");
  351. double blobsize = 0;
  352. if (scores != default && scores != null)
  353. {
  354. foreach (var score in scores)
  355. {
  356. blobsize = blobsize + score.Score;
  357. list.Add(new Dictionary<string, double?>() { { score.Element.ToString(), score.Score } });
  358. }
  359. }
  360. await _azureRedis.GetRedisClient(8).HashSetAsync($"Blob:Record", new RedisValue($"{name}"), new RedisValue($"{blobsize}"));
  361. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-ServiceBus,Blob() 容器:{name}使用:{root},文件分类:{list.ToJsonString()}",
  362. GroupNames.成都开发測試群組);
  363. return Ok(list);
  364. }
  365. else
  366. {
  367. return Ok();
  368. }
  369. }
  370. private async Task<int> SendNotification()
  371. {
  372. HttpClient _httpClient = new HttpClient();
  373. // _httpClient.DefaultRequestHeaders.Add("Authorization", $"Bearer {token.AccessToken}");
  374. var pa = new { grant_type = "device", client_id = "9794e418-c4ef-4fd5-a42d-accaa2d96d6e", client_secret = "ruL?I79h0w1AZaZXtBaZeZuQLQXLa=:-" };
  375. HttpResponseMessage responseMessage = await _httpClient.PostAsJsonAsync("https://api2-rc.teammodel.net/oauth2/token", pa);
  376. if (responseMessage.StatusCode == HttpStatusCode.OK)
  377. {
  378. return 200;
  379. }
  380. else if (responseMessage.StatusCode == HttpStatusCode.Unauthorized)
  381. {
  382. return 401;
  383. }
  384. else
  385. {
  386. return 500;
  387. }
  388. }
  389. /// <summary>
  390. /// 测试redis通配符
  391. /// </summary>
  392. /// <param name="request"></param>
  393. /// <returns></returns>
  394. [ProducesDefaultResponseType]
  395. [HttpGet("test-delete-read")]
  396. public async Task<IActionResult> TestDelete()
  397. {
  398. foreach (var cnt in _azureStorage.GetBlobServiceClient().GetBlobContainers())
  399. {
  400. Console.WriteLine(cnt.Name);
  401. }
  402. await SendNotification();
  403. var client = _azureCosmos.GetCosmosClient();
  404. string aaa = "0";
  405. try
  406. {
  407. ItemResponse<Student> a = await client.GetContainer(Constant.TEAMModelOS, "Student").DeleteItemAsync<Student>("1111111", new PartitionKey($"Course-111111"));
  408. Ok(a.GetRawResponse().Status);
  409. }
  410. catch (CosmosException ex)
  411. {
  412. if (ex.Response.Status == 404)
  413. {
  414. aaa = "404";
  415. }
  416. }
  417. try
  418. {
  419. ItemResponse<Student> a = await client.GetContainer(Constant.TEAMModelOS, "Student").ReadItemAsync<Student>("1111111", new PartitionKey($"Course-111111"));
  420. Ok(a.GetRawResponse().Status);
  421. }
  422. catch (CosmosException ex)
  423. {
  424. if (ex.Response.Status == 404)
  425. {
  426. aaa = aaa + " 404";
  427. }
  428. }
  429. try
  430. {
  431. var a = await client.GetContainer(Constant.TEAMModelOS, "Student").DeleteItemStreamAsync("1111111", new PartitionKey($"Course-111111"));
  432. Ok(a.Status);
  433. }
  434. catch (CosmosException ex)
  435. {
  436. if (ex.Response.Status == 404)
  437. {
  438. aaa = "404";
  439. }
  440. }
  441. try
  442. {
  443. var a = await client.GetContainer(Constant.TEAMModelOS, "Student").ReadItemStreamAsync("1111111", new PartitionKey($"Course-111111"));
  444. Ok(a.Status);
  445. }
  446. catch (CosmosException ex)
  447. {
  448. if (ex.Response.Status == 404)
  449. {
  450. aaa = aaa + " 404";
  451. }
  452. }
  453. return Ok(new { aaa });
  454. }
  455. /// <summary>
  456. /// 测试redis通配符
  457. /// </summary>
  458. /// <param name="request"></param>
  459. /// <returns></returns>
  460. [ProducesDefaultResponseType]
  461. [HttpGet("test-redis")]
  462. public async Task<IActionResult> TestRedis()
  463. {
  464. try
  465. {
  466. var client = _azureCosmos.GetCosmosClient();
  467. List<ItemInfo> items = new List<ItemInfo>();
  468. var queryslt = $"SELECT value(c) FROM c where c.pid = null ";
  469. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryIterator<ItemInfo>(queryText: queryslt, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Item-hbcn") }))
  470. {
  471. items.Add(item);
  472. }
  473. List<ItemCond> itemConds = new List<ItemCond>();
  474. items.GroupBy(x => x.periodId).Select(y => new { key = y.Key, list = y.ToList() }).ToList().ForEach(z =>
  475. {
  476. 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>() };
  477. z.list.ForEach(y =>
  478. {
  479. ItemService.CountItemCond(y, null, cond);
  480. });
  481. itemConds.Add(cond);
  482. });
  483. itemConds.ForEach(async cond =>
  484. {
  485. await client.GetContainer(Constant.TEAMModelOS, "School").UpsertItemAsync<ItemCond>(cond, new PartitionKey(cond.code));
  486. });
  487. return Ok(new { itemConds });
  488. }
  489. catch (Exception ex) { await _dingDing.SendBotMsg($"TEAMModelFunction,ActivityHttpTrigger,fix-itemcond()\n{ex.Message}{ex.StackTrace}", GroupNames.醍摩豆服務運維群組); }
  490. return Ok(new { });
  491. }
  492. /// <summary>
  493. /// 删除
  494. /// </summary>
  495. /// <param name="request"></param>
  496. /// <returns></returns>
  497. [ProducesDefaultResponseType]
  498. //[AuthToken(Roles = "teacher")]
  499. [HttpPost("fix-blob-content")]
  500. public async Task<IActionResult> FixBlobContent(JsonElement request)
  501. {
  502. try
  503. {
  504. if (!request.TryGetProperty("name", out JsonElement name)) return BadRequest();
  505. if (!request.TryGetProperty("scope", out JsonElement _scope)) return BadRequest();
  506. var client = _azureCosmos.GetCosmosClient();
  507. List<string> prefixs = new List<string>() { "audio", "doc", "image", "other", "res", "video", "thum" };
  508. var ContainerClient = _azureStorage.GetBlobContainerClient($"{name}");
  509. string scope = "private";
  510. scope = $"{_scope}";
  511. var tb = "Teacher";
  512. if (scope != "private")
  513. {
  514. tb = "School";
  515. }
  516. long now = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
  517. foreach (var prefix in prefixs)
  518. {
  519. List<string> items = await ContainerClient.List(prefix);
  520. foreach (var item in items)
  521. {
  522. var urlsSize = await ContainerClient.GetBlobsSize(item);
  523. 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 };
  524. await client.GetContainer(Constant.TEAMModelOS, tb).UpsertItemAsync(bloblog, new Azure.Cosmos.PartitionKey(bloblog.code));
  525. }
  526. }
  527. return new OkObjectResult(new { });
  528. }
  529. catch (Exception ex)
  530. {
  531. await _dingDing.SendBotMsg($"TEAMModelFunction,ActivityHttpTrigger,fix-blob-content()\n{ex.Message}{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
  532. return new BadRequestResult();
  533. }
  534. }
  535. /// <summary>
  536. /// 删除
  537. /// </summary>
  538. /// <param name="request"></param>
  539. /// <returns></returns>
  540. [ProducesDefaultResponseType]
  541. //[AuthToken(Roles = "teacher")]
  542. [HttpPost("get-data")]
  543. public async Task<IActionResult> GetData(JsonElement request)
  544. {
  545. try
  546. {
  547. var client = _azureCosmos.GetCosmosClient();
  548. return Ok(new { code = 1 });
  549. }
  550. catch (Exception e)
  551. {
  552. return BadRequest(e.StackTrace);
  553. }
  554. }
  555. }
  556. }