using Microsoft.Extensions.Logging; using Newtonsoft.Json; using NPin.Framework.SettingManagement.Domain; using NPin.Framework.Upms.Domain.Settings; using NPin.Framework.Upms.Domain.Shared.Consts; using NPin.Framework.Upms.Domain.Shared.Enums; using NPin.Framework.Upms.Domain.Shared.Model; using NPin.Framework.Upms.Domain.Sms; using Volo.Abp.Domain.Services; namespace NPin.Framework.Upms.Domain.Managers; public class SmsManager : DomainService { private readonly ILogger _logger; private readonly ISettingManager _settingManager; private readonly IEnumerable _smsProviders; public SmsManager(ILogger logger, ISettingManager settingManager, IEnumerable smsProviders) { _logger = logger; _settingManager = settingManager; _smsProviders = smsProviders; } public async Task GetSmsConfigModelAsync() { var configJson = await _settingManager.GetOrNullUpmsAsync(ConfigConst.SmsConfigModelKey); var settingsJson = await _settingManager.GetOrNullUpmsAsync(ConfigConst.SmsSettingsKey); var providersJson = await _settingManager.GetOrNullUpmsAsync(ConfigConst.SmsProvidersKey); var templateJson = await _settingManager.GetOrNullUpmsAsync(ConfigConst.SmsTemplatesKey); var ret = JsonConvert.DeserializeObject(configJson ?? string.Empty) ?? new SmsConfigModel(); ret.Settings = JsonConvert.DeserializeObject>(settingsJson ?? string.Empty) ?? new Dictionary(); ret.Providers = JsonConvert.DeserializeObject>(providersJson ?? string.Empty) ?? []; ret.Templates = JsonConvert.DeserializeObject>(templateJson ?? string.Empty) ?? []; return ret; } public async Task SendSmsAsync(SmsTypeEnum smsType, string phoneNumbers, object templateParam) { try { var smsConfig = await GetSmsConfigModelAsync(); if (!smsConfig.Enabled) { throw new UserFriendlyException("短信服务未启用,无法发送短信。"); } var settings = smsConfig.GetSetting(smsType); if (settings is null) { throw new UserFriendlyException("未找到对应短信类型,无法发送短信。"); } var providerConfig = smsConfig.GetProvider(settings); var provider = _smsProviders.FirstOrDefault(i => i.ProviderType == providerConfig.ProviderType); if (provider is null) { throw new NotImplementedException("未实现该方式的短信控制器"); } await provider.SendSmsAsync(smsConfig, settings, phoneNumbers, templateParam); } catch (Exception ex) { _logger.LogError(ex, $"短信发送失败: {ex.Message}"); throw new UserFriendlyException($"短信发送失败: {ex.Message}"); } } }