云库增加 AI识图,缓存,我的云库收藏增加安全标志

调用外部API 扣费
This commit is contained in:
chfei committed 2026-11-06 19:25:36 +08:00
1 parent 7c29e57623
commit 150e8644b7
49 files changed
+1069 -28

No files matched your search

@@ -33,6 +33,17 @@ namespace Store.Modules.CloudProduct
new FreeSql.FreeSqlBuilder().UseConnectionString(FreeSql.DataType.MySql, connectionStringBuilder.ConnectionString)
.UseAdoConnectionPool(true).Build());
services.AddHostedService<CloudProductSearchStartup>();
// 服务自行创建客户端,单例复用连接池并由容器负责释放。
services.AddSingleton<ImageAnalysisQuotaService>();
// 图片识别沿用专用缓存库,所有请求共享并发上限。
var inspectionConnection = RequireConfiguration("ProductInspection:ConnectionString");
services.AddKeyedSingleton<IFreeSql>("ProductInspectionConnection", (_, _) =>
new FreeSql.FreeSqlBuilder().UseConnectionString(FreeSql.DataType.MySql, inspectionConnection)
.UseAdoConnectionPool(true).Build());
var maximum = Context.Configuration.GetValue<int?>("ProductInspection:MaxConcurrentAnalysis") ?? 5;
if (maximum is < 1 or > 100) throw new InvalidOperationException("识别并发数必须在 1 至 100 之间。");
services.AddKeyedSingleton<SemaphoreSlim>("ProductInspectionAnalysisGate", (_, _) => new SemaphoreSlim(maximum, maximum));
}
@@ -0,0 +1,7 @@
namespace Store.Modules.CloudProduct.Contracts;
/// <summary>按图片阅读顺序返回文字和中文品牌名,无识别项返回空数组。</summary>
public interface IInspectionIntegration
{
Task<string[]> AnalyzeAsync(Stream image, string mediaType, CancellationToken cancellationToken);
}
@@ -15,8 +15,7 @@ namespace Store.Modules.CloudProduct.Controllers
{
/// <summary>云商品管理:商品查询、导入、违规上报及搜索索引维护。</summary>
[Tags("云商品")]
[ApiVersionNeutral]
[Route("api/CloudGoods/[action]")]
[Route("CloudGoods/[action]")]
public class GoodsController : AppControllerBase
{
private readonly IGoodsService _goodsService;
@@ -0,0 +1,19 @@
using MAX.Framework.Conventions;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Store.Framework.Base;
using Store.Modules.CloudProduct.Dtos;
using Store.Modules.CloudProduct.Services;
namespace Store.Modules.CloudProduct.Controllers;
/// <summary>上传图片识别及当前用户的商品安全记录。</summary>
[Tags("商品检测"), DefaultHttpPost]
[Route("api/CloudGoods/[action]")]
public sealed class ProductInspectionController(ProductInspectionService service) : AppControllerBase
{
[EndpointSummary("识别上传图片中的文字和品牌 Logo")]
[RequestFormLimits(ValueLengthLimit = ProductInspectionService.MaxBase64Length)]
public Task<string[]> InspectImage(InspectImageRequest request, CancellationToken cancellationToken)
=> service.InspectAsync(request, cancellationToken);
}
@@ -58,6 +58,14 @@ namespace Store.Modules.CloudProduct.Controllers
return await _favoritesService.AddFavoritesAsync(request);
}
/// <summary>更新用户已收藏商品的安全结论。</summary>
[HttpPost]
public async Task<ApiResult> SaveProductSafety(SaveProductSafetyRequest request)
{
await _favoritesService.SaveProductSafetyAsync(request);
return ApiResult.Ok();
}
/// <summary>
/// 批量取消收藏:删除 user_goods_favorites 记录并同步删除收藏索引文档,返回实际取消的条数。
/// </summary>
@@ -0,0 +1,22 @@
using System.ComponentModel.DataAnnotations;
namespace Store.Modules.CloudProduct.Dtos;
/// <summary>单张商品图片,使用 multipart/form-data 上传。</summary>
public sealed class InspectImageRequest
{
[Required] public string UserName { get; set; } = "";
/// <summary>客户端指定的 32 位十六进制 MD5 缓存键,大小写均可。</summary>
[Required] public string Md5 { get; set; } = "";
/// <summary>图片原始字节的 Base64 字符串,不含 Data URL 前缀。</summary>
[Required] public string Image { get; set; } = "";
}
///// <summary>在当前登录用户和指定平台内按商品 ID 批量查询。</summary>
//public sealed class QueryProductSafetyRequest
//{
// [Required] public string UserName { get; set; } = "";
// [Required] public string[] ProductIds { get; set; } = [];
//}
//public sealed record ProductSafetyDto(string ProductId, bool IsSafe);
@@ -0,0 +1,11 @@
using System.ComponentModel.DataAnnotations;
namespace Store.Modules.CloudProduct.Dtos;
/// <summary>保存收藏商品的检测结论,沿用原接口的字符串商品编号。</summary>
public sealed class SaveProductSafetyRequest
{
[Required] public string UserName { get; set; } = "";
[Required] public string ProductId { get; set; } = "";
[Required] public bool? IsSafe { get; set; }
}
@@ -0,0 +1,11 @@
using System.ComponentModel.DataAnnotations;
namespace Store.Modules.CloudProduct.Dtos;
/// <summary>外部网站图片识别额度扣减请求。</summary>
public sealed class UseImageAnalysisQuotaRequest
{
/// <summary>需要使用识别额度的外部网站用户名。</summary>
[Required(ErrorMessage = "用户名不能为空")]
public string UserName { get; set; } = string.Empty;
}
@@ -49,5 +49,9 @@ namespace Store.Modules.CloudProduct.Dtos
/// <summary>收藏时间</summary>
public DateTime CreatedAt { get; set; }
/// <summary>
/// 安全检测
/// </summary>
public bool? IsSafe { get; set; }
}
}
@@ -9,6 +9,10 @@ namespace Store.Modules.CloudProduct.Dtos
/// </summary>
public class UserFavoritesSearchDocument
{
/// <summary>安全检测结论;为空表示尚未检测。</summary>
[Boolean(Name = "is_safe")]
public bool? IsSafe { get; set; }
/// <summary>
/// 文档主键(同时作为 OpenSearch 的 _id):{user_name}:{goods_id}
/// </summary>
@@ -5,6 +5,9 @@ namespace Store.Modules.CloudProduct.Dtos
/// </summary>
public class UserFavoritesSearchRequest
{
/// <summary>安全状态:0 全部(默认),1 安全,2 违规,3 未检测。</summary>
public int SafeStatus { get; set; }
/// <summary>
/// 用户名(为空时取当前登录用户)
/// </summary>
@@ -0,0 +1,17 @@
using FreeSql.DataAnnotations;
namespace Store.Modules.CloudProduct.Entities;
/// <summary>跨用户复用的图片识别数据,仅存储成功识别结果。</summary>
[Table(Name = "image_analysis_cache")]
public sealed class ImageAnalysisCache
{
/// <summary>客户端指定的 MD5 缓存键,统一保存为 32 位小写十六进制。</summary>
[Column(IsPrimary = true, StringLength = 32)]
public string CacheKey { get; set; } = "";
/// <summary>模型识别结果的 JSON 字符串数组,空数组表示未识别到文字或品牌。</summary>
[Column(DbType = "longtext")]
public string RecognitionResult { get; set; } = "";
/// <summary>缓存最近更新时间,UTC。</summary>
public DateTime UpdatedAt { get; set; }
}
@@ -34,6 +34,10 @@ namespace Store.Modules.CloudProduct.Entities
[Column(Name = "goods_id", IsNullable = false)]
public long GoodsId { get; set; }
/// <summary>最近上报的安全结论,null 表示尚未检测。</summary>
[Column(Name = "is_safe", IsNullable = true)]
public bool? IsSafe { get; set; }
/// <summary>
/// 收藏时间
/// </summary>
+22
View File
@@ -0,0 +1,22 @@
# 商品图片识别
CloudProduct 提供以下 POST 接口,成功时 ApiResult 的 code 为 200。
| 路径 | JSON 请求 | 成功响应的 data |
|---|---|---|
| `/api/ProductInspection/InspectImage` | `userName`、`md5`、`image` 均必填。md5 为 32 位十六进制缓存键,image 为 JPEG、PNG 或 WebP 原图的纯 Base64(不含 Data URL 前缀),原图最多 10 MiB | 按阅读顺序去重的文字和品牌数组,无识别项时返回 `[]` |
| `/api/CloudGoods/SaveProductSafety` | `{"userName":"alice","productId":"123","isSafe":false}` | 无数据 |
客户端根据识别结果判断商品是否安全,再上报已收藏商品的结论。最新结论可从收藏检索接口读取。
## 配置与部署
图片识别沿用专用数据库。将旧插件配置中的 `ProductInspection` 节迁入 CloudProduct 对应环境的配置文件,环境变量前缀由 `Plugins__ProductInspection__` 改为 `Plugins__CloudProduct__`。例如,密钥使用 `Plugins__CloudProduct__ProductInspection__ApiKey`,为空时读取 `DASHSCOPE_API_KEY`。部署时移出旧的 `Plugins/Store.ProductInspection` 目录,避免宿主重复加载质检功能。
服务端将客户端提交的 MD5 转为小写,命中缓存后直接返回结果。未命中时调用配置的千问接口,最大并发数由 `ProductInspection:MaxConcurrentAnalysis` 控制。
## 验证
从仓库根目录运行 `dotnet run --project Tests/ProductInspection.Checks`,检查专用库结构并通过本地模拟模型验证图片识别和缓存。数据库连接可用 `Plugins__CloudProduct__ProductInspection__ConnectionString` 覆盖。
已有可用缓存表的部署只需迁移插件配置。旧库升级命令 `dotnet run --project Tests/ProductInspection.Checks -- --initialize` 会更名旧结果列,移除 DetectionText、LogoBrands 列及四张旧任务相关表,并同步缓存表结构。执行前请备份数据库,先归档或清理仍使用 SHA-256 键的缓存。
@@ -11,7 +11,12 @@ namespace Store.Modules.CloudProduct.Services;
/// <summary>跨实例串行化违规上报和商品索引写入,防止下架后被旧批次写回。</summary>
public class GoodsIndexLock([FromKeyedServices("CloudProduct")] PluginContext context) : ISingletonDependency
{
public async Task<IAsyncDisposable> AcquireAsync()
public Task<IAsyncDisposable> AcquireAsync() => AcquireAsync("goods-index:");
/// <summary>收藏重建、整条文档写入和安全状态更新共用独立锁,防止旧快照覆盖新结论。</summary>
public virtual Task<IAsyncDisposable> AcquireFavoritesAsync() => AcquireAsync("favorites-index:");
private async Task<IAsyncDisposable> AcquireAsync(string prefix)
{
// 禁用连接池:即使释放锁失败,关闭物理连接也会释放会话锁。
var settings = new MySqlConnectionStringBuilder(context.Configuration["CloudProductConnection"])
@@ -19,7 +24,7 @@ public class GoodsIndexLock([FromKeyedServices("CloudProduct")] PluginContext co
Pooling = false
};
var connection = new MySqlConnection(settings.ConnectionString);
var name = "goods-index:" + Convert.ToHexString(SHA256.HashData(
var name = prefix + Convert.ToHexString(SHA256.HashData(
Encoding.UTF8.GetBytes(settings.Database)))[..40];
try
{
@@ -0,0 +1,65 @@
using MAX.Framework.Commons;
using MAX.Framework.Dtos;
using MAX.Framework.Validation;
using MAX.Plugins;
using Microsoft.AspNetCore.WebUtilities;
using Store.Modules.CloudProduct.Dtos;
using System.Text.Json;
using System.Text.Json.Serialization;
namespace Store.Modules.CloudProduct.Services;
/// <summary>调用外部网站的图片识别额度接口,单例复用 HTTP 连接。</summary>
public sealed class ImageAnalysisQuotaService : IDisposable
{
private readonly HttpClient client;
private readonly PluginContext<CloudProductPlugin> context;
/// <summary>从站点根地址创建客户端,定期更新连接以跟随 DNS 变化。</summary>
public ImageAnalysisQuotaService(PluginContext<CloudProductPlugin> context)
{
this.context = context;
var url = context.RequireConfiguration("ImageAnalysisQuota:Url");
if (!Uri.TryCreate(url, UriKind.Absolute, out var endpoint) ||
(endpoint.Scheme != Uri.UriSchemeHttp && endpoint.Scheme != Uri.UriSchemeHttps))
throw new InvalidOperationException("ImageAnalysisQuota:Url 必须是 HTTP 或 HTTPS 站点地址。");
client = new HttpClient(new SocketsHttpHandler
{
PooledConnectionLifetime = TimeSpan.FromMinutes(5),
AllowAutoRedirect = false
})
{ BaseAddress = endpoint };
}
/// <summary>随服务释放客户端及连接池。</summary>
public void Dispose() => client.Dispose();
/// <summary>
/// 使用指定用户的识别额度,返回外部接口原始响应;HTTP 失败直接抛出异常。
/// 额度扣减不自动重试,避免请求已执行但响应丢失时重复扣减。
/// </summary>
public async Task<bool> UseImageAnalysisQuotaAsync(UseImageAnalysisQuotaRequest request,
CancellationToken cancellationToken = default)
{
RequestValidator.Validate(request);
// 外部协议要求 token 和 username 放在查询字符串中,统一编码特殊字符。
var requestUrl = QueryHelpers.AddQueryString("/wxxd_user/UseImageAnalysisQuota", new Dictionary<string, string?>
{
["token"] = context.RequireConfiguration("ImageAnalysisQuota:APIKey"),
["username"] = request.UserName
});
using var response = await client.PostAsync(requestUrl, null, cancellationToken);
response.EnsureSuccessStatusCode();
// shortcut: 尚未提供响应协议,明确业务成功字段后再添加响应 DTO 和业务失败判断。
string html = await response.Content.ReadAsStringAsync(cancellationToken);
var result = JsonSerializer.Deserialize<ApiResult>(html);
if (result != null && result.Success)
{
return true;
}
throw new AppException(result.Msg);
}
}
@@ -0,0 +1,93 @@
using MAX.Core.DependencyInjection;
using MAX.Framework.Security;
using MAX.Framework.Validation;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Store.Modules.CloudProduct.Contracts;
using Store.Modules.CloudProduct.Dtos;
using Store.Modules.CloudProduct.Entities;
using System.ComponentModel.DataAnnotations;
using System.Text.Encodings.Web;
using System.Text.Json;
using System.Text.Unicode;
namespace Store.Modules.CloudProduct.Services;
/// <summary>商品检测业务入口,负责上传图片识别、MD5 缓存和当前用户的商品安全记录。</summary>
public sealed class ProductInspectionService(IInspectionIntegration integration, ICurrentUser user, ImageAnalysisQuotaService imageAnalysisQuotaService,
[FromKeyedServices("CloudProductConnection")] IFreeSql database,
[FromKeyedServices("ProductInspectionAnalysisGate")] SemaphoreSlim gate,
ILogger<ProductInspectionService> logger
) : IScopedDependency
{
public const int MaxBytes = 10 * 1024 * 1024;
// 缓存 JSON 保留中文原文,字符串中的引号和控制字符仍由序列化器转义。
private static readonly JsonSerializerOptions CacheJsonOptions = new()
{
Encoder = JavaScriptEncoder.Create(UnicodeRanges.All)
};
// 每三个图片字节编码为四个 Base64 字符,末组向上取整。
public const int MaxBase64Length = (MaxBytes + 2) / 3 * 4;
public async Task<string[]> InspectAsync(InspectImageRequest request, CancellationToken cancellationToken)
{
RequestValidator.Validate(request);
if (request.Md5.Length != 32 || !request.Md5.All(char.IsAsciiHexDigit))
throw new ValidationException("md5 必须是 32 位十六进制缓存键。");
var md5 = request.Md5.ToLowerInvariant();
if (request.Image.Length > MaxBase64Length)
throw new ValidationException("图片超过 10 MiB 或 Base64 文本过长。");
byte[] image;
try { image = Convert.FromBase64String(request.Image); }
catch (FormatException) { throw new ValidationException("image 必须是有效的 Base64 字符串。"); }
if (image.Length is < 12 or > MaxBytes)
throw new ValidationException("图片为空、格式无效或超过 10 MiB。");
// 依据文件签名识别允许的图片类型,避免信任客户端文件名和 MIME 类型。
string mediaType;
if (image[0] == 0xff && image[1] == 0xd8 && image[2] == 0xff) mediaType = "image/jpeg";
else if (image.AsSpan(0, 8).SequenceEqual(new byte[] { 137, 80, 78, 71, 13, 10, 26, 10 })) mediaType = "image/png";
else if (image.AsSpan(0, 4).SequenceEqual("RIFF"u8) && image.AsSpan(8, 4).SequenceEqual("WEBP"u8)) mediaType = "image/webp";
else throw new ValidationException("请上传 JPEG、PNG 或 WebP 图片。");
var cached = await database.Select<ImageAnalysisCache>().Where(x => x.CacheKey == md5).FirstAsync();
string[] result;
// 旧对象格式缺少逐项阅读顺序,重新识别成功后再覆盖。
if (cached?.RecognitionResult.TrimStart().StartsWith('[') == true)
result = JsonSerializer.Deserialize<string[]>(cached.RecognitionResult)!;
else
{
await gate.WaitAsync(cancellationToken);
try
{
using var stream = new MemoryStream(image, writable: false);
var recognized = await integration.AnalyzeAsync(stream, mediaType, cancellationToken);
result = recognized.Distinct(StringComparer.Ordinal).ToArray();
await database.InsertOrUpdate<ImageAnalysisCache>().SetSource(new ImageAnalysisCache
{
CacheKey = md5,
RecognitionResult = JsonSerializer.Serialize(result, CacheJsonOptions),
UpdatedAt = DateTime.UtcNow
}).ExecuteAffrowsAsync();
}
finally { gate.Release(); }
}
try
{
var useRet = await imageAnalysisQuotaService.UseImageAnalysisQuotaAsync(new UseImageAnalysisQuotaRequest
{
UserName = request.UserName
});
}
catch (Exception ex)
{
logger.LogError(ex, "调用图片识别扣费程序失败");
//扣费失败显示空
result = [];
}
return result;
}
}
@@ -0,0 +1,112 @@
using System.Net;
using System.Net.Http.Json;
using System.Text.Json;
using MAX.Core.DependencyInjection;
using MAX.Plugins;
using Store.Modules.CloudProduct.Contracts;
namespace Store.Modules.CloudProduct.Services;
/// <summary>通过千问兼容接口识别上传图片中的文字及品牌。</summary>
public sealed class QwenInspectionIntegration : IInspectionIntegration, ISingletonDependency, IDisposable
{
private readonly HttpClient client;
private readonly string model;
/// <summary>按插件配置创建并复用模型客户端,定期更新池内连接以跟随 DNS 变化。</summary>
public QwenInspectionIntegration(PluginContext<CloudProductPlugin> context)
{
model = context.RequireConfiguration("ProductInspection:Model");
var endpoint = new Uri(context.RequireConfiguration("ProductInspection:Endpoint"));
var key = context.Configuration["ProductInspection:ApiKey"];
if (string.IsNullOrWhiteSpace(key)) key = Environment.GetEnvironmentVariable("DASHSCOPE_API_KEY");
client = new HttpClient(new SocketsHttpHandler
{
PooledConnectionLifetime = TimeSpan.FromMinutes(5),
//Proxy = new WebProxy("http://127.0.0.1:8080")
})
{
BaseAddress = endpoint,
Timeout = TimeSpan.FromMinutes(10)
};
if (!string.IsNullOrWhiteSpace(key))
client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", key);
}
public void Dispose() => client.Dispose();
private const string Prompt = """
你是图像品牌与文字识别引擎。请识别图片中的文字和品牌 Logo,并严格按下方规则输出。
【识别范围】
- 所有可见文字(标题、正文、按钮文字、标签、说明等),原样识别输出。
- 品牌 Logo:识别 Logo 对应的品牌,输出品牌中文名(不输出 Logo 上的原始英文/字母)。
- 图片、图标、二维码、条形码、分隔线等非文字非品牌元素:忽略,不输出。
【Logo 处理规则】
- 遇到品牌 Logo 时,不要输出 Logo 上的原始英文/字母。
- 必须输出该品牌对应的中文品牌名。
- 示例:
* 看到 "ERKE" 或鸿鹄图形 → 输出 "鸿星尔克"
* 看到 "Nike" 或钩子图形 → 输出 "耐克"
* 看到 "Adidas" 或三叶草/三条纹 → 输出 "阿迪达斯"
* 看到 "Li-Ning" 或李宁图形 → 输出 "李宁"
* 看到 "ANTA" 或安踏图形 → 输出 "安踏"
* 看到 "Xtep" 或特步图形 → 输出 "特步"
* 看到 "361°" → 输出 "361度"
- 如遇无法识别为已知品牌的 Logo,输出 "未知品牌"。
- 如 Logo 上同时有中英文,优先输出中文品牌名。
【品牌名归一化规则(重要)】
- 输出的品牌必须是一个独立、纯净的品牌名,不能包含子品牌、系列名、品类词、修饰词,也不能用连接符拼接。
- 子品牌或系列要归并到主品牌,只输出主品牌名。
- 正例:
* "安踏儿童" → 输出 "安踏"(不要输出 "安踏儿童")
* "安踏冠军系列" → 输出 "安踏"
* "Nike Air" / "耐克 Air" → 输出 "耐克"
* "Adidas Originals" / "阿迪达斯三叶草" → 输出 "阿迪达斯"
* "李宁中国李宁" → 输出 "李宁"
* "鸿星尔克ERKE" → 输出 "鸿星尔克"
- 反例(禁止输出):
* "安踏儿童"、"安踏-儿童"、"安踏 儿童"、"安踏(儿童)"
* "耐克/Nike"、"阿迪达斯 Adidas"
- 禁止使用 "/"、"-"、"·"、空格、括号等连接符拼接多个名称。
【输出要求】
1. 只输出一个 JSON 字符串数组,不要输出对象、markdown 代码块、解释性文字或多余内容。
2. 格式固定为:["文字1", "文字2", "文字3", ...]
3. 按从上到下、从左到右的阅读顺序排列。
4. 每个元素只包含文字本身,不包含类型、坐标等额外字段。
5. 文字中的双引号需转义(\"),确保输出是合法 JSON。
6. 若图中没有任何可识别文字或品牌,输出 []。
""";
public async Task<string[]> AnalyzeAsync(Stream image, string mediaType, CancellationToken cancellationToken)
{
if (client.DefaultRequestHeaders.Authorization is null)
throw new InvalidOperationException("请配置 ProductInspection:ApiKey 或 DASHSCOPE_API_KEY。");
using var buffer = new MemoryStream();
await image.CopyToAsync(buffer, cancellationToken);
var url = $"data:{mediaType};base64,{Convert.ToBase64String(buffer.GetBuffer(), 0, (int)buffer.Length)}";
using var response = await client.PostAsJsonAsync("", new
{
model,
messages = new[] { new { role = "user", content = new object[]
{
new { type = "image_url", image_url = new { url } },
new { type = "text", text = Prompt }
} } },
stream = false,
enable_thinking = false
}, cancellationToken);
response.EnsureSuccessStatusCode();
using var body = await response.Content.ReadFromJsonAsync<JsonDocument>(cancellationToken);
var content = body!.RootElement.GetProperty("choices")[0].GetProperty("message").GetProperty("content").GetString();
var words = JsonSerializer.Deserialize<string[]>(content ?? throw new JsonException("模型未返回识别内容。"));
if (words == null || words.Any(word => word == null)) throw new JsonException("模型必须返回 JSON 字符串数组。");
return words;
}
}
@@ -33,6 +33,9 @@ namespace Store.Modules.CloudProduct.Services
/// <summary>批量写入收藏文档(存在则覆盖)</summary>
Task IndexDocumentsAsync(IEnumerable<UserFavoritesSearchDocument> documents);
/// <summary>更新单条收藏的安全字段并等待对检索可见。</summary>
Task UpdateSafetyAsync(string documentId, bool isSafe);
/// <summary>按文档Id批量删除收藏文档</summary>
Task DeleteDocumentsAsync(IEnumerable<string> documentIds);
@@ -172,6 +175,7 @@ namespace Store.Modules.CloudProduct.Services
)
.Map<UserFavoritesSearchDocument>(m => m
.Properties(p => p
.Boolean(b => b.Name(x => x.IsSafe))
.Keyword(k => k.Name(x => x.Id))
.Number(n => n.Name(x => x.FavId).Type(NumberType.Long))
.Keyword(k => k.Name(x => x.UserName))
@@ -221,6 +225,14 @@ namespace Store.Modules.CloudProduct.Services
return await CreateIndexAsync();
}
public async Task UpdateSafetyAsync(string documentId, bool isSafe)
{
var response = await _client.UpdateAsync<UserFavoritesSearchDocument, object>(documentId, u => u
.Index(_indexName).Doc(new { is_safe = isSafe }).Refresh(Refresh.WaitFor));
if (!response.IsValid)
throw new AppException("更新收藏安全状态索引失败: " + response.DebugInformation);
}
private async Task RefreshIndexAsync()
{
var response = await _client.Indices.RefreshAsync(_indexName, d => d
@@ -316,6 +328,9 @@ namespace Store.Modules.CloudProduct.Services
throw new AppException("用户名不能为空", ResultCode.ValidationError);
}
if (request.SafeStatus is < 0 or > 3)
throw new AppException("状态必须为 0(全部)、1(安全)、2(违规)或 3(未检测)", ResultCode.ValidationError);
var keyword = request.Title;
int? groupId = request.GroupId;
var groupName = request.GroupName;
@@ -341,6 +356,12 @@ namespace Store.Modules.CloudProduct.Services
// 只检索当前用户自己的收藏 —— 放进 filters,避免被后面的 Filter 覆盖
filters.Add(f => f.Term(t => t.Field(x => x.UserName).Value(request.UserName)));
// is_safe 为 null 或缺失时没有索引值,两者均表示暂无检测结论。
if (request.SafeStatus is 1 or 2)
filters.Add(f => f.Term(t => t.Field(x => x.IsSafe).Value(request.SafeStatus == 1)));
else if (request.SafeStatus == 3)
filters.Add(f => f.Bool(b => b.MustNot(q => q.Exists(e => e.Field(x => x.IsSafe)))));
if (groupId.HasValue)
{
filters.Add(f => f.Term(t => t.Field(x => x.GroupId).Value(groupId.Value)));
@@ -1,11 +1,14 @@
using MAX.Core.DependencyInjection;
using MAX.Framework.Commons;
using MAX.Framework.Dtos;
using MAX.Framework.Validation;
using Microsoft.Extensions.Logging;
using Store.Modules.CloudProduct.Dtos;
using Store.Modules.CloudProduct.Entities;
using Store.Modules.CloudProduct.Enums;
using Store.Modules.CloudProduct.Repositorys;
using Store.Users.Contracts;
using System.Globalization;
namespace Store.Modules.CloudProduct.Services
{
@@ -17,6 +20,9 @@ namespace Store.Modules.CloudProduct.Services
/// <summary>批量收藏商品,返回本次成功收藏的商品数量(已收藏的商品视为修改收藏分组)</summary>
Task<int> AddFavoritesAsync(AddUserFavoriteRequest request);
/// <summary>按用户和商品编号更新已存在的收藏记录。</summary>
Task SaveProductSafetyAsync(SaveProductSafetyRequest request);
/// <summary>批量取消收藏,返回实际取消的条数</summary>
Task<int> RemoveFavoritesAsync(RemoveUserFavoritesRequest request);
@@ -47,6 +53,8 @@ namespace Store.Modules.CloudProduct.Services
private readonly UserGoodsFavoriteRepository _favoriteRepository;
private readonly UserGoodsFavoriteGroupRepository _groupRepository;
private readonly GoodsRepository _goodsRepository;
private readonly IUserQueryService _queryService;
private readonly GoodsIndexLock _indexLock;
private readonly IUserFavoritesIndexService _indexService;
private readonly ILogger<UserFavoritesService> _logger;
@@ -54,13 +62,16 @@ namespace Store.Modules.CloudProduct.Services
UserGoodsFavoriteRepository favoriteRepository,
UserGoodsFavoriteGroupRepository groupRepository,
GoodsRepository goodsRepository,
IUserQueryService queryService,
IUserFavoritesIndexService indexService,
ILogger<UserFavoritesService> logger)
ILogger<UserFavoritesService> logger, GoodsIndexLock indexLock)
{
_favoriteRepository = favoriteRepository;
_groupRepository = groupRepository;
_goodsRepository = goodsRepository;
_queryService = queryService;
_indexService = indexService;
_indexLock = indexLock;
_logger = logger;
}
@@ -81,6 +92,8 @@ namespace Store.Modules.CloudProduct.Services
{
throw new AppException("用户名不能为空", ResultCode.ValidationError);
}
var mainUser = await _queryService.GetMainUser(userName);
userName = mainUser.UserName;
var goodsIds = request.GoodsIds?.Where(x => x > 0).Distinct().ToList() ?? new List<long>();
if (goodsIds.Count == 0)
@@ -93,6 +106,7 @@ namespace Store.Modules.CloudProduct.Services
throw new AppException("收藏分组无效", ResultCode.ValidationError);
}
await using var lease = await _indexLock.AcquireFavoritesAsync();
// 1. 校验分组归属(分组ID > 0 时必须是该用户自己创建的分组)
if (request.GroupId > 0)
{
@@ -206,6 +220,28 @@ namespace Store.Modules.CloudProduct.Services
return documents.Count;
}
/// <summary>仅修改安全字段,避免覆盖同时发生的收藏分组变更。</summary>
public async Task SaveProductSafetyAsync(SaveProductSafetyRequest request)
{
RequestValidator.Validate(request);
if (!long.TryParse(request.ProductId, NumberStyles.None, CultureInfo.InvariantCulture, out var goodsId) || goodsId <= 0)
throw new AppException("商品编号必须是正整数", ResultCode.ValidationError);
var userName = request.UserName.Trim();
await using var lease = await _indexLock.AcquireFavoritesAsync();
using var work = _favoriteRepository.Orm.CreateUnitOfWork();
work.GetOrBeginTransaction();
var favorite = await work.Orm.Select<UserGoodsFavoriteEntity>()
.Where(x => x.UserName == userName && x.GoodsId == goodsId).FirstAsync()
?? throw new AppException("该用户尚未收藏此商品", ResultCode.NotFound);
await work.Orm.Update<UserGoodsFavoriteEntity>().Set(x => x.IsSafe, request.IsSafe)
.Where(x => x.Id == favorite.Id).ExecuteAffrowsAsync();
// 重复上报也同步索引,索引明确失败时由工作单元回滚数据库。
await _indexService.UpdateSafetyAsync(UserFavoritesSearchDocument.BuildId(favorite.UserName, goodsId), request.IsSafe!.Value);
work.Commit();
}
/// <summary>
/// 批量取消收藏:先删除数据库记录,再删除索引文档;
/// 索引删除失败时回补数据库记录,避免“库里有收藏但搜索不到”。
@@ -229,6 +265,7 @@ namespace Store.Modules.CloudProduct.Services
throw new AppException("请提供要取消收藏的商品编号", ResultCode.ValidationError);
}
await using var lease = await _indexLock.AcquireFavoritesAsync();
var favorites = await _favoriteRepository.Select
.Where(x => x.UserName == userName && goodsIds.Contains(x.GoodsId))
.ToListAsync();
@@ -404,8 +441,8 @@ namespace Store.Modules.CloudProduct.Services
{
throw new AppException("用户名不能为空", ResultCode.ValidationError);
}
request.UserName = userName;
var mainUser = await _queryService.GetMainUser(userName);
request.UserName = mainUser.UserName;
var searchResult = await _indexService.SearchAsync(request, ParseSortBy(request.SortBy));
var list = searchResult.Documents.Select(ToItem).ToList();
@@ -417,6 +454,7 @@ namespace Store.Modules.CloudProduct.Services
/// </summary>
public async Task<long> RebuildSearchIndexAsync()
{
await using var lease = await _indexLock.AcquireFavoritesAsync();
// 1. 删除并重建索引(清空所有用户收藏索引)
await _indexService.ClearIndexAsync();
@@ -546,6 +584,7 @@ namespace Store.Modules.CloudProduct.Services
{
Id = UserFavoritesSearchDocument.BuildId(favorite.UserName, favorite.GoodsId),
FavId = favorite.Id,
IsSafe = favorite.IsSafe,
UserName = favorite.UserName,
GroupId = favorite.GroupId,
GroupName = groupName,
@@ -568,6 +607,7 @@ namespace Store.Modules.CloudProduct.Services
return new UserFavoriteItem
{
Id = document.FavId,
IsSafe = document.IsSafe,
UserName = document.UserName,
GroupId = document.GroupId,
GroupName = document.GroupName,
@@ -11,8 +11,8 @@
<FrameworkReference Include="Microsoft.AspNetCore.App" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\Modules\Store.Plugins\Store.Plugins.csproj" />
<ProjectReference Include="..\..\Store.Framework\Store.Framework.csproj" />
<ProjectReference Include="..\..\Core\MAX.Plugins\MAX.Plugins.csproj" />
</ItemGroup>
+12 -1
View File
@@ -6,7 +6,7 @@
"FavoritesIndexName": "user_goods_favorites_search"
},
"RawData": {
"Path": "E:\\GoodsRawData"
"Path": "Z:\\GoodsRawData"
},
"Indexing": {
"Mode": "Background",
@@ -15,5 +15,16 @@
},
"Delete": {
"SoftDelete": true
},
"ImageAnalysisQuota": {
"Url": "http://localhost:9000", //http://119.45.29.75:9000
"APIKey": "e3b0c44298fc1c149afbf4c8996fb924"
},
"ProductInspection": {
"Endpoint": "https://llm-lq2jys2ky6yxo7rh.cn-beijing.maas.aliyuncs.com/compatible-mode/v1/chat/completions",
"Model": "qwen3.7-flash",
"ApiKey": "sk-fa7fbaa3bb4047928f30bf05ff52c03a",
"MaxConcurrentAnalysis": 5,
"ConnectionString": "Server=192.168.0.200;Port=3306;Database=product_inspection;Uid=root;Pwd=123456;Allow User Variables=true"
}
}
@@ -13,8 +13,7 @@ using System.Collections.Generic;
namespace KJD_Web.Controllers
{
[ApiVersionNeutral]
[Route("api/ImageCache/[action]")]
[Route("[controller]/[action]")]
public class ImageCacheController : AppControllerBase
{
private readonly ImageCacheService _imageCacheService;