Browse Source

返回授权信息。

CrazyIter_Bin 3 years ago
parent
commit
d5237a1950

+ 242 - 2
TEAMModelOS.SDK/Models/Service/Common/TeacherService.cs

@@ -29,9 +29,249 @@ namespace TEAMModelOS.Services
 {
     public static class TeacherService
     {
+        public static async Task<TeacherInfo> TeacherInfo(AzureCosmosFactory _azureCosmos, Teacher teacher, string name, string picture, string id, AzureStorageFactory _azureStorage, Option _option)
+        {
+            List<object> schools = new List<object>();
+            List<AreaDto> areas = new List<AreaDto>();
+            string defaultschool = null;
+            //TODO 取得Teacher 個人相關數據(課程清單、虛擬教室清單、歷史紀錄清單等),學校數據另外API處理,多校切換時不同
+            var client = _azureCosmos.GetCosmosClient();
+            int total = 0;
+            int tsize = 0;
+            List<Area> areasDbs = new List<Area>();
+            List<AreaSetting> areaSettings = new List<AreaSetting>();
+            try
+            {
+                if (teacher == null)
+                {
+                    teacher = await client.GetContainer(Constant.TEAMModelOS, "Teacher").ReadItemAsync<Teacher>(id, new PartitionKey("Base"));
+                    teacher.name = $"{name}";
+                    teacher.picture = $"{picture}";
+                }
+                else
+                {
+                    name = teacher.name;
+                    picture = teacher.picture;
+                    id = teacher.id;
+                }
+                ///教师的个人空间
+                tsize = teacher.size;
+                ///教师的总空间 包含 个人空间和学校赠送的空间累加
+                total = teacher.size;
 
-
-        
+                HashSet<string> areaIds = new HashSet<string>();
+                if (teacher.areas.IsNotEmpty())
+                {
+                    teacher.areas.ForEach(x => {
+                        areaIds.Add(x.areaId);
+                    });
+                   
+                }
+                if (teacher.schools.IsNotEmpty())
+                {
+                    teacher.schools.ForEach(x => {
+                        if (!string.IsNullOrEmpty(x.areaId))
+                        {
+                            areaIds.Add(x.areaId);
+                        }
+                    });
+                }
+                if (areaIds.Count > 0)
+                {
+                    string queryText = $"select value(c) from c where c.id in ({string.Join(",", areaIds.Select(x => $"'{x}'"))})";
+                    await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Normal").GetItemQueryIterator<Area>(queryText: queryText, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey("Base-Area") }))
+                    {
+                        areasDbs.Add(item);
+                    }
+                    await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Normal").GetItemQueryIterator<AreaSetting>(queryText: queryText, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey("AreaSetting") }))
+                    {
+                        areaSettings.Add(item);
+                    }
+                }
+                if (teacher.areas.IsNotEmpty())
+                {
+                    foreach (var areat in teacher.areas)
+                    {
+                        Area area = areasDbs.Find(x => x.id.Equals(areat.areaId));
+                        AreaSetting setting = null;
+                        if (area != null)
+                        {
+                            setting = areaSettings.Find(x => x.id.Equals(areat.areaId));
+                        }
+                        int access = 0;
+                        if (setting != null && !string.IsNullOrWhiteSpace(setting.accessConfig))
+                        {
+                            access = 1;
+                        }
+                        if (setting != null)
+                        {
+                            setting.accessConfig = null;
+                        }
+                        areas.Add(new AreaDto { areaId = area.id, name = area.name, standard = area.standard, standardName = area.standardName, setting = setting, access = access });
+                    }
+                }
+                //检查是否有加入学校,如果加入学校,则当个人空间size是0G的时候,则免费获得一个G空间,但无论加入多少个学校,只能获取一次 1G的免费空间。没有加入学校则默认0G空间,除非自己购买空间
+                if (teacher.schools.IsNotEmpty())
+                {
+                    foreach (var sc in teacher.schools)
+                    {
+                        string statusNow = sc.status != null ? sc.status : "";
+                        if (statusNow.Equals("join") || statusNow.Equals("invite") || statusNow.Equals("request"))
+                        {
+                            dynamic schoolExtobj = new ExpandoObject();
+                            schoolExtobj.schoolId = sc.schoolId;
+                            schoolExtobj.name = sc.name;
+                            schoolExtobj.status = sc.status;
+                            schoolExtobj.time = sc.time;
+                            schoolExtobj.picture = sc.picture;
+                            schoolExtobj.areaId = $"{sc.areaId}";
+                            Area area = null;
+                            int access = 0;
+                            if (!string.IsNullOrEmpty($"{sc.areaId}"))
+                            {
+                                area = areasDbs.Find(x => x.id.Equals(sc.areaId));
+                                AreaSetting setting = null;
+                                if (area != null)
+                                {
+                                    setting = areaSettings.Find(x => x.id.Equals(sc.areaId));
+                                }
+                                if (setting != null && !string.IsNullOrWhiteSpace(setting.accessConfig))
+                                {
+                                    access = 1;
+                                }
+                            }
+                            if (area != null)
+                            {
+                                schoolExtobj.area = new { area.name, area.id, area.institution, area.provName, area.code, area.cityCode, area.cityName, area.standard, area.provCode, area.pk, access };
+                            }
+                            else
+                            {
+                                schoolExtobj.area = area;
+                            }
+                            var sctch = await client.GetContainer(Constant.TEAMModelOS, "School").ReadItemStreamAsync(id, new PartitionKey($"Teacher-{sc.schoolId}"));
+                            if (sctch.Status == 200)
+                            {
+                                var jsonDoc = await JsonDocument.ParseAsync(sctch.ContentStream);
+                                SchoolTeacher schoolTeacher = jsonDoc.RootElement.ToObject<SchoolTeacher>();
+                                if (!schoolTeacher.name.Equals($"{name}") || !schoolTeacher.picture.Equals($"{picture}")) {
+                                    schoolTeacher.name = $"{name}";
+                                    schoolTeacher.picture = $"{picture}";
+                                    await client.GetContainer(Constant.TEAMModelOS, "School").ReplaceItemAsync(schoolTeacher, id, new PartitionKey($"Teacher-{sc.schoolId}"));
+                                }
+                                if (jsonDoc.RootElement.TryGetProperty("size", out JsonElement _size) && _size.ValueKind.Equals(JsonValueKind.Number))
+                                {
+                                    total += _size.GetInt32();
+                                    schoolExtobj.size = _size.GetInt32();
+                                }
+                                else { schoolExtobj.size = 0; }
+                            }
+                            else
+                            {
+                                schoolExtobj.size = 0;
+                            }
+                            //if (statusNow.Equals("join"))
+                            //{
+                            //    await TmdUserService.JoinSchool(client, teacher.id, teacher.picture, teacher.name, sc.schoolId, sc.name);
+                            //}
+                            schools.Add(schoolExtobj);
+                        }
+                    }
+                    //如果包含任何申请,邀请,加入学校的记录 且个人空间未分配2G  则默认分配个人空间至2G.
+                    if (teacher.size < 2 && teacher.schools.Count > 0)
+                    {
+                        teacher.size = 2;
+                    }
+                    //如果未包含任何申请,邀请,加入学校的记录 且 个人空间没有分配1G 则默认赠送一个G 
+                    if (teacher.schools.Count == 0 && teacher.size < 1)
+                    {
+                        teacher.size = 1;
+                    }
+                }
+                if (string.IsNullOrEmpty(teacher.defaultSchool) && teacher.schools.IsNotEmpty())
+                {
+                    var tech = teacher.schools.FindAll(x => x.status.Equals("join"));
+                    if (tech.IsNotEmpty())
+                    {
+                        teacher.defaultSchool = teacher.schools[0].schoolId;
+                    }
+                }
+                await client.GetContainer(Constant.TEAMModelOS, "Teacher").ReplaceItemAsync<Teacher>(teacher, id, new PartitionKey("Base"));
+                //預設學校ID
+                defaultschool = teacher.defaultSchool;
+            }
+            catch (CosmosException ex)
+            {
+                if (ex.Status == 404 && teacher == null)
+                {
+                    //如果沒有,則初始化Teacher基本資料到Cosmos
+                    teacher = new Teacher
+                    {
+                        id = id,
+                        pk = "Base",
+                        code = "Base",
+                        name = name?.ToString(),
+                        picture = picture?.ToString(),
+                        //创建账号并第一次登录IES5则默认赠送1G
+                        size = 1,
+                        defaultSchool = null,
+                        schools = new List<Teacher.TeacherSchool>(),
+                    };
+                    var container = _azureStorage.GetBlobContainerClient(id);
+                    await container.CreateIfNotExistsAsync(PublicAccessType.None); //嘗試創建Teacher私有容器,如存在則不做任何事,保障容器一定存在
+                    teacher = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Teacher").CreateItemAsync<Teacher>(teacher, new PartitionKey("Base"));
+                    total = teacher.size;
+                    tsize = teacher.size;
+                }
+            }
+            catch (Exception ex)
+            {
+                throw new Exception($"{ex.Message}{ex.StackTrace}");
+            }
+            //私人課程
+            List<object> courses = new List<object>();
+            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}") }))
+            {
+                using var json = await JsonDocument.ParseAsync(item.ContentStream);
+                if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
+                {
+                    foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
+                    {
+                        courses.Add(obj.ToObject<object>());
+                    }
+                }
+            }
+            List<string> roles = new List<string>() { "teacher" };
+            Area areaa = null;
+            if (areas.Count > 0)
+            {
+                roles.Add("area");
+                if (!string.IsNullOrEmpty($"{areas[0]}"))
+                {
+                    areaa = areasDbs.Find(x => x.Equals(areas[0].areaId));
+                }
+            }
+            //換取AuthToken,提供給前端
+            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());
+            //取得Teacher Blob 容器位置及SAS 
+            await _azureStorage.GetBlobContainerClient(id).CreateIfNotExistsAsync(PublicAccessType.None); //嘗試創建Teacher私有容器,如存在則不做任何事,保障容器一定存在
+            var (blob_uri, blob_sas) = _azureStorage.GetBlobContainerSAS(id, BlobContainerSasPermissions.Write | BlobContainerSasPermissions.Read | BlobContainerSasPermissions.List | BlobContainerSasPermissions.Delete);
+            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);
+            return new TeacherInfo
+            {
+                auth_token = auth_token,
+                blob_uri = blob_uri,
+                blob_sas = blob_sas,
+                schools = schools,
+                defaultschool = defaultschool,
+                courses = courses,
+                total = total,
+                osblob_sas = osblob_sas,
+                osblob_uri = osblob_uri,
+                tsize = tsize,
+                areas = areas,
+                teacher = teacher
+            };
+        }
 
         public static async Task<TeacherInfo> GetTeacherInfo (AzureCosmosFactory _azureCosmos,Teacher teacher,string name,string picture,string id , AzureStorageFactory _azureStorage, Option _option)
         {

+ 67 - 73
TEAMModelOS/Controllers/Teacher/InitController.cs

@@ -240,8 +240,7 @@ namespace TEAMModelOS.Controllers
                 jwt.Payload.TryGetValue("name", out object name);
                 jwt.Payload.TryGetValue("picture", out object picture);
                 Teacher teacher = null;
-
-                TeacherInfo teacherInfo= await TeacherService.GetTeacherInfo(_azureCosmos, teacher, $"{name}", $"{picture}", id, _azureStorage, _option);
+                TeacherInfo teacherInfo= await TeacherService.TeacherInfo(_azureCosmos, teacher, $"{name}", $"{picture}", id, _azureStorage, _option);
                 return Ok(new { location = _option.Location, teacherInfo. auth_token, teacherInfo. blob_uri, teacherInfo.blob_sas, teacherInfo.schools, teacherInfo.defaultschool, teacherInfo. courses,
                     teacherInfo.total,
                     teacherInfo.osblob_uri,
@@ -284,39 +283,58 @@ namespace TEAMModelOS.Controllers
                 List<string> permissions = new List<string>();
                 int size = 0;
                 Teacher teacher = await client.GetContainer(Constant.TEAMModelOS, "Teacher").ReadItemAsync<Teacher>(id, new PartitionKey("Base"));
-                
                 List<AreaDto> areas = new List<AreaDto>();
+                HashSet<string> areaIds = new HashSet<string>();
+                if (teacher.areas.IsNotEmpty())
+                {
+                    teacher.areas.ForEach(x => {
+                        areaIds.Add(x.areaId);
+                    });
+                }
+                if (teacher.schools.IsNotEmpty())
+                {
+                    teacher.schools.ForEach(x => {
+                        if (!string.IsNullOrEmpty(x.areaId)) {
+                            areaIds.Add(x.areaId);
+                        }
+                        
+                    });
+                }
+                List<Area> areasDbs = new List<Area>();
+                List<AreaSetting> areaSettings = new List<AreaSetting>();
+                if (areaIds.Count > 0)
+                {
+                    string queryText = $"select value(c) from c where c.id in ({string.Join(",", areaIds.Select(x => $"'{x}'"))})";
+                    await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Normal").GetItemQueryIterator<Area>(queryText: queryText, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey("Base-Area") }))
+                    {
+                        areasDbs.Add(item);
+                    }
+                    await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Normal").GetItemQueryIterator<AreaSetting>(queryText: queryText, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey("AreaSetting") }))
+                    {
+                        areaSettings.Add(item);
+                    }
+                }
                 if (teacher.areas.IsNotEmpty()) {
                     foreach (var areat in teacher.areas)
                     {
-                        try
+                         
+                        Area area = areasDbs.Find(x => x.id.Equals(areat.areaId));
+                        AreaSetting setting = null;
+                        if (area != null)
                         {
-                            Area area = await client.GetContainer(Constant.TEAMModelOS, "Normal").ReadItemAsync<Area>($"{areat.areaId}", new PartitionKey("Base-Area"));
-                            AreaSetting setting = null;
-                            try
-                            {
-                                setting = await client.GetContainer(Constant.TEAMModelOS, "Normal").ReadItemAsync<AreaSetting>($"{areat.areaId}", new PartitionKey("AreaSetting"));
-                            }
-                            catch (CosmosException ex)
-                            {
-                                setting = null;
-                            }
-                            int access = 0;
-                            if (setting != null && !string.IsNullOrWhiteSpace(setting.accessConfig))
-                            {
-                                access = 1;
-                            }
-                            if (setting != null)
-                            {
-                                setting.accessConfig = null;
-                            }
-                            areas.Add(new AreaDto { areaId = area.id, name = area.name, standard = area.standard, standardName = area.standardName, setting= setting, access = access });
+                            setting = areaSettings.Find(x => x.id.Equals(areat.areaId));
                         }
-                        catch (CosmosException)
+
+                        int access = 0;
+                        if (setting != null && !string.IsNullOrWhiteSpace(setting.accessConfig))
                         {
-                            //数据库捞不到数据
-                            continue;
+                            access = 1;
                         }
+                        if (setting != null)
+                        {
+                            setting.accessConfig = null;
+                        }
+                        areas.Add(new AreaDto { areaId = area.id, name = area.name, standard = area.standard, standardName = area.standardName, setting= setting, access = access });
                     }
                 }
                 if (school_code.Equals(teacher.defaultSchool) && teacher.schools.IsNotEmpty() && !teacher.schools.Select(x => x.schoolId).Contains(school_code))
@@ -383,16 +401,12 @@ namespace TEAMModelOS.Controllers
                 if (!string.IsNullOrEmpty(school_base.areaId)) {
                     try
                     {
-                        Area  area = await client.GetContainer(Constant.TEAMModelOS, "Normal").ReadItemAsync<Area>($"{school_base.areaId}", new PartitionKey("Base-Area"));
+                        Area area = areasDbs.Find(x => x.id.Equals(school_base.areaId));
                         AreaSetting setting = null;
-                        try
-                        {
-                            setting = await client.GetContainer(Constant.TEAMModelOS, "Normal").ReadItemAsync<AreaSetting>($"{school_base.areaId}", new PartitionKey("AreaSetting"));
-                        }
-                        catch (CosmosException ex)
-                        {
-                            setting = null;
+                        if (area != null) {
+                            setting= areaSettings.Find(x => x.id.Equals(school_base.areaId));
                         }
+                        
                         int access = 0;
                         AccessConfig accessConfig = null;
                         if (setting != null && !string.IsNullOrWhiteSpace(setting.accessConfig))
@@ -405,10 +419,10 @@ namespace TEAMModelOS.Controllers
                         }
                         currArea = new   
                         {
-                            areaId = area.id, 
-                            name = area.name, 
-                            standard = area.standard, 
-                            standardName = area.standardName, 
+                            areaId = area?.id, 
+                            name = area?.name, 
+                            standard = area?.standard, 
+                            standardName = area?.standardName, 
                             setting = setting, 
                             access = access,
                             //submitType=accessConfig?.submitType,
@@ -430,7 +444,9 @@ namespace TEAMModelOS.Controllers
 
                 //取得班级
                 List<object> school_classes = new List<object>();
-                await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryStreamIterator(queryText: $"SELECT c.id,c.x,c.y,c.name,c.year,c.teacher,c.periodId,c.gradeId,c.room,c.sn,c.no,c.style,c.status,c.openType,c.school, ARRAY_LENGTH(c.students) AS studCount FROM c", requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Class-{school_code}") }))
+                await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryStreamIterator
+                    (queryText: $"SELECT c.id,c.x,c.y,c.name,c.year,c.teacher,c.periodId,c.gradeId,c.room,c.sn,c.no,c.style,c.status,c.openType,c.school, ARRAY_LENGTH(c.students) AS studCount FROM c", 
+                    requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Class-{school_code}") }))
                 {
                     var jsonc = await JsonDocument.ParseAsync(item.ContentStream);
                     foreach (var classeinfo in jsonc.RootElement.GetProperty("Documents").EnumerateArray())
@@ -445,35 +461,6 @@ namespace TEAMModelOS.Controllers
                 {
                     school_rooms.Add(item);
                 }
-                //List<object> periods = new List<object>();
-                //List<object> grades = new List<object>();
-                //var responsesch = await client.GetContainer(Constant.TEAMModelOS, "School").ReadItemStreamAsync(school_code.ToString(), new PartitionKey($"Base"));
-                //if (responsesch.Status == 200)
-                //{
-                //    var jsons = await JsonDocument.ParseAsync(responsesch.ContentStream);
-                //    if (jsons.RootElement.TryGetProperty("period", out JsonElement periodJobj))
-                //    {
-                //        foreach (var periodinfo in periodJobj.EnumerateArray())
-                //        {
-                //            dynamic periodExtobj = new ExpandoObject();
-                //            periodExtobj.id = periodinfo.GetProperty("id");
-                //            periodExtobj.name = periodinfo.GetProperty("name");
-                //            periods.Add(periodExtobj);
-                //            if (periodinfo.TryGetProperty("grades", out JsonElement gradesJobj))
-                //            {
-                //                foreach (var gradeinfo in gradesJobj.EnumerateArray())
-                //                {
-                //                    dynamic gradeExtobj = new ExpandoObject();
-                //                    gradeExtobj.id = gradeinfo.GetProperty("id");
-                //                    gradeExtobj.name = gradeinfo.GetProperty("name");
-                //                    gradeExtobj.periodId = periodinfo.GetProperty("id");
-                //                    grades.Add(gradeExtobj);
-                //                }
-                //            }
-                //        }
-                //    }
-                //}
-
                 //該老師排定的學校課程
                 List<object> school_courses = new List<object>();
                 var query = $"SELECT distinct value(c) FROM c JOIN A1 IN c.schedule where A1.teacherId='{id}'";
@@ -488,7 +475,14 @@ namespace TEAMModelOS.Controllers
                         }
                     }
                 }
-
+                List<SchoolProductSumProdInfo> prodInfos = new List<SchoolProductSumProdInfo>();
+                Azure.Response productSumResponse = await client.GetContainer(Constant.TEAMModelOS, "School").ReadItemStreamAsync(school_code, new PartitionKey("ProductSum"));
+                if (productSumResponse.Status == 200) {
+                    var doc= JsonDocument.Parse(productSumResponse.Content);
+                    if (doc.RootElement.TryGetProperty("prodinfo", out JsonElement element)) {
+                        prodInfos = element.ToObject<List<SchoolProductSumProdInfo>>();                  
+                    }
+                }
                 //校本課綱 [式樣未定 先不取]
                 
                 //取得School Blob 容器位置及SAS
@@ -498,7 +492,7 @@ namespace TEAMModelOS.Controllers
                 var (blob_uri, blob_sas) = (roles.Contains("admin") || permissions.Contains("schoolAc-upd")) ? _azureStorage.GetBlobContainerSAS(school_code_blob, BlobContainerSasPermissions.Write | BlobContainerSasPermissions.Read | BlobContainerSasPermissions.List | BlobContainerSasPermissions.Delete) : _azureStorage.GetBlobContainerSAS(school_code_blob, BlobContainerSasPermissions.Read | BlobContainerSasPermissions.List | BlobContainerSasPermissions.Write);
                 ///https://teammodelstorage.blob.core.chinacloudapi.cn/teammodelos
                 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);
-                return Ok(new { auth_token, blob_uri, blob_sas, school_base, school_courses,  school_classes, school_rooms, size, osblob_uri, osblob_sas, status = 200, areas , currArea });
+                return Ok(new { auth_token, blob_uri, blob_sas, school_base, school_courses,  school_classes, school_rooms, size, osblob_uri, osblob_sas, status = 200, areas , currArea , productSum= new { prodinfo= prodInfos } });
             }
             catch (CosmosException ex)
             {
@@ -507,7 +501,7 @@ namespace TEAMModelOS.Controllers
                 HttpContext.Request.Headers.TryGetValue("sec-ch-ua-platform", out var platform);
                 HttpContext.Request.Headers.TryGetValue("user-agent", out var useragent);
                 await _dingDing.SendBotMsg($"IES5,{_option.Location},Teacher/init/get-school-info()\n{ex.Message}{ex.StackTrace}\n{request.ToJsonString()}\nreferer:{referer}\nsec-ch-ua:{chua}\nsec-ch-ua-platform:{platform}\nuser-agent:{useragent}", GroupNames.醍摩豆服務運維群組);
-                return Ok(new { status = ex.Status });
+                return BadRequest(new { status = ex.Status });
             }
             catch (Exception ex)
             {
@@ -516,7 +510,7 @@ namespace TEAMModelOS.Controllers
                 HttpContext.Request.Headers.TryGetValue("sec-ch-ua-platform", out var platform);
                 HttpContext.Request.Headers.TryGetValue("user-agent", out var useragent);
                 await _dingDing.SendBotMsg($"IES5,{_option.Location},Teacher/init/get-school-info()\n{ex.Message}{ex.StackTrace}\n{request.ToJsonString()}\nreferer:{referer}\nsec-ch-ua:{chua}\nsec-ch-ua-platform:{platform}\nuser-agent:{useragent}", GroupNames.醍摩豆服務運維群組);
-                return Ok(new { status = 500 });
+                return BadRequest(new { status = 500 });
             }
         }
 

+ 2 - 259
TEAMModelOS/Controllers/Teacher/TeacherInitController.cs

@@ -68,7 +68,7 @@ namespace TEAMModelOS.Controllers
                 jwt.Payload.TryGetValue("name", out object name);
                 jwt.Payload.TryGetValue("picture", out object picture);
                 Teacher teacher = null;
-                TeacherInfo teacherInfo = await TeacherInfo(_azureCosmos, teacher, $"{name}", $"{picture}", id, _azureStorage, _option);
+                TeacherInfo teacherInfo = await TeacherService. TeacherInfo(_azureCosmos, teacher, $"{name}", $"{picture}", id, _azureStorage, _option);
                 return Ok(new
                 {
                     location = _option.Location,
@@ -98,263 +98,6 @@ namespace TEAMModelOS.Controllers
             }
         }
 
-        public static async Task<TeacherInfo> TeacherInfo(AzureCosmosFactory _azureCosmos, Teacher teacher, string name, string picture, string id, AzureStorageFactory _azureStorage, Option _option)
-        {
-            List<object> schools = new List<object>();
-            List<AreaDto> areas = new List<AreaDto>();
-            List<Area> areasd = new List<Area>();
-            string defaultschool = null;
-            //TODO 取得Teacher 個人相關數據(課程清單、虛擬教室清單、歷史紀錄清單等),學校數據另外API處理,多校切換時不同
-            var client = _azureCosmos.GetCosmosClient();
-            int total = 0;
-            int tsize = 0;
-            try
-            {
-                if (teacher == null)
-                {
-                    teacher = await client.GetContainer(Constant.TEAMModelOS, "Teacher").ReadItemAsync<Teacher>(id, new PartitionKey("Base"));
-                    teacher.name = $"{name}";
-                    teacher.picture = $"{picture}";
-                }
-                else
-                {
-                    name = teacher.name;
-                    picture = teacher.picture;
-                    id = teacher.id;
-                }
-                ///教师的个人空间
-                tsize = teacher.size;
-                ///教师的总空间 包含 个人空间和学校赠送的空间累加
-                total = teacher.size;
-                //areas = teacher.areas;
-                if (teacher.areas.IsNotEmpty())
-                {
-                    //teacher.areas.Select(x => x.areaId);
-                    //await foreach (var item    client.GetContainer(Constant.TEAMModelOS, "Normal").GetItemQueryIterator<Area>($"{areat.areaId}", new PartitionKey("Base-Area"))) { 
-
-                    //}
-                    //https://test.teammodel.cn/hita/join-school?ts=1644291704907&school=cdxcwgy
-                    foreach (var areat in teacher.areas)
-                    {
-                        try
-                        {
-                            Area area = await client.GetContainer(Constant.TEAMModelOS, "Normal").ReadItemAsync<Area>($"{areat.areaId}", new PartitionKey("Base-Area"));
-                            areasd.Add(area);
-                            AreaSetting setting = null;
-                            try
-                            {
-                                setting = await client.GetContainer(Constant.TEAMModelOS, "Normal").ReadItemAsync<AreaSetting>($"{areat.areaId}", new PartitionKey("AreaSetting"));
-                            }
-                            catch (CosmosException ex)
-                            {
-                                setting = null;
-                            }
-                            int access = 0;
-                            if (setting != null && !string.IsNullOrWhiteSpace(setting.accessConfig))
-                            {
-                                access = 1;
-                            }
-                            if (setting != null)
-                            {
-                                setting.accessConfig = null;
-                            }
-                            areas.Add(new AreaDto { areaId = area.id, name = area.name, standard = area.standard, standardName = area.standardName, setting = setting, access = access });
-                        }
-                        catch (CosmosException)
-                        {
-                            //数据库捞不到数据
-                            continue;
-                        }
-                    }
-                }
-                //检查是否有加入学校,如果加入学校,则当个人空间size是0G的时候,则免费获得一个G空间,但无论加入多少个学校,只能获取一次 1G的免费空间。没有加入学校则默认0G空间,除非自己购买空间
-                if (teacher.schools.IsNotEmpty())
-                {
-                    foreach (var sc in teacher.schools)
-                    {
-                        string statusNow = sc.status != null ? sc.status : "";
-                        if (statusNow.Equals("join") || statusNow.Equals("invite") || statusNow.Equals("request"))
-                        {
-                            dynamic schoolExtobj = new ExpandoObject();
-                            // var schoolJson = await client.GetContainer(Constant.TEAMModelOS, "School").ReadItemStreamAsync($"{sc.schoolId}", new PartitionKey("Base"));
-                            //var school = await JsonDocument.ParseAsync(schoolJson.ContentStream);
-                            schoolExtobj.schoolId = sc.schoolId;
-                            schoolExtobj.name = sc.name;
-                            schoolExtobj.status = sc.status;
-                            schoolExtobj.time = sc.time;
-                            schoolExtobj.picture = sc.picture;
-                            schoolExtobj.areaId = $"{sc.areaId}";
-                            Area area = null;
-                            int access = 0;
-                            if (!string.IsNullOrEmpty($"{sc.areaId}"))
-                            {
-
-                                try
-                                {
-
-                                    area = await client.GetContainer(Constant.TEAMModelOS, "Normal").ReadItemAsync<Area>($"{sc.areaId}", new PartitionKey("Base-Area"));
-                                    AreaSetting setting = null;
-                                    try
-                                    {
-                                        setting = await client.GetContainer(Constant.TEAMModelOS, "Normal").ReadItemAsync<AreaSetting>($"{area.id}", new PartitionKey("AreaSetting"));
-                                    }
-                                    catch (CosmosException ex)
-                                    {
-                                        setting = null;
-                                    }
-
-                                    if (setting != null && !string.IsNullOrWhiteSpace(setting.accessConfig))
-                                    {
-                                        access = 1;
-                                    }
-                                    areasd.Add(area);
-
-                                }
-                                catch (CosmosException)
-                                {
-                                    area = null;
-                                }
-                            }
-                            if (area != null)
-                            {
-                                schoolExtobj.area = new { area.name, area.id, area.institution, area.provName, area.code, area.cityCode, area.cityName, area.standard, area.provCode, area.pk, access };
-
-                            }
-                            else
-                            {
-                                schoolExtobj.area = area;
-                            }
-                            var sctch = await client.GetContainer(Constant.TEAMModelOS, "School").ReadItemStreamAsync(id, new PartitionKey($"Teacher-{sc.schoolId}"));
-                            if (sctch.Status == 200)
-                            {
-                                var jsonDoc = await JsonDocument.ParseAsync(sctch.ContentStream);
-                                SchoolTeacher schoolTeacher = jsonDoc.RootElement.ToObject<SchoolTeacher>();
-                                schoolTeacher.name = $"{name}";
-                                schoolTeacher.picture = $"{picture}";
-                                await client.GetContainer(Constant.TEAMModelOS, "School").ReplaceItemAsync(schoolTeacher, id, new PartitionKey($"Teacher-{sc.schoolId}"));
-                                if (jsonDoc.RootElement.TryGetProperty("size", out JsonElement _size) && _size.ValueKind.Equals(JsonValueKind.Number))
-                                {
-                                    total += _size.GetInt32();
-                                    schoolExtobj.size = _size.GetInt32();
-                                }
-                                else { schoolExtobj.size = 0; }
-                            }
-                            else
-                            {
-                                schoolExtobj.size = 0;
-                            }
-                            if (statusNow.Equals("join"))
-                            {
-                                //初始化
-                                await TmdUserService.JoinSchool(client, teacher.id, teacher.picture, teacher.name, sc.schoolId, sc.name);
-                            }
-                            schools.Add(schoolExtobj);
-                        }
-                    }
-                    //如果包含任何申请,邀请,加入学校的记录 且个人空间未分配2G  则默认分配个人空间至2G.
-                    if (teacher.size < 2 && teacher.schools.Count > 0)
-                    {
-                        teacher.size = 2;
-                    }
-                    //如果未包含任何申请,邀请,加入学校的记录 且 个人空间没有分配1G 则默认赠送一个G 
-                    if (teacher.schools.Count == 0 && teacher.size < 1)
-                    {
-                        teacher.size = 1;
-                    }
-                }
-                if (string.IsNullOrEmpty(teacher.defaultSchool) && teacher.schools.IsNotEmpty())
-                {
-                    var tech = teacher.schools.FindAll(x => x.status.Equals("join"));
-                    if (tech.IsNotEmpty())
-                    {
-                        teacher.defaultSchool = teacher.schools[0].schoolId;
-                    }
-                }
-                await client.GetContainer(Constant.TEAMModelOS, "Teacher").ReplaceItemAsync<Teacher>(teacher, id, new PartitionKey("Base"));
-                //預設學校ID
-                defaultschool = teacher.defaultSchool;
-            }
-            catch (CosmosException ex)
-            {
-                if (ex.Status == 404)
-                {
-                    //如果沒有,則初始化Teacher基本資料到Cosmos
-                    teacher = new Teacher
-                    {
-                        id = id,
-                        pk = "Base",
-                        code = "Base",
-                        name = name?.ToString(),
-                        picture = picture?.ToString(),
-                        //创建账号并第一次登录IES5则默认赠送1G
-                        size = 1,
-                        defaultSchool = null,
-                        schools = new List<Teacher.TeacherSchool>(),
-                    };
-                    var container = _azureStorage.GetBlobContainerClient(id);
-                    await container.CreateIfNotExistsAsync(PublicAccessType.None); //嘗試創建Teacher私有容器,如存在則不做任何事,保障容器一定存在
-                    teacher = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Teacher").CreateItemAsync<Teacher>(teacher, new PartitionKey("Base"));
-                    total = teacher.size;
-                    tsize = teacher.size;
-                }
-            }
-            catch (Exception ex) {
-                throw new Exception($"{ex.Message}{ex.StackTrace}");
-            }
-            //私人課程
-            List<object> courses = new List<object>();
-            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}") }))
-            {
-                using var json = await JsonDocument.ParseAsync(item.ContentStream);
-                if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
-                {
-                    foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
-                    {
-                        courses.Add(obj.ToObject<object>());
-                    }
-                }
-            }
-
-
-            List<string> roles = new List<string>() { "teacher" };
-            Area areaa = null;
-            if (areas.Count > 0)
-            {
-                roles.Add("area");
-                if (!string.IsNullOrEmpty($"{areas[0]}"))
-                {
-
-                    try
-                    {
-                        areaa = await client.GetContainer(Constant.TEAMModelOS, "Normal").ReadItemAsync<Area>($"{areas[0].areaId}", new PartitionKey("Base-Area"));
-                    }
-                    catch (CosmosException)
-                    {
-                        areaa = null;
-                    }
-                }
-            }
-            //換取AuthToken,提供給前端
-            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());
-            //取得Teacher Blob 容器位置及SAS 
-            await _azureStorage.GetBlobContainerClient(id).CreateIfNotExistsAsync(PublicAccessType.None); //嘗試創建Teacher私有容器,如存在則不做任何事,保障容器一定存在
-            var (blob_uri, blob_sas) = _azureStorage.GetBlobContainerSAS(id, BlobContainerSasPermissions.Write | BlobContainerSasPermissions.Read | BlobContainerSasPermissions.List | BlobContainerSasPermissions.Delete);
-            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);
-            return new TeacherInfo
-            {
-                auth_token = auth_token,
-                blob_uri = blob_uri,
-                blob_sas = blob_sas,
-                schools = schools,
-                defaultschool = defaultschool,
-                courses = courses,
-                total = total,
-                osblob_sas = osblob_sas,
-                osblob_uri = osblob_uri,
-                tsize = tsize,
-                areas = areas,
-                teacher = teacher
-            };
-        }
+        
     }
 }