You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

330 lines
13 KiB

using Microsoft.Data.SqlClient;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using Npgsql;
using Oracle.ManagedDataAccess.Client;
using Shentun.Utilities;
using System;
using System.Collections.Generic;
using System.Data.Common;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Linq.Dynamic.Core.Tokenizer;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
namespace Shentun.WebPeis.PlugIns
{
public class PlugInsBase
{
protected IConfiguration? AppConfig;
protected IConfiguration? InterfaceConfig;
protected string? AppConnctionStr;
private string? _appBaseAddress;
private static string? _accesToken;
protected string? AppUser;
protected string? AppPassword;
protected string? InterfaceSql;
protected string? InterfaceSqlKeyColumn;
protected string? InterfaceDbType;
protected string? InterfaceConnctionStr;
protected string? InterfaceWebApiUrl;
protected Guid ItemColumnReferenceId;
protected Guid AsbitemColumnReferenceId;
protected Guid DepartmentColumnReferenceId;
protected Guid UserColumnReferenceId;
protected ILogger<PlugInsBase> Logger;
static PlugInsBase()
{
Dapper.DefaultTypeMap.MatchNamesWithUnderscores = true;
}
public PlugInsBase()
{
Init();
}
public PlugInsBase(string parmValue)
{
Init();
Init(parmValue);
}
public void Init()
{
AppConfig = new ConfigurationBuilder()
.SetBasePath(DirectoryHelper.GetAppDirectory()) // 设置基础路径为当前目录
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.Build();
AppConnctionStr = AppConfig.GetSection("ConnectionStrings")
.GetSection("Default").Value;
_appBaseAddress = AppConfig.GetSection("App")
.GetSection("SelfUrl").Value;
AppUser = AppConfig.GetSection("App")
.GetSection("SelfUser").Value;
AppPassword = AppConfig.GetSection("App")
.GetSection("SelfPassword").Value;
using var loggerFactory = LoggerFactory.Create(builder =>
{
});
Logger = loggerFactory.CreateLogger<PlugInsBase>();
}
public void Init(string parmValue)
{
var configurationBuilder = new ConfigurationBuilder()
.AddJsonStream(new MemoryStream(System.Text.Encoding.UTF8.GetBytes(parmValue)));
InterfaceConfig = configurationBuilder.Build();
//如果接口配置里面配置了用户名密码,则用接口中的覆盖本地配置
var appUser = InterfaceConfig.GetSection("App").GetSection("User").Value;
if(!string.IsNullOrWhiteSpace(appUser))
{
AppUser = appUser;
}
var appPassword = InterfaceConfig.GetSection("App").GetSection("Password").Value;
if (!string.IsNullOrWhiteSpace(appPassword))
{
AppPassword = appPassword;
}
//设置接口有关配置
InterfaceSql = InterfaceConfig.GetSection("Interface").GetSection("Sql").Value;
InterfaceSqlKeyColumn = InterfaceConfig.GetSection("Interface").GetSection("SqlKeyColumn").Value;
InterfaceDbType = InterfaceConfig.GetSection("Interface").GetSection("DbType").Value;
InterfaceWebApiUrl = InterfaceConfig.GetSection("Interface").GetSection("WebApiUrl").Value;
InterfaceConnctionStr = InterfaceConfig.GetSection("Interface").GetSection("ConnectionStrings").Value;
var itemColumnReferenceIdStr = InterfaceConfig.GetSection("Interface")
.GetSection("ItemColumnReferenceId").Value;
if (!string.IsNullOrWhiteSpace(itemColumnReferenceIdStr))
{
ItemColumnReferenceId = new Guid(itemColumnReferenceIdStr);
}
var asbItemColumnReferenceIdStr = InterfaceConfig.GetSection("Interface")
.GetSection("AsbitemColumnReferenceId").Value;
if (!string.IsNullOrWhiteSpace(asbItemColumnReferenceIdStr))
{
AsbitemColumnReferenceId = new Guid(asbItemColumnReferenceIdStr);
}
var departmentColumnReferenceIdStr = InterfaceConfig.GetSection("Interface")
.GetSection("DepartmentColumnReferenceId").Value;
if (!string.IsNullOrWhiteSpace(departmentColumnReferenceIdStr))
{
DepartmentColumnReferenceId = new Guid(departmentColumnReferenceIdStr);
}
var userColumnReferenceIdStr = InterfaceConfig.GetSection("Interface")
.GetSection("UserColumnReferenceId").Value;
if (!string.IsNullOrWhiteSpace(userColumnReferenceIdStr))
{
UserColumnReferenceId = new Guid(userColumnReferenceIdStr);
}
}
protected DbConnection CreateInterfaceDbConnect()
{
DbConnection conn;
if (string.IsNullOrWhiteSpace(InterfaceConnctionStr))
{
throw new ArgumentException("数据连接设置中的DbType不能为空");
}
InterfaceDbType = InterfaceDbType.ToLower();
//Logger.LogInformation("数据库类型:" + InterfaceDbType);
if (InterfaceDbType == "sqlserver")
{
//Logger.LogInformation("调用sqlserver:" + InterfaceDbType);
conn = new SqlConnection(InterfaceConnctionStr);
}
else if (InterfaceDbType == "postgres")
{
//Logger.LogInformation("调用postgres:" + InterfaceDbType);
conn = new NpgsqlConnection(InterfaceConnctionStr);
}
else if (InterfaceDbType == "oracle")
{
//Logger.LogInformation("调用oracle:" + InterfaceDbType);
conn = new OracleConnection(InterfaceConnctionStr);
}
else
{
throw new ArgumentException("数据连接设置中的DbType不支持");
}
return conn;
}
public async Task<TOut> CallAppServiceAsync<TInput, TOut>(string url, TInput data, string method = "post")
{
if(string.IsNullOrWhiteSpace(_appBaseAddress))
{
throw new Exception("_appBaseAddress不能为空");
}
string baseAddress = _appBaseAddress;
await CheckLoginAsync();
using (var httpClientHandler = new HttpClientHandler())
{
using (var httpClient = new HttpClient(httpClientHandler))
{
httpClient.BaseAddress = new Uri(baseAddress);
httpClient.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));//设置accept标头,告诉JSON是可接受的响应类型
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", _accesToken);
IsoDateTimeConverter timeFormat = new IsoDateTimeConverter();
timeFormat.DateTimeFormat = "yyyy-MM-dd HH:mm:ss";
var sendData = JsonConvert.SerializeObject(data, Newtonsoft.Json.Formatting.Indented, timeFormat);
using (HttpContent httpContent = new StringContent(sendData))
{
httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
HttpResponseMessage response = null;
if (method == "post")
{
response = await httpClient.PostAsync(url, httpContent);
}
else
{
response = await httpClient.GetAsync(url);
}
string result;
if (!response.IsSuccessStatusCode)
{
result = response.Content.ReadAsStringAsync().Result;
throw new Exception("http通信错误:" + response.StatusCode + ",结果:" + result);
}
result = await response.Content.ReadAsStringAsync();
var resultDto = JsonConvert.DeserializeObject< WebApiOutDto<TOut>>(result);
if (resultDto.Code == -1)
{
throw new Exception($"调用WebApi失败,返回-1,消息:" + resultDto.Message);
}
return resultDto.Data;
}
}
}
}
public virtual async Task DoWorkAsync()
{
}
public virtual Task DoWork()
{
return Task.CompletedTask;
}
public async virtual Task<WebApiOutDto<LoginOutDataDto>> LoginAsync()
{
if(string.IsNullOrWhiteSpace(AppUser))
{
throw new Exception("SelfUser不能为空");
}
if (string.IsNullOrWhiteSpace(AppPassword))
{
throw new Exception("SelfPassword不能为空");
}
var relult = await LoginAsync(AppUser, AppPassword);
return relult;
}
public async Task<WebApiOutDto<LoginOutDataDto>> LoginAsync(string userId, string password)
{
if (string.IsNullOrWhiteSpace(userId))
{
throw new Exception("用户ID不能为空");
}
if (string.IsNullOrWhiteSpace(password))
{
throw new Exception("密码不能为空");
}
using (var httpClientHandler = new HttpClientHandler())
{
using (var httpClient = new HttpClient(httpClientHandler))
{
httpClient.BaseAddress = new Uri(_appBaseAddress);
httpClient.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));//设置accept标头,告诉JSON是可接受的响应类型
var url = "api/identity/users/login";
var loginUser = new LoginInputDto()
{
UserName = userId,
Password = password
};
var sendData = JsonConvert.SerializeObject(loginUser);
using (HttpContent httpContent = new StringContent(sendData))
{
httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
HttpResponseMessage response = await httpClient.PostAsync(url, httpContent);
string result;
if (!response.IsSuccessStatusCode)
{
result = response.Content.ReadAsStringAsync().Result;
throw new Exception("http通信错误:" + response.StatusCode + ",结果:" + result);
}
result = await response.Content.ReadAsStringAsync();
var restultDto = JsonConvert.DeserializeObject<WebApiOutDto<LoginOutDataDto>>(result);
if (restultDto == null)
{
throw new Exception("返回结果是空");
}
if (restultDto.Code != 1)
{
throw new Exception($"登录失败{restultDto.Message}");
}
_accesToken = restultDto.Data.access_token;
return restultDto;
}
}
}
}
private async Task CheckLoginAsync()
{
if (string.IsNullOrWhiteSpace(_accesToken))
{
await LoginAsync();
}
else
{
var handler = new JwtSecurityTokenHandler();
var payload = handler.ReadJwtToken(_accesToken).Payload;
var claims = payload.Claims;
var exp = claims.First(claim => claim.Type == "exp").Value;
if (exp == null)
{
await LoginAsync();
}
else
{
if (long.TryParse(exp, out var expires))
{
var expireTime = DateTimeOffset.FromUnixTimeSeconds(expires).LocalDateTime;
if (expireTime <= DateTime.Now)
{
await LoginAsync();
}
}
else
{
await LoginAsync();
}
}
}
}
}
}