1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009 |
- using Microsoft.AspNetCore.Mvc;
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Threading.Tasks;
- using TEAMModelOS.Models;
- using TEAMModelOS.SDK.DI;
- using System.Text.Json;
- using TEAMModelOS.SDK.Models;
- using Microsoft.AspNetCore.Http;
- using TEAMModelOS.SDK.Extension;
- using Azure.Cosmos;
- using System.Text;
- using TEAMModelOS.SDK.DI.AzureCosmos.Inner;
- using Microsoft.Extensions.Options;
- using Azure.Messaging.ServiceBus;
- using Microsoft.Extensions.Configuration;
- using TEAMModelOS.Services.Common;
- using HTEXLib.COMM.Helpers;
- using TEAMModelOS.SDK;
- using System.IdentityModel.Tokens.Jwt;
- using TEAMModelOS.Services;
- using TEAMModelOS.SDK.Models.Service;
- using System.IO;
- using System.Dynamic;
- using Microsoft.AspNetCore.Authorization;
- using Azure.Storage.Blobs.Models;
- using static TEAMModelOS.SDK.Models.Teacher;
- using System.Web;
- using static TEAMModelOS.Controllers.FixDataController;
- using static TEAMModelOS.SDK.SchoolService;
- using Microsoft.AspNetCore.Hosting;
- namespace TEAMModelOS.Controllers.Third
- {
- /// <summary>
- ///
- /// </summary>
- ///
- [ProducesResponseType(StatusCodes.Status200OK)]
- [ProducesResponseType(StatusCodes.Status400BadRequest)]
- //[Authorize(Roles = "IES")]
- //[Route("")]
- //[Route("api/[controller]")]
- [ApiController]
- public class ScController : ControllerBase
- {
- private readonly SnowflakeId _snowflakeId;
- private readonly AzureCosmosFactory _azureCosmos;
- private readonly DingDing _dingDing;
- private readonly Option _option;
- private readonly AzureStorageFactory _azureStorage;
- private readonly AzureServiceBusFactory _serviceBus;
- private readonly AzureRedisFactory _azureRedis;
- private readonly CoreAPIHttpService _coreAPIHttpService;
- private readonly ThirdApisService _scsApisService;
- public readonly string type = "scsyxpt";
- private readonly HttpTrigger _httpTrigger;
- private readonly IWebHostEnvironment _environment;
- /// <summary>
- /// 机构安全码
- /// </summary>
- public string _sc_passKey;
- /// <summary>
- /// 机构ID
- /// </summary>
- public string _sc_trainComID;
- /// <summary>
- /// 机构 AES 密钥
- /// </summary>
- public string _sc_privateKey;
- /// <summary>
- /// 访问地址
- /// </summary>
- public string _sc_url;
- public IConfiguration _configuration { get; set; }
- public ScController(IWebHostEnvironment environment,AzureCosmosFactory azureCosmos, SnowflakeId snowflakeId, DingDing dingDing, IOptionsSnapshot<Option> option, AzureStorageFactory azureStorage,
- AzureRedisFactory azureRedis, AzureServiceBusFactory serviceBus, IConfiguration configuration, CoreAPIHttpService coreAPIHttpService, ThirdApisService scsApisService, HttpTrigger httpTrigger)
- {
- _azureCosmos = azureCosmos;
- _snowflakeId = snowflakeId;
- _dingDing = dingDing;
- _option = option?.Value;
- _azureStorage = azureStorage;
- _serviceBus = serviceBus;
- _configuration = configuration;
- _azureRedis = azureRedis;
- _coreAPIHttpService = coreAPIHttpService;
- _scsApisService = scsApisService;
- _sc_passKey = _configuration.GetValue<string>("Third:scsyxpt:passKey");
- _sc_trainComID = _configuration.GetValue<string>("Third:scsyxpt:trainComID");
- _sc_privateKey = _configuration.GetValue<string>("Third:scsyxpt:privateKey");
- _sc_url = _configuration.GetValue<string>("Third:scsyxpt:url");
- _httpTrigger = httpTrigger;
- _environment = environment;
- }
- /// <summary>
- /// 检查醍摩豆id存在多个学校的情况
- /// </summary>
- /// <param name="request"></param>
- /// <returns></returns>
- [ProducesDefaultResponseType]
- [HttpPost("sc/get-project-school-teacher")]
- [AllowAnonymous]
- public async Task<IActionResult> GetProjectSchoolTeacher(JsonElement request) {
- if (!request.TryGetProperty("accessConfig", out JsonElement accessConfig)) return BadRequest();
- if (!request.TryGetProperty("ignoreSchools", out JsonElement ignoreSchools)) return BadRequest();
- if (!request.TryGetProperty("city", out JsonElement city)) return BadRequest();
- if (!request.TryGetProperty("dist", out JsonElement dist)) return BadRequest();
- if (!request.TryGetProperty("areaId", out JsonElement areaId)) return BadRequest();
- if (!request.TryGetProperty("standard", out JsonElement standard)) return BadRequest();
- List<IdNameCode> ignore = ignoreSchools.ToObject<List<IdNameCode>>();
- Dictionary<string, object> dict = new Dictionary<string, object> { { "accessConfig", $"{accessConfig}" } };
- int status = -1;string json = null;
- //5.3.1.1获取项目列表
- (status, json) = await _httpTrigger.RequestHttpTrigger(dict, _option.Location, "GetProjectInfoByTrainComID");
- List<ScProject> projects = null;
- List<ScSchool> saveschools = null;
- List<ScSchool> schools = null;
- List<ScSchool> matchSchools = null;
- List<ScSchool> tbschools=null;
- if (status == 200)
- {
- projects = json.ToObject<List<ScProject>>(new JsonSerializerOptions { PropertyNameCaseInsensitive = false });
- }
- // 5.3.1.18根据机构ID、项目ID、子项目ID返回学校列表
- (status, json) = await _httpTrigger.RequestHttpTrigger(dict, _option.Location, "GetSchoolList");
- if (status == 200)
- {
- schools = json.ToObject<List<ScSchool>>(new JsonSerializerOptions { PropertyNameCaseInsensitive = false });
- if (ignore.IsNotEmpty())
- {
- matchSchools = schools.FindAll(x => ignore.Select(y=>y.name).Contains(x.schoolname));
- if (matchSchools.IsNotEmpty())
- {
- if (matchSchools.Count != ignore.Count)
- {
- var matched = matchSchools.Select(x => x.schoolname);
- var unmatch = ignore.Select(y => y.name).Except(matched);
- return Ok(new { matched, unmatch });
- }
- else {
- matchSchools.ForEach(x => {
- var exschool= ignore.Find(y => y.name.Equals(x.schoolname));
- if (exschool != null) {
- x.schoolCode = exschool.id;
- x.areaId = $"{areaId}";
- x.city = $"{city}";
- x.dist = $"{dist}";
- }
- });
- }
- }
- else {
- return Ok(new { unmatch=ignore, schools }) ;
- }
- }
- //数据校验
- tbschools = await _azureStorage.FindListByDict<ScSchool>(new Dictionary<string, object>() { { "PartitionKey", $"ScSchool" } });
- if (tbschools.IsNotEmpty())
- {
-
- var a = tbschools.Select(y => $"{y.RowKey}").ToList();
- saveschools = schools.Where(x=>!a.Exists(z=>z.Equals($"{x.schoolid}"))).ToList();
- List<SchoolData> schoolDatas = new List<SchoolData>();
- saveschools.ForEach(x =>
- {
- x.RowKey = $"{x.schoolid}";
- x.PartitionKey = "ScSchool";
- x.areaId = $"{areaId}";
- x.city = $"{city}";
- x.dist = $"{dist}";
- if (string.IsNullOrEmpty(x.schoolCode))
- {
- schoolDatas.Add(new SchoolData { uid = $"{x.schoolid}", province = "四川省", city = $"{city}", name = x.schoolname });
- }
- });
- schoolDatas = await SchoolService.GenerateSchoolCode(schoolDatas, _dingDing, _environment);
- saveschools.ForEach(x => {
- var schoolData = schoolDatas.Find(y => y.uid.Equals($"{x.schoolid}"));
- if (schoolData != null && !string.IsNullOrEmpty(schoolData.id))
- {
- x.schoolCode = schoolData.id;
- x.areaId = $"{areaId}";
- x.city = $"{city}";
- x.dist = $"{dist}";
- }
- });
- saveschools.RemoveAll(x => string.IsNullOrEmpty(x.schoolCode));
- saveschools.RemoveAll(x => tbschools.FindAll(z=>!string.IsNullOrEmpty(z.schoolCode)).Exists(y=>y.schoolCode.Equals(x.schoolCode)));
- saveschools = await _azureStorage.SaveAll(saveschools);
- }
- else {
- List<SchoolData> schoolDatas = new List<SchoolData>();
- schools.ForEach(x =>
- {
- x.RowKey = $"{x.schoolid}";
- x.PartitionKey = "ScSchool";
- x.areaId = $"{areaId}";
- x.city = $"{city}";
- x.dist = $"{dist}";
- if (string.IsNullOrEmpty(x.schoolCode))
- {
- schoolDatas.Add(new SchoolData { uid = $"{x.schoolid}", province = "四川省", city = $"{city}", name = x.schoolname });
- }
-
- });
- schoolDatas = await SchoolService.GenerateSchoolCode(schoolDatas, _dingDing, _environment);
- schools.ForEach(x => {
-
- var schoolData = schoolDatas.Find(y => y.uid.Equals($"{x.schoolid}"));
- if (schoolData != null && !string.IsNullOrEmpty(schoolData.id)) {
- x.schoolCode = schoolData.id;
- x.areaId = $"{areaId}";
- x.city = $"{city}";
- x.dist = $"{dist}";
- }
- });
- schools.RemoveAll(x => string.IsNullOrEmpty(x.schoolCode));
- saveschools = await _azureStorage.SaveAll(schools);
- }
- }
-
- List<string> unsave = new List<string>();
- if (saveschools.IsNotEmpty()) {
- var ex = schools.Select(x => $"{x.schoolid}").Except(saveschools.Select(y=>y.RowKey));
- if (ex.Count() > 0) {
- unsave.AddRange(ex);
- }
- }
- if (tbschools.IsNotEmpty())
- {
- var ex = schools.Select(x => $"{x.schoolid}").Except(tbschools.Select(y => y.RowKey));
- if (ex.Count() > 0)
- {
- unsave.AddRange(ex);
- }
- }
- var areaschools = await _azureStorage.FindListByDict<ScSchool>(new Dictionary<string, object>() { { "PartitionKey", $"ScSchool" } ,{ "areaId",$"{areaId}" } });
- List<School> cosbdschools = new List<School>();
- await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "School").GetItemQueryIterator<School>(queryText: $"select value(c) from c where c.areaId='{areaId}'", requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Base") }))
- {
- cosbdschools.Add(item);
- }
- var tbs = areaschools.FindAll(x => areaschools.Select(z => z.schoolCode).Except(cosbdschools.Select(x => x.id)).Contains(x.schoolCode));
- List<CSchool> cSchools = new List<CSchool>();
- foreach (var sch in tbs) {
- cSchools.Add(new CSchool
- {
- id = sch.schoolCode,
- name = sch.schoolname,
- // admin = "1530606136",
- period = new List<string>() { sch.schooltypename },
- size = 100,
- });
-
- }
-
- var client = _azureCosmos.GetCosmosClient();
- List<School> schoolsfailed = new List<School>();
- List<School> schoolsScucess = new List<School>();
- List<string> failedmsg= new List<string>();
- foreach (var sc in cSchools)
- {
- List<Period> periods = new List<Period>();
- string campusId = Guid.NewGuid().ToString();
- sc.period.ForEach(x => {
- periods.Add(new Period { id = Guid.NewGuid().ToString(), name = x, campusId = campusId });
- });
- School school = new School
- {
- id = sc.id,
- name = sc.name,
- size = sc.size,
- code = "Base",
- campuses = new List<Campus> { new Campus { name = sc.name, id = campusId } },
- region = "中国",
- province = "四川省",
- city = $"{city}",
- timeZone = new SDK.Models.TimeZone { label = "(UTC+08:00) 北京,重庆,香港特别行政区,乌鲁木齐", value = "+08:00" },
- type = 1,
- pk = "School",
- ttl = -1,
- schoolCode = sc.id,
- dist=$"{dist}",
- period = periods,
- areaId =$"{areaId}",
- standard=$"{standard}"
- };
- try
- {
- await client.GetContainer(Constant.TEAMModelOS, "School").CreateItemAsync<School>(school, new PartitionKey(school.code));
- schoolsScucess.Add(school);
- }
- catch (CosmosException ex)
- {
- failedmsg.Add($"{school.ToJsonString()}\n \n{ex.Status}{ex.Message }\n {ex.StackTrace}");
- schoolsfailed.Add(school);
- }
- catch (Exception ex) {
- failedmsg.Add($"{school.ToJsonString()}\n{ex.Message }\n {ex.StackTrace}");
- schoolsfailed.Add(school);
- }
- }
- //省平台获取到的学生。
- List<ScTeacher> teachers = new();
- // 5.3.1.2获取学员名单
- (status, json) = await _httpTrigger.RequestHttpTrigger(dict, _option.Location, "GetTeachersListByProject");
- if (status == 200)
- {
- teachers = json.ToObject<List<ScTeacher>>(new JsonSerializerOptions { PropertyNameCaseInsensitive = false });
- if (teachers.IsNotEmpty()) {
- teachers.ForEach(x => {
- x.RowKey = $"{x.PXID}";
- x.PartitionKey = "ScTeacher";
- x.areaId = $"{areaId}";
- });
- var areaTeacher = await _azureStorage.FindListByDict<ScSchool>(new Dictionary<string, object>() { { "PartitionKey", $"ScTeacher" }, { "areaId", $"{areaId}" } });
- if (areaTeacher.IsNotEmpty())
- {
- // areaTeacher
- }
- else
- {
- teachers= await _azureStorage.SaveAll(teachers);
- }
- }
-
- }
- return Ok(new {
- projects, msg=$"Table中已经有:{tbschools.Count}个学校,省平台获取到:{schools.Count}个学校,本次保存有:{saveschools?.Count},没有被保存的学校:{unsave.Count},创建失败的学校有:{schoolsfailed.Count()},创建成功的的学校有:{schoolsScucess.Count()}",
- schoolsfailed,
- failedmsg,
- schoolsScucess,
- tbsch= tbschools.Select(x=>new { x.schoolname,x.schoolCode})
- });
- }
- /// <summary>
- /// 检查醍摩豆id存在多个学校的情况
- /// </summary>
- /// <param name="request"></param>
- /// <returns></returns>
- [ProducesDefaultResponseType]
- [HttpPost("sc/check-bind")]
- [AllowAnonymous]
- public async Task<IActionResult> CheckBlobBinds(JsonElement json)
- {
- List<GroupList> teachers = new List<GroupList>();
- string sqs = "select c.members from c where c.pk='GroupList' and c.type='yxtrain' and c.school in ('pjsyzx','pjzx','pjsazx','pjbjxx','pjxnxx','pjthxx','pjcyxx','pjfxxx','pjwjxx','pjzyzx','psywgy','hscjzx','cyhjnz','psasmx','psacjz','pwxjnx','pptsfx','pjjysx','xlzjnx','pdtjnx','pgxjnx','pcjjnx','pdxjnx','pnjyey','pbjyey','pcbyey','pcxyey','pcnyey','xjwhye','pxlyey','sazxye','saxcye','pthyey','psmyey','pshyey','pwxyey','pjysye','pfxyey','pgxyey','pcjyey','pcyhye','pbyyey','pdtyey','xyheye','xhyey','xbeyey','hhzyey','xxyey','saxgye','xllxye','dxxmye','dtxmye','dtydye','pnjdxy','pcxgmy','pcbgqy','saxccq','pjjsjx') ";
- await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "School").GetItemQueryIterator<GroupList>(queryText: sqs))
- {
- teachers.Add(item);
-
- }
- var a = teachers.SelectMany(x => x.members).GroupBy(y=>y.id).ToList();
- var ae= a.Select(x => new { key = x.Key, val = x.ToList().Count() });
- ae= ae.Where(x => x.val > 1);
- return Ok(new { ae });
- }
- /// <summary>
- ///
- /// </summary>
- /// <param name="request"></param>
- /// <returns></returns>
- [ProducesDefaultResponseType]
- [HttpPost("sc/fix-bind")]
- [AllowAnonymous]
- public async Task<IActionResult> FixBlobBinds(JsonElement json)
- {
- List<string> teacherids = new List<string>();
- string sql = $" SELECT value(c.id) FROM c where ARRAY_LENGTH(c.binds)>0 ";
- await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Teacher").GetItemQueryIterator<string>(queryText: sql, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Base") }))
- {
- teacherids.Add(item);
- }
- var bloblist = await _azureStorage.GetBlobContainerClient("teammodelos").List($"yxpt/scpjx/scbind");
- bloblist = bloblist.Select(x => x.Substring(18, 10)).ToList();
- List<string> tmdids = teacherids.Except(bloblist).ToList();
- List<Teacher> teachers = new List<Teacher>();
- sql = $" SELECT value(c) FROM c where ARRAY_LENGTH(c.binds)>0 ";
- if (tmdids != null)
- {
- sql = $"{sql} and c.id in ( {string.Join(",", tmdids.Select(x => $"'{x}'"))} )";
- await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Teacher").GetItemQueryIterator<Teacher>(queryText: sql,
- requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Base") }))
- {
- teachers.Add(item);
- }
- }
- List<string> unbind = new List<string>();
- List<string> list = new List<string>();
- HashSet<string> schoolIds= teachers.Where(z=>z.schools.IsNotEmpty()).SelectMany(x => x.schools).Where(m=>m.status.Equals("join")).Select(y => y.schoolId).ToHashSet();
- List<GroupList> groupLists = new List<GroupList>();
- foreach (var schoolid in schoolIds) {
- StringBuilder queryText = new StringBuilder($"SELECT distinct value(c) FROM c where c.type='yxtrain'");
- await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "School").GetItemQueryIterator<GroupList>(queryText: queryText.ToString(),
- requestOptions: new QueryRequestOptions() { PartitionKey = new Azure.Cosmos.PartitionKey($"GroupList-{schoolid}") }))
- {
- groupLists.Add(item);
- }
- }
- foreach (var teacher in teachers)
- {
- var a = teacher.binds.SelectMany(y => y.data).ToList().Find(x => !string.IsNullOrEmpty(x));
- if (a != null)
- {
- await _azureStorage.UploadFileByContainer("teammodelos", a, $"yxpt/scpjx/scbind", $"{teacher.id}.json");
- }
- else
- {
- unbind.Add(teacher.id);
- }
- if (teacher.schools.IsNotEmpty())
- {
- foreach (var school in teacher.schools)
- {
- if (!string.IsNullOrEmpty(school.schoolId) )
- {
-
- if (school.status.Equals("join")) {
- List<GroupList> yxtrain = groupLists.FindAll(x=>x.code.Equals($"GroupList-{school.schoolId}"));
- if (yxtrain.IsNotEmpty())
- {
- var meber = yxtrain.SelectMany(x => x.members).Where(y => y.id.Equals(teacher.id));
- //不在研修名单
- if (meber == null || meber.Count() <= 0)
- {
- yxtrain[0].members.Add(new Member { id = teacher.id, type = 1 });
- await GroupListService.UpsertList(yxtrain[0], _azureCosmos, _configuration, _serviceBus);
- }
- }
- else
- {
- GroupList groupList = new GroupList()
- {
- id = Guid.NewGuid().ToString(),
- code = $"GroupList-{school.schoolId}",
- creatorId = teacher.id,
- type = "yxtrain",
- year = DateTimeOffset.UtcNow.Year,
- members = new List<Member> { new Member { id = teacher.id, type = 1 } },
- scope = "school",
- school = school.schoolId,
- name = "研修名单",
- pk = "GroupList",
- ttl = -1
- };
- await GroupListService.UpsertList(groupList, _azureCosmos, _configuration, _serviceBus);
- }
- }
- Azure.Response response = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "School").ReadItemStreamAsync(teacher.id, new PartitionKey($"Teacher-{school.schoolId}"));
- if (response.Status != 200)
- {
- SchoolTeacher schoolTeacher = new SchoolTeacher
- {
- id = teacher.id,
- code = $"Teacher-{school.schoolId}",
- pk = "Teacher",
- name = teacher.name,
- picture = teacher.picture,
- size = 0,
- roles = new List<string> { "teacher" },
- permissions = new List<string>(),
- status = school.status,
- createTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(),
- ttl = -1
- };
- await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "School").CreateItemAsync(teacher.id, new PartitionKey($"Teacher-{school.schoolId}"));
- }
- else {
- JsonDocument document = await JsonDocument.ParseAsync(response.ContentStream);
- SchoolTeacher schoolTeacher = document.RootElement.ToObject<SchoolTeacher>();
- schoolTeacher.status =school.status;
- schoolTeacher.pk = "Teacher";
- schoolTeacher.name = teacher.name;
- schoolTeacher.picture = teacher.picture;
- if (schoolTeacher.roles.IsEmpty() || !schoolTeacher.roles.Contains("teacher"))
- {
- schoolTeacher.roles = new List<string> { "teacher" };
- }
- schoolTeacher.permissions = schoolTeacher.permissions.IsNotEmpty() ? schoolTeacher.permissions : new List<string>();
-
- schoolTeacher.createTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
- schoolTeacher.ttl = -1;
- await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "School").ReplaceItemAsync(schoolTeacher, schoolTeacher.id, new PartitionKey($"Teacher-{school.schoolId}"));
- }
- }
- }
- }
- }
- return Ok(new { unbind ,list});
- }
- /// <summary>
- ///
- /// </summary>
- /// <param name="request"></param>
- /// <returns></returns>
- [ProducesDefaultResponseType]
- [HttpPost("sc/bind")]
- [AllowAnonymous]
- public async Task<IActionResult> Bind(SSO sso) {
- try
- {
- Teacher teacher = null;
- if (string.IsNullOrEmpty(sso.id_token) && string.IsNullOrEmpty(sso.mobile)) {
- return Ok(new
- {
- location = _option.Location,
- status = 2,
- });
- }
- if (string.IsNullOrEmpty(sso.id_token) && !string.IsNullOrEmpty(sso.mobile)) {
-
- }
- JwtSecurityToken jwt = null;
- try {
- jwt = new JwtSecurityToken(sso.id_token);
- } catch (Exception ex) {
- await _dingDing.SendBotMsg($"OS,{_option.Location}\n绑定失败,出现的原因可能是 参数异常:\n{sso.ToJsonString()},{ex.Message}\n{ex.StackTrace}", GroupNames.成都开发測試群組);
- return BadRequest();
- }
- if (!jwt.Payload.Iss.Equals("account.teammodel", StringComparison.OrdinalIgnoreCase)) return BadRequest();
- var id = jwt.Payload.Sub;
- jwt.Payload.TryGetValue("name", out object name);
- jwt.Payload.TryGetValue("picture", out object picture);
- ScSSOData scsso = HttpUtility.UrlDecode(sso.param, Encoding.UTF8).ToObject<ScSSOData>();
- var client = _azureCosmos.GetCosmosClient();
- try
- {
- teacher = await client.GetContainer(Constant.TEAMModelOS, "Teacher").ReadItemAsync<Teacher>(id, new PartitionKey("Base"));
- //先检查绑定的平台是否已经被绑定
- //四川研训平台跳转隐式登录/或者绑定IES平台接入规范
- string sql = $"SELECT distinct value(c) FROM c join A1 in c.binds where A1.tid='{scsso.tid}'";
- await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Teacher").GetItemQueryIterator<Teacher>(queryText: sql,
- requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Base") }))
- {
- teacher = item;
- break;
- }
- if (teacher != null)
- {
- if (teacher.id.Equals(id))
- {
- //var bind = teacher.binds.Find(x => x.source.Equals($"{scsso.Webid}") && x.userid.Equals($"{scsso.tid}"));
- var bind = teacher.binds.Find(x => x.userid.Equals($"{scsso.tid}"));
- if (bind == null)
- {
- teacher.binds = new List<Teacher.ThirdBind> { new Teacher.ThirdBind { data = new List<string> { scsso.data }, userid = $"{scsso.tid}",account=scsso.account,username=scsso.username, type = type } };
- await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Teacher").ReplaceItemAsync<Teacher>(teacher, teacher.id, new PartitionKey(teacher.code));
- }
- else
- {
- bind.username=scsso.username;
- bind.account=scsso.account;
- var bindData = scsso.data.ToObject<ScBindData>();
- bool isnew = true;
- for (int index = 0; index < bind.data.Count; index++)
- {
- ScBindData scBind = bind.data[index].ToObject<ScBindData>();
- if (scBind.pxid.Equals(bindData.pxid))
- {
- bind.data[index] = bindData.ToJsonString();
- isnew = false;
- }
- }
- if (isnew)
- {
- bind.data.Add(bindData.ToJsonString());
- }
- if (bindData != null) {
- bindData.userid = scsso.tid;
- bindData.username=scsso.username;
- bindData.account = scsso.account;
- }
- if (teacher.schools.IsNotEmpty())
- {
- foreach (var school in teacher.schools)
- {
-
- if (!string.IsNullOrEmpty(school.schoolId))
- {
- if (school.status.Equals("join")) {
- StringBuilder queryText = new StringBuilder($"SELECT distinct value(c) FROM c where c.type='yxtrain'");
- List<GroupList> yxtrain = new List<GroupList>();
- await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "School").GetItemQueryIterator<GroupList>(queryText: queryText.ToString(),
- requestOptions: new QueryRequestOptions() { PartitionKey = new Azure.Cosmos.PartitionKey($"GroupList-{school.schoolId}") }))
- {
- yxtrain.Add(item);
- }
- if (yxtrain.IsNotEmpty())
- {
- var meber = yxtrain.SelectMany(x => x.members).Where(y => y.id.Equals(teacher.id));
- //不在研修名单
- if (meber == null || meber.Count() <= 0)
- {
- yxtrain[0].members.Add(new Member { id = teacher.id, type = 1 });
- await GroupListService.UpsertList(yxtrain[0], _azureCosmos, _configuration, _serviceBus);
- }
- }
- else
- {
- GroupList groupList = new GroupList()
- {
- id = Guid.NewGuid().ToString(),
- code = $"GroupList-{school.schoolId}",
- creatorId = teacher.id,
- type = "yxtrain",
- year = DateTimeOffset.UtcNow.Year,
- members = new List<Member> { new Member { id = teacher.id, type = 1 } },
- scope = "school",
- school = school.schoolId,
- name = "研修名单",
- pk = "GroupList",
- ttl = -1
- };
- await GroupListService.UpsertList(groupList, _azureCosmos, _configuration, _serviceBus);
- }
- }
- Azure.Response response = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "School").ReadItemStreamAsync(teacher.id, new PartitionKey($"Teacher-{school.schoolId}"));
- if (response.Status != 200)
- {
- SchoolTeacher schoolTeacher = new SchoolTeacher
- {
- id = teacher.id,
- code = $"Teacher-{school.schoolId}",
- pk = "Teacher",
- name = teacher.name,
- picture = teacher.picture,
- size = 0,
- roles = new List<string> { "teacher" },
- permissions = new List<string>(),
- status = school.status,
- createTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(),
- ttl = -1
- };
- await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "School").CreateItemAsync(schoolTeacher, new PartitionKey($"Teacher-{school.schoolId}"));
- }
- else {
- JsonDocument document = await JsonDocument.ParseAsync(response.ContentStream);
- SchoolTeacher schoolTeacher = document.RootElement.ToObject<SchoolTeacher>();
- schoolTeacher.status = school.status;
- schoolTeacher.pk = "Teacher";
- schoolTeacher.name = teacher.name;
- schoolTeacher.picture = teacher.picture;
- if (schoolTeacher.roles.IsEmpty() || !schoolTeacher.roles.Contains("teacher"))
- {
- schoolTeacher.roles = new List<string> { "teacher" };
- }
- schoolTeacher.permissions = schoolTeacher.permissions.IsNotEmpty() ? schoolTeacher.permissions : new List<string>();
- schoolTeacher.createTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
- schoolTeacher.ttl = -1;
- await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "School").ReplaceItemAsync(schoolTeacher, schoolTeacher.id, new PartitionKey($"Teacher-{school.schoolId}"));
- }
- }
- }
- }
- await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Teacher").ReplaceItemAsync<Teacher>(teacher, teacher.id, new PartitionKey(teacher.code));
- await _azureStorage.UploadFileByContainer("teammodelos", bindData.ToJsonString(), $"yxpt/{scsso.path}/scbind", $"{teacher.id}.json");
- }
- }
- else
- {
- return Ok(new
- {
- location = _option.Location,
- //账号已被别的醍摩豆id绑定
- status = 3,
- tmdid = teacher.id,
- name = teacher.name,
- tid = scsso.tid
- });
- }
- }
- }
- catch (CosmosException ex)
- {
- teacher = new Teacher
- {
- id = id,
- pk = "Teacher",
- code = "Base",
- name = name?.ToString(),
- picture = picture?.ToString(),
- //创建账号并第一次登录IES5则默认赠送1G
- size = 1,
- defaultSchool = null,
- schools = new List<Teacher.TeacherSchool>(),
- binds = new List<Teacher.ThirdBind> { new Teacher.ThirdBind { data = new List<string> { scsso.data }, userid = $"{scsso.tid}", /*source = $"{scsso.Webid}",*/ type = type } }
- };
- 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"));
- ScBindData bindData = scsso.data.ToObject<ScBindData>();
- if (bindData != null)
- {
- bindData.userid = scsso.tid;
- bindData.username = scsso.username;
- bindData.account = scsso.account;
- await _azureStorage.UploadFileByContainer("teammodelos", bindData.ToJsonString(), $"yxpt/{scsso.path}/scbind", $"{teacher.id}.json");
- }
- else {
- await _azureStorage.UploadFileByContainer("teammodelos", scsso.data.ToJsonString(), $"yxpt/{scsso.path}/scbind", $"{teacher.id}.json");
- }
-
- }
- catch (Exception ex) {
- await _dingDing.SendBotMsg($"OS,{_option.Location}\n绑定失败:\n{sso.ToJsonString()},{ex.Message}\n{ex.StackTrace}", GroupNames.成都开发測試群組);
- return Ok(new
- {
- location = _option.Location,
- status = 2,
- });
- }
- return Ok(new
- {
- location = _option.Location,
- status = 200,
- });
-
- } catch (Exception ex ) {
- await _dingDing.SendBotMsg($"OS,{_option.Location}\n绑定失败:\n{sso.ToJsonString()},{ex.Message}\n{ex.StackTrace}", GroupNames.成都开发測試群組);
- return Ok(new
- {
- location = _option.Location,
- status = 2,
- });
- }
- }
- /// <summary>
- /// 动态地址路由。"config":"scsyxpt","path":"sc{pjx/jinniu}"
- /// </summary>
- /// <param name="request"></param>
- /// <returns></returns>
- [HttpGet("{path}/sso")]
- [AllowAnonymous]
- public async Task<IActionResult> Sso([FromQuery] ScSSO scsso,string path)
- {
- var HostName = HttpContext.GetHostName();
- if (path.Equals("sc"))
- {
- path = $"scpjx";
- }
- else
- {
- path = $"sc{path}";
- }
- //var rurl = new StringBuilder($"https://{_option.HostName}/sso");
- var rurl = new StringBuilder($"https://{HostName}/sso");
- try {
-
- string parmas = $"Pxid={scsso.Pxid}&Webid={scsso.Webid}&tid={scsso.tid}&time={scsso.time}";
- if (Md5Hash.GetMd5String(parmas).Equals($"{scsso.Encrypt}"))
- {
- //四川研训平台跳转隐式登录/或者绑定IES平台接入规范
- long ssotime = long.Parse($"{scsso.time}");
- long nowtime = DateTimeOffset.UtcNow.ToUnixTimeSeconds();
- if (nowtime - ssotime > 60 * 10)//10分钟有效期
- {
- // return Ok(new { status = 2, msg = "登录超时!" });
- }
- }
- else
- {
- return Redirect(rurl.Append($"?status=1").ToString());
- }
- string setsql = $"select value(c) from c where contains(c.accessConfig,'{path}') and contains(c.accessConfig,'scsyxpt') ";
- AreaSetting setting = null;
- await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Normal").GetItemQueryIterator<AreaSetting>(queryText: setsql,
- requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"AreaSetting") }))
- {
- setting = item;
- break;
- }
- if (setting==null ||(setting != null && string.IsNullOrEmpty(setting.accessConfig)))
- {
- return Redirect(rurl.Append($"?status=1").ToString());
- }
- string accessConfig = setting.accessConfig;
- Dictionary<string, object> dict = new Dictionary<string, object> { { "accessConfig", accessConfig }, { "pxid", scsso.Pxid }, { "tid", scsso.tid } };
- string SchoolName = "", SchoolID = "", ProjectID = "", ProjectItemID = "", TeacherName = "" , Account="";
- (int status, string json) = await _httpTrigger.RequestHttpTrigger(dict, _option.Location, "GetSingleTeacherByProject");
- if (status == 200)
- {
- ScTeacher scTeacher = json.ToObject<ScTeacher>(new JsonSerializerOptions { PropertyNameCaseInsensitive = false });
- if (scTeacher != null && $"{scTeacher.PXID}".Equals(scsso.Pxid) && $"{scTeacher.TID}".Equals(scsso.tid))
- {
- SchoolName = scTeacher.SchoolName;
- SchoolID = $"{scTeacher.SchoolID}";
- ProjectID = $"{ scTeacher.ProjectID}";
- ProjectItemID = $"{ scTeacher.ProjectItemID}";
- TeacherName = $"{ scTeacher.TeacherName}";
- Account = $"{ scTeacher.Account}";
- }
- }
- else {
- await _dingDing.SendBotMsg($"OS,{_option.Location}\n省平台教师信息:\nstatus:{status}{json}\n{dict.ToJsonString()} \nGetSingleTeacherByProject", GroupNames.成都开发測試群組);
- }
- ScBindData bindData = new ScBindData
- {
- sn = SchoolName,
- sid = SchoolID,
- pd = ProjectID,
- pid = ProjectItemID,
- pxid = scsso.Pxid,
- userid = scsso.tid,
- username = TeacherName,
- account = Account,
- path = path,
- };
- var data = bindData.ToJsonString();
- ScSSOData sso = new ScSSOData {
- username = TeacherName,
- account=Account,
- path = path,
- Pxid = scsso.Pxid,
- Encrypt = scsso.Encrypt,
- tid = scsso.tid,
- time = scsso.time,
- data= data
- };
- Teacher teacher = null;
- //四川研训平台跳转隐式登录/或者绑定IES平台接入规范
- //string sql = $"SELECT distinct value(c) FROM c join A1 in c.binds where A1.pxid='{sso.Pxid}' and A1.webid='{sso.Webid}' and A1.tid='{sso.tid}'";
- string sql = $"SELECT distinct value(c) FROM c join A1 in c.binds where A1.userid='{sso.tid}'";
- await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Teacher").GetItemQueryIterator<Teacher>(queryText: sql,
- requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Base") }))
- {
- teacher = item;
- break;
- }
- if (teacher == null)
- {
- //string enurl = HttpUtility.UrlEncode(rurl.Append($"?status=4¶m={sso.ToJsonString()}&type={type}&bindurl=sc/bind").ToString());
- string enurl = $"status=4¶m={HttpUtility.UrlEncode(sso.ToJsonString(), Encoding.UTF8)}&type={type}&bindurl=sc/bind";
- return Redirect(rurl.Append($"?{enurl}").ToString());
- }
- else
- {
- var clientID = _configuration.GetValue<string>("HaBookAuth:CoreService:clientID");
- var location = _option.Location;
- TmdidImplicit implicit_token = await _coreAPIHttpService.Implicit(
- new Dictionary<string, string>()
- {
- { "grant_type", "implicit" },
- { "client_id",clientID },
- { "account",teacher.id },
- { "nonce",Guid.NewGuid().ToString()}
- },location,_configuration);
- if (implicit_token!=null)
- {
- if (string.IsNullOrEmpty(implicit_token.id_token)) {
- await _dingDing.SendBotMsg($"OS,隐式登录获得信息为空:{_option.Location}-\n{scsso.ToJsonString()} \npath:{path}\n{implicit_token.ToJsonString()}", GroupNames.成都开发測試群組);
- return Redirect(rurl.Append($"?status=1").ToString());
- }
- var bind = teacher.binds.Find(x => x.userid.Equals(sso.tid));
- //var bind = teacher.binds.Find(x => x.userid.Equals(sso.tid) && x.source.Equals(sso.Webid));
- if (bind != null)
- {
- bool isnew = true;
- for (int index = 0;index< bind.data.Count; index++) {
- ScBindData scBind = bind.data[index].ToObject<ScBindData>();
- if (scBind.pxid.Equals(bindData.pxid))
- {
- bind.data[index]= bindData.ToJsonString();
- isnew = false;
- }
- }
- if (isnew)
- {
- bind.data.Add(bindData.ToJsonString());
- }
- bind.username = TeacherName;
- bind.account = Account;
- if (teacher.schools.IsNotEmpty()) {
- foreach (var school in teacher.schools) {
-
- if (!string.IsNullOrEmpty(school.schoolId) ) {
- if (school.status.Equals("join")) {
- StringBuilder queryText = new StringBuilder($"SELECT distinct value(c) FROM c where c.type='yxtrain'");
- List<GroupList> yxtrain = new List<GroupList>();
- await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "School").GetItemQueryIterator<GroupList>(queryText: queryText.ToString(),
- requestOptions: new QueryRequestOptions() { PartitionKey = new Azure.Cosmos.PartitionKey($"GroupList-{school.schoolId}") }))
- {
- yxtrain.Add(item);
- }
- if (yxtrain.IsNotEmpty())
- {
- var meber = yxtrain.SelectMany(x => x.members).Where(y => y.id.Equals(teacher.id));
- //不在研修名单
- if (meber == null || meber.Count() <= 0)
- {
- yxtrain[0].members.Add(new Member { id = teacher.id, type = 1 });
- await GroupListService.UpsertList(yxtrain[0], _azureCosmos, _configuration, _serviceBus);
- }
- }
- else
- {
- GroupList groupList = new GroupList()
- {
- id = Guid.NewGuid().ToString(),
- code = $"GroupList-{school.schoolId}",
- creatorId = teacher.id,
- type = "yxtrain",
- year = DateTimeOffset.UtcNow.Year,
- members = new List<Member> { new Member { id = teacher.id, type = 1 } },
- scope = "school",
- school = school.schoolId,
- name = "研修名单",
- pk = "GroupList",
- ttl = -1
- };
- await GroupListService.UpsertList(groupList, _azureCosmos, _configuration, _serviceBus);
- }
- }
- Azure.Response response= await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "School").ReadItemStreamAsync(teacher.id, new PartitionKey($"Teacher-{school.schoolId}"));
- if (response.Status != 200) {
- SchoolTeacher schoolTeacher = new SchoolTeacher
- {
- id = teacher.id,
- code = $"Teacher-{school.schoolId}",
- pk= "Teacher",
- name=teacher.name,
- picture= teacher.picture,
- size=0,
- roles=new List<string> { "teacher" },
- permissions= new List<string>(),
- status=school.status,
- createTime=DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(),
- ttl=-1
- };
- await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "School").CreateItemAsync(schoolTeacher, new PartitionKey($"Teacher-{school.schoolId}"));
- }
- else
- {
- JsonDocument document = await JsonDocument.ParseAsync(response.ContentStream);
- SchoolTeacher schoolTeacher = document.RootElement.ToObject<SchoolTeacher>();
- schoolTeacher.status =school.status;
- schoolTeacher.pk = "Teacher";
- schoolTeacher.name = teacher.name;
- schoolTeacher.picture = teacher.picture;
- if (schoolTeacher.roles.IsEmpty() ||! schoolTeacher.roles.Contains("teacher")) {
- schoolTeacher.roles = new List<string> { "teacher" };
- }
- schoolTeacher.permissions = schoolTeacher.permissions.IsNotEmpty()? schoolTeacher.permissions: new List<string>();
- schoolTeacher.createTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
- schoolTeacher.ttl = -1;
- await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "School").ReplaceItemAsync(schoolTeacher, schoolTeacher.id, new PartitionKey($"Teacher-{school.schoolId}"));
- }
- }
- }
- }
- await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Teacher").ReplaceItemAsync<Teacher>(teacher, teacher.id, new PartitionKey(teacher.code));
- }
- try
- {
- await _azureStorage.UploadFileByContainer("teammodelos", bindData.ToJsonString(), $"yxpt/{sso.path}/scbind", $"{teacher.id}.json");
- }
- catch (Exception ex) {
- await _dingDing.SendBotMsg($"OS,{_option.Location}-\n文件失败 \npath:{path}\n{ex.StackTrace}\n{ex.Message}\n yxpt/{sso.path}/scbind/{teacher.id}.json", GroupNames.醍摩豆服務運維群組);
- }
- rurl.Append($"?status=200&id_token={implicit_token.id_token}&access_token={implicit_token.access_token}&expires_in={HttpUtility.UrlEncode(implicit_token.expires_in)}&token_type={HttpUtility.UrlEncode(implicit_token.token_type)}").ToString();
- string uri = rurl.ToString();
- return Redirect(uri);
- }
- else
- {
- //绑定失效
- if (teacher.binds.IsNotEmpty())
- {
- // teacher.binds.RemoveAll(x => x.userid.Equals(sso.tid) && x.source.Equals(sso.Webid));
- teacher.binds.RemoveAll(x => x.userid.Equals(sso.tid) );
- await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Teacher").ReplaceItemAsync<Teacher>(teacher, teacher.id, new PartitionKey(teacher.code));
- }
- // string enurl = HttpUtility.UrlEncode(rurl.Append($"status=4¶m={sso.ToJsonString()}&type={type}&bindurl=sc/bind").ToString());
- string enurl = $"status=4¶m={HttpUtility.UrlEncode(sso.ToJsonString(),Encoding.UTF8)}&type={type}&bindurl=sc/bind";
- return Redirect(rurl.Append($"?{enurl}").ToString());
- }
- }
- } catch (Exception ex) {
- await _dingDing.SendBotMsg($"OS,{_option.Location}-\n{scsso.ToJsonString()} \npath:{path}\n{ex.StackTrace}\n{ex.Message}", GroupNames.醍摩豆服務運維群組);
- return Redirect(rurl.Append($"?status=1").ToString());
- }
- }
-
- }
- }
|