Merge pull request 'dev_lx' (#18) from dev_lx into main

Reviewed-on: #18
pull/19/head
刘鑫 2 months ago
commit 64c7cbb0f8
  1. 46
      WeiCloud.Fusion/AlarmService/Alarm.DomainService/DahAlarm/DahuaGeneralCtlService.cs
  2. 4
      WeiCloud.Fusion/AlarmService/Alarm.DomainService/DahAlarm/IDahuaGeneralCtlService.cs
  3. 4
      WeiCloud.Fusion/AlarmService/AlarmService.API/Controllers/AlarmController.cs
  4. 11
      WeiCloud.Fusion/AlarmService/AlarmService.API/Program.cs
  5. 8
      WeiCloud.Fusion/AlarmService/AlarmService.API/appsettings.json
  6. 6
      WeiCloud.Fusion/Common.SharedService/Common.Shared.API/Program.cs
  7. 3
      WeiCloud.Fusion/Common.SharedService/Common.Shared.API/appsettings.json
  8. 13
      WeiCloud.Fusion/Common.SharedService/Common.Shared.Application/Core/CorsWithOrigins.cs
  9. 86
      WeiCloud.Fusion/Common.SharedService/Common.Shared.Application/DaHua/ResponeDto/EventEnvelopeDto.cs
  10. 58
      WeiCloud.Fusion/Common.SharedService/Common.Shared.DomainService/DaHTokenService/TokenProviderService.cs
  11. 14
      WeiCloud.Fusion/ParkingLotService/ParkingLotService.API/Program.cs
  12. 8
      WeiCloud.Fusion/VideoService/Video.API/Program.cs
  13. 10
      WeiCloud.Fusion/VideoService/Video.API/appsettings.json
  14. 38
      WeiCloud.Fusion/VideoService/Video.DomainService/Dahvision/DahuaGeneralCtlService.cs

@ -18,7 +18,7 @@ namespace Alarm.DomainService.DahAlarm
private readonly IMqttClientService _mqttClientService;
private readonly ITokenProviderService _tokenProviderService;
private readonly HttpClient _http;
// private readonly HttpClient _http;
private string mqttHostIp;
private int mqttHostPort;
@ -50,16 +50,16 @@ namespace Alarm.DomainService.DahAlarm
topicName = _configuration["SubscribeMQTT:TopicName"]!;
_mqttClientService = mqttClientService;
_tokenProviderService = tokenProviderService;
_http = http;
// _http = http;
}
///// <summary>
///// 开发测试的时候,忽略证书
///// </summary>
//private static readonly HttpClient _http = new(new HttpClientHandler
//{
// ServerCertificateCustomValidationCallback = HttpClientHandler.DangerousAcceptAnyServerCertificateValidator,
//});
/// <summary>
/// 开发测试的时候,忽略证书
/// </summary>
private static readonly HttpClient _http = new(new HttpClientHandler
{
ServerCertificateCustomValidationCallback = HttpClientHandler.DangerousAcceptAnyServerCertificateValidator,
});
/// <summary>
/// 新增报警事件订阅
@ -189,12 +189,13 @@ namespace Alarm.DomainService.DahAlarm
/// <param name="dto"></param>
/// <returns></returns>
/// <exception cref="NotImplementedException"></exception>
public async Task<DaHApiResult<bool>> HandleAsync(EventEnvelopeDto dto)
public async Task<DaHApiResult<bool>> HandleAsync(object dto2)
{
DaHApiResult<bool> result = new() { Code = "200", Msg = "接口调用成功", Data = true };
_logger.LogWarning($"报警回调的数据{dto2}");
try
{
if (dto is null)
if (dto2 is null)
{
result.Code = "500";
result.Msg = "请求参数不能为空";
@ -202,7 +203,7 @@ namespace Alarm.DomainService.DahAlarm
_logger.LogWarning("大华报警事件订阅回调处理失败,参数不能为空");
return result;
}
EventEnvelopeDto dto = dto2 as EventEnvelopeDto;
if (dto.Info is not null)
{
//这是大华的残卫报警类型
@ -210,7 +211,7 @@ namespace Alarm.DomainService.DahAlarm
{
//拼接物联平台标准的mqtt消息格式
var payload = "[{\"taglabel\":\"" + dto.Info.DeviceCode + ".alart." + dto.Info.DeviceName + "\",\"value\":\"" + dto.Info.AlarmStat + "\",\"time\":\"" + DateTimeOffset.UtcNow.ToUnixTimeSeconds() + "\"}]";
//var payload = "[{\"taglabel\":\"残卫测试报警按钮.alarmStat\",\"value\":\"" + dto.Info.AlarmStat + "\",\"time\":\"" + DateTimeOffset.UtcNow.ToUnixTimeSeconds() + "\"}]";
// var payload = "[{\"taglabel\":\"残卫测试报警按钮.alarmStat\",\"value\":\"" + dto.Info.AlarmStat + "\",\"time\":\"" + DateTimeOffset.UtcNow.ToUnixTimeSeconds() + "\"}]";
await _mqttClient.EnsureConnectedAsync(mqttHostIp, mqttHostPort, mqttUsername, mqttPassword, topicName, mqttClientId);
await _mqttClientService.PublishAsync(topicName, payload);
@ -246,7 +247,7 @@ namespace Alarm.DomainService.DahAlarm
try
{
var request = new HttpRequestMessage(HttpMethod.Delete, url);
request.Headers.Authorization = new AuthenticationHeaderValue("Authorization", token);
request.Headers.TryAddWithoutValidation("Authorization", token);
using var resp = await _http.SendAsync(request);
var body = await resp.Content.ReadAsStringAsync();
@ -279,18 +280,17 @@ namespace Alarm.DomainService.DahAlarm
/// <param name="name"></param>
/// <returns></returns>
/// <exception cref="NotImplementedException"></exception>
public async Task<DaHApiResult<SubscriptionMapDto>> GetEventList(string name = "alarm")
public async Task<DaHApiResult<SubscribeDataDto>> GetEventList(string name = "alarm")
{
var clientId = _configuration["DahuaAuth:ClientId"];
var token = await _tokenProviderService.GetTokenAsync(clientId!);
if (!_tokenProviderService.IsTokenValid(token))
{
_logger.LogWarning("获取事件列表:token无效");
return new DaHApiResult<SubscriptionMapDto> { Success = false, Code = "1009", Msg = "token无效" };
return new DaHApiResult<SubscribeDataDto> { Success = false, Code = "1009", Msg = "token无效" };
}
var url = $"https://{_configuration["DahuaAuth:Host"]}/evo-apigw/evo-brm/1.0.0/device/1000021";
//var url = $"https://{_configuration["DahuaAuth:Host"]}/evo-apigw/evo-event/1.0.0/subscribe/subscribe-list?monitorType=url&category={name}";
// var url = $"http://demo.weienergy.cn:15230/open-api/token/v1/oauth/token?client_id=69591850&client_secret=WHcpAryKFc28suzL&grant_type=client_credentials";
var url = $"https://{_configuration["DahuaAuth:Host"]}/evo-apigw/evo-event/1.0.0/subscribe/subscribe-list?monitorType=url&category={name}";
try
{
var request = new HttpRequestMessage(HttpMethod.Get, url);
@ -303,14 +303,14 @@ namespace Alarm.DomainService.DahAlarm
if (!resp.IsSuccessStatusCode)
{
_logger.LogWarning("实时流请求 HTTP 失败: {Status}, Body: {Body}", (int)resp.StatusCode, body);
return new DaHApiResult<SubscriptionMapDto> { Success = false, Code = "1010", Msg = $"HTTP错误 {(int)resp.StatusCode}" };
return new DaHApiResult<SubscribeDataDto> { Success = false, Code = "1010", Msg = $"HTTP错误 {(int)resp.StatusCode}" };
}
var result = JsonSerializer.Deserialize<DaHApiResult<SubscriptionMapDto>>(body);
var result = JsonSerializer.Deserialize<DaHApiResult<SubscribeDataDto>>(body);
if (result == null || !result.Success)
{
_logger.LogWarning("实时流请求业务失败: {Body}", body);
return new DaHApiResult<SubscriptionMapDto> { Success = false, Code = "1010", Msg = "实时流请求失败" };
return new DaHApiResult<SubscribeDataDto> { Success = false, Code = "1010", Msg = "实时流请求失败" };
}
return result;
@ -318,7 +318,7 @@ namespace Alarm.DomainService.DahAlarm
catch (Exception ex)
{
_logger.LogError(ex, "大华实时流请求出错");
return new DaHApiResult<SubscriptionMapDto> { Success = false, Code = "1010", Msg = "实时流请求失败" };
return new DaHApiResult<SubscribeDataDto> { Success = false, Code = "1010", Msg = "实时流请求失败" };
}
}

@ -16,7 +16,7 @@ namespace Alarm.DomainService.DahAlarm
Task<bool> DeleteEvent(string name);
Task<DaHApiResult<SubscriptionMapDto>> GetEventList(string name = "alarm");
Task<DaHApiResult<SubscribeDataDto>> GetEventList(string name = "alarm");
/// <summary>
/// AddSubscribeEvent回调函数处理
@ -25,6 +25,6 @@ namespace Alarm.DomainService.DahAlarm
/// <param name="env"></param>
/// <param name="ct"></param>
/// <returns></returns>
Task<DaHApiResult<bool>> HandleAsync(EventEnvelopeDto env);
Task<DaHApiResult<bool>> HandleAsync(object env);
}
}

@ -37,7 +37,7 @@ namespace AlarmService.API.Controllers
/// <param name="env"></param>
/// <returns></returns>
[HttpPost]
public async Task<DaHApiResult<bool>> DahuaAuthCallback(EventEnvelopeDto env)
public async Task<DaHApiResult<bool>> DahuaAuthCallback(object env)
{
return await _generalCtlService.HandleAsync(env);
}
@ -48,7 +48,7 @@ namespace AlarmService.API.Controllers
/// <param name="name"></param>
/// <returns></returns>
[HttpGet]
public async Task<DaHApiResult<SubscriptionMapDto>> GetEventList(string name = "alarm")
public async Task<DaHApiResult<SubscribeDataDto>> GetEventList(string name = "alarm")
{
return await _generalCtlService.GetEventList(name);

@ -1,6 +1,7 @@
using AlarmService.API.Infrastructure;
using Autofac;
using Autofac.Extensions.DependencyInjection;
using Common.Shared.Application.Core;
using Common.Shared.DomainService;
using Microsoft.OpenApi.Models;
using NLog;
@ -22,18 +23,20 @@ namespace AlarmService.API
builder.Services.AddHttpContextAccessor();
builder.Services.AddHttpClient();
builder.Services.AddControllers();
builder.Services.AddSingleton(builder.Configuration);
#region Cors
var isconfig = builder.Configuration.GetSection("IdentityClientConfig").Get<CorsWithOrigins>();
builder.Services.AddCors(options =>
{
options.AddPolicy("_myAllowSpecificOrigins",
builder =>
{
builder.AllowAnyOrigin() //允许所有源访问本API(开发环境设置)
builder
//.WithOrigins(isconfig.CorsOrigins) //被允许的来源,多个使用逗号分隔
.AllowAnyOrigin() //允许所有源访问本API(开发环境设置)
.AllowAnyHeader()
.AllowAnyMethod()
.AllowCredentials()
@ -112,9 +115,9 @@ namespace AlarmService.API
});
}
app.UseHttpsRedirection();
// app.UseHttpsRedirection();
app.UseAuthorization();
// app.UseAuthorization();
app.MapControllers();
app.MapGet("/healthz", () => Results.Ok("OK"));

@ -5,6 +5,7 @@
"Microsoft.AspNetCore": "Warning"
}
},
"SubscribeMQTT": {
"TopicName": "/zrh/sun/alarm",
"ProjectId": 530522108656160,
@ -16,6 +17,7 @@
"ClientId": "datasource_points_AXYJPT_v4",
"ApiUrl": "http://v4.weienergy.cn/datastream"
},
"CorsWithOrigins": [ "https://demo.weienergy.cn:15214", "http://59.110.150.214", "https://demo.weienergy.cn/" ],
"AllowedHosts": "*",
//
"DahuaAuth": {
@ -25,8 +27,8 @@
"ClientSecret": "6d6c78f8-3d4c-4e76-ab6b-827942a7b725",
"Username": "system",
"Password": "Admin123",
"Callback": "http://demo.weienergy.cn:5000/api/Alarm/DahuaAuthCallback",
"SubsystemName": "192.168.21.43_alarm",
"SubsystemMagic": "192.168.21.43_5001"
"Callback": "http://192.168.21.42:18080/axalarm/api/Alarm/DahuaAuthCallback",
"SubsystemName": "192.168.21.42_alarm",
"SubsystemMagic": "192.168.21.42_18080"
}
}

@ -1,6 +1,7 @@
using Autofac;
using Autofac.Extensions.DependencyInjection;
using Common.Shared.API.Infrastructure;
using Common.Shared.Application.Core;
using Microsoft.OpenApi.Models;
using NLog;
using NLog.Extensions.Logging;
@ -27,12 +28,15 @@ namespace Common.Shared.API
#region Cors
var isconfig = builder.Configuration.GetSection("IdentityClientConfig").Get<CorsWithOrigins>();
builder.Services.AddCors(options =>
{
options.AddPolicy("_myAllowSpecificOrigins",
builder =>
{
builder.AllowAnyOrigin() //允许所有源访问本API(开发环境设置)
builder
//.WithOrigins(isconfig.CorsOrigins) //被允许的来源,多个使用逗号分隔
.AllowAnyOrigin() //允许所有源访问本API(开发环境设置)
.AllowAnyHeader()
.AllowAnyMethod()
.AllowCredentials()

@ -5,6 +5,9 @@
"Microsoft.AspNetCore": "Warning"
}
},
"IdentityClientConfig": {
"CorsWithOrigins": [ "http://10.0.102.104:8100" ]
},
//
"DahuaAuth": {
"Host": "demo.weienergy.cn:15214",

@ -0,0 +1,13 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Common.Shared.Application.Core
{
public class CorsWithOrigins
{
public string[] CorsOrigins { get; set; }
}
}

@ -120,101 +120,53 @@ namespace Common.Shared.Application.DaHua
public JsonElement? Extend { get; set; }
}
/// <summary>
/// 订阅映射配置
/// 用于定义不同服务节点的订阅参数配置
/// </summary>
public class SubscriptionMapDto
public sealed class SubscribeDataDto
{
/// <summary>
/// 订阅配置字典
/// 键:服务节点标识(格式:IP地址_端口号)
/// 值:该节点的订阅参数列表
/// </summary>
public Dictionary<string, List<SubscriptionConfig>>? Items { get; set; } = new Dictionary<string, List<SubscriptionConfig>>();
[JsonPropertyName("subscribeMap")]
public SubscribeMap? SubscribeMap { get; set; }
}
/// <summary>
/// 订阅配置
/// 定义单个订阅的具体参数
/// 语义化的字典类型:键为如 "59.110.150.214_alarm" 的分组名,值为该分组下的一组订阅项。
/// 继承 Dictionary 便于序列化/反序列化,保持类型语义。
/// </summary>
public class SubscriptionConfig
public class SubscribeMap : Dictionary<string, List<SubscribeItem>>
{
public SubscribeMap() : base()
{
}
}
public sealed class SubscribeItem
{
/// <summary>
/// 订阅类型列表
/// 可为空,表示订阅所有类型
/// 事件类型编码;上游可能给字符串形式的数字,保持字符串列表以兼容。
/// </summary>
[JsonPropertyName("types")]
public List<string>? Types { get; set; }
/// <summary>
/// 节点编码列表
/// 可为空,表示订阅所有节点
/// </summary>
[JsonPropertyName("nodeCodes")]
public List<string>? NodeCodes { get; set; }
/// <summary>
/// 组织机构列表
/// 可为空,表示订阅所有组织
/// </summary>
[JsonPropertyName("orgs")]
public List<string>? Orgs { get; set; }
/// <summary>
/// 等级列表
/// 可为空,表示订阅所有等级
/// </summary>
[JsonPropertyName("grades")]
public List<string>? Grades { get; set; }
/// <summary>
/// 域订阅级别
/// 枚举值:
/// 0 = 不订阅
/// 1 = 订阅本域
/// 2 = 订阅本域及下级域
/// </summary>
[JsonPropertyName("domainSubscribe")]
public int DomainSubscribe { get; set; }
public int? DomainSubscribe { get; set; }
/// <summary>
/// 传输方案
/// 枚举值:
/// 0 = HTTP
/// 1 = HTTPS
/// 2 = WebSocket
/// 3 = MQTT
/// </summary>
[JsonPropertyName("scheme")]
public int Scheme { get; set; }
public int? Scheme { get; set; }
/// <summary>
/// 事件类型
/// 枚举值:
/// 0 = 所有事件
/// 1 = 告警事件
/// 2 = 状态事件
/// 3 = 操作事件
/// </summary>
[JsonPropertyName("eventType")]
public int EventType { get; set; }
public int? EventType { get; set; }
/// <summary>
/// 监控回调地址
/// 接收事件推送的目标URL
/// </summary>
[JsonPropertyName("monitor")]
public string Monitor { get; set; } = string.Empty;
public string? Monitor { get; set; }
/// <summary>
/// 监控类型
/// 枚举值:
/// "url" = HTTP/HTTPS 回调
/// "websocket" = WebSocket 连接
/// "queue" = 消息队列
/// </summary>
[JsonPropertyName("monitorType")]
public string MonitorType { get; set; } = string.Empty;
public string? MonitorType { get; set; }
}
}

@ -1,6 +1,8 @@
using Common.Shared.Application.DaHua;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using MongoDB.Bson;
using OfficeOpenXml.FormulaParsing.LexicalAnalysis;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.Security;
using System.Net.Http.Json;
@ -34,12 +36,18 @@ namespace Common.Shared.DomainService
public async Task<string> GetTokenAsync(string clientId)
{
if (TokenCache.TokenMap.TryGetValue(clientId, out var tokenEntry)
&& tokenEntry.ExpireAt > DateTimeOffset.UtcNow.AddMinutes(5))
&& tokenEntry.ExpireAt > DateTimeOffset.UtcNow.AddMinutes(1))
{
return tokenEntry.AccessToken!;
if (!IsTokenValid(tokenEntry.AccessToken!))
{
_logger.LogWarning("从字典里匹配");
return tokenEntry.AccessToken!;
}
}
var tokenLock = TokenLockProvider.GetLock(clientId);
_logger.LogWarning("枷锁");
await tokenLock.WaitAsync();
try
{
@ -47,7 +55,12 @@ namespace Common.Shared.DomainService
if (TokenCache.TokenMap.TryGetValue(clientId, out tokenEntry)
&& tokenEntry.ExpireAt > DateTimeOffset.UtcNow.AddMinutes(5))
{
return tokenEntry.AccessToken!;
if (!IsTokenValid(tokenEntry.AccessToken!))
{
_logger.LogWarning("再次匹配");
return tokenEntry.AccessToken!;
}
}
var refreshed = await TryRefreshOrLoginAsync(clientId, tokenEntry);
@ -137,7 +150,8 @@ namespace Common.Shared.DomainService
dto.ClientSecret = _configuration["DahuaAuth:ClientSecret"]!;
dto.Password = _configuration["DahuaAuth:Password"]!;
dto.Username = _configuration["DahuaAuth:Username"]!;
_logger.LogWarning("在GetDaHToken方法中的记录:Dahua Host = {Host}, ClientId = {ClientId}",
_configuration["DahuaAuth:Host"], _configuration["DahuaAuth:ClientId"], _configuration["DahuaAuth:ClientSecret"]);
DaHApiResult<LoginResDto> loginResult = await GetToken(dto);
TokenEntry refreshed = new()
@ -207,10 +221,11 @@ namespace Common.Shared.DomainService
try
{
var url = $"https://{_configuration["DahuaAuth:Host"]}/evo-apigw/evo-oauth/1.0.0/oauth/public-key";
_logger.LogWarning($"获取的url{url}");
using var resp = await _http.GetAsync(url);
resp.EnsureSuccessStatusCode();
var json = await resp.Content.ReadAsStringAsync();
_logger.LogWarning($"获取密钥的结果json{json}");
var envelope = JsonSerializer.Deserialize<DaHApiResult<PublicKeyDto>>(json, new JsonSerializerOptions
{
PropertyNameCaseInsensitive = true
@ -230,7 +245,7 @@ namespace Common.Shared.DomainService
}
catch (Exception ex)
{
_logger.LogWarning(ex, "大华平台获取公钥出错");
_logger.LogWarning(ex, $"大华平台获取公钥出错{ex.Message}");
result.Success = false;
result.Code = "1001";
result.Msg = "获取大华公钥失败";
@ -267,33 +282,44 @@ namespace Common.Shared.DomainService
{
var url = $"https://{_configuration["DahuaAuth:Host"]}/evo-apigw/evo-oauth/1.0.0/oauth/extend/token";
//必须加密
_logger.LogWarning($"获取token的url{url}");
_logger.LogWarning($"获取token的dto的json{dto.ToJson()}");
dto.Password = EncryptByPublicKey(dto.Password, dto.PublicKey!);
using var resp = await _http.PostAsJsonAsync(url, dto);
resp.EnsureSuccessStatusCode();
_logger.LogWarning("这是正式请求的:Dahua Host = {Host}, ClientId = {ClientId},ClientSecret={ClientSecret}", _configuration["DahuaAuth:Host"], _configuration["DahuaAuth:ClientId"], _configuration["DahuaAuth:ClientSecret"]);
var tokenInfo = await resp.Content.ReadFromJsonAsync<DaHApiResult<LoginResDto>>();
_logger.LogWarning($"获取大华登录令牌返回结果:{tokenInfo.ToJson()}");
if (tokenInfo == null || !result.Success || result.Code != "0")
{
result.Success = false;
result.Code = "1004";
result.Msg = "获取大华登录令牌失败";
_logger.LogWarning("获取大华登录令牌失败,返回结果:{Result}", result);
_logger.LogWarning($"获取大华登录令牌失败,返回结果:{result}");
}
result = tokenInfo!;
//固定的拼接方式
result.Data!.AccessToken = string.Concat(tokenInfo?.Data!.TokenType, " ", tokenInfo?.Data!.AccessToken);
TokenEntry refreshed = new TokenEntry
if (tokenInfo?.Data!.AccessToken != null && tokenInfo?.Data!.AccessToken.Length > 1)
{
AccessToken = string.Concat(result!.Data.TokenType, " ", result.Data.AccessToken),
result.Data!.AccessToken = string.Concat(tokenInfo?.Data!.TokenType, " ", tokenInfo?.Data!.AccessToken);
TokenEntry refreshed = new TokenEntry
{
AccessToken = string.Concat(result!.Data.TokenType, " ", result.Data.AccessToken),
ExpireAt = DateTimeOffset.UtcNow.AddSeconds(result.Data.ExpiresIn)
};
ExpireAt = DateTimeOffset.UtcNow.AddSeconds(result.Data.ExpiresIn)
};
}
else
{
result.Success = false;
result.Code = "1006";
result.Msg = "没拿到token";
_logger.LogWarning($"获取大华登录令牌失败,返回结果:{result}");
}
}
catch (Exception ex)
{
_logger.LogError(ex, "获取大华登录令牌出错");
_logger.LogError(ex, $"获取大华登录令牌出错{ex.Message}");
result.Success = false;
result.Code = "1004";
result.Msg = "获取大华登录令牌失败";

@ -1,4 +1,3 @@
using Microsoft.EntityFrameworkCore;
using Microsoft.OpenApi.Models;
using ParkingLotEntity.DB;
@ -6,6 +5,7 @@ using ParkingLotEntity.ParkingLotModels;
using ParkingLotService.API.HostService;
using ParkLotInfoService;
using Serilog;
namespace ParkingLotService.API
{
public class Program
@ -44,9 +44,11 @@ namespace ParkingLotService.API
builder.Services.AddScoped<WeiCloud.Utils.IRedisHelper, WeiCloud.Utils.RedisHelper>();
builder.Services.AddScoped<WeiCloud.Utils.IDictionaryService, WeiCloud.Utils.DictionaryService>();
builder.Services.AddScoped<IParkingLotDataService, ParkingLotDataService>();
//---
#region 日志
Log.Logger = new LoggerConfiguration()
.MinimumLevel.Information() // 最低日志级别
.WriteTo.File(
@ -60,7 +62,8 @@ namespace ParkingLotService.API
builder.Services.AddHttpClient();
//使用 Serilog 替换默认日志
builder.Host.UseSerilog();
#endregion
#endregion 日志
// 注册PingService
builder.Services.AddHostedService<PingService>();
@ -75,8 +78,6 @@ namespace ParkingLotService.API
c.SwaggerEndpoint("/swagger/v1/swagger.json", "ParkingLotAPI V1");
});
}
//var app = builder.Build();
@ -91,10 +92,9 @@ namespace ParkingLotService.API
app.UseAuthorization();
app.MapControllers();
app.Run();
}
}
}
}

@ -41,8 +41,8 @@ namespace Video.API
builder =>
{
builder
.WithOrigins(isconfig.CorsWithOrigins) //被允许的来源,多个使用逗号分隔
//.AllowAnyOrigin() //允许所有源访问本API(开发环境设置)
// .WithOrigins(isconfig.CorsWithOrigins) //被允许的来源,多个使用逗号分隔
.AllowAnyOrigin() //允许所有源访问本API(开发环境设置)
.AllowAnyHeader()
.AllowAnyMethod()
.AllowCredentials()
@ -150,9 +150,9 @@ namespace Video.API
});
}
app.UseHttpsRedirection();
// app.UseHttpsRedirection();
app.UseAuthorization();
// app.UseAuthorization();
app.MapGet("/healthz", () => Results.Ok("OK"));
app.MapControllers();

@ -9,13 +9,9 @@
"ConnectionStrings": {
"RedisNodes": "Zrhredis#2019@v4.weienergy.cn:6380 "
},
"IdentityClientConfig": {
"Scheme": "Bearer",
"Authority": "http://v4.weienergy.cn:8100",
"RequireHttpsMetadata": false,
"ApiName": "WeiCloudInfoAPI",
"CorsWithOrigins": [ "http://10.0.102.104:8100" ]
},
"CorsWithOrigins": [ "https://demo.weienergy.cn:15214", "http://59.110.150.214", "https://demo.weienergy.cn/" ],
"Cap": {
//"CapGroupName": "local-ax-group-api-msg",
"CapGroupName": "v4-ax-group-api-msg",

@ -2,6 +2,7 @@
using Common.Shared.DomainService;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using NPOI.XWPF.UserModel;
using System.Net.Http.Json;
using System.Text.Json;
using Video.DomainService.Dahvision;
@ -13,7 +14,7 @@ namespace Video.DomainService
private readonly ILogger<DahuaGeneralCtlService> _logger;
private readonly IConfiguration _configuration;
private readonly ITokenProviderService _tokenProviderService;
private readonly HttpClient _http;
// private readonly HttpClient _http;
public DahuaGeneralCtlService(ILogger<DahuaGeneralCtlService> logger, IConfiguration configuration, ITokenProviderService tokenProviderService, HttpClient http)
{
@ -21,16 +22,16 @@ namespace Video.DomainService
_configuration = configuration;
_tokenProviderService = tokenProviderService;
_http = http;
// _http = http;
}
///// <summary>
///// 开发测试的时候,忽略证书
///// </summary>
//private static readonly HttpClient _http = new HttpClient(new HttpClientHandler
//{
// ServerCertificateCustomValidationCallback = HttpClientHandler.DangerousAcceptAnyServerCertificateValidator
//});
/// <summary>
/// 开发测试的时候,忽略证书
/// </summary>
private static readonly HttpClient _http = new HttpClient(new HttpClientHandler
{
ServerCertificateCustomValidationCallback = HttpClientHandler.DangerousAcceptAnyServerCertificateValidator
});
/// <summary>
/// hls等录像回放
@ -416,11 +417,12 @@ namespace Video.DomainService
if (dto == null || dto.Data == null)
{
_logger.LogWarning("实时流请求失败:请求参数不能为空");
return new DaHApiResult<UrlDataDto> { Success = false, Code = "1009", Msg = "请求参数不能为空" };
return new DaHApiResult<UrlDataDto> { Success = false, Code = "1005", Msg = "请求参数不能为空" };
}
var clientId = _configuration["DahuaAuth:ClientId"];
var token = await _tokenProviderService.GetTokenAsync(clientId!);
_logger.LogWarning($"我的token: {token}");
if (!_tokenProviderService.IsTokenValid(token))
{
_logger.LogWarning("rtsp实时预览接口方式:token无效");
@ -432,7 +434,7 @@ namespace Video.DomainService
{
url = $"https://{ipaddress}/evo-apigw/admin/API/MTS/Video/StartVideo";
}
_logger.LogWarning($"我的url: {url}");
using var req = new HttpRequestMessage(HttpMethod.Post, url)
{
Content = JsonContent.Create(dto) // 等价于 PostAsJsonAsync,但和 req 绑定
@ -447,14 +449,15 @@ namespace Video.DomainService
if (!resp.IsSuccessStatusCode)
{
_logger.LogWarning("实时流请求 HTTP 失败: {Status}, Body: {Body}", (int)resp.StatusCode, body);
return new DaHApiResult<UrlDataDto> { Success = false, Code = "1010", Msg = $"HTTP错误 {(int)resp.StatusCode}" };
_logger.LogWarning($"{resp.StatusCode}: {body}");
return new DaHApiResult<UrlDataDto> { Success = false, Code = "1014", Msg = $"HTTP错误 {(int)resp.StatusCode}" };
}
_logger.LogWarning($"大华实时流请求返回body{body}");
var result = JsonSerializer.Deserialize<DaHApiResult<UrlDataDto>>(body);
if (result == null || !result.Success)
{
_logger.LogWarning("实时流请求业务失败: {Body}", body);
return new DaHApiResult<UrlDataDto> { Success = false, Code = "1010", Msg = "实时流请求失败" };
_logger.LogWarning("实时流请求业务反序列化失败: {Body}", body);
return new DaHApiResult<UrlDataDto> { Success = false, Code = "1013", Msg = "实时流请求业务反序列化失败" };
}
result.Data!.Url = UrlHostReplacer.ReplaceHost(
result.Data.Url,
@ -466,8 +469,9 @@ namespace Video.DomainService
}
catch (Exception ex)
{
_logger.LogError(ex, "大华实时流请求出错");
return new DaHApiResult<UrlDataDto> { Success = false, Code = "1010", Msg = "实时流请求失败" };
_logger.LogError(ex, $"大华实时流请求出错{ex.Message}");
_logger.LogWarning($"{ex.Message}");
return new DaHApiResult<UrlDataDto> { Success = false, Code = "1012", Msg = $"实时流请求失败{ex.Message}" };
}
}

Loading…
Cancel
Save