工单 优化 ,增加图片

This commit is contained in:
chfei committed 2026-10-20 17:03:23 +08:00
1 parent bf5a70597c
commit cf2efbcb16
27 files changed
+3555 -1538

No files matched your search

+342 -20
View File
@@ -1,11 +1,14 @@
using AllBase;
using AllBase;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using OrderSupportTicket.Models;
using OrderSupportTicket.Models.Api;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using WxOrder.Framework.Commons;
@@ -19,6 +22,16 @@ public sealed class TicketApiService
{
internal static string ServerUrl = "https://ai.e57.cn";
private const string ApiRoot = "/api/open/v2/customer-work-orders";
/// <summary>
/// 每条留言最多可携带的图片数量。
/// </summary>
public const int MaxImageCount = 3;
/// <summary>
/// 单张图片允许的最大字节数(5 MiB)。
/// </summary>
public const long MaxImageBytes = 5 * 1024 * 1024;
private static readonly Regex AppIdRegex =
new Regex(@"^wx[0-9a-f]{16}$", RegexOptions.Compiled | RegexOptions.CultureInvariant);
private static readonly Regex OrderIdRegex =
@@ -27,6 +40,14 @@ public sealed class TicketApiService
new Regex(@"^[\p{L}\p{N}_.@-]{2,120}$", RegexOptions.Compiled);
private static readonly Regex OperationIdRegex =
new Regex(@"^[A-Za-z0-9_.:-]{1,128}$", RegexOptions.Compiled | RegexOptions.CultureInvariant);
private static readonly HashSet<string> SupportedImageMimeTypes =
new HashSet<string>(StringComparer.OrdinalIgnoreCase)
{
"image/jpeg",
"image/png",
"image/webp"
};
private static readonly HttpClient ImageUploadClient = CreateImageUploadClient();
internal static readonly JsonSerializerSettings JsonSettings = new JsonSerializerSettings
{
NullValueHandling = NullValueHandling.Ignore,
@@ -158,22 +179,25 @@ public sealed class TicketApiService
TicketClientOptions options,
WorkOrderSummaryDto workOrder,
string text,
string clientMessageId)
string clientMessageId,
IList<MessageAttachmentReceipt> attachments = null)
{
ValidateOptions(options);
if (workOrder == null)
throw new ArgumentNullException(nameof(workOrder));
ValidateAppId(workOrder.AppId);
ValidateWechatOrderId(workOrder.WechatOrderId);
ValidateMessageText(text);
ValidateMessageContent(text, attachments);
ValidateOperationId(clientMessageId, "clientMessageId", required: true);
var hasAttachments = attachments != null && attachments.Count > 0;
var request = new SendMessageRequest
{
PurchaseAccount = options.UserName,
AppId = workOrder.AppId,
ClientMessageId = clientMessageId,
Text = text
Text = string.IsNullOrWhiteSpace(text) ? null : text,
Attachments = hasAttachments ? attachments.ToList() : null
};
var path = ApiRoot
+ "/orders/"
@@ -182,6 +206,139 @@ public sealed class TicketApiService
return await PostAsync<SendMessageResponse>(path, request);
}
/// <summary>
/// 申请单张图片的短时直传凭证。每张图片单独申请。
/// </summary>
public async Task<ImageUploadTicketResponse> CreateImageUploadTicketAsync(
TicketClientOptions options,
string appId,
string wechatOrderId,
string fileName,
string mimeType,
long size,
string requestId = null)
{
ValidateOptions(options);
ValidateAppId(appId);
ValidateWechatOrderId(wechatOrderId);
var normalizedFileName = ValidateImageFileName(fileName);
var normalizedMimeType = ValidateImageMimeType(mimeType);
ValidateImageSize(size);
ValidateOperationId(requestId, "requestId", required: false);
var request = new CreateImageUploadTicketRequest
{
PurchaseAccount = options.UserName,
AppId = appId,
FileName = normalizedFileName,
MimeType = normalizedMimeType,
Size = size,
RequestId = string.IsNullOrWhiteSpace(requestId) ? null : requestId
};
var path = ApiRoot
+ "/orders/"
+ Uri.EscapeDataString(wechatOrderId)
+ "/message-attachments/upload-ticket";
var response = await PostAsync<ImageUploadTicketResponse>(path, request);
ValidateImageUploadTicket(response?.Upload);
return response;
}
/// <summary>
/// 使用服务端签发的凭证把图片二进制直接 PUT 到 COS。
/// 返回的 requestId/ticket/etag 需原样提交到留言接口。
/// </summary>
public async Task<MessageAttachmentReceipt> UploadImageAsync(
ImageUploadTicketDto upload,
string filePath)
{
ValidateImageUploadTicket(upload);
if (string.IsNullOrWhiteSpace(filePath))
throw new ArgumentException("图片文件路径不能为空。", nameof(filePath));
byte[] bytes;
try
{
bytes = await Task.Run(() => File.ReadAllBytes(filePath)).ConfigureAwait(false);
}
catch (Exception ex) when (
ex is IOException
|| ex is UnauthorizedAccessException
|| ex is ArgumentException)
{
throw new ArgumentException("读取图片文件失败:" + ex.Message, nameof(filePath));
}
if (bytes.Length < 1 || bytes.Length > MaxImageBytes)
throw new ArgumentException("单张图片必须为 1 字节~5 MiB。", nameof(filePath));
var contentType = GetUploadHeader(upload.Headers, "Content-Type")
?? "application/octet-stream";
using (var request = new HttpRequestMessage(
new HttpMethod(upload.Method.ToUpperInvariant()),
upload.UploadUrl))
using (var content = new ByteArrayContent(bytes))
{
content.Headers.TryAddWithoutValidation("Content-Type", contentType);
foreach (var header in upload.Headers ?? new Dictionary<string, string>())
{
if (string.IsNullOrWhiteSpace(header.Key))
continue;
if (string.Equals(header.Key, "Content-Type", StringComparison.OrdinalIgnoreCase)
|| string.Equals(header.Key, "Content-Length", StringComparison.OrdinalIgnoreCase))
continue;
if (!request.Headers.TryAddWithoutValidation(header.Key, header.Value))
content.Headers.TryAddWithoutValidation(header.Key, header.Value);
}
request.Content = content;
HttpResponseMessage response;
try
{
response = await ImageUploadClient
.SendAsync(request)
.ConfigureAwait(false);
}
catch (Exception ex) when (
ex is HttpRequestException
|| ex is TaskCanceledException)
{
throw new TicketApiException(0, "图片直传网络异常,请稍后重试。");
}
using (response)
{
if (!response.IsSuccessStatusCode)
{
var statusCode = (int)response.StatusCode;
string body = null;
try
{
body = await response.Content
.ReadAsStringAsync()
.ConfigureAwait(false);
}
catch
{
// 存储端错误正文仅用于提取可读提示,失败时使用通用文案。
}
throw new TicketApiException(
statusCode,
ExtractUploadErrorMessage(body, statusCode));
}
var etag = response.Headers.TryGetValues("ETag", out var values)
? values.FirstOrDefault()
: null;
return new MessageAttachmentReceipt
{
RequestId = upload.RequestId,
Ticket = upload.Ticket,
Etag = string.IsNullOrWhiteSpace(etag) ? null : etag
};
}
}
}
public async Task MarkReadAsync(
TicketClientOptions options,
string appId,
@@ -342,25 +499,52 @@ public sealed class TicketApiService
return new TicketApiException(
ExtractStatusCode(responseBody),
message,
responseBody);
responseBody,
ExtractErrorCode(responseBody));
}
private static ApiErrorResponse ExtractErrorResponse(string responseBody)
{
if (string.IsNullOrWhiteSpace(responseBody))
return null;
try
{
return JsonConvert.DeserializeObject<ApiErrorResponse>(responseBody, JsonSettings);
}
catch (JsonException)
{
return null;
}
}
private static string ExtractErrorCode(string responseBody)
{
return ExtractErrorResponse(responseBody)?.Code;
}
private static int ExtractStatusCode(string responseBody)
{
if (string.IsNullOrWhiteSpace(responseBody))
var error = ExtractErrorResponse(responseBody);
if (error == null || string.IsNullOrWhiteSpace(error.Code))
return 0;
if (int.TryParse(error.Code, out var code))
return code;
try
switch (error.Code.Trim().ToLowerInvariant())
{
var error = JsonConvert.DeserializeObject<ApiErrorResponse>(responseBody, JsonSettings);
if (error != null && int.TryParse(error.Code, out var code))
return code;
case "client_api_image_expired":
return 410;
case "client_api_image_already_used":
return 409;
case "client_api_image_invalid":
return 422;
case "client_api_image_upload_failed":
return 400;
case "client_api_images_unavailable":
return 503;
default:
return 0;
}
catch (JsonException)
{
// GetHtml 在网络异常时会返回普通错误文本,此时没有 HTTP 状态码。
}
return 0;
}
private static List<string> NormalizeAppIds(IEnumerable<string> appIds)
@@ -389,14 +573,152 @@ public sealed class TicketApiService
}
}
private static void ValidateMessageText(string text)
private static void ValidateMessageContent(
string text,
IList<MessageAttachmentReceipt> attachments)
{
if (string.IsNullOrWhiteSpace(text)
|| text.Length < 1
|| text.Length > 4000)
var attachmentCount = attachments?.Count ?? 0;
if (attachmentCount > MaxImageCount)
{
throw new ArgumentException("text 必须为 1~4000 字。", nameof(text));
throw new ArgumentException(
"每条留言最多提交 " + MaxImageCount + " 张图片。",
nameof(attachments));
}
if (attachmentCount > 0)
ValidateAttachmentReceipts(attachments);
if (!string.IsNullOrWhiteSpace(text))
{
if (text.Length > 4000)
throw new ArgumentException("text 不能超过 4000 字。", nameof(text));
}
else if (attachmentCount == 0)
{
throw new ArgumentException("text 与图片附件不能同时为空。", nameof(text));
}
}
private static void ValidateAttachmentReceipts(
IList<MessageAttachmentReceipt> attachments)
{
var requestIds = new HashSet<string>(StringComparer.Ordinal);
foreach (var attachment in attachments)
{
if (attachment == null
|| string.IsNullOrWhiteSpace(attachment.RequestId)
|| !OperationIdRegex.IsMatch(attachment.RequestId)
|| string.IsNullOrWhiteSpace(attachment.Ticket))
{
throw new ArgumentException(
"图片上传回执不完整或 requestId 格式不正确。",
nameof(attachments));
}
if (!requestIds.Add(attachment.RequestId))
throw new ArgumentException("图片上传回执不能重复。", nameof(attachments));
}
}
private static string ValidateImageFileName(string fileName)
{
var normalized = (fileName ?? string.Empty).Trim();
if (normalized.Length < 1
|| normalized.Length > 180
|| normalized.Any(char.IsControl)
|| normalized.IndexOfAny(new[] { '/', '\\' }) >= 0)
{
throw new ArgumentException(
"fileName 必须为 1~180 字符且不能包含路径分隔符或控制字符。",
nameof(fileName));
}
return normalized;
}
private static string ValidateImageMimeType(string mimeType)
{
var normalized = (mimeType ?? string.Empty).Trim().ToLowerInvariant();
if (!SupportedImageMimeTypes.Contains(normalized))
{
throw new ArgumentException(
"mimeType 仅支持 image/jpeg、image/png 或 image/webp。",
nameof(mimeType));
}
return normalized;
}
private static void ValidateImageSize(long size)
{
if (size < 1 || size > MaxImageBytes)
{
throw new ArgumentException(
"单张图片必须为 1 字节~5 MiB。",
nameof(size));
}
}
private static void ValidateImageUploadTicket(ImageUploadTicketDto upload)
{
if (upload == null
|| string.IsNullOrWhiteSpace(upload.RequestId)
|| string.IsNullOrWhiteSpace(upload.Ticket)
|| string.IsNullOrWhiteSpace(upload.UploadUrl)
|| string.IsNullOrWhiteSpace(GetUploadHeader(upload.Headers, "Content-Type"))
|| !string.Equals(upload.Method, "PUT", StringComparison.OrdinalIgnoreCase))
{
throw new TicketApiException(0, "服务端返回的图片上传凭证不完整。");
}
if (!Uri.TryCreate(upload.UploadUrl, UriKind.Absolute, out var uri)
|| (uri.Scheme != Uri.UriSchemeHttps && uri.Scheme != Uri.UriSchemeHttp))
{
throw new TicketApiException(0, "服务端返回的图片上传地址无效。");
}
}
private static string GetUploadHeader(
IDictionary<string, string> headers,
string name)
{
if (headers == null)
return null;
foreach (var header in headers)
{
if (string.Equals(header.Key, name, StringComparison.OrdinalIgnoreCase))
return header.Value;
}
return null;
}
private static string ExtractUploadErrorMessage(
string body,
int statusCode)
{
var error = ExtractErrorResponse(body);
if (!string.IsNullOrWhiteSpace(error?.Message))
return error.Message;
if (!string.IsNullOrWhiteSpace(error?.Error))
return error.Error;
if (statusCode == 403)
return "图片上传地址已失效或无权访问,请重新选择图片后发送。";
return "图片直传失败(HTTP " + statusCode + "),请重试。";
}
private static HttpClient CreateImageUploadClient()
{
try
{
ServicePointManager.SecurityProtocol |= SecurityProtocolType.Tls12;
}
catch
{
// 旧系统不支持显式 TLS 1.2 时保留运行时默认值。
}
return new HttpClient(new HttpClientHandler
{
UseProxy = false
})
{
Timeout = TimeSpan.FromSeconds(120)
};
}
private static void ValidateOperationId(