using Azure.Core;
using Furion;
using Furion.DatabaseAccessor;
using Furion.FriendlyException;
using Furion.UnifyResult;
using Mapster;
using MediatR;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Options;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace FlexJobApi.Core
{
///
/// 短信工具
///
public class SmsUtils
{
private readonly IRepository rep;
private readonly IOptions options;
private readonly AliyunSmsUtils aliyunSmsUtils;
public SmsUtils(
IRepository rep,
IOptions options,
AliyunSmsUtils aliyunSmsUtils)
{
this.rep = rep;
this.options = options;
this.aliyunSmsUtils = aliyunSmsUtils;
}
public async Task Send(SendSmsModel model, object templateParam, CancellationToken cancellationToken = default)
{
var entity = new SmsLog();
model.Adapt(entity);
entity.Expiry = DateTime.Now.AddMinutes(10);
entity.TemplateParam = templateParam.ToJson();
await aliyunSmsUtils.SendAsync(model.PhoneNumber, model.TemplateCode, entity.TemplateParam, cancellationToken);
await rep.InsertAsync(entity);
return entity.Id;
}
public async Task SendVerifyCode(SendVerifyCodeModel model, CancellationToken cancellationToken = default)
{
var code = new Random().Next(100000, 999999).ToString();
var entity = new SmsLog();
model.Adapt(entity);
entity.Expiry = DateTime.Now.AddMinutes(10);
entity.TemplateParam = new { code }.ToJson();
await aliyunSmsUtils.SendAsync(model.PhoneNumber, model.TemplateCode, entity.TemplateParam, cancellationToken);
await rep.InsertAsync(entity);
if (options.Value.SMS.WithoutVerifyCode)
{
UnifyContext.Fill(new
{
Code = code
});
}
return entity.Id;
}
public async Task CheckVerifyCode(CheckVerifyCodeModel model, CancellationToken cancellationToken = default)
{
var entity = await rep.AsQueryable().AsNoTracking()
.Where(it =>
it.PhoneNumber == model.PhoneNumber
&& it.TemplateCode == model.TemplateCode.ToString()
&& it.TemplateParam == new { code = model.VerifyCode }.ToJson()
&& it.Expiry > DateTimeOffset.Now
&& !it.IsUsed)
.FirstOrDefaultAsync(cancellationToken);
if (entity == null) throw Oops.Oh(EnumErrorCodeType.s400, "验证码无效");
entity.IsUsed = true;
await rep.UpdateAsync(entity);
}
}
}