using System.Data.Common; using DS.Module.Core; using DS.Module.SqlSugar; using DS.Module.UserModule; using DS.WMS.Core; using DS.WMS.Core.Code.Interface; using DS.WMS.MainApi.Models; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using SqlSugar; namespace DS.WMS.MainApi.Controllers { /// /// 运维API /// public class MaintenanceController : ApiController { readonly IConfiguration config; readonly ApiFox api; /// /// 初始化 /// /// public MaintenanceController(IConfiguration config) { this.config = config; api = new ApiFox(); } /// /// 运行SQL脚本 /// /// /// SQL脚本 /// 运行的数据库,为空时执行全部租户库 /// [HttpPost, Route("RunScript"), AllowAnonymous] public async Task RunScriptAsync([FromServices] ISqlSugarClient sugarClient, [FromForm] string script, [FromQuery] params string[] dbNames) { bool hasError = default; var linkList = await sugarClient.Queryable().ToListAsync(); DbConnection? connection = null; try { foreach (var item in linkList) { var paramArr = item.Connection.Split(';', StringSplitOptions.RemoveEmptyEntries); if (dbNames != null && dbNames.Length > 0) //指定了数据库名 { var seg = Array.Find(paramArr, x => x.StartsWith("database", StringComparison.OrdinalIgnoreCase)); if (seg == null) continue; string dbName = seg.Split('=')[1]; if (!dbNames.Contains(dbName, StringComparer.OrdinalIgnoreCase)) continue; } var fac = DbProviderFactories.GetFactory(sugarClient.Ado.Connection as DbConnection); connection = fac!.CreateConnection(); connection.ConnectionString = item.Connection; var cmd = connection.CreateCommand(); cmd.CommandText = script; await connection.OpenAsync(); await cmd.ExecuteNonQueryAsync(); } } catch (Exception ex) { await ex.LogAsync(sugarClient); hasError = true; } finally { connection?.Dispose(); } return hasError ? StatusCode(500) : Ok(); } /// /// 发送自定义邮件 /// /// /// /// 邮件发送模型 /// [HttpPost, Route("SendMail")] public async Task SendMailAsync([FromServices] IUserEmailService userEmailService, [FromServices] IUser user, [FromBody] SendMailModel model) { if (string.IsNullOrEmpty(config["MailConfig:ApiUrl"])) return DataResult.Failed("请联系站点管理员配置邮件服务URL"); var userEmail = await userEmailService.GetCurrentUserEmailAsync(); if (!userEmail.Succeeded || userEmail.Data == null || string.IsNullOrEmpty(userEmail.Data.MailAccount)) return DataResult.Failed("你尚未配置邮箱设置,请到系统设置中维护后重试此操作"); if (string.IsNullOrEmpty(userEmail.Data.Password)) return DataResult.Failed("你尚未配置邮箱账户密码,请到系统设置中维护后重试此操作"); if (model.Attachments?.Length > 0) { for (int i = 0; i < model.Attachments.Length; i++) { var attachment = model.Attachments[i]; var response = await api.SendRequestAsync(HttpMethod.Get, attachment.Url); if (!response.IsSuccessStatusCode) return DataResult.Failed("无法从下列地址中获取文件作为附件:" + attachment.Url); var bytes = await response.Content.ReadAsByteArrayAsync(); if (bytes == null || bytes.Length == 0) return DataResult.Failed("下列地址中获取的文件大小为零,无法生成附件:" + attachment.Url); attachment.Base64 = Convert.ToBase64String(bytes); if (string.IsNullOrEmpty(attachment.FileName)) attachment.FileName = Path.GetFileName(attachment.Url); } } string sendTo = string.Join(",", model.Receivers); dynamic[] mailParams = [new { SendTo = sendTo, model.Title, Body = model.Content, model.CCTo, ShowName = string.IsNullOrEmpty(userEmail.Data.ShowName) ? userEmail.Data.MailAccount : userEmail.Data.ShowName, Account = userEmail.Data.MailAccount, userEmail.Data.Password, Server = userEmail.Data.SmtpServer, Port = userEmail.Data.SmtpPort, UseSSL = userEmail.Data.SmtpSSL.GetValueOrDefault(), Attaches = model.Attachments?.Select(x => new { AttachName = x.FileName, AttachContent = x.Base64 }).ToList() }]; var mailResult = await api.SendRequestAsync(HttpMethod.Post, config["MailConfig:ApiUrl"]!, mailParams); return mailResult.IsSuccessStatusCode ? DataResult.Success : DataResult.Failed("发送失败,邮件服务返回状态码为错误"); } } }