12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043 |
- using Microsoft.Azure.Cosmos;
- using Azure.Storage.Blobs.Models;
- using FastJSON;
- using Microsoft.AspNetCore.Authorization;
- using Microsoft.AspNetCore.Hosting;
- using Microsoft.AspNetCore.Http;
- using Microsoft.AspNetCore.Mvc;
- using Microsoft.Extensions.Configuration;
- using Microsoft.Extensions.Hosting;
- using Microsoft.Extensions.Options;
- using Microsoft.OData.UriParser;
- using StackExchange.Redis;
- using System;
- using System.Collections.Generic;
- using System.Drawing.Imaging;
- using System.IdentityModel.Tokens.Jwt;
- using System.IO;
- using System.Linq;
- using System.Net;
- using System.Net.Http;
- using System.Reflection;
- using System.Runtime.InteropServices;
- using System.Security.Policy;
- using System.Text;
- using System.Text.Json;
- using System.Text.RegularExpressions;
- using System.Threading.Tasks;
- using System.Web;
- using TEAMModelOS.Models;
- using TEAMModelOS.Models.Request;
- using TEAMModelOS.SDK;
- using TEAMModelOS.SDK.DI;
- using TEAMModelOS.SDK.Extension;
- using TEAMModelOS.SDK.Models;
- using TEAMModelOS.SDK.Models.Dtos;
- using TEAMModelOS.SDK.Models.Service;
- using TEAMModelOS.SDK.Models.Service.BI;
- using TEAMModelOS.SDK.PngQuant;
- using Top.Api;
- using static Google.Protobuf.Reflection.SourceCodeInfo.Types;
- using static TEAMModelOS.SDK.CoreAPIHttpService;
- using Pipelines.Sockets.Unofficial.Arenas;
- using System.Text.Json.Nodes;
- using TEAMModelOS.Services;
- namespace TEAMModelOS.Controllers
- {
- [Route("core")]
- [ApiController]
- public class CoreController : ControllerBase
- {
- private readonly AzureCosmosFactory _azureCosmos;
- private readonly AzureRedisFactory _azureRedis;
- private readonly AzureStorageFactory _azureStorage;
- private readonly DingDing _dingDing;
- private readonly Option _option;
- private readonly IHttpClientFactory _httpClientFactory;
- private readonly IPSearcher _searcher;
- private readonly CoreAPIHttpService _coreAPIHttpService;
- private readonly IConfiguration _configuration;
- private readonly SnowflakeId _snowflakeId;
- private readonly IWebHostEnvironment _environment;
- private readonly HttpTrigger _httpTrigger;
- public CoreController(HttpTrigger httpTrigger, IWebHostEnvironment environment, IHttpClientFactory httpClientFactory,AzureCosmosFactory azureCosmos, SnowflakeId snowflakeId,CoreAPIHttpService coreAPIHttpService,IConfiguration configuration,IPSearcher searcher, AzureRedisFactory azureRedis, AzureStorageFactory azureStorage, DingDing dingDing, IOptionsSnapshot<Option> option)
- {
- _azureCosmos = azureCosmos;
- _searcher = searcher;
- _azureStorage = azureStorage;
- _dingDing = dingDing;
- _option = option?.Value;
- _azureRedis = azureRedis;
- _configuration = configuration;
- _coreAPIHttpService = coreAPIHttpService;
- _snowflakeId = snowflakeId;
- _httpClientFactory = httpClientFactory;
- _environment= environment;
- _httpTrigger = httpTrigger;
- }
- public class NotifyData {
- public string notifyCode { get; set; }
- public string data { get; set; }
- public int notifyEvent { get; set; }
- public string ticket { get; set; }
- public string token { get; set; }
- }
- [HttpGet("process-notify")]
- public async Task<IActionResult> ProcessNotify([FromQuery] NotifyData notifyData) {
- string msg = "";
- /// code =-1 参数异常,0 凭据失效 1不是管理员,2操作成功,3服务端异常
- int code = -1;
- string scope = "";
- string lang = _option.Location.Contains("China") ? "zh-cn" : "en-us";
- string path = Path.Combine("", $"Lang/{lang}.json");
- var jsonAuth = System.IO.File.ReadAllText(path, Encoding.UTF8);
- var jsonData = jsonAuth.ToObject<JsonElement>();
- var status = jsonData.GetProperty("notify-status");
- Teacher teacher = null;
- try {
- string opttmdid = "";
-
- if (!string.IsNullOrWhiteSpace(notifyData.ticket))
- {
- var clientID = _configuration.GetValue<string>("HaBookAuth:CoreService:clientID");
- (HttpStatusCode statusCode, CoreAPIToken token) = await _coreAPIHttpService.GetCoreAPIoAuth2Token(
- new Dictionary<string, object> { { "client_id", clientID }, { "grant_type", "authorization_code" }, { "code", notifyData.ticket } }, _option.Location, _configuration, _dingDing);
- if (statusCode.Equals(HttpStatusCode.OK))
- {
- var jwt = new JwtSecurityToken(token.id_token);
- opttmdid = jwt.Payload.Sub;
- }
- else
- {
- code = 0;
- msg = "凭据失效";
- msg = status.TryGetProperty($"code{code}", out JsonElement text) ? $"{text}" : msg;
- }
- scope = "HiTA";
- }
- else if (!string.IsNullOrWhiteSpace(notifyData.token) && string.IsNullOrWhiteSpace(opttmdid))
- {
- var jwt = new JwtSecurityToken(notifyData.token);
- opttmdid = jwt.Payload.Sub;
- scope = "IES";
- }
- Dictionary<string, object> dict = new Dictionary<string, object>();
- if (string.IsNullOrWhiteSpace(opttmdid)) {
- code = 1;
- msg = "参数异常";
- msg = status.TryGetProperty($"code{code}", out JsonElement text) ? $"{text}" : msg;
- }
- var rdata = HttpUtility.UrlDecode(notifyData.data, Encoding.UTF8);
- //取消base64,但是旧数据需要处理
- var d= rdata.Replace("\\", "");
- try {
- dict = d.ToObject<Dictionary<string, object>>();
- }
- catch {
-
- var dataByte = Convert.FromBase64String(rdata);
- string data = Encoding.Unicode.GetString(dataByte);
- data.ToObject<Dictionary<string, object>>();
- }
- dict.TryGetValue("schoolId", out object _schoolId);
- dict.TryGetValue("tmdid", out object _tmdid);
- if (!string.IsNullOrWhiteSpace($"{_schoolId}") && !string.IsNullOrWhiteSpace($"{_tmdid}") && !string.IsNullOrWhiteSpace(opttmdid))
- {
- ResponseMessage teacherResponse = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.Teacher)
- .ReadItemStreamAsync($"{_tmdid}", new PartitionKey("Base"));
- if (teacherResponse.StatusCode==System.Net.HttpStatusCode.OK) {
- teacher = JsonDocument.Parse(teacherResponse.Content).RootElement.Deserialize<Teacher>();
- if (!string.IsNullOrWhiteSpace(teacher.lang) &&(teacher.lang.Equals("zh-cn")||teacher.lang.Equals("zh-tw") || teacher.lang.Equals("en-us"))) {
- lang= teacher.lang;
- path = Path.Combine("", $"Lang/{lang}.json");
- jsonAuth = System.IO.File.ReadAllText(path, Encoding.UTF8);
- jsonData = jsonAuth.ToObject<JsonElement>();
- status = jsonData.GetProperty("notify-status");
- }
- }
- switch (true)
- {
- case bool when $"{notifyData.notifyCode}".Equals("quit_school"):
- {
- ResponseMessage adminResponse = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.School)
- .ReadItemStreamAsync(opttmdid, new PartitionKey($"Teacher-{_schoolId}"));
- //是否是管理员
- if (adminResponse.StatusCode==System.Net.HttpStatusCode.OK)
- {
- var adminTeacher = JsonDocument.Parse(adminResponse.Content).RootElement.Deserialize<SchoolTeacher>();
- if (adminTeacher.roles.Contains("admin"))
- {
- ResponseMessage schoolTeacherResponse = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.School)
- .ReadItemStreamAsync($"{_tmdid}", new PartitionKey($"Teacher-{_schoolId}"));
- if (teacher!=null && schoolTeacherResponse.StatusCode==System.Net.HttpStatusCode.OK)
- {
- // var teacher = JsonDocument.Parse(teacherResponse.Content).RootElement.Deserialize<Teacher>();
- var schoolTeacher = JsonDocument.Parse(schoolTeacherResponse.Content).RootElement.Deserialize<SchoolTeacher>();
- //同意
- if (notifyData.notifyEvent == 1)
- {
- teacher.schools.RemoveAll(z =>!string.IsNullOrWhiteSpace($"{_schoolId}") && !string.IsNullOrWhiteSpace(z.schoolId) && z.schoolId.Equals($"{_schoolId}"));
- try
- {
- await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.School).DeleteItemStreamAsync( schoolTeacher.id, new PartitionKey(schoolTeacher.code));
- await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.Teacher).ReplaceItemAsync(teacher, teacher.id, new PartitionKey(teacher.code));
- School qschool = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.School).ReadItemAsync<School>($"{_schoolId}", new PartitionKey("Base"));
- _coreAPIHttpService.PushNotify(new List<IdNameCode> { new IdNameCode {id= teacher.id,name= teacher.name,code= teacher.lang } }, $"quited_school", Constant.NotifyType_IES5_Management,
- new Dictionary<string, object> { { "schoolName", qschool.name }, { "schoolId", $"{_schoolId}" } }, _option.Location, _configuration, _dingDing, _environment.ContentRootPath);
- }
- catch (CosmosException ex) when (ex.StatusCode == HttpStatusCode.NotFound)
- {
- }
- code = 2;
- msg = "操作成功";
- msg = status.TryGetProperty($"code{code}", out JsonElement text) ? $"{text}" : msg;
- }
- //拒绝退出学校,直接不管。
- if (notifyData.notifyEvent == 2)
- {
- code = 2;
- msg = "操作成功";
- msg = status.TryGetProperty($"code{code}", out JsonElement text) ? $"{text}" : msg;
- }
- }
- else
- {
- code = 5;
- msg = "老师已离开学校";
- msg = status.TryGetProperty($"code{code}", out JsonElement text) ? $"{text}" : msg;
- }
- }
- else
- {
- code = 3;
- msg = "您已不是管理员";
- msg = status.TryGetProperty($"code{code}", out JsonElement text) ? $"{text}" : msg;
- }
- }
- else
- {
- code = 3;
- msg = "您已不是管理员";
- msg = status.TryGetProperty($"code{code}", out JsonElement text) ? $"{text}" : msg;
- }
- }
- break;
- case bool when $"{notifyData.notifyCode}".Equals("request_school"):
- {
- ResponseMessage adminResponse = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.School)
- .ReadItemStreamAsync(opttmdid, new PartitionKey($"Teacher-{_schoolId}"));
- //是否是管理员
- if (adminResponse.StatusCode==System.Net.HttpStatusCode.OK)
- {
- var adminTeacher = JsonDocument.Parse(adminResponse.Content).RootElement.Deserialize<SchoolTeacher>();
- if (adminTeacher.roles.Contains("admin"))
- {
-
- ResponseMessage schoolTeacherResponse = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.School)
- .ReadItemStreamAsync($"{_tmdid}", new PartitionKey($"Teacher-{_schoolId}"));
-
- if (teacher!=null && schoolTeacherResponse.StatusCode==System.Net.HttpStatusCode.OK)
- {
- var schoolTeacher = JsonDocument.Parse(schoolTeacherResponse.Content).RootElement.Deserialize<SchoolTeacher>();
- //同意
- if (notifyData.notifyEvent == 1)
- {
- teacher.schools.ForEach(school =>
- {
- if (school.schoolId.Equals($"{_schoolId}"))
- {
- school.status = "join";
- }
- });
- schoolTeacher.status = "join";
- try {
- await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.School).ReplaceItemAsync(schoolTeacher, schoolTeacher.id, new PartitionKey(schoolTeacher.code));
- await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.Teacher).ReplaceItemAsync(teacher, teacher.id, new PartitionKey(teacher.code));
- } catch (CosmosException ex) when (ex.StatusCode == HttpStatusCode.NotFound) {
-
- }
- code = 2;
- msg = "操作成功";
- msg = status.TryGetProperty($"code{code}", out JsonElement text) ? $"{text}" : msg;
- await BIStats.SetTypeAddStats(_azureCosmos.GetCosmosClient(), _dingDing, $"{_schoolId}", "Teacher", 1);//BI统计增/减量
- }
- //拒绝
- int count = 0;
- if (notifyData.notifyEvent == 2)
- {
- //只有在未正式加入成功才能拒绝成功,防止HiTA消息未清除,再次操作。
- count=teacher.schools.RemoveAll(z => z.schoolId.Equals($"{_schoolId}") && (z.status.Equals("request") || z.status.Equals("invite")));
- if (count > 0)
- {
- try {
- await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.School).DeleteItemStreamAsync($"{opttmdid}", new PartitionKey($"Teacher-{_schoolId}"));
- await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.Teacher).ReplaceItemAsync(teacher, teacher.id, new PartitionKey(teacher.code));
- }
- catch (CosmosException ex) when (ex.StatusCode == HttpStatusCode.NotFound)
- {
- }
- code = 2;
- msg = "操作成功";
- msg = status.TryGetProperty($"code{code}", out JsonElement text) ? $"{text}" : msg;
- }
- else
- {
- code = 6;
- msg = "已加入学校,请勿重复操作";
- msg = status.TryGetProperty($"code{code}", out JsonElement text) ? $"{text}" : msg;
- }
- }
- }
- else
- {
- code = 5;
- msg = "老师已离开学校";
- msg = status.TryGetProperty($"code{code}", out JsonElement text) ? $"{text}" : msg;
- }
- }
- else
- {
- code = 3;
- msg = "您已不是管理员";
- msg = status.TryGetProperty($"code{code}", out JsonElement text) ? $"{text}" : msg;
- }
- }
- else
- {
- code = 3;
- msg = "您已不是管理员";
- msg = status.TryGetProperty($"code{code}", out JsonElement text) ? $"{text}" : msg;
- }
- }
- break;
- case bool when $"{notifyData.notifyCode}".Equals("invite_school"):
- {
- ResponseMessage schoolTeacherResponse = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.School)
- .ReadItemStreamAsync($"{opttmdid}", new PartitionKey($"Teacher-{_schoolId}"));
- ResponseMessage optTeacherResponse = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.Teacher)
- .ReadItemStreamAsync($"{opttmdid}", new PartitionKey($"Base"));
- if (optTeacherResponse.StatusCode == HttpStatusCode.OK && schoolTeacherResponse.StatusCode==System.Net.HttpStatusCode.OK)
- {
- var optteacher = JsonDocument.Parse(optTeacherResponse.Content).RootElement.Deserialize<Teacher>();
- var schoolTeacher = JsonDocument.Parse(schoolTeacherResponse.Content).RootElement.Deserialize<SchoolTeacher>();
- //同意
- if (notifyData.notifyEvent == 1)
- {
- optteacher.schools.ForEach(school =>
- {
- if (school.schoolId.Equals($"{_schoolId}"))
- {
- school.status = "join";
- }
- });
- schoolTeacher.status = "join";
- try {
- await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.School).ReplaceItemAsync(schoolTeacher, schoolTeacher.id, new PartitionKey(schoolTeacher.code));
- await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.Teacher).ReplaceItemAsync(optteacher, optteacher.id, new PartitionKey(optteacher.code));
- }
- catch (CosmosException ex) when (ex.StatusCode == HttpStatusCode.NotFound)
- {
- }
- code = 2;
- msg = "操作成功";
- msg = status.TryGetProperty($"code{code}", out JsonElement text) ? $"{text}" : msg;
- await BIStats.SetTypeAddStats(_azureCosmos.GetCosmosClient(), _dingDing, $"{_schoolId}", "Teacher", 1);//BI统计增/减量
- }
- //拒绝
- int count = 0;
- if (notifyData.notifyEvent == 2)
- {
- //只有在未正式加入成功才能拒绝成功,防止HiTA消息未清除,再次操作。
- count = optteacher.schools.RemoveAll(z => z.schoolId.Equals($"{_schoolId}") && (z.status.Equals("request") || z.status.Equals("invite")));
- if (count >0)
- {
- try {
- await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.School).DeleteItemStreamAsync($"{opttmdid}", new PartitionKey($"Teacher-{_schoolId}"));
- await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.Teacher).ReplaceItemAsync(optteacher, optteacher.id, new PartitionKey(optteacher.code));
- }
- catch (CosmosException ex) when (ex.StatusCode == HttpStatusCode.NotFound)
- {
- }
- code = 2;
- msg = "操作成功";
- msg = status.TryGetProperty($"code{code}", out JsonElement text) ? $"{text}" : msg;
- }
- else
- {
- code = 6;
- msg = "已加入学校,请勿重复操作";
- msg = status.TryGetProperty($"code{code}", out JsonElement text) ? $"{text}" : msg;
- }
- }
- }
- else
- {
- code = 5;
- msg = "教师不存在";
- msg = status.TryGetProperty($"code{code}", out JsonElement text) ? $"{text}" : msg;
- }
- }
- break;
- }
- }
- else
- {
- code = 1;
- msg = "参数异常";
- msg = status.TryGetProperty($"code{code}", out JsonElement text) ? $"{text}" : msg;
- }
- } catch (Exception ex) {
- await _dingDing.SendBotMsg($"{ex.Message}\n{ex.StackTrace}\n{notifyData.ToJsonString()}", GroupNames.醍摩豆服務運維群組);
- code = 4;
- msg = "服务端异常";
- msg = status.TryGetProperty($"code{code}", out JsonElement text) ? $"{text}" : msg;
- }
- if (scope.Equals("HiTA"))
- {
- string HostName = HttpContext.GetHostName();
- var rurl = $"https://{HostName}/resultPage?code={code}&msg={HttpUtility.UrlEncode(msg)}";
- return Redirect(rurl);
- }
- else {
- return Ok(new { code, msg });
- }
- }
- /// <summary>
- ///{"grant_type":"create","client_id":"c7317f88-7cea-4e48-ac57-a16071f7b884","nonce":"habook","name":"User","pin_code":"985395","account":"+86-15283771540"}
- ///{"error":2,"message":"帳號已存在"}
- ///{"error":3,"message":"驗證PIN碼失敗"}
- ///{
- ///"id_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJhY2NvdW50LnRlYW1tb2RlbCIsInN1YiI6IjY3MzQ2NjQ4NTUiLCJhdWQiOiJjNzMxN2Y4OC03Y2VhLTRlNDgtYWM1Ny1hMTYwNzFmN2I4ODQiLCJleHAiOjE3MzQ3NTEyNTUsImlhdCI6MTczNDY2NDg1NSwibm9uY2UiOiJoYWJvb2siLCJuYW1lIjoiVXNlciIsImlzQWN0aXZhdGUiOiJmYWxzZSIsImlzTW9iaWxlIjoidHJ1ZSIsImlzTWFpbCI6ImZhbHNlIiwiYXJlYSI6ImNoaW5hIiwibmJmIjoxNzM0NjY0ODU1fQ.8P2IKq44ML13vYb03GbbrDSJqGpjkIQjiztNYSnbBRg",
- ///"access_token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsImtpZCI6InF4dklNdDk1OEpHWFFrWjF1QzF2RHQ1N3dRTSJ9.eyJhdWQiOiI3MjY0MzcwNC1iMmU3LTRiMjYtYjg4MS1iZDU4NjVlN2E3YTUiLCJpc3MiOiJodHRwczovL2xvZ2luLnBhcnRuZXIubWljcm9zb2Z0b25saW5lLmNuLzQ4MDdlOWNmLTg3YjgtNDE3NC1hYTViLWU3NjQ5N2Q3MzkyYi92Mi4wIiwiaWF0IjoxNzM0NjY0NTU1LCJuYmYiOjE3MzQ2NjQ1NTUsImV4cCI6MTczNDY2ODQ1NSwiYWlvIjoiNDJOZ1lBalJsZGM2OVcvZjQ2ZnRPak16K1BVT3ZVeTJ2TCtzTjZTeU15NytZeE5IbndZQSIsImF6cCI6ImM3MzE3Zjg4LTdjZWEtNGU0OC1hYzU3LWExNjA3MWY3Yjg4NCIsImF6cGFjciI6IjEiLCJvaWQiOiJkNDliYjc4Mi02ZGMyLTQ5MzktODY3OC1kMzNjMjY3MTliZjkiLCJyaCI6IjAuREFJQXota0hTTGlIZEVHcVctZGtsOWM1S3dRM1pITG5zaVpMdUlHOVdHWG5wNlVCQUFBLiIsInJvbGVzIjpbIklFUyJdLCJzdWIiOiJkNDliYjc4Mi02ZGMyLTQ5MzktODY3OC1kMzNjMjY3MTliZjkiLCJ0aWQiOiI0ODA3ZTljZi04N2I4LTQxNzQtYWE1Yi1lNzY0OTdkNzM5MmIiLCJ1dGkiOiJEV0VtaGxUeXcwT295YVdGaU04MEFRIiwidmVyIjoiMi4wIn0.CaikbZjaVASy_E7_S4L8ZVjP8FipNqr9vLOdt-FQj9cmeoBXl2sQtb5F-vpkJ-QNfN1J3h8qJRYrGdyrMp8FBNliYFX7Mwij8pIXsdTI00DNSNDJ6b9trdiS4DUW9c7R3wzvQ-UEyhNkNcI4b8gJCNcxYDIEiCL358svYs_8jz4vyCUhuDDLdJMJimVFCRezvoG8kFE-ZO82Cj5VL6pBN8q9ZZs74k4C94tE1TBs4ixm-3jQOGrwovkdFkHqG2g7R7-F1V_w5-RqfRDCQR-mr1cGpShDlOyUx6oph6-xi5lCZJPgmQsW0vIAAVpzqI_t62-IuBekmDKNqK35xkjG5w",
- ///"expires_in": "2024-12-20T04:20:54.1635029+00:00",
- ///"token_type": "Bearer"
- ///}
- /// </summary>
- /// <param name="request"></param>
- /// <returns></returns>
- [HttpPost("sendsms/check")]
- public async Task<IActionResult> SendSmsCheck(JsonNode request)
- {
- string msg = string.Empty;
- int timezone = 8;
- if (HttpContext.Request.Headers.TryGetValue("Time-Zone", out var Time_Zone) && int.TryParse(Time_Zone, out int tz))
- {
- timezone=tz;
- }
- var pin_code = request["pin_code"];
- var account = request["account"];
- TmdidImplicit implicit_token = null;
- var loginData= await _coreAPIHttpService.Auth2Login($"{pin_code}", $"{account}", _option.Location, _configuration, _dingDing);
- if (loginData.code.Equals(HttpStatusCode.OK))
- {
-
- var node = JsonSerializer.Deserialize<JsonNode>(loginData.content);
- if (node?["id_token"]!=null)
- {
- implicit_token= JsonSerializer.Deserialize<TmdidImplicit>(loginData.content);
- }
- else
- {
- if (node?["error"]!=null && $"{node?["error"]}".Equals("2"))
- {
- string mobile = $"{account}".Split("-").Last();
- var coreUser = await _coreAPIHttpService.GetUserInfo(new Dictionary<string, string> { { "key", $"{mobile}" } }, _option.Location, _configuration);
- if (coreUser!=null)
- {
- var clientID = _configuration.GetValue<string>("HaBookAuth:CoreService:clientID");
- var location = _option.Location;
- implicit_token = await _coreAPIHttpService.Implicit(
- new Dictionary<string, string>()
- {
- { "grant_type", "implicit" },
- { "client_id",clientID },
- { "account",coreUser.id },
- { "nonce",Guid.NewGuid().ToString()}
- }, location, _configuration);
- }
- }
- else {
- msg=$"验证失败!{loginData.content}";
- }
- }
- if (implicit_token!=null)
- {
- object name = null, picture = null;
- var jwt = new JwtSecurityToken(implicit_token.id_token);
- jwt.Payload.TryGetValue("name", out name);
- jwt.Payload.TryGetValue("picture", out picture);
- jwt.Payload.TryGetValue("lang", out object _jwtlang);
- var tmdid = jwt.Payload.Sub;
- IEnumerable<dynamic> schools = new List<dynamic>();
- var response = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.Teacher).ReadItemStreamAsync(tmdid, new PartitionKey("Base"));
- if (response.StatusCode==System.Net.HttpStatusCode.OK)
- {
- Teacher teacher = JsonDocument.Parse(response.Content).RootElement.ToObject<Teacher>();
- schools= teacher.schools.Where(x => x.status.Equals("join")).Select(x => new { id = x.schoolId, name = x.name, picture = x.picture });
- }
- (string ip, string region) = await LoginService.LoginIp(HttpContext, _searcher);
- TeacherInfo teacherInfo = await TeacherService.TeacherInfoLite(_azureCosmos, $"{name}", $"{picture}", $"{jwt.Payload.Sub}", _azureStorage, _option, _azureRedis, "", _httpTrigger, $"{_jwtlang}", timezone);
- string x_auth_token = string.Empty;
- if (teacherInfo!=null)
- {
- x_auth_token= teacherInfo.auth_token;
- }
- return Ok(new { code = 200, implicit_token, schools, x_auth_token });
- }
- else {
- msg=$"验证失败!隐式登录未找到用户{account}";
- }
- }
- else {
- msg=$"验证失败,{loginData.code}";
- }
- return Ok(new { code=400,msg= msg });
- }
- [HttpPost("sendsms/pin")]
- public async Task<IActionResult> SendSmsPinCode(JsonElement request)
- {
- (string ip, string region) = await LoginService.LoginIp(HttpContext, _searcher);
-
- //获取投票活动的选项及投票数
- string ipkey = $"Ip:Pin:Count:{ip}";
-
- bool ipkeyexist = await _azureRedis.GetRedisClient(8).KeyExistsAsync(ipkey);
- if (ipkeyexist)
- {
- await _azureRedis.GetRedisClient(8).SortedSetIncrementAsync(ipkey, ip, 1);
- }
- else {
- await _azureRedis.GetRedisClient(8).SortedSetIncrementAsync(ipkey, ip, 1);
- var Expire = DateTime.UtcNow.AddSeconds(600);
- _azureRedis.GetRedisClient(8).KeyExpire(ipkey, Expire);
- }
- var counts = _azureRedis.GetRedisClient(8).SortedSetRangeByScoreWithScores(ipkey);
- long sum = 0;
- if (counts != null && counts.Length > 0)
- {
- foreach (var count in counts)
- {
- sum += (int)count.Score;
- }
- }
- int limit = 1000;
- if (sum > limit) {
- await _dingDing.SendBotMsg($"{_option.Location}\nIp:{ip}\n位置:{region}\n 短信验证码10分钟内访问次数超过:{limit}次!",GroupNames.成都开发測試群組);
- return Ok(new { send = 2 });
- }
- if (!request.TryGetProperty("area", out JsonElement _area)) return BadRequest();
- if (!request.TryGetProperty("to", out JsonElement _to)) return BadRequest();
- if (!request.TryGetProperty("lang", out JsonElement _lang)) return BadRequest();
- request.TryGetProperty("HasUser", out JsonElement _HasUser);
- string code=$"{_area}{_to}";
- int exp = 120;
- string key = $"Random:Code:PinCode-{_area}{_to}";
- bool exist = await _azureRedis.GetRedisClient(8).KeyExistsAsync(key);
- if (!exist)
- {
- //不存在则发送请求。
-
- Dictionary<string, object> dict = null;
- if (_HasUser.ValueKind.Equals(JsonValueKind.True))
- {
- dict = new Dictionary<string, object> { { "country", $"{_area}" }, { "to", $"{_to}" }, { "lang", $"{_lang}" }, { "HasUser", true } };
- }
- else if (_HasUser.ValueKind.Equals(JsonValueKind.False)) {
- dict = new Dictionary<string, object> { { "country", $"{_area}" }, { "to", $"{_to}" }, { "lang", $"{_lang}" }, { "HasUser", false } };
- }
- else
- {
- dict = new Dictionary<string, object> { { "country", $"{_area}" }, { "to", $"{_to}" }, { "lang", $"{_lang}" } };
- }
- var httpresp = await _coreAPIHttpService.SendSmsPin(dict, _option.Location, _configuration, _dingDing);
- if (httpresp.code.Equals(HttpStatusCode.OK))
- {
- var Expire = DateTime.UtcNow.AddSeconds(exp);
- //send=1 表示已发送
- await _azureRedis.GetRedisClient(8).StringSetAsync(key, new { code = code, send = 1, Expire = Expire.Ticks }.ToJsonString());
- _azureRedis.GetRedisClient(8).KeyExpire(key, Expire);
- if (!string.IsNullOrWhiteSpace(httpresp.content))
- {
- return Ok(httpresp.content.ToObject<JsonElement>());
- }
- else {
- return Ok(new { send = 1 });
- }
- }
- else
- {
- return Ok(new { send = 0 });
- }
- }
- else
- {
- //检查当前key是否已经发送了.
- RedisValue value = await _azureRedis.GetRedisClient(8).StringGetAsync(key);
- JsonElement element = value.ToString().ToObject<JsonElement>();
- int send = 0;
- if (element.TryGetProperty("send", out JsonElement _send))
- {
- if (_send.ValueKind.Equals(JsonValueKind.Number))
- {
- if (int.Parse($"{_send}") == 1)
- {
- send = 1;
- }
- else if (int.Parse($"{_send}") == 0)
- {
- send = 0;
- }
- }
- }
- if (send == 0)
- {
- await _azureRedis.GetRedisClient(8).KeyDeleteAsync(key);
- return Ok(new { send = 0 });
- }
- else
- {
- TimeSpan? timeSpan = await _azureRedis.GetRedisClient(8).KeyTimeToLiveAsync(key);
- if (timeSpan != null && timeSpan.HasValue)
- {
- int seconds = timeSpan.Value.Seconds;
- return Ok(new { send = 1 });
- }
- else
- {
- return Ok(new { send = 0 });
- }
- }
- }
- }
-
- [HttpPost("apply-school")]
- public async Task<IActionResult> ApplySchool(ApplySchool request)
- {
- if (_option.Location.Equals("China"))
- {
- string msg = $"有新学校申请。\n" +
- $"申请站点:{_option.Location}\n" +
- $"申请学校:{request.name}\n" +
- $"学制:{string.Join(",", request.period)}\n" +
- $"机构代码:{request.orgCode}\n" +
- $"所在国家/地区:{request.area}\n" +
- $"申请人:{request.tmdname}({request.tmdid})\n" +
- $"联系电话:{request.cellphone}\n" +
- $"联系邮箱:{request.email}\n"+
- $"备注:{request.content}";
- await _dingDing.SendBotMsg(msg, GroupNames.大陸客戶聯繫通知群);
- }
- else if (_option.Location.Equals("Global"))
- {
- string msg = $"有新學校申請。\n" +
- $"申請站點:{_option.Location}\n" +
- $"申請學校:{request.name}\n" +
- $"學制:{string.Join(",", request.period)}\n" +
- $"機構代碼:{request.orgCode}\n" +
- $"所在國家/地區:{request.area}\n" +
- $"申請人:{request.tmdname}({request.tmdid})\n" +
- $"聯繫電話:{request.cellphone}\n" +
- $"聯繫郵箱:{request.email}\n" +
- $"備註:{request.content}";
- await _dingDing.SendBotMsg(msg, GroupNames.國際客戶聯繫通知群);
- }
- else
- {
- string devmsg = _option.Location.Contains("Test") || _option.Location.Contains("Dep") ? "(测试消息)" : "";
- string msg = $"有新学校申请。{devmsg}\n" +
- $"申请站点:{_option.Location}\n" +
- $"申请学校:{request.name}\n" +
- $"学制:{string.Join(",", request.period)}\n" +
- $"机构代码:{request.orgCode}\n" +
- $"所在国家/地区:{request.area}\n" +
- $"申请人:{request.tmdname}({request.tmdid})\n" +
- $"联系电话:{request.cellphone}\n" +
- $"联系邮箱:{request.email}\n" +
- $"备注:{request.content}";
- await _dingDing.SendBotMsg(msg, GroupNames.成都开发測試群組);
- }
- return Ok();
- }
-
- [HttpPost("apply-manager")]
- public async Task<IActionResult> ApplyManager(ApplySchool request)
- {
- if (_option.Location.Equals("China"))
- {
- string msg = $"有新的申请管理员咨询。\n" +
- $"站点:{_option.Location}\n" +
- //$"所在国家/地区:{request.area}\n" +
- $"咨询学校:{request.name}\n" +
- $"联系人:{request.tmdname} - {request.gender}({request.tmdid})\n " +
- $"联系电话:{request.cellphone}\n" +
- $"联系邮箱:{request.email}\n";
- await _dingDing.SendBotMsg(msg, GroupNames.大陸客戶聯繫通知群);
- }
- else if (_option.Location.Equals("Global"))
- {
- string msg = $"有新的申請管理員諮詢。\n" +
- $"站點:{_option.Location}\n" +
- //$"所在国家/地区:{request.area}\n" +
- $"諮詢學校:{request.name}\n" +
- $"聯繫人:{request.tmdname} - {request.gender}({request.tmdid})\n" +
- $"聯繫電話:{request.cellphone}\n" +
- $"聯繫郵箱:{request.email}\n";
- await _dingDing.SendBotMsg(msg, GroupNames.國際客戶聯繫通知群);
- }
- else
- {
- string devmsg = _option.Location.Contains("Test") || _option.Location.Contains("Dep") ? "(测试消息)" : "";
- string msg = $"有新的申请管理员咨询。{devmsg}\n" +
- $"站点:{_option.Location}\n" +
- //$"所在国家/地区:{request.area}\n" +
- $"咨询学校:{request.name}\n" +
- $"联系人:{request.tmdname} - {request.gender}({request.tmdid})\n" +
- $"联系电话:{request.cellphone}\n" +
- $"联系邮箱:{request.email}\n";
- await _dingDing.SendBotMsg(msg, GroupNames.成都开发測試群組);
- }
- return Ok();
- }
- [HttpPost("apply-service")]
- public async Task<IActionResult> ApplyService(ApplySchool request)
- {
- if (_option.Location.Equals("China"))
- {
- string msg = $"有新的產品咨询。\n" +
- $"站点:{_option.Location}\n" +
- //$"所在国家/地区:{request.area}\n" +
- $"咨询学校:{request.name}\n" +
- $"联系人:{request.tmdname} - {request.gender}({request.tmdid})\n " +
- $"联系电话:{request.cellphone}\n" +
- $"联系邮箱:{request.email}\n" +
- $"咨询内容:{request.content}";
- await _dingDing.SendBotMsg(msg, GroupNames.大陸客戶聯繫通知群);
- }
- else if (_option.Location.Equals("Global"))
- {
- string msg = $"有新的產品諮詢。\n" +
- $"站點:{_option.Location}\n" +
- //$"所在国家/地区:{request.area}\n" +
- $"諮詢學校:{request.name}\n" +
- $"聯繫人:{request.tmdname} - {request.gender}({request.tmdid})\n" +
- $"聯繫電話:{request.cellphone}\n" +
- $"聯繫郵箱:{request.email}\n" +
- $"諮詢內容:{request.content}";
- await _dingDing.SendBotMsg(msg, GroupNames.國際客戶聯繫通知群);
- }
- else
- {
- string devmsg = _option.Location.Contains("Test") || _option.Location.Contains("Dep") ? "(测试消息)" : "";
- string msg = $"有新的產品咨询。{devmsg}\n" +
- $"站点:{_option.Location}\n" +
- //$"所在国家/地区:{request.area}\n" +
- $"咨询学校:{request.name}\n" +
- $"联系人:{request.tmdname} - {request.gender}({request.tmdid})\n" +
- $"联系电话:{request.cellphone}\n" +
- $"联系邮箱:{request.email}\n" +
- $"咨询内容:{request.content}";
- await _dingDing.SendBotMsg(msg, GroupNames.成都开发測試群組);
- }
- return Ok();
- }
- [HttpPost("random-code")]
- [RequestSizeLimit(100_000_000)] //最大100m左右
- public async Task<IActionResult> RandomCode(JsonElement request)
- {
- if (!request.TryGetProperty("code", out JsonElement code)) return BadRequest();//学校编码 或者醍摩豆id
- request.TryGetProperty("snowflakeId", out JsonElement snowflakeId);
- string _num09 = "123456789";
- string no = $"{Utils.CreatSaltString(6, _num09)}";
- var Expire = DateTime.UtcNow.AddHours(1);
- string key = $"Random:Code:{no}-{code}";
- await _azureRedis.GetRedisClient(8).StringSetAsync(key, new { code = code, no = no, Expire = Expire.Ticks }.ToJsonString());
- _azureRedis.GetRedisClient(8).KeyExpire(key, Expire);
- long time=0;
- if (JsonValueKind.Number.Equals(snowflakeId.ValueKind) && !string.IsNullOrWhiteSpace($"{snowflakeId}"))
- {
- long id = long.Parse($"{snowflakeId}");
- time = _snowflakeId.ParseIdToTimeStamp(id);
- }
- return Ok(new { random = no , time });
- }
- [HttpPost("system-info")]
- [RequestSizeLimit(100_000_000)] //最大100m左右
- public async Task<IActionResult> SystemInfo(JsonElement request)
- {
- Type attr = this.GetType();
- string currentDirectory = Path.GetDirectoryName(attr.Assembly.Location);
- Assembly assembly = Assembly.LoadFrom($"{currentDirectory}\\TEAMModelOS.dll");
- var description = assembly.GetCustomAttribute<AssemblyDescriptionAttribute>().Description;
-
- var version = Assembly.GetEntryAssembly().GetCustomAttribute<AssemblyFileVersionAttribute>().Version;
- long.TryParse(version.PadRight(12, '0').Replace(".", ""),out long aver);
- long.TryParse(_option.Version.PadRight(12, '0').Replace(".", ""),out long bver );
- if (bver > aver) {
- version = _option.Version;
- }
- var date = DateTimeOffset.UtcNow;
- long nowtime = date.ToUnixTimeMilliseconds();
- var IpPort = HttpContext.Request.Headers["X-Forwarded-For"].FirstOrDefault();
- if (string.IsNullOrEmpty(IpPort))
- {
- IpPort = HttpContext.Connection.RemoteIpAddress.ToString();
- }
- if (IpPort.Contains("::"))
- {
- IpPort = "127.0.0.1";
- }
- string ip = IpPort.Split(":")[0];
- //string os = "";
- //if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
- //{//Linux
- // os = "Linux";
- //}
- //else if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
- //{//Windows
- // os = "Windows";
- //}
- //else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
- //{//OSX
- // os = "OSX";
- //}
- string region = await _searcher.SearchIpAsync(ip);
-
- return Ok(new { version, description, nowtime, region, ip, date });
- }
- /// <summary>
- /// 等待P1V3,啟動Dcoker,支持EMF GDI+
- /// </summary>
- /// <param name="request"></param>
- /// <returns></returns>
- [HttpPost("convert-emf")]
- [RequestSizeLimit(100_000_000)] //最大100m左右
- public async Task<IActionResult> ConvertEmf(ImageQuangRequest request)
- {
- try
- {
- if (string.IsNullOrWhiteSpace(request.base64)) return BadRequest();
- byte[] obase64data = Convert.FromBase64String(request.base64);
- using var obase64ms = new MemoryStream(obase64data);
- var (isimg, type, dupe) = Utils.ImageValidateByStream(obase64ms);
- if (isimg && type.Equals("emf"))
- {
- var pngimagebase64 = Utils.ConvertEMFtoPNG(obase64ms);
- return Ok(pngimagebase64);
- }
- else
- {
- return BadRequest("非EMF圖片格式");
- }
- }
- catch (Exception ex)
- {
- await _dingDing.SendBotMsg($"Core,{_option.Location},convert-emf()\n{ex.Message}\n{ex.StackTrace}\n", GroupNames.醍摩豆服務運維群組);
- return BadRequest();
- }
- }
- /// <summary>
- /// PNG JPF 圖片輕量化
- /// </summary>
- /// <param name="request">支持html base64標籤解析</param>
- /// <returns></returns>
- [HttpPost("image-quant")]
- //
- [RequestSizeLimit(100_000_000)] //最大100m左右
- public async Task<IActionResult> ImageQuang(List<ImageQuangRequest> request)
- {
- if (request.Count < 1) return BadRequest();
- Regex rex = new(@"data:(?<key1>image.+?);base64,(?<key2>.+)");
- List<object> respons = new List<object>();
- var quantizer = new PngQuantizer();
- foreach (var item in request)
- {
- //正則處理,移除空白
- string trim = Regex.Replace(item.base64, @"\s", "");
- Match match = rex.Match(trim);
- string otype = match.Groups["key1"].Value;
- string obase64 = match.Groups["key2"].Value;
- byte[] obase64data = Convert.FromBase64String(obase64);
- using var obase64ms = new MemoryStream(obase64data);
- //驗證圖片格式及位深,判斷是否要處理量化演算
- var (isimg, type, dupe) = Utils.ImageValidateByStream(obase64ms);
- if (isimg && (type.Equals("png") || type.Equals("jpg")) && dupe > 8)
- {
- string img = string.Empty;
- using var quantized = quantizer.QuantizeImage(obase64ms, item.width, item.height); //JPEG,PNG輕量化
- if (quantized != null)
- {
- //檢查是否需要保存原圖到blob
- if (!string.IsNullOrWhiteSpace(item.blob))
- {
- img = $"{Guid.NewGuid():N}.{type}"; //命名新圖片名稱
- string Container = item.blob.Substring(0, item.blob.IndexOf("/")); //取得容器名稱
- string blobpath = $"{item.blob[(item.blob.Trim('/').IndexOf("/") + 1)..]}/{img}"; //處理路徑,避免多餘的字符
- obase64ms.Position = 0;
- await _azureStorage.GetBlobContainerClient(Container).GetBlobClient(blobpath).UploadAsync(obase64ms, new BlobHttpHeaders { ContentType = otype });
- }
- using var nbase64ms = new MemoryStream();
- quantized.Save(nbase64ms, ImageFormat.Png); //保存為PNG格式
- byte[] data = nbase64ms.ToArray();
- string base64 = $"data:image/png;base64,{Convert.ToBase64String(data)}"; //創建新的img src base64
- respons.Add(new { base64, blob = img });
- // TODO 下面註解,無法解決保存時,真正改變Format32bppArgb為Format8bppIndexed,需要再研究
- //ImageCodecInfo imageCodecInfo = ImageCodecInfo.GetImageEncoders().FirstOrDefault(info => info.MimeType == "image/png");
- //var parameters = new EncoderParameters(1);
- //parameters.Param[0] = new EncoderParameter(Encoder.ColorDepth, 8);
- //quantized.Save(nbase64ms, imageCodecInfo, parameters); //保存為PNG格式
- }
- else
- {
- respons.Add(new { item.base64, blob = "" }); //異常的圖片,原Base64返回
- }
- }
- else
- {
- respons.Add(new { item.base64, blob = "" }); //不符合的圖片,原Base64返回
- }
- }
- return Ok(respons);
- }
- /// <summary>
- /// 取得短網址
- /// </summary>
- [HttpPost("get-short-url")]
- public async Task<IActionResult> GetShortUrl(JsonElement request)
- {
- if (!request.TryGetProperty("url", out JsonElement url)) return BadRequest();
- try
- {
- var uri = new Uri(url.GetString());
- string md5url = Md5Hash.GetMd5String(uri.OriginalString);
- char[] chars = new char[]
- {
- 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h',
- 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p',
- 'q', 'r', 's', 't', 'u', 'v', 'w', 'x',
- 'y', 'z', '0', '1', '2', '3', '4', '5',
- '6', '7', '8', '9', 'A', 'B', 'C', 'D',
- 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L',
- 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T',
- 'U', 'V', 'W', 'X', 'Y', 'Z'
- };
- //把加密字元按照8位一組16進位制與0x3FFFFFFF進行位與運算
- int hexint = 0x3FFFFFFF & Convert.ToInt32(string.Concat("0x", md5url.AsSpan(0, 8)), 16);
- StringBuilder outShort = new();
- for (int j = 0; j < 6; j++)
- {
- //把得到的值與0x0000003D進行位與運算,取得字元陣列chars索引
- int index = 0x0000003D & hexint;
- //把取得的字元相加
- outShort.Append(chars[index]);
- //每次迴圈按位右移5位
- hexint >>= 5;
- }
- var shortid = outShort.ToString();
- var table = _azureStorage.GetCloudTableClient().GetTableReference("ShortUrl");
- ShortUrl su = new() { PartitionKey = uri.Host, RowKey = shortid, Url = uri.AbsoluteUri };
- await table.SaveOrUpdate<ShortUrl>(su);
- var result = new UriBuilder() { Scheme = uri.Scheme, Host = uri.Host, Path = shortid }.ToString();
- return Ok(new { result });
- }
- catch
- {
- return Ok(new { error = 1, message = "无法转换" });
- }
- }
- /// <summary>
- /// 短網址換長網址
- /// </summary>
- [HttpPost("get-long-url")]
- public IActionResult GetLongUrl(JsonElement request)
- {
- if (!request.TryGetProperty("url", out JsonElement url)) return BadRequest();
- try
- {
- var uri = new Uri(url.GetString());
- var table = _azureStorage.GetCloudTableClient().GetTableReference("ShortUrl");
- var shortUrl = table.Get<ShortUrl>(uri.Host, uri.AbsolutePath.Replace("/", string.Empty));
- if (shortUrl is not null)
- {
- return Ok(new { result = shortUrl.Url });
- }
- else
- {
- return Ok(new { error = 1, message = "无法转换" });
- }
- }
- catch
- {
- return Ok(new { error = 1, message = "无法转换" });
- }
- }
- }
- public record ApplySchool
- {
- /// <summary>
- /// 学校名称
- /// </summary>
- public string name { get; set; }
- /// <summary>
- /// 性别
- /// </summary>
- public string gender { get; set; }
- /// <summary>
- /// 站点
- /// </summary>
- public string site { get; set; }
- public string area { get; set; }
- public string tmdname { get; set; }
- public string tmdid { get; set; }
- /// <summary>
- /// 手机号
- /// </summary>
- public string cellphone { get; set; }
- public string email { get; set; }
- /// <summary>
- /// 备注
- /// </summary>
- public string content { get; set; }
- /// <summary>
- /// 学制
- /// </summary>
- public List<string> period { get; set; } = new List<string>();
- /// <summary>
- /// 机构代码
- /// </summary>
- public string orgCode { get; set; }
- }
- }
|