云收藏 增加AI检测图片

This commit is contained in:
chfei committed 2026-11-05 18:50:13 +08:00
1 parent b28940c02d
commit b54a5f5310
36 files changed
+1978 -523

No files matched your search

+3 -1
View File
@@ -8,10 +8,12 @@ public sealed class ApiException : HttpException
{
public int? Code { get; }
public JToken ResponseData { get; }
public string TraceId { get; }
public ApiException(string message, int? code, JToken responseData) : base(message)
public ApiException(string message, int? code, JToken responseData, string traceId = null) : base(message)
{
Code = code;
ResponseData = responseData;
TraceId = traceId;
}
}
+119 -62
View File
@@ -1,4 +1,5 @@
using CsharpHttpHelper;
using AllBase.Model.Result;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
@@ -6,6 +7,8 @@ using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
namespace Work.Store.Api;
@@ -14,16 +17,14 @@ public sealed class ApiTransport
{
private readonly string _baseUrl;
private string _token;
private Func<string> _login;
internal object SessionGate { get; } = new object();
private LoginRequest _credentials;
internal SemaphoreSlim SessionGate { get; } = new SemaphoreSlim(1, 1);
internal void SetSession(string token, Func<string> login)
// 调用方持有 SessionGate。
internal void SetSession(string token, LoginRequest credentials)
{
lock (SessionGate)
{
_token = token;
_login = login;
}
_token = token;
_credentials = credentials;
}
public ApiTransport(string baseUrl)
@@ -39,29 +40,102 @@ public sealed class ApiTransport
/// <summary>仅存于内存;手动赋值会清除自动登录凭据,设为 null 退出本地会话。</summary>
public string Token
{
get { lock (SessionGate) return _token; }
get
{
SessionGate.Wait();
try { return _token; }
finally { SessionGate.Release(); }
}
set
{
if (value != null && (string.IsNullOrWhiteSpace(value) || value.IndexOfAny(new[] { '\r', '\n' }) >= 0))
throw new ArgumentException("Token 不能为空白或包含换行。", nameof(value));
SetSession(value, null);
SessionGate.Wait();
try { SetSession(value, null); }
finally { SessionGate.Release(); }
}
}
/// <summary>同步请求;无 data 时返回 default(T),界面调用需放在后台线程。</summary>
public T Send<T>(string route, MethodType method, object body = null,
IDictionary<string, string> query = null, bool authenticated = true,
int timeoutMilliseconds = 30000)
{
var item = CreateRequest(route, method, body, query, timeoutMilliseconds);
string token = null;
if (authenticated)
{
//SessionGate.Wait();
//try { token = _token ?? throw new HttpException("请先登录。") { IsOnline = false }; }
//finally { SessionGate.Release(); }
}
for (int attempt = 0; ; attempt++)
{
if (token != null) item.Header["Authorization"] = "Bearer " + token;
var response = HttpHelper.Request(item);
try { return ReadResult<T>(response); }
catch (HttpException ex) when (authenticated && !ex.IsOnline)
{
SessionGate.Wait();
try
{
if (_token == token)
{
_token = null;
if (attempt == 0 && _credentials != null)
_token = AuthApi.LoginCore(this, _credentials).Token;
}
if (attempt != 0 || _token == null) throw;
token = _token;
}
finally { SessionGate.Release(); }
}
}
}
public async Task<T> SendAsync<T>(string route, MethodType method, object body = null,
IDictionary<string, string> query = null, bool authenticated = true,
int timeoutMilliseconds = 30000)
{
var item = CreateRequest(route, method, body, query, timeoutMilliseconds);
string token = null;
if (authenticated)
{
//await SessionGate.WaitAsync().ConfigureAwait(false);
//try { token = _token ?? throw new HttpException("请先登录。") { IsOnline = false }; }
//finally { SessionGate.Release(); }
}
for (int attempt = 0; ; attempt++)
{
if (token != null) item.Header["Authorization"] = "Bearer " + token;
var response = await HttpHelper.RequestAsync(item).ConfigureAwait(false);
try { return ReadResult<T>(response); }
catch (HttpException ex) when (authenticated && !ex.IsOnline)
{
await SessionGate.WaitAsync().ConfigureAwait(false);
try
{
if (_token == token)
{
_token = null;
if (attempt == 0 && _credentials != null)
_token = (await AuthApi.LoginCoreAsync(this, _credentials).ConfigureAwait(false)).Token;
}
if (attempt != 0 || _token == null) throw;
token = _token;
}
finally { SessionGate.Release(); }
}
}
}
private HttpItem CreateRequest(string route, MethodType method, object body,
IDictionary<string, string> query, int timeoutMilliseconds)
{
if (string.IsNullOrWhiteSpace(route) ||
!Regex.IsMatch(route, @"\A[A-Za-z0-9_-]+(/[A-Za-z0-9_-]+)*\z"))
throw new ArgumentException("接口必须使用相对路由,例如 Auth/Login。", nameof(route));
if (body != null) Validator.ValidateObject(body, new ValidationContext(body), true);
if (timeoutMilliseconds <= 0) throw new ArgumentOutOfRangeException(nameof(timeoutMilliseconds));
string token = authenticated ? Token : null;
if (authenticated && token == null)
throw new HttpException("请先登录。") { IsOnline = false };
var url = new StringBuilder(_baseUrl).Append(route);
if (query != null)
{
@@ -74,7 +148,7 @@ public sealed class ApiTransport
first = false;
}
}
var item = new HttpItem
return new HttpItem
{
URL = url.ToString(),
Method = method,
@@ -87,54 +161,31 @@ public sealed class ApiTransport
ReadWriteTimeout = timeoutMilliseconds,
Allowautoredirect = false
};
for (int attempt = 0; ; attempt++)
{
if (token != null) item.Header["Authorization"] = "Bearer " + token;
var response = HttpHelper.Request(item);
int status = (int)response.StatusCode;
if (status == 0) throw new HttpException("无法连接服务器或请求超时。");
}
JObject result = null;
JsonException parseError = null;
try { result = JObject.Parse(response.Html ?? ""); }
catch (JsonException ex) { parseError = ex; }
private static T ReadResult<T>(HttpResult response)
{
int status = (int)response.StatusCode;
if (status == 0) throw new HttpException("无法连接服务器或请求超时。");
var code = result?["code"];
if (status == 401 || (code?.Type == JTokenType.Integer && code.ToString() == "401"))
{
if (authenticated)
{
lock (SessionGate)
{
// 并发旧请求复用已更新的 Token;同一请求最多重新发送一次。
if (_token == token)
{
_token = null;
if (attempt == 0 && _login != null)
_token = _login();
}
if (attempt == 0 && _token != null)
{
token = _token;
continue;
}
}
}
throw new HttpException(result?["msg"]?.ToString() ?? "登录已失效,请重新登录。") { IsOnline = false };
}
if (status < 200 || status >= 300)
throw new HttpException($"请求失败(HTTP {status}):{result?["msg"]}");
if (result == null)
throw new HttpException("服务器响应不是有效的 JSON 对象。", parseError);
// 先检查业务码,避免错误响应的 data 结构掩盖服务端错误。
if (code?.Type != JTokenType.Integer || code.ToString() != "200")
throw new ApiException("请求失败:" + (result["msg"]?.ToString() ?? "响应缺少成功状态码。"),
code?.Type == JTokenType.Integer && int.TryParse(code.ToString(), out var businessCode) ? businessCode : (int?)null,
result["data"]);
if (result["data"] == null || result["data"].Type == JTokenType.Null) return default;
try { return result["data"].ToObject<T>(); }
catch (JsonException ex) { throw new HttpException("服务器响应 data 格式无效。", ex); }
}
Result<JToken> result = null;
JsonException parseError = null;
try { result = JsonConvert.DeserializeObject<Result<JToken>>(response.Html ?? ""); }
catch (JsonException ex) { parseError = ex; }
if (status == 401 || (result?.Success == false && result.Code == 401))
throw new HttpException(result?.Msg ?? "登录已失效,请重新登录。") { IsOnline = false };
// 统一错误响应即使使用 HTTP 4xx/5xx,也保留业务码、数据和追踪 ID。
if (result?.Success == false)
throw new ApiException("请求失败:" + (result.Msg ?? $"业务码 {result.Code}。"),
result.Code, result.Data, result.TraceId);
if (status < 200 || status >= 300)
throw new HttpException($"请求失败(HTTP {status}):{result?.Msg}");
if (result?.Success == null)
throw new HttpException("服务器响应不是有效的 Result 格式。", parseError);
if (result.Data == null || result.Data.Type == JTokenType.Null) return default;
try { return result.Data.ToObject<T>(); }
catch (JsonException ex) { throw new HttpException("服务器响应 data 格式无效。", ex); }
}
public T GetRequired<T>(string route, MethodType method, object body = null,
@@ -142,5 +193,11 @@ public sealed class ApiTransport
int timeoutMilliseconds = 30000) where T : class
=> Send<T>(route, method, body, query, authenticated, timeoutMilliseconds)
?? throw new HttpException("服务器响应缺少 data。");
public async Task<T> GetRequiredAsync<T>(string route, MethodType method, object body = null,
IDictionary<string, string> query = null, bool authenticated = true,
int timeoutMilliseconds = 30000) where T : class
=> await SendAsync<T>(route, method, body, query, authenticated, timeoutMilliseconds).ConfigureAwait(false)
?? throw new HttpException("服务器响应缺少 data。");
}
+19 -5
View File
@@ -1,5 +1,6 @@
using CsharpHttpHelper;
using System;
using System.Threading.Tasks;
using System.ComponentModel.DataAnnotations;
@@ -52,17 +53,30 @@ public sealed class AuthApi
DeviceId = _deviceId ?? request.DeviceId,
DeviceName = request.DeviceName
};
lock (_transport.SessionGate)
_transport.SessionGate.Wait();
try
{
var result = LoginCore(credentials);
_transport.SetSession(result.Token, () => LoginCore(credentials).Token);
var result = LoginCore(_transport, credentials);
_transport.SetSession(result.Token, credentials);
return result;
}
finally { _transport.SessionGate.Release(); }
}
private LoginResult LoginCore(LoginRequest request)
internal static LoginResult LoginCore(ApiTransport transport, LoginRequest request)
{
var result = transport.GetRequired<LoginResult>("Auth/Login", MethodType.Post, request, authenticated: false);
return ValidateToken(result);
}
internal static async Task<LoginResult> LoginCoreAsync(ApiTransport transport, LoginRequest request)
{
var result = await transport.GetRequiredAsync<LoginResult>("Auth/Login", MethodType.Post, request, authenticated: false).ConfigureAwait(false);
return ValidateToken(result);
}
private static LoginResult ValidateToken(LoginResult result)
{
var result = _transport.GetRequired<LoginResult>("Auth/Login", MethodType.Post, request, authenticated: false);
if (result == null || string.IsNullOrWhiteSpace(result.Token) ||
result.Token.IndexOfAny(new[] { '\r', '\n' }) >= 0 ||
!string.Equals(result.TokenType, "Bearer", StringComparison.OrdinalIgnoreCase))
+62 -31
View File
@@ -1,55 +1,86 @@
using AllBase.Model.Result;
using AllBase;
using AllBase.Helper;
using AllBase.Model.Result;
using CsharpHttpHelper;
using NaiBa.Util.Helper;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Threading.Tasks;
using Work.Services;
using static System.Windows.Forms.VisualStyles.VisualStyleElement.StartPanel;
namespace Work.Store.Api;
/// <summary>云商品接口,沿用服务端不带版本号的路由。</summary>
public sealed class CloudGoodsApi
{
private readonly ApiTransport _transport;
private readonly ApiTransport _transport;
public CloudGoodsApi(ApiTransport transport)
=> _transport = transport ?? throw new ArgumentNullException(nameof(transport));
public CloudGoodsApi(ApiTransport transport)
=> _transport = transport ?? throw new ArgumentNullException(nameof(transport));
public Task<PageData<CloudGoods>> GetGoods(GoodsSearchRequest request)
=> Task.Run(() => _transport.GetRequired<PageData<CloudGoods>>("CloudGoods/SearchGoods", MethodType.Post, request));
public Task<PageData<CloudGoods>> GetGoods(GoodsSearchRequest request)
=> _transport.GetRequiredAsync<PageData<CloudGoods>>("CloudGoods/SearchGoods", MethodType.Post, request);
public string GetGoodsDetail(long goodsId)
=> _transport.GetRequired<string>("CloudGoods/GetGoodsRawData", MethodType.Post,
query: new Dictionary<string, string> { ["goodsId"] = goodsId.ToString(CultureInfo.InvariantCulture) });
public string GetGoodsDetail(long goodsId)
=> _transport.GetRequired<string>("CloudGoods/GetGoodsRawData", MethodType.Post,
query: new Dictionary<string, string> { ["goodsId"] = goodsId.ToString(CultureInfo.InvariantCulture) });
public Task<List<ReportGoodsViolationResult>> ReportViolations(List<ReportGoodsViolationItem> items)
=> Task.Run(() => _transport.GetRequired<List<ReportGoodsViolationResult>>("CloudGoods/ReportViolations", MethodType.Post, items,
timeoutMilliseconds: 5000));
public Task<List<ReportGoodsViolationResult>> ReportViolations(List<ReportGoodsViolationItem> items)
=> _transport.GetRequiredAsync<List<ReportGoodsViolationResult>>("CloudGoods/ReportViolations", MethodType.Post, items,
timeoutMilliseconds: 5000);
public List<GoodsViolationStatus> GetViolationStatus(List<long> goodsIds)
=> _transport.GetRequired<List<GoodsViolationStatus>>("CloudGoods/GetViolationStatus", MethodType.Post, goodsIds,
timeoutMilliseconds: 5000);
public List<GoodsViolationStatus> GetViolationStatus(List<long> goodsIds)
=> _transport.GetRequired<List<GoodsViolationStatus>>("CloudGoods/GetViolationStatus", MethodType.Post, goodsIds,
timeoutMilliseconds: 5000);
public Task RecordViolationLogs(IReadOnlyList<RecordViolationLogRequest> requests)
=> Task.Run(() => _transport.Send<object>("CloudGoods/RecordViolationLog", MethodType.Post, requests,
timeoutMilliseconds: 5000));
public Task RecordViolationLogs(IReadOnlyList<RecordViolationLogRequest> requests)
=> _transport.SendAsync<object>("CloudGoods/RecordViolationLog", MethodType.Post, requests,
timeoutMilliseconds: 5000);
public Task<List<CloudGoodsService.ViolationReason>> GetViolationReasons()
=> Task.Run(() => _transport.GetRequired<List<CloudGoodsService.ViolationReason>>("CloudGoods/GetViolationReasons", MethodType.Get));
public Task<List<CloudGoodsService.ViolationReason>> GetViolationReasons()
=> _transport.GetRequiredAsync<List<CloudGoodsService.ViolationReason>>("CloudGoods/GetViolationReasons", MethodType.Get);
public Task<List<GoodsViolationLogEntity>> GetViolationLogs(GetViolationLogsRequest request)
=> Task.Run(() => _transport.GetRequired<List<GoodsViolationLogEntity>>("CloudGoods/GetViolationLogs", MethodType.Post, request,
timeoutMilliseconds: 5000));
public Task<List<GoodsViolationLogEntity>> GetViolationLogs(GetViolationLogsRequest request)
=> _transport.GetRequiredAsync<List<GoodsViolationLogEntity>>("CloudGoods/GetViolationLogs", MethodType.Post, request,
timeoutMilliseconds: 5000);
public Task<PageData<CloudGoods>> SearchFavorites(UserFavoritesGoodsSearchRequest request)
=> Task.Run(() => _transport.GetRequired<PageData<CloudGoods>>("CloudGoods/SearchFavorites", MethodType.Post, request));
public Task<PageData<CloudGoods>> SearchFavorites(UserFavoritesGoodsSearchRequest request)
=> _transport.GetRequiredAsync<PageData<CloudGoods>>("CloudGoods/SearchFavorites", MethodType.Post, request);
public Task<int> Favorite(string userName, List<long> goodsIds)
=> Task.Run(() => _transport.Send<int>("CloudGoods/AddFavorite", MethodType.Post,
new { UserName = userName, GoodsIds = goodsIds }));
public Task<int> Favorite(string userName, List<long> goodsIds)
=> _transport.SendAsync<int>("CloudGoods/AddFavorite", MethodType.Post,
new { UserName = userName, GoodsIds = goodsIds });
public Task<int> RemoveFavorites(string userName, List<long> goodsIds)
=> Task.Run(() => _transport.Send<int>("CloudGoods/RemoveFavorites", MethodType.Post,
new { UserName = userName, GoodsIds = goodsIds }));
public Task<int> RemoveFavorites(string userName, List<long> goodsIds)
=> _transport.SendAsync<int>("CloudGoods/RemoveFavorites", MethodType.Post,
new { UserName = userName, GoodsIds = goodsIds });
/// <summary>识别上传图片中的文字和品牌 Logo。</summary>
public async Task<List<string>> RecognizeAsync(string urlMd5, byte[] jpeg)
{
int sleep = 0;
if (EnvironmentHelper.IsProduction)
{
sleep = RandomHelper.GetRandom(600, 1200);
}
var minimumDuration = Task.Delay(TimeSpan.FromMilliseconds(sleep));
var request = new { UserName = BaseClass.UserName, Md5 = urlMd5, Image = Convert.ToBase64String(jpeg) };
var recognitionTask = _transport.GetRequiredAsync<List<string>>("CloudGoods/InspectImage", MethodType.Post, request);
await Task.WhenAll(minimumDuration, recognitionTask).ConfigureAwait(false);
return await recognitionTask.ConfigureAwait(false);
}
public async Task SaveProductSafety(SaveProductSafetyRequest request)
{
var ret = await _transport.SendAsync<int>("CloudGoods/SaveProductSafety", MethodType.Post, new
{
UserName = request.UserName,
ProductId = request.ProductId,
IsSafe = request.IsSafe
});
}
}
+70
View File
@@ -0,0 +1,70 @@
using AllBase;
using AllBase.Helper;
using CsharpHttpHelper;
using NaiBa.Util.Helper;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.IO;
using System.Threading.Tasks;
namespace Work.Store.Api;
public sealed class GoodsComplianceApi
{
private readonly ApiTransport transport;
internal GoodsComplianceApi(ApiTransport transport) => this.transport = transport;
///// <summary>上报平台商品的安全检测记录。</summary>
//public Task SaveProductSafety(SaveProductSafetyRequest request)
//{
// request.UserName = BaseClass.UserName;
// return transport.SendAsync<object>("ProductInspection/SaveProductSafety", MethodType.Post,
// request ?? throw new ArgumentNullException(nameof(request)));
//}
/// <summary>按平台和商品 ID 批量查询安全记录。</summary>
public Task<List<ProductSafetyDto>> QueryProductSafety(QueryProductSafetyRequest request)
{
request.UserName = BaseClass.UserName;
return transport.GetRequiredAsync<List<ProductSafetyDto>>("ProductInspection/QueryProductSafety", MethodType.Post,
request ?? throw new ArgumentNullException(nameof(request)));
}
/// <summary>识别上传图片中的文字和品牌 Logo。</summary>
public async Task<List<string>> RecognizeAsync(string urlMd5, byte[] jpeg)
{
int sleep = 0;
if (EnvironmentHelper.IsProduction)
{
sleep = RandomHelper.GetRandom(600, 1200);
}
var minimumDuration = Task.Delay(TimeSpan.FromMilliseconds(sleep));
var request = new { UserName = BaseClass.UserName, Md5 = urlMd5, Image = Convert.ToBase64String(jpeg) };
var recognitionTask = transport.GetRequiredAsync<List<string>>("ProductInspection/InspectImage", MethodType.Post, request);
await Task.WhenAll(minimumDuration, recognitionTask).ConfigureAwait(false);
return await recognitionTask.ConfigureAwait(false);
}
}
public sealed class SaveProductSafetyRequest
{
[Required] public string UserName { get; set; } = "";
[Required] public string ProductId { get; set; } = "";
[Required] public bool? IsSafe { get; set; }
}
public sealed class QueryProductSafetyRequest
{
[Required] public string UserName { get; set; } = "";
[Required] public string PlatformId { get; set; } = "";
[Required] public string[] ProductIds { get; set; } = [];
}
public sealed record ProductSafetyDto(string ProductId, bool IsSafe)
{
[Required] public string UserName { get; set; } = "";
public string ProductId { get; } = ProductId;
public bool IsSafe { get; } = IsSafe;
}
+5 -3
View File
@@ -9,15 +9,16 @@ namespace Work.Store.Api;
/// <summary>全局共用一个用户会话与请求出口,窗体通过 Instance 访问。</summary>
public sealed class StoreApiClient
{
private static readonly string BaseUrl = EnvironmentHelper.IsDevelopment
? "http://localhost:14312/api/"
: "http://103.90.155.78:9001/api/";
private static readonly string BaseUrl = EnvironmentHelper.IsProduction
? "http://103.90.155.78:9001/api/"
: "http://localhost:14312/api/";
public static StoreApiClient Instance { get; } = new StoreApiClient();
public ApiTransport Transport { get; }
public AuthApi Auth { get; }
public CloudGoodsApi CloudGoods { get; }
//public GoodsComplianceApi GoodsCompliance { get; }
public ImageCacheApi ImageCache { get; }
/// <summary>当前 Windows 安装的 SHA-256 设备指纹,登录时作为 DeviceId 发送。</summary>
public string DeviceId { get; }
@@ -28,6 +29,7 @@ public sealed class StoreApiClient
Transport = new ApiTransport(BaseUrl);
Auth = new AuthApi(Transport, DeviceId);
CloudGoods = new CloudGoodsApi(Transport);
//GoodsCompliance = new GoodsComplianceApi(Transport);
ImageCache = new ImageCacheApi(Transport);
}