SchoolStatsWay.cs 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385
  1. using Azure.Cosmos;
  2. using DocumentFormat.OpenXml.Bibliography;
  3. using DocumentFormat.OpenXml.Math;
  4. using MathNet.Numerics.LinearAlgebra.Double;
  5. using Microsoft.AspNetCore.Mvc;
  6. using Microsoft.Azure.Amqp.Framing;
  7. using Newtonsoft.Json;
  8. using StackExchange.Redis;
  9. using System;
  10. using System.Collections.Generic;
  11. using System.Linq;
  12. using System.Net.Http.Headers;
  13. using System.Net.Http;
  14. using System.Net;
  15. using System.Text;
  16. using System.Text.Json;
  17. using System.Threading.Tasks;
  18. using TEAMModelOS.Models;
  19. using TEAMModelOS.SDK.DI;
  20. using TEAMModelOS.SDK.Extension;
  21. using TEAMModelOS.SDK.Models.Cosmos.BI;
  22. using TEAMModelOS.SDK.Models.Service.BI;
  23. using Microsoft.Extensions.Configuration;
  24. using System.Configuration;
  25. using System.Net.Http.Json;
  26. namespace TEAMModelOS.SDK.Models.Service.BIStatsWay
  27. {
  28. public static class SchoolStatsWay
  29. {
  30. /// <summary>
  31. /// 统计单个学校
  32. /// </summary>
  33. /// <param name="cosmosClient"></param>
  34. /// <param name="scId"></param>
  35. /// <returns></returns>
  36. public static async Task<StatsInfo> GetSingleSc(CosmosClient cosmosClient, IDatabase redisClinet, string scId, int year = 0)
  37. {
  38. DateTimeOffset dateTime = DateTimeOffset.UtcNow;
  39. if (year < dateTime.Year)
  40. dateTime = new(year, 12, 31, 23, 59, 59, TimeSpan.Zero);
  41. long userSize = 0;
  42. RedisValue redisValue = redisClinet.HashGet($"Blob:Record", scId);
  43. if (redisValue != default && !redisValue.IsNullOrEmpty)
  44. {
  45. JsonElement record = redisValue.ToString().ToObject<JsonElement>();
  46. if (record.TryGetInt64(out userSize)) { }
  47. }
  48. StatsInfo statsInfo = new() { id = $"{year}-{scId}" };
  49. var (dayS, dayE) = TimeHelper.GetStartOrEnd(dateTime); //今天开始时间 13位
  50. var (lastWeekS, lastWeekE) = TimeHelper.GetStartOrEnd(dateTime, "lastweek"); //计算上周开始/结束时间
  51. var (weekS, weekE) = TimeHelper.GetStartOrEnd(dateTime, "week"); //计算本周开始/结束时间
  52. var (lastTermS, lastTermE) = TimeHelper.GetStartOrEnd(dateTime, "lastterm"); //计算上学期开始/结束时间
  53. var (termS, termE) = TimeHelper.GetStartOrEnd(dateTime, "term"); //计算本学期开始/结束时间
  54. var (lastMthS, LastmthE) = TimeHelper.GetStartOrEnd(dateTime, "lastMonth"); //上月开始/结束时间
  55. var (mthS, mthE) = TimeHelper.GetStartOrEnd(dateTime, "month"); //本月开始/结束时间
  56. var (lastYearS, lastYearE) = TimeHelper.GetStartOrEnd(DateTimeOffset.Parse($"{dateTime.Year - 1}-1-1"), "year"); //计算去年开始/结束时间
  57. var (yearS, yearE) = TimeHelper.GetStartOrEnd(dateTime, "year"); //计算今年开始/结束时间
  58. var (weekDayS, weekDayE) = TimeHelper.GetLongToTime(weekS, weekE);
  59. var (monthDayS, monthDayE) = TimeHelper.GetLongToTime(mthS, mthE);
  60. string currSql = "select value(count(c.id)) from c";
  61. string dayWhereSql = $"c.createTime >= {dayS} and c.createTime <= {dayE}";
  62. string weekWhereSql = $"c.createTime >= {weekS} and c.createTime <= {weekE}";
  63. string monthWhereSql = $"c.createTime >= {mthS} and c.createTime <= {mthE}";
  64. ScBase scBase = await cosmosClient.GetContainer("TEAMModelOS", "School").ReadItemAsync<ScBase>(scId, new PartitionKey("Base"));
  65. statsInfo.schoolId = scBase.id;
  66. statsInfo.name = scBase.name;
  67. statsInfo.picture = scBase.picture;
  68. statsInfo.size = scBase.size;
  69. statsInfo.scCreateTime = scBase.createTime;
  70. statsInfo.areaId = scBase.areaId;
  71. statsInfo.year = year;
  72. statsInfo.useSize = userSize;
  73. string tchSql = $"{currSql} where ARRAY_CONTAINS(c.roles, 'teacher', true) AND c.status = 'join'";
  74. statsInfo.tch = await JointlySingleQuery.GetValueInt(cosmosClient, "School", $"Teacher-{scBase.id}", tchSql);
  75. List<double> tchDoubles = await UserStatsWay.GetYearTecherStudent(cosmosClient, scBase.id, year, 1);
  76. statsInfo.tchYear = tchDoubles;
  77. statsInfo.dayTch = ((int)tchDoubles[dateTime.DayOfYear - 1]);
  78. DenseMatrix tchDouble = DenseMatrix.OfColumns(new List<List<double>>() { tchDoubles });
  79. int weekDay = 0;
  80. if ((dateTime.DayOfYear - weekDayS.DayOfYear) <= 7)
  81. weekDay = dateTime.DayOfYear - weekDayS.DayOfYear + 1;
  82. else
  83. weekDay = 7;
  84. statsInfo.weekTch = ((int)tchDouble.SubMatrix(weekDayS.DayOfYear - 1, weekDay, 0, tchDouble.ColumnCount).ColumnSums().Sum());
  85. statsInfo.monthTch += ((int)tchDouble.SubMatrix(monthDayS.DayOfYear - 1, (dateTime.DayOfYear - monthDayS.DayOfYear + 1), 0, tchDouble.ColumnCount).ColumnSums().Sum());
  86. //statsInfo.dayTch = await JointlySingleQuery.GetValueInt(cosmosClient, "School", $"Teacher-{scBase.id}", $"{tchSql} and {dayWhereSql} ");
  87. //statsInfo.weekTch = await JointlySingleQuery.GetValueInt(cosmosClient, "School", $"Teacher-{scBase.id}", $"{tchSql} and {weekWhereSql}");
  88. //statsInfo.monthTch = await JointlySingleQuery.GetValueInt(cosmosClient, "School", $"Teacher-{scBase.id}", $"{tchSql} and {monthWhereSql}");
  89. statsInfo.tchUpTime = dateTime.ToUnixTimeMilliseconds();
  90. statsInfo.stu = await JointlySingleQuery.GetValueInt(cosmosClient, "Student", $"Base-{scBase.id}", currSql);
  91. List<double> stuDoubles = await UserStatsWay.GetYearTecherStudent(cosmosClient, scBase.id, year, 2);
  92. statsInfo.stuYear = stuDoubles;
  93. statsInfo.dayStu = ((int)stuDoubles[dateTime.DayOfYear]);
  94. DenseMatrix stuDouble = DenseMatrix.OfColumns(new List<List<double>>() { stuDoubles });
  95. statsInfo.weekStu = ((int)stuDouble.SubMatrix(weekDayS.DayOfYear - 1, weekDay, 0, stuDouble.ColumnCount).ColumnSums().Sum());
  96. statsInfo.monthStu += ((int)stuDouble.SubMatrix(monthDayS.DayOfYear - 1, (dateTime.DayOfYear - monthDayS.DayOfYear + 1), 0, stuDouble.ColumnCount).ColumnSums().Sum());
  97. //statsInfo.dayStu = await JointlySingleQuery.GetValueInt(cosmosClient, "Student", $"Base-{scBase.id}", $"{currSql} where {dayWhereSql}");
  98. //statsInfo.weekStu = await JointlySingleQuery.GetValueInt(cosmosClient, "Student", $"Base-{scBase.id}", $"{currSql} where {weekWhereSql}");
  99. //statsInfo.monthStu = await JointlySingleQuery.GetValueInt(cosmosClient, "Student", $"Base-{scBase.id}", $"{currSql} where {monthWhereSql}");
  100. statsInfo.stuUpTime = dateTime.ToUnixTimeMilliseconds();
  101. statsInfo.room = await JointlySingleQuery.GetValueInt(cosmosClient, "School", $"Room-{scBase.id}", currSql);
  102. //statsInfo.witRoom = await JointlySingleQuery.GetValueInt(cosmosClient, "School", $"Room-{scBase.id}", $"{currSql} where (c.serial != null or c.serial != '' or IS_DEFINED(c.serial) = true)");
  103. statsInfo.resourceCnt = await JointlySingleQuery.GetValueInt(cosmosClient, "School", $"Bloblog-{scBase.id}", currSql);
  104. statsInfo.upTime = dateTime.ToUnixTimeMilliseconds();
  105. statsInfo.lesson = await LessonRecordStatsWay.GetSchoolAll(cosmosClient, statsInfo.schoolId, year);
  106. statsInfo.activity = await ActivityStatsWay.GetSchoolAll(cosmosClient, statsInfo.schoolId, year);
  107. statsInfo.study = await StudyStatsWay.GetSchoolAll(cosmosClient, statsInfo.schoolId);
  108. return statsInfo;
  109. }
  110. /// <summary>
  111. /// 多个学校统计
  112. /// </summary>
  113. /// <param name="cosmosClient"></param>
  114. /// <param name="statsInfos"></param>
  115. /// <param name="_httpTrigger"></param>
  116. /// <param name="_option"></param>
  117. /// <param name="area"></param>
  118. /// <returns></returns>
  119. public static StatsInfo GetAreaStats(CosmosClient cosmosClient, Option _option, List<StatsInfo> statsInfos, List<string> scIds = null, Area area = null)
  120. {
  121. StatsInfo areaInfo = new()
  122. {
  123. id = area == null ? "" : $"{DateTimeOffset.UtcNow.Year}-{area.id}",
  124. pk = "Statistics",
  125. code = "Statistics",
  126. name = area == null ? "" : area.name,
  127. areaId = area == null ? "" : area.id,
  128. picture = "",
  129. tch = statsInfos.Select(s => s.tch).Sum(),
  130. dayTch = statsInfos.Select(s => s.dayTch).Sum(),
  131. weekTch = statsInfos.Select(s => s.weekTch).Sum(),
  132. monthTch = statsInfos.Select(s => s.monthTch).Sum(),
  133. stu = statsInfos.Select(s => s.stu).Sum(),
  134. dayStu = statsInfos.Select(s => s.dayStu).Sum(),
  135. weekStu = statsInfos.Select(s => s.weekStu).Sum(),
  136. monthStu = statsInfos.Select(s => s.monthStu).Sum(),
  137. room = statsInfos.Select(s => s.room).Sum(),
  138. witRoom = statsInfos.Select(s => s.witRoom).Sum(),
  139. resourceCnt = statsInfos.Select(s => s.resourceCnt).Sum(),
  140. size = statsInfos.Select(s => s.size).Sum(),
  141. useSize = statsInfos.Select(s => s.useSize).Sum()
  142. };
  143. areaInfo.lesson.all = statsInfos.Select(s => s.lesson.all).Sum();
  144. areaInfo.lesson.open = statsInfos.Select(s => s.lesson.open).Sum();
  145. areaInfo.lesson.less = statsInfos.Select(s => s.lesson.less).Sum();
  146. areaInfo.lesson.lastDay = statsInfos.Select(s => s.lesson.lastDay).Sum();
  147. areaInfo.lesson.day = statsInfos.Select(s => s.lesson.day).Sum();
  148. areaInfo.lesson.lastWeek = statsInfos.Select(s => s.lesson.lastWeek).Sum();
  149. areaInfo.lesson.week = statsInfos.Select(s => s.lesson.week).Sum();
  150. areaInfo.lesson.lastTerm = statsInfos.Select(s => s.lesson.lastTerm).Sum();
  151. areaInfo.lesson.term = statsInfos.Select(s => s.lesson.term).Sum();
  152. areaInfo.lesson.lastDayInter = statsInfos.Select(s => s.lesson.lastDayInter).Sum();
  153. areaInfo.lesson.dayInter = statsInfos.Select(s => s.lesson.dayInter).Sum();
  154. //areaInfo.lesson.lastMonthInter = statsInfos.Select(s => s.lesson.lastMonthInter).Sum();
  155. //areaInfo.lesson.monthInter = statsInfos.Select(s => s.lesson.monthInter).Sum();
  156. areaInfo.lesson.lastYearInter = statsInfos.Select(s => s.lesson.lastYearInter).Sum();
  157. //areaInfo.lesson.yearInter = statsInfos.Select(s => s.lesson.yearInter).Sum();
  158. areaInfo.lesson.yearInters = BICommonWay.ManyDoubleMerge(statsInfos.Select(s => s.lesson.yearInters).ToList());
  159. areaInfo.lesson.year = BICommonWay.ManyDoubleMerge(statsInfos.Select(s => s.lesson.year).Where(w => w.Count > 0).ToList());
  160. areaInfo.activity.all = statsInfos.Select(s => s.activity.all).Sum();
  161. areaInfo.activity.exam = statsInfos.Select(s => s.activity.exam).Sum();
  162. areaInfo.activity.survey = statsInfos.Select(s => s.activity.survey).Sum();
  163. areaInfo.activity.vote = statsInfos.Select(s => s.activity.vote).Sum();
  164. areaInfo.activity.homework = statsInfos.Select(s => s.activity.homework).Sum();
  165. areaInfo.activity.lastDay = statsInfos.Select(s => s.activity.lastDay).Sum();
  166. areaInfo.activity.dayCnt = statsInfos.Select(s => s.activity.dayCnt).Sum();
  167. areaInfo.activity.lastWeek = statsInfos.Select(s => s.activity.lastWeek).Sum();
  168. areaInfo.activity.week = statsInfos.Select(s => s.activity.week).Sum();
  169. areaInfo.activity.lastTerm = statsInfos.Select(s => s.activity.lastTerm).Sum();
  170. areaInfo.activity.term = statsInfos.Select(s => s.activity.term).Sum();
  171. areaInfo.activity.lastMonth = statsInfos.Select(s => s.activity.lastMonth).Sum();
  172. areaInfo.activity.month = statsInfos.Select(s => s.activity.month).Sum();
  173. //areaInfo.activity.LastYear = BICommonWay.ManyDoubleMerge(statsInfos.Select(s => s.activity.LastYear).ToList());
  174. areaInfo.activity.year = BICommonWay.ManyDoubleMerge(statsInfos.Select(s => s.activity.year).Where(w => w.Count > 0).ToList());
  175. return areaInfo;
  176. }
  177. /// <summary>
  178. /// 计算学校智慧教室数
  179. /// </summary>
  180. /// <param name="_azureCosmos"></param>
  181. /// <param name="_azureRedis"></param>
  182. /// <param name="_configuration"></param>
  183. /// <param name="_httpClient"></param>
  184. /// <param name="code"></param>
  185. /// <returns></returns>
  186. public static async Task<double> GetShoolWisdomRoomCount(AzureCosmosFactory _azureCosmos, AzureRedisFactory _azureRedis, IConfiguration _configuration, IHttpClientFactory _httpClient, DingDing _dingDing, string code)
  187. {
  188. try
  189. {
  190. var db = _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "School");
  191. var r8 = _azureRedis.GetRedisClient(8);
  192. List<SchoolProductSerial> serial = new(); //承接DB資料用:序號
  193. List<deviceForCoreService> uuidList = new(); //要向CoreService詢問deviceID及硬體資訊的UUID列表
  194. long UTCNow = DateTimeOffset.UtcNow.ToUnixTimeSeconds();
  195. //軟體
  196. List<string> serialPermitList = StaticValue.GetSerialPermitProdcodeList();
  197. string serialPermitJsonStr = JsonConvert.SerializeObject(serialPermitList);
  198. string serialQueryText = $"SELECT * FROM c WHERE c.dataType = 'serial' AND ARRAY_CONTAINS({serialPermitJsonStr}, c.prodCode)";
  199. await foreach (var itemsr in db.GetItemQueryStreamIterator(queryText: serialQueryText, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Product-{code}") }))
  200. {
  201. using var json = await JsonDocument.ParseAsync(itemsr.ContentStream);
  202. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  203. {
  204. deviceForCoreService uuidForCore;
  205. foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
  206. {
  207. serial.Add(obj.ToObject<SchoolProductSerial>());
  208. if (obj.TryGetProperty("deviceBound", out JsonElement deviceBoundJobj) && !string.IsNullOrWhiteSpace(deviceBoundJobj.ToString()))
  209. {
  210. foreach (var deviceBoundTmpRow in deviceBoundJobj.EnumerateArray())
  211. {
  212. uuidForCore = new deviceForCoreService
  213. {
  214. sn = (!string.IsNullOrWhiteSpace(Convert.ToString(obj.GetProperty("serial")))) ? Convert.ToString(obj.GetProperty("serial")) : null,
  215. uuid1 = (!string.IsNullOrWhiteSpace(Convert.ToString(deviceBoundTmpRow.GetProperty("uuid")))) ? Convert.ToString(deviceBoundTmpRow.GetProperty("uuid")) : null,
  216. uuid2 = (!string.IsNullOrWhiteSpace(Convert.ToString(deviceBoundTmpRow.GetProperty("uuid2")))) ? Convert.ToString(deviceBoundTmpRow.GetProperty("uuid2")) : null,
  217. device_id = (!string.IsNullOrWhiteSpace(Convert.ToString(deviceBoundTmpRow.GetProperty("deviceId")))) ? Convert.ToString(deviceBoundTmpRow.GetProperty("deviceId")) : null,
  218. class_id = (!string.IsNullOrWhiteSpace(Convert.ToString(deviceBoundTmpRow.GetProperty("classId")))) ? Convert.ToString(deviceBoundTmpRow.GetProperty("classId")) : null
  219. };
  220. uuidList.Add(uuidForCore);
  221. }
  222. }
  223. }
  224. }
  225. }
  226. ////取得DeviceInfo From Core 並更新序號資料
  227. List<deviceFromCoreService> coreUuidList = (List<deviceFromCoreService>)GetDeviceFromCoreAsync(uuidList, _configuration, _httpClient).GetAwaiter().GetResult();
  228. List<deviceBoundExt> deviceBoundArray;
  229. List<deviceBoundExt> counts = new();
  230. List<deviceFromCoreService> coreUuid;
  231. deviceForCoreService deviceBoundRow;
  232. deviceBoundExt deviceBoundExt;
  233. List<SchoolProductSerial> updSchoolProductSerialList = new List<SchoolProductSerial>(); //更新學校產品序號用
  234. foreach (SchoolProductSerial serialRow in serial)
  235. {
  236. deviceBoundArray = new List<deviceBoundExt>();
  237. coreUuid = coreUuidList
  238. .Where((deviceFromCoreService x) => x.sn == serialRow.serial)
  239. .ToList();
  240. foreach (deviceFromCoreService deviceRow in coreUuid)
  241. {
  242. if (!string.IsNullOrWhiteSpace(deviceRow.uuid1) || !string.IsNullOrWhiteSpace(deviceRow.uuid2) || !string.IsNullOrWhiteSpace(deviceRow.device_id)) //uuid1、uuid2、device_id 任一欄有值
  243. {
  244. //前端顯示用
  245. deviceBoundRow = uuidList.Where(u => u.sn == deviceRow.sn && u.uuid1 == deviceRow.uuid1 && u.uuid2 == deviceRow.uuid2).FirstOrDefault();
  246. deviceBoundExt = new deviceBoundExt
  247. {
  248. uuid = deviceBoundRow.uuid1,
  249. uuid2 = deviceBoundRow.uuid2,
  250. classId = deviceBoundRow.class_id,
  251. deviceId = deviceRow.device_id,
  252. os = deviceRow.os,
  253. ip = deviceRow.local_ip,
  254. cpu = deviceRow.cpu,
  255. pcname = deviceRow.pc_name,
  256. osver = deviceRow.os_ver
  257. };
  258. deviceBoundArray.Add(deviceBoundExt);
  259. }
  260. }
  261. if (deviceBoundArray.Count.Equals(0)) //無法取得CS的硬體資訊,則用序號的硬體資訊帶入
  262. {
  263. if (serialRow.deviceBound != null)
  264. {
  265. foreach (deviceBound serialRowDeviceBound in serialRow.deviceBound)
  266. {
  267. if (!string.IsNullOrEmpty(serialRowDeviceBound.uuid) || !string.IsNullOrEmpty(serialRowDeviceBound.uuid2))
  268. {
  269. deviceBoundExt = new deviceBoundExt
  270. {
  271. uuid = serialRowDeviceBound.uuid,
  272. uuid2 = serialRowDeviceBound.uuid2,
  273. classId = serialRowDeviceBound.classId,
  274. deviceId = serialRowDeviceBound.deviceId
  275. };
  276. deviceBoundArray.Add(deviceBoundExt);
  277. }
  278. }
  279. }
  280. }
  281. //序號更新
  282. //updSchoolProductSerialList.Add(serialRow);
  283. counts.AddRange(deviceBoundArray);
  284. //await db.ReplaceItemAsync<SchoolProductSerial>(serialRow, serialRow.id, new PartitionKey($"Product-{school_code}"));
  285. }
  286. //取得CC授權使用狀態
  287. var hashs = await r8.HashGetAllAsync($"CC:License:{code}");
  288. var ccuser = hashs.Select(x => JsonDocument.Parse(x.Value.ToString())).ToList();
  289. //更新學校產品序號
  290. //_ = UpdupdSchoolProductSerialListAsync(updSchoolProductSerialList, school_code.GetString());
  291. double roomCount = counts.Count + ccuser.Count;
  292. return roomCount;
  293. }
  294. catch (Exception ex)
  295. {
  296. await _dingDing.SendBotMsg($"BI, {Environment.GetEnvironmentVariable("Option:Location")},GetShoolWisdomRoomCount() {code} \n {ex.Message}\n{ex.StackTrace}", GroupNames.成都开发測試群組);
  297. return 0;
  298. }
  299. }
  300. private static async Task<List<deviceFromCoreService>> GetDeviceFromCoreAsync(List<deviceForCoreService> uuidList, IConfiguration _configuration, IHttpClientFactory _httpClient)
  301. {
  302. List<deviceFromCoreService> result = new List<deviceFromCoreService>();
  303. try
  304. {
  305. string url = _configuration.GetValue<string>("HaBookAuth:CoreService:deviceinfo");
  306. string AccessToken = await getCoreAccessToken(_configuration, _httpClient);
  307. var client = _httpClient.CreateClient();
  308. client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", AccessToken);
  309. string uuidListJson = JsonConvert.SerializeObject(uuidList);
  310. var content = new StringContent(uuidListJson, Encoding.UTF8, "application/json");
  311. HttpResponseMessage responseMessage = await client.PostAsync(url, content);
  312. if (responseMessage.StatusCode == HttpStatusCode.OK)
  313. {
  314. string responseBody = responseMessage.Content.ReadAsStringAsync().Result;
  315. result = System.Text.Json.JsonSerializer.Deserialize<List<deviceFromCoreService>>(responseBody.ToString());
  316. }
  317. return result;
  318. }
  319. catch (Exception ex)
  320. {
  321. return result;
  322. }
  323. }
  324. private static async Task<string> getCoreAccessToken(IConfiguration _configuration, IHttpClientFactory _httpClient)
  325. {
  326. string AccessToken = "";
  327. try
  328. {
  329. string Url = _configuration.GetValue<string>("HaBookAuth:CoreAPI") + "/oauth2/token";
  330. string GrantType = "device";
  331. string ClientID = _configuration.GetValue<string>("HaBookAuth:CoreService:clientID");
  332. string Secret = _configuration.GetValue<string>("HaBookAuth:CoreService:clientSecret");
  333. var content = new { grant_type = GrantType, client_id = ClientID, client_secret = Secret };
  334. var response = await _httpClient.CreateClient().PostAsJsonAsync($"{Url}", content);
  335. if (response.IsSuccessStatusCode)
  336. {
  337. string responseBody = response.Content.ReadAsStringAsync().Result;
  338. using (JsonDocument document = JsonDocument.Parse(responseBody.ToString()))
  339. {
  340. if (document.RootElement.TryGetProperty("access_token", out JsonElement AccessTokenObj))
  341. {
  342. AccessToken = AccessTokenObj.ToString();
  343. }
  344. }
  345. }
  346. return AccessToken;
  347. }
  348. catch (Exception ex)
  349. {
  350. return AccessToken;
  351. }
  352. }
  353. }
  354. }