TeacherService.cs 17 KB

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