TeacherService.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344
  1. using Azure.Cosmos;
  2. using Azure.Storage.Blobs.Models;
  3. using Azure.Storage.Sas;
  4. using Microsoft.AspNetCore.Http;
  5. using Microsoft.AspNetCore.Mvc;
  6. using Microsoft.Extensions.Options;
  7. using System;
  8. using System.Collections.Generic;
  9. using System.Dynamic;
  10. using System.IdentityModel.Tokens.Jwt;
  11. using System.IO;
  12. using System.Linq;
  13. using System.Text.Json;
  14. using System.Threading.Tasks;
  15. using TEAMModelOS.Models;
  16. using TEAMModelOS.SDK.Models;
  17. using TEAMModelOS.SDK.DI;
  18. using TEAMModelOS.SDK.Extension;
  19. using TEAMModelOS.SDK.Filter;
  20. using TEAMModelOS.SDK.Models.Cosmos;
  21. using HTEXLib.COMM.Helpers;
  22. using TEAMModelOS.SDK.Models.Service;
  23. using Microsoft.Extensions.Configuration;
  24. using System.Net.Http;
  25. using TEAMModelOS.SDK;
  26. using static TEAMModelOS.SDK.Models.Teacher;
  27. namespace TEAMModelOS.Services
  28. {
  29. public static class TeacherService
  30. {
  31. public static async Task<TeacherInfo> TeacherInfo(AzureCosmosFactory _azureCosmos, Teacher teacher, string name, string picture, string id,
  32. AzureStorageFactory _azureStorage, Option _option, AzureRedisFactory _azureRedis, string ip, HttpTrigger _httpTrigger, string lang)
  33. {
  34. List<object> schools = new List<object>();
  35. List<AreaDto> areas = new List<AreaDto>();
  36. string defaultschool = null;
  37. //TODO 取得Teacher 個人相關數據(課程清單、虛擬教室清單、歷史紀錄清單等),學校數據另外API處理,多校切換時不同
  38. var client = _azureCosmos.GetCosmosClient();
  39. int total = 0;
  40. int tsize = 0;
  41. List<Area> areasDbs = new List<Area>();
  42. List<AreaSetting> areaSettings = new List<AreaSetting>();
  43. try
  44. {
  45. if (teacher == null)
  46. {
  47. teacher = await client.GetContainer(Constant.TEAMModelOS, "Teacher").ReadItemAsync<Teacher>(id, new PartitionKey("Base"));
  48. if (!string.IsNullOrWhiteSpace(lang) && string.IsNullOrWhiteSpace(teacher.lang))
  49. {
  50. teacher.lang = lang;
  51. }
  52. teacher.name = $"{name}";
  53. teacher.picture = $"{picture}";
  54. }
  55. else
  56. {
  57. name = teacher.name;
  58. picture = teacher.picture;
  59. id = teacher.id;
  60. }
  61. ///教师的个人空间
  62. tsize = teacher.size;
  63. ///教师的总空间 包含 个人空间和学校赠送的空间累加
  64. total = teacher.size;
  65. HashSet<string> areaIds = new HashSet<string>();
  66. if (teacher.areas.IsNotEmpty())
  67. {
  68. teacher.areas.ForEach(x => {
  69. areaIds.Add(x.areaId);
  70. });
  71. }
  72. if (teacher.schools.IsNotEmpty())
  73. {
  74. teacher.schools.ForEach(x => {
  75. if (!string.IsNullOrEmpty(x.areaId))
  76. {
  77. areaIds.Add(x.areaId);
  78. }
  79. });
  80. }
  81. if (areaIds.Count > 0)
  82. {
  83. string queryText = $"select value(c) from c where c.id in ({string.Join(",", areaIds.Select(x => $"'{x}'"))})";
  84. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Normal").GetItemQueryIterator<Area>(queryText: queryText, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey("Base-Area") }))
  85. {
  86. areasDbs.Add(item);
  87. }
  88. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Normal").GetItemQueryIterator<AreaSetting>(queryText: queryText, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey("AreaSetting") }))
  89. {
  90. areaSettings.Add(item);
  91. }
  92. }
  93. if (teacher.areas.IsNotEmpty())
  94. {
  95. foreach (var areat in teacher.areas)
  96. {
  97. Area area = areasDbs.Find(x => x.id.Equals(areat.areaId));
  98. AreaSetting setting = null;
  99. if (area != null)
  100. {
  101. setting = areaSettings.Find(x => x.id.Equals(areat.areaId));
  102. }
  103. int access = 0;
  104. if (setting != null && !string.IsNullOrWhiteSpace(setting.accessConfig))
  105. {
  106. access = 1;
  107. }
  108. //if (setting != null)
  109. //{
  110. // setting.accessConfig = null;
  111. //}
  112. areas.Add(new AreaDto { areaId = area.id, name = area.name, standard = area.standard, standardName = area.standardName, setting = setting, access = access });
  113. }
  114. }
  115. //检查是否有加入学校,如果加入学校,则当个人空间size是0G的时候,则免费获得一个G空间,但无论加入多少个学校,只能获取一次 1G的免费空间。没有加入学校则默认0G空间,除非自己购买空间
  116. if (teacher.schools.IsNotEmpty())
  117. {
  118. foreach (var sc in teacher.schools)
  119. {
  120. string statusNow = sc.status != null ? sc.status : "";
  121. if (statusNow.Equals("join") || statusNow.Equals("invite") || statusNow.Equals("request"))
  122. {
  123. dynamic schoolExtobj = new ExpandoObject();
  124. schoolExtobj.schoolId = sc.schoolId;
  125. schoolExtobj.name = sc.name;
  126. schoolExtobj.status = sc.status;
  127. schoolExtobj.time = sc.time;
  128. schoolExtobj.picture = sc.picture;
  129. schoolExtobj.areaId = $"{sc.areaId}";
  130. Area area = null;
  131. int access = 0;
  132. if (!string.IsNullOrEmpty($"{sc.areaId}"))
  133. {
  134. area = areasDbs.Find(x => x.id.Equals(sc.areaId));
  135. AreaSetting setting = null;
  136. if (area != null)
  137. {
  138. setting = areaSettings.Find(x => x.id.Equals(sc.areaId));
  139. }
  140. if (setting != null && !string.IsNullOrWhiteSpace(setting.accessConfig))
  141. {
  142. access = 1;
  143. }
  144. }
  145. if (area != null)
  146. {
  147. schoolExtobj.area = new { area.name, area.id, area.institution, area.provName, area.code, area.cityCode, area.cityName, area.standard, area.provCode, area.pk, access };
  148. }
  149. else
  150. {
  151. schoolExtobj.area = area;
  152. }
  153. var sctch = await client.GetContainer(Constant.TEAMModelOS, "School").ReadItemStreamAsync(id, new PartitionKey($"Teacher-{sc.schoolId}"));
  154. if (sctch.Status == 200 && sctch != null && sctch.ContentStream != null)
  155. {
  156. var jsonDoc = await JsonDocument.ParseAsync(sctch.ContentStream);
  157. SchoolTeacher schoolTeacher = jsonDoc.RootElement.ToObject<SchoolTeacher>();
  158. if (schoolTeacher.name == null || schoolTeacher.picture == null || !schoolTeacher.name.Equals($"{name}") || !schoolTeacher.picture.Equals($"{picture}"))
  159. {
  160. schoolTeacher.name = $"{name}";
  161. schoolTeacher.picture = $"{picture}";
  162. await client.GetContainer(Constant.TEAMModelOS, "School").ReplaceItemAsync(schoolTeacher, id, new PartitionKey($"Teacher-{sc.schoolId}"));
  163. }
  164. if (jsonDoc.RootElement.TryGetProperty("size", out JsonElement _size) && _size.ValueKind.Equals(JsonValueKind.Number))
  165. {
  166. total += _size.GetInt32();
  167. schoolExtobj.size = _size.GetInt32();
  168. }
  169. else { schoolExtobj.size = 0; }
  170. }
  171. else
  172. {
  173. schoolExtobj.size = 0;
  174. }
  175. //if (statusNow.Equals("join"))
  176. //{
  177. // await TmdUserService.JoinSchool(client, teacher.id, teacher.picture, teacher.name, sc.schoolId, sc.name);
  178. //}
  179. schools.Add(schoolExtobj);
  180. }
  181. }
  182. //如果包含任何申请,邀请,加入学校的记录 且个人空间未分配2G 则默认分配个人空间至2G.
  183. if (teacher.size < 2 && teacher.schools.Count > 0)
  184. {
  185. teacher.size = 2;
  186. }
  187. //如果未包含任何申请,邀请,加入学校的记录 且 个人空间没有分配1G 则默认赠送一个G
  188. if (teacher.schools.Count == 0 && teacher.size < 1)
  189. {
  190. teacher.size = 1;
  191. }
  192. }
  193. if (string.IsNullOrEmpty(teacher.defaultSchool) && teacher.schools.IsNotEmpty())
  194. {
  195. var tech = teacher.schools.FindAll(x => x.status.Equals("join"));
  196. if (tech.IsNotEmpty())
  197. {
  198. teacher.defaultSchool = teacher.schools[0].schoolId;
  199. }
  200. }
  201. if (!string.IsNullOrEmpty(teacher.defaultSchool))
  202. {
  203. if (teacher.schools.IsNotEmpty())
  204. {
  205. var tech = teacher.schools.FindAll(x => x.status.Equals("join") && x.schoolId.Equals(teacher.defaultSchool));
  206. if (!tech.IsNotEmpty())
  207. {
  208. var techde = teacher.schools.FindAll(x => x.status.Equals("join"));
  209. if (techde.IsNotEmpty())
  210. {
  211. teacher.defaultSchool = techde[0].schoolId;
  212. }
  213. else
  214. {
  215. teacher.defaultSchool = null;
  216. }
  217. }
  218. }
  219. else
  220. {
  221. teacher.defaultSchool = null;
  222. }
  223. }
  224. await client.GetContainer(Constant.TEAMModelOS, "Teacher").ReplaceItemAsync<Teacher>(teacher, id, new PartitionKey("Base"));
  225. //預設學校ID
  226. defaultschool = teacher.defaultSchool;
  227. }
  228. catch (CosmosException ex)
  229. {
  230. if (ex.Status == 404 && teacher == null)
  231. {
  232. //如果沒有,則初始化Teacher基本資料到Cosmos
  233. teacher = new Teacher
  234. {
  235. createTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(),
  236. id = id,
  237. pk = "Base",
  238. code = "Base",
  239. name = name?.ToString(),
  240. picture = picture?.ToString(),
  241. //创建账号并第一次登录IES5则默认赠送1G
  242. size = 1,
  243. defaultSchool = null,
  244. schools = new List<Teacher.TeacherSchool>(),
  245. lang=lang
  246. };
  247. var container = _azureStorage.GetBlobContainerClient(id);
  248. await container.CreateIfNotExistsAsync(PublicAccessType.None); //嘗試創建Teacher私有容器,如存在則不做任何事,保障容器一定存在
  249. teacher = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Teacher").CreateItemAsync<Teacher>(teacher, new PartitionKey("Base"));
  250. total = teacher.size;
  251. tsize = teacher.size;
  252. }
  253. }
  254. catch (Exception ex)
  255. {
  256. throw new Exception($"{ex.Message}\n{ex.StackTrace}");
  257. }
  258. //私人課程
  259. List<object> courses = new List<object>();
  260. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Teacher").GetItemQueryStreamIterator(queryText: $"select value(c) from c ", requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Course-{id}") }))
  261. {
  262. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  263. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  264. {
  265. foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
  266. {
  267. courses.Add(obj.ToObject<object>());
  268. }
  269. }
  270. }
  271. List<string> roles = new List<string>() { "teacher" };
  272. Area areaa = null;
  273. if (areas.Count > 0)
  274. {
  275. roles.Add("area");
  276. if (!string.IsNullOrEmpty($"{areas[0]}"))
  277. {
  278. areaa = areasDbs.Find(x => x.Equals(areas[0].areaId));
  279. }
  280. }
  281. //換取AuthToken,提供給前端
  282. var auth_token = JwtAuthExtension.CreateAuthToken(_option.HostName, id, name?.ToString(), picture?.ToString(), _option.JwtSecretKey, Website: "IES", scope: Constant.ScopeTeacher, standard: areaa != null ? areaa.standard : "", roles: roles.ToArray(), expire: 1);
  283. //用户在线记录
  284. try
  285. {
  286. _ = _httpTrigger.RequestHttpTrigger(new { school = defaultschool, scope = $"{Constant.ScopeTeacher}", id = $"{id}", ip = $"{ip}", expire = 1 }, _option.Location, "online-record");
  287. }
  288. catch { }
  289. //取得Teacher Blob 容器位置及SAS
  290. await _azureStorage.GetBlobContainerClient(id).CreateIfNotExistsAsync(PublicAccessType.None); //嘗試創建Teacher私有容器,如存在則不做任何事,保障容器一定存在
  291. var (blob_uri, blob_sas) = _azureStorage.GetBlobContainerSAS(id, BlobContainerSasPermissions.Write | BlobContainerSasPermissions.Read | BlobContainerSasPermissions.List | BlobContainerSasPermissions.Delete);
  292. var (osblob_uri, osblob_sas) = roles.Contains("area") ? _azureStorage.GetBlobContainerSAS("teammodelos", BlobContainerSasPermissions.Write | BlobContainerSasPermissions.Read | BlobContainerSasPermissions.List | BlobContainerSasPermissions.Delete) : _azureStorage.GetBlobContainerSAS("teammodelos", BlobContainerSasPermissions.Read | BlobContainerSasPermissions.List);
  293. return new TeacherInfo
  294. {
  295. auth_token = auth_token,
  296. blob_uri = blob_uri,
  297. blob_sas = blob_sas,
  298. schools = schools,
  299. defaultschool = defaultschool,
  300. courses = courses,
  301. total = total,
  302. osblob_sas = osblob_sas,
  303. osblob_uri = osblob_uri,
  304. tsize = tsize,
  305. areas = areas,
  306. teacher = teacher
  307. };
  308. }
  309. }
  310. public record AreaDto
  311. {
  312. //areaId = area.id, name = area.name, area.standard, area.standardName
  313. public string areaId { get; set; }
  314. public string name { get; set; }
  315. public string standard { get; set; }
  316. public string standardName { get; set; }
  317. //public string accessConfig { get; set; }
  318. public AreaSetting setting { get; set; }
  319. public int access { get; set; } = 0;
  320. }
  321. public record TeacherInfo
  322. {
  323. public string auth_token { get; set; }
  324. public string blob_uri { get; set; }
  325. public string blob_sas { get; set; }
  326. public List<object> schools { get; set; } = new List<object>();
  327. public string defaultschool { get; set; }
  328. public string defaultschoolPeriod { get; set; }
  329. public List<object> courses { get; set; } = new List<object>();
  330. public int total { get; set; }
  331. public string osblob_uri { get; set; }
  332. public string osblob_sas { get; set; }
  333. public int tsize { get; set; }
  334. public List<AreaDto> areas { get; set; } = new List<AreaDto>();
  335. public Teacher teacher { get; set; }
  336. }
  337. }