123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944 |
- using Azure.Cosmos;
- using Azure.Storage.Blobs.Models;
- using DocumentFormat.OpenXml.Spreadsheet;
- using DocumentFormat.OpenXml.Wordprocessing;
- 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 OpenXmlPowerTools;
- 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;
- 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;
- public CoreController(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;
- }
- 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");
- 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))
- {
- Azure.Response teacherResponse = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.Teacher)
- .ReadItemStreamAsync($"{_tmdid}", new Azure.Cosmos.PartitionKey("Base"));
- if (teacherResponse.Status == 200) {
- var 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"):
- {
- Azure.Response adminResponse = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.School)
- .ReadItemStreamAsync(opttmdid, new Azure.Cosmos.PartitionKey($"Teacher-{_schoolId}"));
- //是否是管理员
- if (adminResponse.Status == 200)
- {
- var adminTeacher = JsonDocument.Parse(adminResponse.Content).RootElement.Deserialize<SchoolTeacher>();
- if (adminTeacher.roles.Contains("admin"))
- {
- Azure.Response schoolTeacherResponse = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.School)
- .ReadItemStreamAsync($"{_tmdid}", new Azure.Cosmos.PartitionKey($"Teacher-{_schoolId}"));
- if (teacherResponse.Status == 200 && schoolTeacherResponse.Status == 200)
- {
- 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 Azure.Cosmos.PartitionKey(schoolTeacher.code));
- await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.Teacher).ReplaceItemAsync(teacher, teacher.id, new Azure.Cosmos.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.Status == 404)
- {
- }
- 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"):
- {
- Azure.Response adminResponse = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.School)
- .ReadItemStreamAsync(opttmdid, new Azure.Cosmos.PartitionKey($"Teacher-{_schoolId}"));
- //是否是管理员
- if (adminResponse.Status == 200)
- {
- var adminTeacher = JsonDocument.Parse(adminResponse.Content).RootElement.Deserialize<SchoolTeacher>();
- if (adminTeacher.roles.Contains("admin"))
- {
-
- Azure.Response schoolTeacherResponse = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.School)
- .ReadItemStreamAsync($"{_tmdid}", new Azure.Cosmos.PartitionKey($"Teacher-{_schoolId}"));
- if (teacherResponse.Status == 200 && schoolTeacherResponse.Status == 200)
- {
- var teacher = JsonDocument.Parse(teacherResponse.Content).RootElement.Deserialize<Teacher>();
- 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 Azure.Cosmos.PartitionKey(schoolTeacher.code));
- await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.Teacher).ReplaceItemAsync(teacher, teacher.id, new Azure.Cosmos.PartitionKey(teacher.code));
- } catch (CosmosException ex) when (ex.Status == 404) {
-
- }
- 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 Azure.Cosmos.PartitionKey($"Teacher-{_schoolId}"));
- await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.Teacher).ReplaceItemAsync(teacher, teacher.id, new Azure.Cosmos.PartitionKey(teacher.code));
- }
- catch (CosmosException ex) when (ex.Status == 404)
- {
- }
- 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"):
- {
- Azure.Response schoolTeacherResponse = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.School)
- .ReadItemStreamAsync($"{opttmdid}", new Azure.Cosmos.PartitionKey($"Teacher-{_schoolId}"));
- Azure.Response optTeacherResponse = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.Teacher)
- .ReadItemStreamAsync($"{opttmdid}", new Azure.Cosmos.PartitionKey($"Base"));
- if (optTeacherResponse.Status == 200 && schoolTeacherResponse.Status == 200)
- {
- var teacher = JsonDocument.Parse(optTeacherResponse.Content).RootElement.Deserialize<Teacher>();
- 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 Azure.Cosmos.PartitionKey(schoolTeacher.code));
- await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.Teacher).ReplaceItemAsync(teacher, teacher.id, new Azure.Cosmos.PartitionKey(teacher.code));
- }
- catch (CosmosException ex) when (ex.Status == 404)
- {
- }
- 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 Azure.Cosmos.PartitionKey($"Teacher-{_schoolId}"));
- await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.Teacher).ReplaceItemAsync(teacher, teacher.id, new Azure.Cosmos.PartitionKey(teacher.code));
- }
- catch (CosmosException ex) when (ex.Status == 404)
- {
- }
- 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 });
- }
- }
- [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;
- }
- long nowtime = DateTimeOffset.UtcNow.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 });
- }
- /// <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; }
- }
- }
|