DataMaintenance
洁 任 2 weeks ago
commit 312e944be7

@ -0,0 +1,410 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Security;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading.Tasks;
namespace Infrastructure.Utilities
{
public class HttpUtillib
{
/// <summary>
/// 设置信息参数
/// </summary>
/// <param name="appkey">合作方APPKey</param>
/// <param name="secret">合作方APPSecret</param>
/// <param name="ip">平台IP</param>
/// <param name="port">平台端口默认HTTPS的443端口</param>
/// <param name="isHttps">是否启用HTTPS协议默认HTTPS</param>
/// <return></return>
public static void SetPlatformInfo(string appkey, string secret, string ip, int port = 443, bool isHttps = true)
{
_appkey = appkey;
_secret = secret;
_ip = ip;
_port = port;
_isHttps = isHttps;
}
/// <summary>
/// HTTP GET请求
/// </summary>
/// <param name="uri">HTTP接口Url不带协议和端口如/artemis/api/resource/v1/cameras/indexCode?cameraIndexCode=a10cafaa777c49a5af92c165c95970e0</param>
/// <param name="timeout">请求超时时间,单位:秒</param>
/// <returns></returns>
public static byte[] HttpGet(string uri, int timeout)
{
Dictionary<string, string> header = new Dictionary<string, string>();
// 初始化请求:组装请求头,设置远程证书自动验证通过
initRequest(header, uri, "", false);
// build web request object
StringBuilder sb = new StringBuilder();
sb.Append(_isHttps ? "https://" : "http://").Append(_ip).Append(":").Append(_port.ToString()).Append(uri);
HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(sb.ToString());
req.KeepAlive = false;
req.ProtocolVersion = HttpVersion.Version11;
req.AllowAutoRedirect = false; // 不允许自动重定向
req.Method = "GET";
req.Timeout = timeout * 1000; // 传入是秒,需要转换成毫秒
req.Accept = header["Accept"];
req.ContentType = header["Content-Type"];
foreach (string headerKey in header.Keys)
{
if (headerKey.Contains("x-ca-"))
{
req.Headers.Add(headerKey + ":" + header[headerKey]);
}
}
HttpWebResponse rsp = null;
try
{
rsp = (HttpWebResponse)req.GetResponse();
if (HttpStatusCode.OK == rsp.StatusCode)
{
Stream rspStream = rsp.GetResponseStream(); // 响应内容字节流
StreamReader sr = new StreamReader(rspStream);
string strStream = sr.ReadToEnd();
long streamLength = strStream.Length;
byte[] response = System.Text.Encoding.UTF8.GetBytes(strStream);
rsp.Close();
return response;
}
else if (HttpStatusCode.Found == rsp.StatusCode || HttpStatusCode.Moved == rsp.StatusCode) // 302/301 redirect
{
string reqUrl = rsp.Headers["Location"].ToString(); // 获取重定向URL
WebRequest wreq = WebRequest.Create(reqUrl); // 重定向请求对象
WebResponse wrsp = wreq.GetResponse(); // 重定向响应
long streamLength = wrsp.ContentLength; // 重定向响应内容长度
Stream rspStream = wrsp.GetResponseStream(); // 响应内容字节流
byte[] response = new byte[streamLength];
rspStream.Read(response, 0, (int)streamLength); // 读取响应内容至byte数组
rspStream.Close();
rsp.Close();
return response;
}
rsp.Close();
}
catch (WebException e)
{
if (rsp != null)
{
rsp.Close();
}
}
return null;
}
/// <summary>
/// HTTP Post请求
/// </summary>
/// <param name="uri">HTTP接口Url不带协议和端口如/artemis/api/resource/v1/org/advance/orgList</param>
/// <param name="body">请求参数</param>
/// <param name="timeout">请求超时时间,单位:秒</param>
/// <return>请求结果</return>
public static byte[] HttpPost(string uri, string body, int timeout, int flag)
{
Dictionary<string, string> header = new Dictionary<string, string>();
// 初始化请求:组装请求头,设置远程证书自动验证通过
initRequest(header, uri, body, true);
// build web request object
StringBuilder sb = new StringBuilder();
sb.Append(_isHttps ? "https://" : "http://").Append(_ip).Append(":").Append(_port.ToString()).Append(uri);
// 创建POST请求
HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(sb.ToString());
req.KeepAlive = false;
req.ProtocolVersion = HttpVersion.Version11;
req.AllowAutoRedirect = false; // 不允许自动重定向
req.Method = "POST";
req.Timeout = timeout * 1000; // 传入是秒,需要转换成毫秒
req.Accept = header["Accept"];
req.ContentType = header["Content-Type"];
foreach (string headerKey in header.Keys)
{
if (headerKey.Contains("x-ca-"))
{
req.Headers.Add(headerKey + ":" + header[headerKey]);
}
}
if (!string.IsNullOrWhiteSpace(body))
{
byte[] postBytes = Encoding.UTF8.GetBytes(body);
req.ContentLength = postBytes.Length;
Stream reqStream = null;
try
{
reqStream = req.GetRequestStream();
reqStream.Write(postBytes, 0, postBytes.Length);
reqStream.Close();
}
catch (WebException e)
{
if (reqStream != null)
{
reqStream.Close();
}
return null;
}
}
HttpWebResponse rsp = null;
try
{
rsp = (HttpWebResponse)req.GetResponse();
if (HttpStatusCode.OK == rsp.StatusCode)
{
Stream rspStream = rsp.GetResponseStream();
StreamReader sr = new StreamReader(rspStream);
string strStream = sr.ReadToEnd();
long streamLength = strStream.Length;
byte[] response = System.Text.Encoding.UTF8.GetBytes(strStream);
rsp.Close();
return response;
}
else if (HttpStatusCode.Found == rsp.StatusCode || HttpStatusCode.Moved == rsp.StatusCode) // 302/301 redirect
{
string reqUrl = rsp.Headers["Location"].ToString(); // 如需要重定向URL请自行修改接口返回此参数
WebRequest wreq = WebRequest.Create(reqUrl);
WebResponse wrsp = wreq.GetResponse();
long streamLength = wrsp.ContentLength;
Stream rspStream = wrsp.GetResponseStream();
byte[] response = new byte[streamLength];
rspStream.Read(response, 0, (int)streamLength);
rspStream.Close();
rsp.Close();
return response;
}
rsp.Close();
}
catch (WebException e)
{
if (rsp != null)
{
rsp.Close();
}
}
return null;
}
private static void initRequest(Dictionary<string, string> header, string url, string body, bool isPost)
{
// Accept
//string accept = "application/json";// "*/*";
string accept = "*/*";
header.Add("Accept", accept);
// ContentType
string contentType = "application/json";
//string contentType = "application/json";
header.Add("Content-Type", contentType);
if (isPost)
{
// content-md5be careful it must be lower case.
string contentMd5 = computeContentMd5(body);
header.Add("content-md5", contentMd5);
}
// x-ca-timestamp
//string timestamp = ((DateTime.Now.Ticks - TimeZoneInfo.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1, 0, 0, 0, 0)).Ticks) / 1000).ToString();
string timestamp = ((DateTime.Now.Ticks - TimeZoneInfo.ConvertTimeToUtc(new System.DateTime(1970, 1, 1, 0, 0, 0, 0)).Ticks) / 1000).ToString();
header.Add("x-ca-timestamp", timestamp);
// x-ca-nonce
string nonce = System.Guid.NewGuid().ToString();
header.Add("x-ca-nonce", nonce);
// x-ca-key
header.Add("x-ca-key", _appkey);
// build string to sign
string strToSign = buildSignString(isPost ? "POST" : "GET", url, header);
string signedStr = computeForHMACSHA256(strToSign, _secret);
// x-ca-signature
header.Add("x-ca-signature", signedStr);
if (_isHttps)
{
//// set remote certificate Validation auto pass
//ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(remoteCertificateValidate);
////ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;
//ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;
// set remote certificate Validation auto pass
ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(remoteCertificateValidate);
// FIX修复不同.Net版对一些SecurityProtocolType枚举支持情况不一致导致编译失败等问题这里统一使用数值
ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072 | (SecurityProtocolType)768 | (SecurityProtocolType)192;
//ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;
}
}
/// <summary>
/// 计算content-md5
/// </summary>
/// <param name="body"></param>
/// <returns>base64后的content-md5</returns>
private static string computeContentMd5(string body)
{
MD5 md5 = new MD5CryptoServiceProvider();
byte[] result = md5.ComputeHash(System.Text.Encoding.UTF8.GetBytes(body));
return Convert.ToBase64String(result);
}
/// <summary>
/// 远程证书验证
/// </summary>
/// <param name="sender"></param>
/// <param name="cert"></param>
/// <param name="chain"></param>
/// <param name="error"></param>
/// <returns>验证是否通过,始终通过</returns>
private static bool remoteCertificateValidate(object sender, X509Certificate cert, X509Chain chain, SslPolicyErrors error)
{
return true;
}
/// <summary>
/// 计算HMACSHA265
/// </summary>
/// <param name="str">待计算字符串</param>
/// <param name="secret">平台APPSecet</param>
/// <returns>HMAXH265计算结果字符串</returns>
private static string computeForHMACSHA256(string str, string secret)
{
var encoder = new System.Text.UTF8Encoding();
byte[] secretBytes = encoder.GetBytes(secret);
byte[] strBytes = encoder.GetBytes(str);
var opertor = new HMACSHA256(secretBytes);
byte[] hashbytes = opertor.ComputeHash(strBytes);
return Convert.ToBase64String(hashbytes);
}
/// <summary>
/// 计算签名字符串
/// </summary>
/// <param name="method">HTTP请求方法如“POST”</param>
/// <param name="url">接口Url如/artemis/api/resource/v1/org/advance/orgList</param>
/// <param name="header">请求头</param>
/// <returns>签名字符串</returns>
private static string buildSignString(string method, string url, Dictionary<string, string> header)
{
StringBuilder sb = new StringBuilder();
sb.Append(method.ToUpper()).Append("\n");
if (null != header)
{
if (null != header["Accept"])
{
sb.Append((string)header["Accept"]);
sb.Append("\n");
}
if (header.ContainsKey("Content-MD5") && null != header["Content-MD5"])
{
sb.Append((string)header["Content-MD5"]);
sb.Append("\n");
}
if (null != header["Content-Type"])
{
sb.Append((string)header["Content-Type"]);
sb.Append("\n");
}
if (header.ContainsKey("Date") && null != header["Date"])
{
sb.Append((string)header["Date"]);
sb.Append("\n");
}
}
// build and add header to sign
string signHeader = buildSignHeader(header);
sb.Append(signHeader);
sb.Append(url);
return sb.ToString();
}
/// <summary>
/// 计算签名头
/// </summary>
/// <param name="header">请求头</param>
/// <returns>签名头</returns>
private static string buildSignHeader(Dictionary<string, string> header)
{
Dictionary<string, string> sortedDicHeader = new Dictionary<string, string>();
sortedDicHeader = header;
//var dic = from objDic in sortedDicHeader orderby objDic.Key ascending select objDic;
Dictionary<string, string> dic = sortedDicHeader.OrderBy(p => p.Key).ToDictionary(p => p.Key, o => o.Value);
StringBuilder sbSignHeader = new StringBuilder();
StringBuilder sb = new StringBuilder();
foreach (KeyValuePair<string, string> kvp in dic)
{
if (kvp.Key.Replace(" ", "").Contains("x-ca-"))
{
sb.Append(kvp.Key + ":");
if (!string.IsNullOrWhiteSpace(kvp.Value))
{
sb.Append(kvp.Value);
}
sb.Append("\n");
if (sbSignHeader.Length > 0)
{
sbSignHeader.Append(",");
}
sbSignHeader.Append(kvp.Key);
}
}
header.Add("x-ca-signature-headers", sbSignHeader.ToString());
return sb.ToString();
}
/// <summary>
/// 平台ip
/// </summary>
private static string _ip;
/// <summary>
/// 平台端口
/// </summary>
private static int _port = 443;
/// <summary>
/// 平台APPKey
/// </summary>
private static string _appkey;
/// <summary>
/// 平台APPSecret
/// </summary>
private static string _secret;
/// <summary>
/// 是否使用HTTPS协议
/// </summary>
private static bool _isHttps = true;
}
}

@ -0,0 +1,25 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace OpenAuth.App.Common
{
public class KikvisionConfig
{
/// <summary>
/// 综合安防管理平台 url
/// </summary>
public string Url { get; set; }
public int Port { get; set; }
/// <summary>
/// AppKey
/// </summary>
public string AppKey { get; set; }
/// <summary>
/// SecretKey
/// </summary>
public string SecretKey { get; set; }
}
}

@ -3,15 +3,19 @@ using DocumentFormat.OpenXml.Spreadsheet;
using Hopetry.App.SugarModel.CommonModel;
using Infrastructure;
using Infrastructure.Extensions;
using Infrastructure.Utilities;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Options;
using Newtonsoft.Json;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using OpenAuth.App.BaseApp.Base;
using OpenAuth.App.Common;
using OpenAuth.App.Const;
using OpenAuth.App.Interface;
using OpenAuth.App.Response;
@ -23,6 +27,7 @@ using OpenAuth.Repository.Domain.FireManagement;
using Org.BouncyCastle.Ocsp;
using SqlSugar;
using System.Net.WebSockets;
using System.Security.Cryptography;
using System.Text;
using Yitter.IdGenerator;
@ -32,11 +37,12 @@ namespace OpenAuth.App.ServiceApp.FireManagement
{
private ClientWebSocket _socket;
private IConfiguration _configuration;
public FireManagementApp(IConfiguration configuration, ISugarUnitOfWork<SugarDbContext> unitWork,
IOptions<KikvisionConfig> _options;
public FireManagementApp(IConfiguration configuration, IOptions<KikvisionConfig> options, ISugarUnitOfWork<SugarDbContext> unitWork,
ISimpleClient<FmFireclueTask> repository, IAuth auth) : base(unitWork, repository, auth)
{
_auth = auth;
_options = options;
_configuration = configuration;
}
@ -848,6 +854,119 @@ namespace OpenAuth.App.ServiceApp.FireManagement
}
}
private static readonly string baseUrl = "http://10.176.126.121:8766/liveBroadCast/bd/api/v1/device/liveBroadCast";
private static readonly string sk = "ba98a152296f13c565d2a6dfd219994f"; // 用户的sk
private static readonly string account = "AK202006291525121"; // 用户的ak
public async Task<string> GetFlvUrlAsync(string deviceCode)
{
// 获取当前的时间戳
var requestTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds().ToString();
// 构建请求体
var requestBody = new
{
deviceCode = deviceCode
};
// 序列化请求体
var jsonBody = JsonConvert.SerializeObject(requestBody);
// 计算signature
var signature = CalculateSignature(requestTime, jsonBody);
// 创建 HttpClient 和 HttpRequestMessage
using (var client = new HttpClient())
{
// 创建 HttpRequestMessage 实例
var requestMessage = new HttpRequestMessage(HttpMethod.Post, baseUrl)
{
Content = new StringContent(jsonBody, Encoding.UTF8, "application/json")
};
// 设置请求头(其他类型的请求头设置在这里)
requestMessage.Headers.Add("account", account);
requestMessage.Headers.Add("requestTime", requestTime);
requestMessage.Headers.Add("signature", signature);
// 设置 Content-Type 和 Accept 请求头
requestMessage.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");
requestMessage.Headers.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
// 发送请求
var response = await client.SendAsync(requestMessage);
if (response.IsSuccessStatusCode)
{
// 解析响应
var responseContent = await response.Content.ReadAsStringAsync();
dynamic responseData = JsonConvert.DeserializeObject(responseContent);
// 检查返回的code是否为0
if (responseData.code == "0")
{
return responseData.data.flvUrl;
}
else
{
throw new Exception($"API error: {responseData.message}");
}
}
else
{
throw new Exception($"HTTP request failed with status code {response.StatusCode}");
}
}
}
private string CalculateSignature(string requestTime, string requestBody)
{
// 按照要求的计算规则计算signature
string dataToSign = account + sk + requestTime + requestBody;
// 使用SHA256算法计算签名
using (SHA256 sha256 = SHA256.Create())
{
byte[] hashBytes = sha256.ComputeHash(Encoding.UTF8.GetBytes(dataToSign));
return BitConverter.ToString(hashBytes).Replace("-", "").ToLower();
}
}
public async Task<string> GetLive(string deviceCode)
{
string flvUrl = await GetFlvUrlAsync(deviceCode);
return flvUrl;
}
#region 海康设备
/// <summary>
/// 获取单个设备的视频流
/// </summary>
/// <param name="cameraIndexCode">视频标识</param>
/// <returns></returns>
[HttpPost]
[AllowAnonymous]
public string GetPreviewURLs(string cameraIndexCode, string protocol)
{
HttpUtillib.SetPlatformInfo(_options.Value.AppKey, _options.Value.SecretKey, _options.Value.Url, _options.Value.Port, true);
var obj = new
{
cameraIndexCode,
streamType = 0,
protocol = protocol,
transmode = 1,
expand = "transcode=0",
streamform = "ps"
};
string body = JsonConvert.SerializeObject(obj);
string uri = "/artemis/api/video/v2/cameras/previewURLs";
byte[] result = HttpUtillib.HttpPost(uri, body, 15, 1);
if (null != result)
{
return Encoding.UTF8.GetString(result);
}
return "fail";
}
#endregion
#region 人员类型统计
/// <summary>
/// 人员类型统计

@ -492,6 +492,25 @@ namespace OpenAuth.WebApi.Controllers.ServiceControllers.FireManagement
{
return await _app.LoadFireClueInfoByUserId(pageIndex, state, pageSize, userid);
}
/// <summary>
/// 获取视频流
/// </summary>
/// <param name="deviceCode"></param>
/// <returns></returns>
[HttpGet]
[AllowAnonymous]
public string GetPreviewURLs(string deviceCode,string protocol)
{
try
{
return _app.GetPreviewURLs(deviceCode, protocol);
}
catch (Exception ex)
{
return ex.Message.ToString();
}
}
#region 人员类型统计查询
[HttpGet]

@ -1,4 +1,5 @@
using Autofac;
using Autofac.Core;
using Autofac.Extensions.DependencyInjection;
using ce.autofac.extension;
using IdentityServer4.AccessTokenValidation;
@ -19,6 +20,7 @@ using Newtonsoft.Json.Serialization;
using Npgsql;
using OpenAuth.App;
using OpenAuth.App.BaseApp.ImMsgManager;
using OpenAuth.App.Common;
using OpenAuth.App.HostedService;
using OpenAuth.Repository;
using OpenAuth.WebApi.Model;
@ -299,6 +301,10 @@ namespace OpenAuth.WebApi
#region SignalR
services.AddSignalR();
#endregion
#region 配置文件
services.Configure<KikvisionConfig>(Configuration.GetSection("Hik"));
#endregion
}
public void ConfigureContainer(ContainerBuilder builder)

@ -73,6 +73,12 @@
"UserName": "sdhc",
"Password": ""
},
"Hik": {
"Url": "221.2.83.54",
"Port": 1443,
"AppKey": "23604396",
"SecretKey": "NZJ8L3bxCOOV6rtTFjsx"
},
"FlyImageDir": "e:/fly",
"WebSocket": "ws://192.168.10.106:5698/ws",
"TaiShiGanZhi": {

Loading…
Cancel
Save