using System.Data;
using System.Diagnostics;
using System.Security.Cryptography;
using System.Text;
using System.Text.Json.Nodes;
using System.Text.RegularExpressions;
using System.Web;
using JNPF.Common.Configuration;
using JNPF.Common.Const;
using JNPF.Common.Core.Manager;
using JNPF.Common.Core.Manager.Files;
using JNPF.Common.Dtos.OAuth;
using JNPF.Common.Dtos.VisualDev;
using JNPF.Common.Enums;
using JNPF.Common.Extension;
using JNPF.Common.Filter;
using JNPF.Common.Manager;
using JNPF.Common.Models;
using JNPF.Common.Net;
using JNPF.Common.Security;
using JNPF.DatabaseAccessor;
using JNPF.DependencyInjection;
using JNPF.DynamicApiController;
using JNPF.Extras.DatabaseAccessor.SqlSugar.Models;
using JNPF.Extras.Thirdparty.JSEngine;
using JNPF.FriendlyException;
using JNPF.LinqBuilder;
using JNPF.Logging.Attributes;
using JNPF.RemoteRequest.Extensions;
using JNPF.SensitiveDetection;
using JNPF.Systems.Entitys.Dto.DataInterFace;
using JNPF.Systems.Entitys.Dto.System.DataInterFace;
using JNPF.Systems.Entitys.Model.DataInterFace;
using JNPF.Systems.Entitys.Permission;
using JNPF.Systems.Entitys.System;
using JNPF.Systems.Interfaces.System;
using JNPF.UnifyResult;
using Mapster;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using SqlSugar;
using JNPF.Common.Filter;
namespace JNPF.Systems;
///
/// 数据接口
/// 版 本:V3.2
/// 版 权:引迈信息技术有限公司(https://www.jnpfsoft.com)
/// 作 者:JNPF开发平台组
/// 日 期:2021-06-01.
///
[ApiDescriptionSettings(Tag = "System", Name = "DataInterface", Order = 204)]
[Route("api/system/[controller]")]
public class DataInterfaceService : IDataInterfaceService, IDynamicApiController, ITransient
{
///
/// 服务基础仓储.
///
private readonly ISqlSugarRepository _repository;
///
/// 数据字典服务.
///
private readonly IDictionaryDataService _dictionaryDataService;
///
/// 脱敏词汇提供器.
///
private readonly ISensitiveDetectionProvider _sensitiveDetectionProvider;
///
/// 数据库管理.
///
private readonly IDataBaseManager _dataBaseManager;
///
/// 用户管理.
///
private readonly IUserManager _userManager;
///
/// 缓存管理.
///
private readonly ICacheManager _cacheManager;
///
/// 文件服务.
///
private readonly IFileManager _fileManager;
///
/// 初始化 SqlSugar 客户端.
///
private readonly SqlSugarScope _sqlSugarClient;
///
/// 数据库上下文ID.
///
private string _configId = App.Configuration["ConnectionStrings:ConfigId"];
///
/// 数据库名称.
///
private string _dbName = App.Configuration["ConnectionStrings:DBName"];
///
/// 初始化一个类型的新实例.
///
public DataInterfaceService(
ISqlSugarRepository repository,
IDictionaryDataService dictionaryDataService,
IDataBaseManager dataBaseManager,
IUserManager userManager,
ICacheManager cacheManager,
IFileManager fileManager,
ISensitiveDetectionProvider sensitiveDetectionProvider,
ISqlSugarClient context)
{
_sensitiveDetectionProvider = sensitiveDetectionProvider;
_repository = repository;
_dictionaryDataService = dictionaryDataService;
_fileManager = fileManager;
_dataBaseManager = dataBaseManager;
_cacheManager = cacheManager;
_userManager = userManager;
_sqlSugarClient = (SqlSugarScope)context;
}
#region Get
///
/// 获取接口列表(分页).
///
/// 参数.
///
[HttpGet("")]
public async Task GetList([FromQuery] DataInterfaceListQuery input)
{
var list = await _repository.AsSugarClient().Queryable((a, b) => new JoinQueryInfos(JoinType.Left, b.Id == a.CreatorUserId))
.Where(a => a.DeleteMark == null)
.WhereIF(!string.IsNullOrEmpty(input.categoryId), a => a.CategoryId == input.categoryId)
.WhereIF(!string.IsNullOrEmpty(input.keyword), a => a.FullName.Contains(input.keyword) || a.EnCode.Contains(input.keyword))
.OrderBy(a => a.SortCode).OrderBy(a => a.CreatorTime, OrderByType.Desc)
.Select((a, b) => new DataInterfaceListOutput
{
id = a.Id,
categoryId = a.CategoryId,
creatorTime = a.CreatorTime,
creatorUser = SqlFunc.MergeString(b.RealName, "/", b.Account),
dataType = a.DataType,
dbLinkId = a.DBLinkId,
description = a.Description,
enCode = a.EnCode,
fullName = a.FullName,
enabledMark = a.EnabledMark,
path = a.Path,
query = a.Query,
requestMethod = SqlFunc.IF(a.RequestMethod.Equals("1")).Return("新增").ElseIF(a.RequestMethod.Equals("2")).Return("修改")
.ElseIF(a.RequestMethod.Equals("3")).Return("查询").ElseIF(a.RequestMethod.Equals("4")).Return("删除")
.ElseIF(a.RequestMethod.Equals("5")).Return("存储过程").ElseIF(a.RequestMethod.Equals("6")).Return("Get")
.End("Post"),
requestParameters = a.RequestParameters,
responseType = a.ResponseType,
sortCode = a.SortCode,
checkType = a.CheckType,
tenantId = _userManager.TenantId
}).ToPagedListAsync(input.currentPage, input.pageSize);
return PageResult.SqlSugarPageResult(list);
}
///
/// 获取接口列表(分页).
///
/// 参数.
///
[HttpGet("getList")]
public async Task getList([FromQuery] DataInterfaceListQuery input)
{
var list = await _repository.AsSugarClient().Queryable((a, b) => new JoinQueryInfos(JoinType.Left, b.Id == a.CreatorUserId))
.Where(a => a.DeleteMark == null)
.WhereIF(!string.IsNullOrEmpty(input.categoryId), a => a.CategoryId == input.categoryId)
.WhereIF(!string.IsNullOrEmpty(input.dataType), a => a.DataType.ToString() == input.dataType)
.WhereIF(!string.IsNullOrEmpty(input.keyword), a => a.FullName.Contains(input.keyword) || a.EnCode.Contains(input.keyword))
.OrderBy(a => a.SortCode).OrderBy(a => a.CreatorTime, OrderByType.Desc)
.Select((a, b) => new DateInterfaceGetListOutput
{
id = a.Id,
categoryId = a.CategoryId,
creatorTime = a.CreatorTime,
creatorUser = SqlFunc.MergeString(b.RealName, "/", b.Account),
_dataType = a.DataType,
dbLinkId = a.DBLinkId,
description = a.Description,
enCode = a.EnCode,
fullName = a.FullName,
enabledMark = a.EnabledMark,
path = a.Path,
query = a.Query,
requestMethod = SqlFunc.IF(a.RequestMethod.Equals("1")).Return("新增").ElseIF(a.RequestMethod.Equals("2")).Return("修改")
.ElseIF(a.RequestMethod.Equals("3")).Return("查询").ElseIF(a.RequestMethod.Equals("4")).Return("删除")
.ElseIF(a.RequestMethod.Equals("5")).Return("存储过程").ElseIF(a.RequestMethod.Equals("6")).Return("Get")
.End("Post"),
requestParameters = a.RequestParameters,
responseType = a.ResponseType,
sortCode = a.SortCode,
checkType = a.CheckType,
tenantId = _userManager.TenantId
}).ToPagedListAsync(input.currentPage, input.pageSize);
return PageResult.SqlSugarPageResult(list);
}
///
/// 获取接口列表下拉框.
///
///
[HttpGet("Selector")]
public async Task GetSelector()
{
List tree = new List();
foreach (var entity in await _repository.AsQueryable().Where(x => x.DeleteMark == null && x.EnabledMark == 1).OrderBy(x => x.SortCode).ToListAsync())
{
var dictionaryDataEntity = await _dictionaryDataService.GetInfo(entity.CategoryId);
if (dictionaryDataEntity != null && tree.Where(t => t.id == entity.CategoryId).Count() == 0)
{
DataInterfaceSelectorOutput firstModel = dictionaryDataEntity.Adapt();
firstModel.categoryId = "0";
DataInterfaceSelectorOutput treeModel = entity.Adapt();
treeModel.categoryId = "1";
treeModel.parentId = dictionaryDataEntity.Id;
firstModel.children.Add(treeModel);
tree.Add(firstModel);
}
else
{
DataInterfaceSelectorOutput treeModel = entity.Adapt();
treeModel.categoryId = "1";
treeModel.parentId = entity.CategoryId;
var parent = tree.Where(t => t.id == entity.CategoryId).FirstOrDefault();
if (parent != null)
{
parent.children.Add(treeModel);
}
}
}
return tree.OrderBy(x => x.sortCode).ToList();
}
///
/// 获取接口数据.
///
///
[HttpGet("{id}")]
public async Task GetInfo_Api(string id)
{
return (await GetInfo(id)).Adapt();
}
///
/// 获取预览参数.
///
///
///
[HttpGet("GetParam/{id}")]
[UnitOfWork]
public async Task GetParam(string id)
{
var info = await GetInfo(id);
if (info.IsNotEmptyOrNull() && info.RequestParameters.IsNotEmptyOrNull())
{
return info.RequestParameters.ToList();
}
else
{
return new List();
}
}
///
/// 访问接口 选中 回写.
///
///
[AllowAnonymous]
[IgnoreLog]
[HttpGet("{id}/Action/Info")]
public async Task ActionsResponseInfo(string id, [FromQuery] string tenantId, [FromQuery] VisualDevDataFieldDataListInput input)
{
return await GetResponseByType(id, 1, tenantId, input);
}
///
/// 导出.
///
///
///
[HttpGet("{id}/Action/Export")]
public async Task ActionsExport(string id)
{
var data = await GetInfo(id);
var jsonStr = data.ToJsonString();
return await _fileManager.Export(jsonStr, data.FullName, ExportFileType.bd);
}
#endregion
#region Post
///
/// 预览接口.
///
///
///
[HttpPost("{id}/Actions/Preview")]
[UnitOfWork]
public async Task Preview(string id, [FromBody] DataInterfacePreviewInput input)
{
_configId = _userManager.TenantId;
_dbName = _userManager.TenantDbName;
object output = null;
var info = await GetInfo(id);
var dicParameters = new Dictionary();
if (input.paramList.IsNotEmptyOrNull() && input.paramList.Count > 0)
{
dicParameters = input.paramList.ToDictionary(x => x.field, y => y.defaultValue);
}
if (!string.IsNullOrEmpty(info.Path) && !info.Path.StartsWith("http"))
{
info.Path = $"{App.HttpContext.Request.Scheme}://{App.HttpContext.Request.Host}{info.Path}";
}
VerifyRequired(info, dicParameters);
ReplaceParameterValue(info, dicParameters);
if (info?.DataType == 1)
{
output = await GetData(info);
}
else if (info?.DataType == 2)
{
output = info.Query.ToObject