场景:查询机 A 和打包仓库 B 在不同网络,B 没有公网 IP。 B 只能主动出站,所以云端从不反向连它 —— 复用设备出站链路做任务通道。 云端(backend) - 新增 edge_task 服务:Redis List 做队列、短 TTL 存结果, 多实例共享,不依赖 sticky session - POST /api/scanner/tasks/poll:设备长轮询领任务(挂 20 秒, 有任务立刻返回,没任务 204) - POST /api/scanner/tasks/:id/result:设备回结果 - POST /api/web/edge/check:查询机问「这段有没有录像」, 云端按主体选出在线扫码服务 → 下发 check → 等结果(默认 8 秒) - 不阻塞共享 Redis 连接:任务用短间隔轮询而非 BLPOP (egg-redis 是共享连接,阻塞命令会卡住其它请求) 桌面端(desktop) - AgentHost 新增边缘任务循环:长轮询领任务 → 交 worker 执行 → 回结果, 与扫码链路完全解耦,异常只退避重试 - worker 新增 check 能力(复用 HikPlaybackService.CheckAsync) - ApiClient 长轮询单独用不限时客户端(共享 HttpClient 的 15 秒超时会掐断) 三级降级(桌面端校验) 1. 局域网有设备管理服务 → 交给它(共用 NVR 会话池) 2. 没有 → 问云端;云端确认有录像时**隐藏预览、只显示下载** (跨网拉流成本高,短片段/下载更合适) 3. 云端也判断不了 → 本机自己校验(仓库内操作员的常规路径) 实测(真实 NVR 192.168.8.241 通道 34) 设备心跳 → 领任务 → worker 校验 → 回结果 → 网页拿到结论 端到端 2.17 秒(其中 NVR 拉流约 2 秒) Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
899 lines
40 KiB
C#
899 lines
40 KiB
C#
using System;
|
||
using System.Collections.Generic;
|
||
using System.Net;
|
||
using System.Net.Http;
|
||
using System.Text;
|
||
using System.Text.Json;
|
||
using System.Threading;
|
||
using System.Threading.Tasks;
|
||
|
||
namespace YuncangTrace.LocalService.Services;
|
||
|
||
/// <summary>接口调用失败(能拿到后端的 message 就透出去)</summary>
|
||
public sealed class ApiException : Exception
|
||
{
|
||
public ApiException(string message, int statusCode = 0, string? status = null, DateTimeOffset? expireAt = null)
|
||
: base(message)
|
||
{
|
||
StatusCode = statusCode;
|
||
Status = status;
|
||
ExpireAt = expireAt;
|
||
}
|
||
|
||
/// <summary>HTTP 状态码(网络层失败为 0)</summary>
|
||
public int StatusCode { get; }
|
||
|
||
/// <summary>后端 envelope 里的 `status`(如 `subject_expired` / `subject_disabled`)</summary>
|
||
public string? Status { get; }
|
||
|
||
/// <summary>主体到期时间(仅 `subject_expired` 时有)</summary>
|
||
public DateTimeOffset? ExpireAt { get; }
|
||
|
||
/// <summary>主体已过期:上报循环应暂停,等心跳探测到续期后再恢复</summary>
|
||
public bool IsSubjectExpired => Status == "subject_expired";
|
||
|
||
/// <summary>主体不可用(过期 / 停用 / 被删):都不该继续上报</summary>
|
||
public bool IsSubjectUnavailable => Status is "subject_expired" or "subject_disabled" or "subject_missing";
|
||
}
|
||
|
||
/// <summary>登录用户(后端 `/api/web/auth/login` 返回的 user 子集)</summary>
|
||
public sealed record ApiUser(int Id, string? Username, string? Nickname)
|
||
{
|
||
/// <summary>界面显示名</summary>
|
||
public string DisplayName =>
|
||
!string.IsNullOrWhiteSpace(Nickname) ? Nickname!
|
||
: !string.IsNullOrWhiteSpace(Username) ? Username!
|
||
: $"#{Id}";
|
||
}
|
||
|
||
/// <summary>主体(租户)</summary>
|
||
public sealed record ApiSubject(int Id, string Name, string? ExpireAt, bool Expired, int Role, int MemberCount, string? MemberName)
|
||
{
|
||
/// <summary>1 = 管理员(只有管理员能看到 / 使用「开启设备服务」)</summary>
|
||
public bool IsAdmin => Role == 1;
|
||
|
||
/// <summary>下拉/列表里的显示文案</summary>
|
||
public string Display => Expired ? $"{Name}(已到期)" : Name;
|
||
}
|
||
|
||
/// <summary>登录结果:会话 + 用户 + 可进入的主体列表(后端登录接口一起下发)</summary>
|
||
public sealed record LoginResult(Session Session, ApiUser User, IReadOnlyList<ApiSubject> Subjects);
|
||
|
||
/// <summary>微信扫码登录:发码结果</summary>
|
||
public sealed record WechatTicket(string Code, string QrUrl);
|
||
|
||
/// <summary>微信扫码登录:轮询结果</summary>
|
||
public sealed record WechatPollResult(string Status, Session? Session, ApiUser? User, string? Code, string? QrUrl, IReadOnlyList<ApiSubject> Subjects);
|
||
|
||
/// <summary>本机设备(scanners 表的一行,够桌面端展示用)</summary>
|
||
public sealed record ApiDevice(int Id, string Sn, string? Name, string? LastSeenAt);
|
||
|
||
/// <summary>录像机登录凭据(**含明文密码**,只在内存里用,别落盘/别打日志)</summary>
|
||
public sealed record NvrCredential(int Id, string Name, string Host, int Port, string Username, string Password);
|
||
|
||
/// <summary>录像机(列表用,不含密码)</summary>
|
||
public sealed record ApiNvr(int Id, string Name, string Host, int Port, string? SerialNumber);
|
||
|
||
/// <summary>摄像头 = 录像机上的一个通道(校时按 <see cref="ChannelNo"/> 走)</summary>
|
||
public sealed record ApiCamera(int Id, int ChannelNo, string Name, string? ChannelName)
|
||
{
|
||
/// <summary>界面显示名</summary>
|
||
public string Display => string.IsNullOrWhiteSpace(Name)
|
||
? (string.IsNullOrWhiteSpace(ChannelName) ? $"通道{ChannelNo}" : ChannelName!)
|
||
: Name;
|
||
}
|
||
|
||
/// <summary>激活设备服务的结果</summary>
|
||
public sealed record DeviceActivation(
|
||
int Id,
|
||
string Sn,
|
||
string? Name,
|
||
string Token,
|
||
string TokenType,
|
||
string? ExpiresIn,
|
||
bool FirstTime,
|
||
IReadOnlyList<ApiDevice> Kicked,
|
||
string RefreshToken,
|
||
string? RefreshExpiresIn);
|
||
|
||
/// <summary>刷新设备令牌的结果</summary>
|
||
public sealed record DeviceTokenRefresh(
|
||
string Sn,
|
||
string Token,
|
||
string TokenType,
|
||
string? ExpiresIn,
|
||
string RefreshToken,
|
||
string? RefreshExpiresIn);
|
||
|
||
/// <summary>设备所属主体状态(心跳返回;`Expired` 由服务端按缓存计算,客户端不要用本地时间判断)</summary>
|
||
public sealed record DeviceSubjectState(
|
||
int Id,
|
||
string? Name,
|
||
int Status,
|
||
DateTimeOffset? ExpireAt,
|
||
bool Expired,
|
||
bool Disabled,
|
||
long? RemainingSeconds);
|
||
|
||
/// <summary>设备心跳结果:保活信息 + 主体租约状态</summary>
|
||
public sealed record DeviceHeartbeat(
|
||
string? Sn,
|
||
DateTimeOffset? LastSeenAt,
|
||
DateTimeOffset? ServerTime,
|
||
DeviceSubjectState? Subject);
|
||
|
||
/// <summary>
|
||
/// 后端接口客户端(登录 / 主体 / 设备服务 / 上报)
|
||
///
|
||
/// 契约见 backend/README:成功 `{ ok:true, data }`,失败 `{ ok:false, message }`。
|
||
/// 业务接口除了 `Authorization` 还要带 `X-Subject-Id`(主体范围)。
|
||
/// </summary>
|
||
public sealed class ApiClient
|
||
{
|
||
private static readonly HttpClient Http = new() { Timeout = TimeSpan.FromSeconds(15) };
|
||
|
||
/// <summary>长轮询专用:挂起时间比 15 秒长,必须用不限时的客户端</summary>
|
||
private static readonly HttpClient LongPollHttp = new() { Timeout = Timeout.InfiniteTimeSpan };
|
||
|
||
private static readonly JsonSerializerOptions Json = new()
|
||
{
|
||
Encoder = System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping,
|
||
};
|
||
|
||
public ApiClient(string serverBaseUrl)
|
||
{
|
||
BaseUrl = AppSettings.Normalize(serverBaseUrl);
|
||
}
|
||
|
||
/// <summary>后端根地址(已去掉末尾斜杠)</summary>
|
||
public string BaseUrl { get; }
|
||
|
||
// ==================== 登录 ====================
|
||
|
||
/// <summary>账号密码登录(`POST /api/web/auth/login`),返回令牌 + 用户 + 主体列表</summary>
|
||
/// <exception cref="ApiException">账号密码错 / 网络不通 / 返回格式不对</exception>
|
||
public async Task<LoginResult> LoginAsync(string account, string password, CancellationToken ct = default)
|
||
{
|
||
var body = JsonSerializer.Serialize(new { account, password }, Json);
|
||
|
||
using var content = new StringContent(body, Encoding.UTF8, "application/json");
|
||
using var response = await SendAsync(
|
||
() => new HttpRequestMessage(HttpMethod.Post, $"{BaseUrl}/api/web/auth/login") { Content = content },
|
||
"登录", ct).ConfigureAwait(false);
|
||
|
||
var text = await response.Content.ReadAsStringAsync(ct).ConfigureAwait(false);
|
||
var (data, message) = ReadEnvelope(response, text);
|
||
if (data is null) throw Failure(response, text, message);
|
||
|
||
var token = GetString(data.Value, "token") ?? throw new ApiException("登录返回里没有令牌");
|
||
var user = ReadUser(data.Value);
|
||
var subjects = ReadSubjects(data.Value, "subjects");
|
||
|
||
var session = new Session
|
||
{
|
||
Token = token,
|
||
UserId = user.Id,
|
||
DisplayName = user.DisplayName,
|
||
ServerBaseUrl = BaseUrl,
|
||
};
|
||
return new LoginResult(session, user, subjects);
|
||
}
|
||
|
||
/// <summary>微信扫码登录:发一个码(`GET /api/wechat/login`,无需令牌)</summary>
|
||
public async Task<WechatTicket> StartWechatLoginAsync(CancellationToken ct = default)
|
||
{
|
||
using var response = await SendAsync(
|
||
() => new HttpRequestMessage(HttpMethod.Get, $"{BaseUrl}/api/wechat/login"),
|
||
"生成登录二维码", ct).ConfigureAwait(false);
|
||
|
||
var text = await response.Content.ReadAsStringAsync(ct).ConfigureAwait(false);
|
||
var (data, message) = ReadEnvelope(response, text);
|
||
if (data is null) throw Failure(response, text, message);
|
||
|
||
var code = GetString(data.Value, "code") ?? throw new ApiException("没有拿到登录码");
|
||
var qrUrl = GetString(data.Value, "qrUrl") ?? $"/api/wechat/qrcode.svg?code={code}";
|
||
return new WechatTicket(code, qrUrl);
|
||
}
|
||
|
||
/// <summary>微信扫码登录:轮询一次(`GET /api/wechat/login?code=&wait=`)</summary>
|
||
public async Task<WechatPollResult> PollWechatLoginAsync(string code, int waitSeconds, CancellationToken ct = default)
|
||
{
|
||
var url = $"{BaseUrl}/api/wechat/login?code={Uri.EscapeDataString(code)}&wait={waitSeconds}";
|
||
using var response = await SendAsync(
|
||
() => new HttpRequestMessage(HttpMethod.Get, url), "等待扫码", ct).ConfigureAwait(false);
|
||
|
||
var text = await response.Content.ReadAsStringAsync(ct).ConfigureAwait(false);
|
||
var (data, message) = ReadEnvelope(response, text);
|
||
if (data is null) throw Failure(response, text, message);
|
||
|
||
var status = GetString(data.Value, "status") ?? "pending";
|
||
if (status != "confirmed")
|
||
{
|
||
return new WechatPollResult(status, null, null, GetString(data.Value, "code"), GetString(data.Value, "qrUrl"),
|
||
Array.Empty<ApiSubject>());
|
||
}
|
||
|
||
var token = GetString(data.Value, "token") ?? throw new ApiException("扫码确认了但没有令牌");
|
||
var user = ReadUser(data.Value);
|
||
var session = new Session
|
||
{
|
||
Token = token,
|
||
UserId = user.Id,
|
||
DisplayName = user.DisplayName,
|
||
ServerBaseUrl = BaseUrl,
|
||
};
|
||
return new WechatPollResult(status, session, user, null, null, Array.Empty<ApiSubject>());
|
||
}
|
||
|
||
/// <summary>拉图片字节(二维码用;`qrcode.gif` 返回 GIF,WPF 能直接显示)</summary>
|
||
public async Task<byte[]> GetImageAsync(string urlOrPath, CancellationToken ct = default)
|
||
{
|
||
var url = urlOrPath.StartsWith("http", StringComparison.OrdinalIgnoreCase)
|
||
? urlOrPath
|
||
: $"{BaseUrl}{urlOrPath}";
|
||
|
||
using var response = await SendAsync(() => new HttpRequestMessage(HttpMethod.Get, url), "下载二维码", ct)
|
||
.ConfigureAwait(false);
|
||
if (!response.IsSuccessStatusCode)
|
||
{
|
||
throw new ApiException($"二维码下载失败(HTTP {(int)response.StatusCode})", (int)response.StatusCode);
|
||
}
|
||
return await response.Content.ReadAsByteArrayAsync(ct).ConfigureAwait(false);
|
||
}
|
||
|
||
/// <summary>校验令牌是否还有效(`GET /api/web/me`)</summary>
|
||
/// <returns>令牌有效返回用户;**401/403 返回 null**(真失效,调用方可以清掉本地令牌)</returns>
|
||
public async Task<ApiUser?> MeAsync(string token, CancellationToken ct = default)
|
||
{
|
||
using var response = await SendAsync(() =>
|
||
{
|
||
var request = new HttpRequestMessage(HttpMethod.Get, $"{BaseUrl}/api/web/me");
|
||
request.Headers.TryAddWithoutValidation("Authorization", $"Bearer {token}");
|
||
return request;
|
||
}, "校验登录态", ct).ConfigureAwait(false);
|
||
|
||
if (response.StatusCode is HttpStatusCode.Unauthorized or HttpStatusCode.Forbidden) return null;
|
||
if (!response.IsSuccessStatusCode)
|
||
{
|
||
throw new ApiException($"校验登录态失败(HTTP {(int)response.StatusCode})", (int)response.StatusCode);
|
||
}
|
||
|
||
var text = await response.Content.ReadAsStringAsync(ct).ConfigureAwait(false);
|
||
var (data, _) = ReadEnvelope(response, text);
|
||
return data is null ? null : ReadUser(data.Value);
|
||
}
|
||
|
||
// ==================== 主体 ====================
|
||
|
||
/// <summary>我可进入的主体列表(`GET /api/web/subjects`)</summary>
|
||
public async Task<IReadOnlyList<ApiSubject>> SubjectsAsync(string token, CancellationToken ct = default)
|
||
{
|
||
using var response = await SendAuthorizedAsync(HttpMethod.Get, "/api/web/subjects", token, 0, null, "读取主体", ct)
|
||
.ConfigureAwait(false);
|
||
|
||
var text = await response.Content.ReadAsStringAsync(ct).ConfigureAwait(false);
|
||
var (data, message) = ReadEnvelope(response, text);
|
||
if (data is null) throw Failure(response, text, message);
|
||
return ReadSubjects(data.Value, "list");
|
||
}
|
||
|
||
// ==================== 设备服务(本机作为扫码中控) ====================
|
||
|
||
/// <summary>本主体已绑定的设备(开启前检查用;`GET /api/web/devices/active`)</summary>
|
||
public async Task<IReadOnlyList<ApiDevice>> DevicesAsync(string token, int subjectId, CancellationToken ct = default)
|
||
{
|
||
using var response = await SendAuthorizedAsync(HttpMethod.Get, "/api/web/devices/active", token, subjectId, null,
|
||
"读取设备", ct).ConfigureAwait(false);
|
||
|
||
var text = await response.Content.ReadAsStringAsync(ct).ConfigureAwait(false);
|
||
var (data, message) = ReadEnvelope(response, text);
|
||
if (data is null) throw Failure(response, text, message);
|
||
|
||
var devices = new List<ApiDevice>();
|
||
if (data.Value.TryGetProperty("list", out var list) && list.ValueKind == JsonValueKind.Array)
|
||
{
|
||
foreach (var item in list.EnumerateArray())
|
||
{
|
||
devices.Add(new ApiDevice(
|
||
GetInt(item, "id"),
|
||
GetString(item, "sn") ?? string.Empty,
|
||
GetString(item, "name"),
|
||
GetString(item, "lastSeenAt")));
|
||
}
|
||
}
|
||
return devices;
|
||
}
|
||
|
||
/// <summary>
|
||
/// 开启设备服务(`POST /api/web/devices/activate`,**仅主体管理员**)
|
||
///
|
||
/// 服务端保证「一个主体只有一台设备在线」:同主体其他设备的令牌会被作废(踢下线)。
|
||
/// </summary>
|
||
public async Task<DeviceActivation> ActivateDeviceAsync(
|
||
string token, int subjectId, string sn, string name, CancellationToken ct = default)
|
||
{
|
||
var payload = JsonSerializer.Serialize(new { sn, name }, Json);
|
||
using var response = await SendAuthorizedAsync(HttpMethod.Post, "/api/web/devices/activate", token, subjectId,
|
||
payload, "开启设备服务", ct).ConfigureAwait(false);
|
||
|
||
var text = await response.Content.ReadAsStringAsync(ct).ConfigureAwait(false);
|
||
var (data, message) = ReadEnvelope(response, text);
|
||
if (data is null) throw Failure(response, text, message);
|
||
|
||
var kicked = new List<ApiDevice>();
|
||
if (data.Value.TryGetProperty("kicked", out var kickedElement) && kickedElement.ValueKind == JsonValueKind.Array)
|
||
{
|
||
foreach (var item in kickedElement.EnumerateArray())
|
||
{
|
||
kicked.Add(new ApiDevice(GetInt(item, "id"), GetString(item, "sn") ?? string.Empty,
|
||
GetString(item, "name"), null));
|
||
}
|
||
}
|
||
|
||
return new DeviceActivation(
|
||
GetInt(data.Value, "id"),
|
||
GetString(data.Value, "sn") ?? sn,
|
||
GetString(data.Value, "name"),
|
||
GetString(data.Value, "token") ?? throw new ApiException("开启成功但没拿到设备令牌"),
|
||
GetString(data.Value, "tokenType") ?? "Bearer",
|
||
GetString(data.Value, "expiresIn"),
|
||
data.Value.TryGetProperty("firstTime", out var first) && first.ValueKind == JsonValueKind.True,
|
||
kicked,
|
||
GetString(data.Value, "refreshToken") ?? string.Empty,
|
||
GetString(data.Value, "refreshExpiresIn"));
|
||
}
|
||
|
||
/// <summary>
|
||
/// 用刷新令牌换新的设备访问令牌(`POST /api/device/refresh`,无需用户登录)
|
||
///
|
||
/// 后台服务在访问令牌快到期/已 401 时调用;成功后**刷新令牌也会轮换**,必须覆盖保存。
|
||
/// </summary>
|
||
public async Task<DeviceTokenRefresh> RefreshDeviceTokenAsync(string sn, string refreshToken,
|
||
CancellationToken ct = default)
|
||
{
|
||
var payload = JsonSerializer.Serialize(new { sn, refreshToken }, Json);
|
||
using var response = await SendAsync(() =>
|
||
{
|
||
var request = new HttpRequestMessage(HttpMethod.Post, $"{BaseUrl}/api/device/refresh");
|
||
request.Content = new StringContent(payload, Encoding.UTF8, "application/json");
|
||
return request;
|
||
}, "刷新设备令牌", ct).ConfigureAwait(false);
|
||
|
||
var text = await response.Content.ReadAsStringAsync(ct).ConfigureAwait(false);
|
||
var (data, message) = ReadEnvelope(response, text);
|
||
if (data is null) throw Failure(response, text, message);
|
||
|
||
return new DeviceTokenRefresh(
|
||
GetString(data.Value, "sn") ?? sn,
|
||
GetString(data.Value, "token") ?? throw new ApiException("刷新成功但没拿到设备令牌"),
|
||
GetString(data.Value, "tokenType") ?? "Bearer",
|
||
GetString(data.Value, "expiresIn"),
|
||
GetString(data.Value, "refreshToken") ?? string.Empty,
|
||
GetString(data.Value, "refreshExpiresIn"));
|
||
}
|
||
|
||
/// <summary>关闭设备服务(`POST /api/web/devices/:id/logout` → 令牌作废)</summary>
|
||
public async Task DeactivateDeviceAsync(string token, int subjectId, int deviceId, CancellationToken ct = default)
|
||
{
|
||
using var response = await SendAuthorizedAsync(HttpMethod.Post, $"/api/web/devices/{deviceId}/logout", token,
|
||
subjectId, "{}", "关闭设备服务", ct).ConfigureAwait(false);
|
||
|
||
var text = await response.Content.ReadAsStringAsync(ct).ConfigureAwait(false);
|
||
var (data, message) = ReadEnvelope(response, text);
|
||
if (data is null) throw Failure(response, text, message);
|
||
}
|
||
|
||
/// <summary>
|
||
/// 设备心跳(`POST /api/scanner/heartbeat`):刷新服务端 `last_seen_at`,
|
||
/// 同时带回主体状态(`subject.expired`),上报循环据此暂停/恢复。
|
||
/// </summary>
|
||
public async Task<DeviceHeartbeat?> HeartbeatAsync(string deviceToken, CancellationToken ct = default)
|
||
{
|
||
using var response = await SendDeviceAsync("/api/scanner/heartbeat", deviceToken, "{}", "设备心跳", ct)
|
||
.ConfigureAwait(false);
|
||
|
||
var text = await response.Content.ReadAsStringAsync(ct).ConfigureAwait(false);
|
||
var (data, message) = ReadEnvelope(response, text);
|
||
if (data is null) throw Failure(response, text, message);
|
||
|
||
return new DeviceHeartbeat(
|
||
GetString(data.Value, "sn"),
|
||
GetDateTime(data.Value, "lastSeenAt"),
|
||
GetDateTime(data.Value, "serverTime"),
|
||
ReadSubjectState(data.Value));
|
||
}
|
||
|
||
/// <summary>云端校验结论</summary>
|
||
/// <param name="State">ok / no-plan / no-device / no-credential</param>
|
||
/// <param name="HasVideo">true/false 可用;null 表示云端也判断不了</param>
|
||
public sealed record EdgeCheckOutcome(string State, bool? HasVideo, string? Message, string? ScannerSn);
|
||
|
||
/// <summary>
|
||
/// 边缘任务(跨公司取流用):云端入队,设备主动出站领取
|
||
/// </summary>
|
||
/// <param name="Id">任务 id(回结果时带上)</param>
|
||
/// <param name="Type">check / download</param>
|
||
/// <param name="Payload">任务参数(原样交给 worker)</param>
|
||
public sealed record EdgeTask(string Id, string Type, JsonElement Payload);
|
||
|
||
/// <summary>
|
||
/// 领任务(长轮询)
|
||
///
|
||
/// ⚠️ 不能用共享的 <c>Http</c>:它的超时是 15 秒,会把 20 秒的长轮询直接掐断
|
||
/// (现象是"任务永远要等到下一轮才到")。这里单独用不限时的客户端。
|
||
/// </summary>
|
||
public async Task<EdgeTask?> PollEdgeTaskAsync(string deviceToken, int waitSeconds,
|
||
CancellationToken ct = default)
|
||
{
|
||
var wait = Math.Clamp(waitSeconds, 1, 25);
|
||
|
||
using var timeout = CancellationTokenSource.CreateLinkedTokenSource(ct);
|
||
timeout.CancelAfter(TimeSpan.FromSeconds(wait + 15));
|
||
|
||
using var request = new HttpRequestMessage(HttpMethod.Post,
|
||
$"{BaseUrl}/api/scanner/tasks/poll?wait={wait}");
|
||
request.Headers.TryAddWithoutValidation("Authorization", $"Bearer {deviceToken}");
|
||
|
||
HttpResponseMessage response;
|
||
try
|
||
{
|
||
response = await LongPollHttp.SendAsync(request, timeout.Token).ConfigureAwait(false);
|
||
}
|
||
catch (OperationCanceledException) when (!ct.IsCancellationRequested)
|
||
{
|
||
// 本次挂起被网络/反代掐断:当作"没有任务",下一轮再领
|
||
return null;
|
||
}
|
||
catch (HttpRequestException ex)
|
||
{
|
||
throw new ApiException($"无法连接服务器({BaseUrl}):{ex.Message}");
|
||
}
|
||
|
||
using (response)
|
||
{
|
||
if (response.StatusCode == HttpStatusCode.NoContent) return null;
|
||
|
||
var text = await response.Content.ReadAsStringAsync(ct).ConfigureAwait(false);
|
||
var (data, _) = ReadEnvelope(response, text);
|
||
if (data is null || data.Value.ValueKind != JsonValueKind.Object) return null;
|
||
|
||
var id = GetString(data.Value, "id");
|
||
var type = GetString(data.Value, "type");
|
||
if (string.IsNullOrWhiteSpace(id) || string.IsNullOrWhiteSpace(type)) return null;
|
||
|
||
var payload = data.Value.TryGetProperty("payload", out var element) ? element : default;
|
||
return new EdgeTask(id!, type!, payload);
|
||
}
|
||
}
|
||
|
||
/// <summary>
|
||
/// 回任务结果(失败不抛:结果丢了顶多让查询机超时,不该影响扫码链路)
|
||
/// </summary>
|
||
public async Task SubmitEdgeTaskResultAsync(string deviceToken, string taskId, object result,
|
||
CancellationToken ct = default)
|
||
{
|
||
try
|
||
{
|
||
var body = JsonSerializer.Serialize(result);
|
||
using var response = await SendDeviceAsync($"/api/scanner/tasks/{taskId}/result",
|
||
deviceToken, body, "回传边缘任务结果", ct).ConfigureAwait(false);
|
||
if (!response.IsSuccessStatusCode)
|
||
{
|
||
AppLog.Write($"[edge] 回传任务 {taskId} 结果失败:HTTP {(int)response.StatusCode}");
|
||
}
|
||
}
|
||
catch (Exception ex)
|
||
{
|
||
AppLog.Write($"[edge] 回传任务 {taskId} 结果异常:{ex.Message}");
|
||
}
|
||
}
|
||
|
||
/// <summary>解析心跳里的 `subject`(老服务端没有这个字段时返回 null)</summary>
|
||
private static DeviceSubjectState? ReadSubjectState(JsonElement data)
|
||
{
|
||
if (!data.TryGetProperty("subject", out var subject) || subject.ValueKind != JsonValueKind.Object) return null;
|
||
|
||
return new DeviceSubjectState(
|
||
GetInt(subject, "id"),
|
||
GetString(subject, "name"),
|
||
GetInt(subject, "status"),
|
||
GetDateTime(subject, "expireAt"),
|
||
subject.TryGetProperty("expired", out var expired) && expired.ValueKind == JsonValueKind.True,
|
||
subject.TryGetProperty("disabled", out var disabled) && disabled.ValueKind == JsonValueKind.True,
|
||
GetLong(subject, "remainingSeconds"));
|
||
}
|
||
|
||
/// <summary>
|
||
/// 上报通道(设备令牌;`POST /api/scan/channels`)。
|
||
/// `replace = true` = 全量对账:服务器会软删本中控下不在列表里的旧通道,并解绑工作台。
|
||
/// </summary>
|
||
public async Task ReportChannelsAsync(string deviceToken, IEnumerable<(string ChannelId, string ChannelName)> channels,
|
||
bool replace = false, CancellationToken ct = default)
|
||
{
|
||
var rows = new List<object>();
|
||
foreach (var (id, name) in channels) rows.Add(new { channelId = id, channelName = name });
|
||
|
||
var payload = JsonSerializer.Serialize(new { channels = rows, replace }, Json);
|
||
using var response = await SendDeviceAsync("/api/scan/channels", deviceToken, payload, "上报通道", ct)
|
||
.ConfigureAwait(false);
|
||
|
||
var text = await response.Content.ReadAsStringAsync(ct).ConfigureAwait(false);
|
||
var (data, message) = ReadEnvelope(response, text);
|
||
if (data is null) throw Failure(response, text, message);
|
||
}
|
||
|
||
/// <summary>上报一条扫码记录(设备令牌;`POST /api/scan/records`,服务端按 设备+通道+条码+秒 去重)</summary>
|
||
public Task ReportRecordAsync(string deviceToken, string channelId, string barcode, DateTime scanTime,
|
||
CancellationToken ct = default)
|
||
=> ReportRecordsAsync(deviceToken, new[] { (channelId, barcode, scanTime) }, ct);
|
||
|
||
/// <summary>
|
||
/// 批量上报扫码记录(设备令牌;`POST /api/scan/records`)。
|
||
///
|
||
/// 服务端按 **设备 + 通道 + 条码 + 扫描时间(秒)** 去重,重复上报只入库一次、不报错,
|
||
/// 所以断网重试时可以“整批重发”,不用担心重复落库。
|
||
/// </summary>
|
||
public async Task ReportRecordsAsync(string deviceToken,
|
||
IEnumerable<(string ChannelId, string Barcode, DateTime ScanTime)> records, CancellationToken ct = default)
|
||
{
|
||
var rows = new List<object>();
|
||
foreach (var (channelId, barcode, scanTime) in records)
|
||
{
|
||
rows.Add(new { channelId, barcode, scanTime = scanTime.ToString("yyyy-MM-dd HH:mm:ss") });
|
||
}
|
||
if (rows.Count == 0) return;
|
||
|
||
var payload = JsonSerializer.Serialize(new { records = rows }, Json);
|
||
using var response = await SendDeviceAsync("/api/scan/records", deviceToken, payload, "上报扫码记录", ct)
|
||
.ConfigureAwait(false);
|
||
|
||
var text = await response.Content.ReadAsStringAsync(ct).ConfigureAwait(false);
|
||
var (data, message) = ReadEnvelope(response, text);
|
||
if (data is null) throw Failure(response, text, message);
|
||
}
|
||
|
||
/// <summary>
|
||
/// 运单回放查询(**用户令牌**;`GET /api/web/pack-query?code=`)
|
||
///
|
||
/// 后端只返回**本主体**的扫码记录;data 里有:
|
||
/// `found` / `reason` / `hints` / `records`(每条带扫码当时的工作台快照与回放计划)/ `streams`(拍平去重)。
|
||
/// </summary>
|
||
/// <exception cref="ApiException">未登录 / 无权限 / 网络不通</exception>
|
||
public async Task<JsonElement> PackQueryAsync(string token, int subjectId, string code,
|
||
CancellationToken ct = default)
|
||
{
|
||
var path = $"/api/web/pack-query?code={Uri.EscapeDataString(code ?? string.Empty)}";
|
||
using var response = await SendAuthorizedAsync(HttpMethod.Get, path, token, subjectId, null, "查询运单回放", ct)
|
||
.ConfigureAwait(false);
|
||
|
||
var text = await response.Content.ReadAsStringAsync(ct).ConfigureAwait(false);
|
||
var (data, message) = ReadEnvelope(response, text);
|
||
if (data is null) throw Failure(response, text, message);
|
||
return data.Value;
|
||
}
|
||
|
||
/// <summary>
|
||
/// 问云端「这段录像有没有帧」(用户令牌;`POST /api/web/edge/check`)
|
||
///
|
||
/// 用在「本机局域网找不到设备管理服务」时:云端把问题转给能访问 NVR 的
|
||
/// 扫码服务,由它真拉一小段确认。返回 null 表示云端不可用(调用方自行降级)。
|
||
/// </summary>
|
||
public async Task<EdgeCheckOutcome?> EdgeCheckAsync(string token, int subjectId, string code,
|
||
CancellationToken ct = default)
|
||
{
|
||
using var response = await SendAuthorizedAsync(HttpMethod.Post, "/api/web/edge/check",
|
||
token, subjectId, JsonSerializer.Serialize(new { code }), "云端校验录像", ct).ConfigureAwait(false);
|
||
|
||
var text = await response.Content.ReadAsStringAsync(ct).ConfigureAwait(false);
|
||
var (data, _) = ReadEnvelope(response, text);
|
||
if (data is null || data.Value.ValueKind != JsonValueKind.Object) return null;
|
||
|
||
var root = data.Value;
|
||
var state = GetString(root, "state") ?? "";
|
||
bool? hasVideo = root.TryGetProperty("hasVideo", out var value)
|
||
? value.ValueKind switch
|
||
{
|
||
JsonValueKind.True => true,
|
||
JsonValueKind.False => false,
|
||
_ => null,
|
||
}
|
||
: null;
|
||
|
||
return new EdgeCheckOutcome(state, hasVideo, GetString(root, "message"), GetString(root, "scannerSn"));
|
||
}
|
||
|
||
/// <summary>
|
||
/// 取**当前主体**的全部录像机(用户令牌;`GET /api/web/nvrs`,自动翻页)。
|
||
/// 后端本来就按主体隔离,桌面端只需要拿列表 + 自己内网连设备。
|
||
/// </summary>
|
||
/// <exception cref="ApiException">未登录 / 无权限 / 网络不通</exception>
|
||
public async Task<IReadOnlyList<ApiNvr>> NvrsAsync(string token, int subjectId, CancellationToken ct = default)
|
||
{
|
||
var all = new List<ApiNvr>();
|
||
|
||
for (var page = 1; page <= 20; page++)
|
||
{
|
||
using var response = await SendAuthorizedAsync(HttpMethod.Get,
|
||
$"/api/web/nvrs?page={page}&pageSize=100", token, subjectId, null, "查录像机列表", ct)
|
||
.ConfigureAwait(false);
|
||
|
||
var text = await response.Content.ReadAsStringAsync(ct).ConfigureAwait(false);
|
||
var (data, message) = ReadEnvelope(response, text);
|
||
if (data is null) throw Failure(response, text, message);
|
||
|
||
if (!data.Value.TryGetProperty("list", out var list) || list.ValueKind != JsonValueKind.Array) break;
|
||
|
||
foreach (var item in list.EnumerateArray())
|
||
{
|
||
all.Add(new ApiNvr(
|
||
GetInt(item, "id"),
|
||
GetString(item, "name") ?? string.Empty,
|
||
GetString(item, "host") ?? string.Empty,
|
||
GetInt(item, "port"),
|
||
GetString(item, "serialNumber")));
|
||
}
|
||
|
||
if (list.GetArrayLength() < 100 || all.Count >= GetInt(data.Value, "total")) break;
|
||
}
|
||
|
||
return all;
|
||
}
|
||
|
||
/// <summary>
|
||
/// 取录像机登录凭据(**含明文密码**,用户令牌;`GET /api/web/nvrs/:id/credential`)
|
||
///
|
||
/// 后端只存密文、接口平时不返回密码;只有本机软件真正要去连设备时才现取一次。
|
||
/// </summary>
|
||
/// <exception cref="ApiException">不是本主体的 NVR / 网络不通</exception>
|
||
public async Task<NvrCredential> NvrCredentialAsync(string token, int subjectId, int nvrId,
|
||
CancellationToken ct = default)
|
||
{
|
||
using var response = await SendAuthorizedAsync(HttpMethod.Get, $"/api/web/nvrs/{nvrId}/credential",
|
||
token, subjectId, null, "取录像机凭据", ct).ConfigureAwait(false);
|
||
|
||
var text = await response.Content.ReadAsStringAsync(ct).ConfigureAwait(false);
|
||
var (data, message) = ReadEnvelope(response, text);
|
||
if (data is null) throw Failure(response, text, message);
|
||
|
||
return new NvrCredential(
|
||
GetInt(data.Value, "id"),
|
||
GetString(data.Value, "name") ?? string.Empty,
|
||
GetString(data.Value, "host") ?? string.Empty,
|
||
GetInt(data.Value, "port"),
|
||
GetString(data.Value, "username") ?? "admin",
|
||
GetString(data.Value, "password") ?? string.Empty);
|
||
}
|
||
|
||
/// <summary>
|
||
/// 取某台录像机下已导入的摄像头(用户令牌;`GET /api/web/nvrs/:id/channels`)。
|
||
///
|
||
/// 校时要按**通道号**逐个下发给 IPC,所以这里只关心 `channelNo`。
|
||
/// </summary>
|
||
public async Task<IReadOnlyList<ApiCamera>> CamerasOfNvrAsync(string token, int subjectId, int nvrId,
|
||
CancellationToken ct = default)
|
||
{
|
||
using var response = await SendAuthorizedAsync(HttpMethod.Get, $"/api/web/nvrs/{nvrId}/channels",
|
||
token, subjectId, null, "查摄像头列表", ct).ConfigureAwait(false);
|
||
|
||
var text = await response.Content.ReadAsStringAsync(ct).ConfigureAwait(false);
|
||
var (data, message) = ReadEnvelope(response, text);
|
||
if (data is null) throw Failure(response, text, message);
|
||
|
||
var result = new List<ApiCamera>();
|
||
if (!data.Value.TryGetProperty("list", out var list) || list.ValueKind != JsonValueKind.Array) return result;
|
||
|
||
foreach (var item in list.EnumerateArray())
|
||
{
|
||
result.Add(new ApiCamera(
|
||
GetInt(item, "id"),
|
||
GetInt(item, "channelNo"),
|
||
GetString(item, "name") ?? string.Empty,
|
||
GetString(item, "channelName")));
|
||
}
|
||
|
||
return result;
|
||
}
|
||
|
||
/// <summary>查服务器上当前中控已登记的通道(设备令牌;`GET /api/scan/channels`),返回 channelId 集合</summary>
|
||
public async Task<HashSet<string>> ChannelsAsync(string deviceToken, CancellationToken ct = default)
|
||
{
|
||
var result = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
|
||
|
||
using var response = await SendDeviceAsync(HttpMethod.Get, "/api/scan/channels?pageSize=200", deviceToken, null,
|
||
"查通道列表", ct).ConfigureAwait(false);
|
||
|
||
var text = await response.Content.ReadAsStringAsync(ct).ConfigureAwait(false);
|
||
var (data, message) = ReadEnvelope(response, text);
|
||
if (data is null) throw Failure(response, text, message);
|
||
|
||
if (data.Value.TryGetProperty("list", out var list) && list.ValueKind == JsonValueKind.Array)
|
||
{
|
||
foreach (var item in list.EnumerateArray())
|
||
{
|
||
var id = GetString(item, "channelId");
|
||
if (!string.IsNullOrWhiteSpace(id)) result.Add(id);
|
||
}
|
||
}
|
||
|
||
return result;
|
||
}
|
||
|
||
// ==================== 内部:请求 ====================
|
||
|
||
/// <summary>带用户令牌 + 主体 header 的请求</summary>
|
||
private Task<HttpResponseMessage> SendAuthorizedAsync(HttpMethod method, string path, string token, int subjectId,
|
||
string? jsonBody, string action, CancellationToken ct)
|
||
{
|
||
return SendAsync(() =>
|
||
{
|
||
var request = new HttpRequestMessage(method, $"{BaseUrl}{path}");
|
||
request.Headers.TryAddWithoutValidation("Authorization", $"Bearer {token}");
|
||
if (subjectId > 0) request.Headers.TryAddWithoutValidation("X-Subject-Id", subjectId.ToString());
|
||
if (jsonBody is not null) request.Content = new StringContent(jsonBody, Encoding.UTF8, "application/json");
|
||
return request;
|
||
}, action, ct);
|
||
}
|
||
|
||
/// <summary>带设备令牌的请求(POST,body 为 JSON)</summary>
|
||
private Task<HttpResponseMessage> SendDeviceAsync(string path, string deviceToken, string jsonBody, string action,
|
||
CancellationToken ct)
|
||
=> SendDeviceAsync(HttpMethod.Post, path, deviceToken, jsonBody, action, ct);
|
||
|
||
/// <summary>带设备令牌的请求(可指定方法;GET 时 jsonBody 传 null)</summary>
|
||
private Task<HttpResponseMessage> SendDeviceAsync(HttpMethod method, string path, string deviceToken,
|
||
string? jsonBody, string action, CancellationToken ct)
|
||
{
|
||
return SendAsync(() =>
|
||
{
|
||
var request = new HttpRequestMessage(method, $"{BaseUrl}{path}");
|
||
request.Headers.TryAddWithoutValidation("Authorization", $"Bearer {deviceToken}");
|
||
if (jsonBody is not null)
|
||
{
|
||
request.Content = new StringContent(jsonBody, Encoding.UTF8, "application/json");
|
||
}
|
||
return request;
|
||
}, action, ct);
|
||
}
|
||
|
||
/// <summary>发请求:连不上时翻成「无法连接服务器」这种能看懂的提示</summary>
|
||
private async Task<HttpResponseMessage> SendAsync(
|
||
Func<HttpRequestMessage> createRequest, string action, CancellationToken ct)
|
||
{
|
||
try
|
||
{
|
||
using var request = createRequest();
|
||
return await Http.SendAsync(request, ct).ConfigureAwait(false);
|
||
}
|
||
catch (TaskCanceledException)
|
||
{
|
||
throw new ApiException("连接服务器超时,请检查服务器地址或网络");
|
||
}
|
||
catch (HttpRequestException ex)
|
||
{
|
||
throw new ApiException($"无法连接服务器({BaseUrl}):{ex.Message}");
|
||
}
|
||
}
|
||
|
||
/// <summary>
|
||
/// 失败响应 → 异常:除 HTTP 状态码外,把 envelope 里的 `status` / `expireAt`
|
||
/// 一起带出来(上报循环据此区分「网络失败」与「主体过期」)。
|
||
/// </summary>
|
||
private static ApiException Failure(HttpResponseMessage response, string text, string message)
|
||
{
|
||
string? status = null;
|
||
DateTimeOffset? expireAt = null;
|
||
|
||
try
|
||
{
|
||
using var document = JsonDocument.Parse(string.IsNullOrWhiteSpace(text) ? "{}" : text);
|
||
status = GetString(document.RootElement, "status");
|
||
expireAt = GetDateTime(document.RootElement, "expireAt");
|
||
}
|
||
catch (JsonException)
|
||
{
|
||
// 非 JSON:只保留 HTTP 状态码与 message
|
||
}
|
||
|
||
return new ApiException(message, (int)response.StatusCode, status, expireAt);
|
||
}
|
||
|
||
/// <summary>解析 `{ ok, data, message }`:成功返回 data(JSON 片段),失败返回 message</summary>
|
||
private static (JsonElement? Data, string Message) ReadEnvelope(HttpResponseMessage response, string text)
|
||
{
|
||
JsonDocument document;
|
||
try
|
||
{
|
||
document = JsonDocument.Parse(string.IsNullOrWhiteSpace(text) ? "{}" : text);
|
||
}
|
||
catch (JsonException)
|
||
{
|
||
return (null, $"服务器返回了非 JSON 内容(HTTP {(int)response.StatusCode})");
|
||
}
|
||
|
||
using (document)
|
||
{
|
||
var root = document.RootElement;
|
||
|
||
var ok = root.TryGetProperty("ok", out var okElement)
|
||
&& okElement.ValueKind == JsonValueKind.True;
|
||
|
||
if (ok && root.TryGetProperty("data", out var dataElement))
|
||
{
|
||
return (dataElement.Clone(), "ok");
|
||
}
|
||
|
||
var message = GetString(root, "message")
|
||
?? $"请求失败(HTTP {(int)response.StatusCode})";
|
||
return (null, message);
|
||
}
|
||
}
|
||
|
||
/// <summary>读主体数组:登录接口是 `data.subjects`,主体列表接口是 `data.list`</summary>
|
||
private static IReadOnlyList<ApiSubject> ReadSubjects(JsonElement data, string property)
|
||
{
|
||
var list = new List<ApiSubject>();
|
||
if (!data.TryGetProperty(property, out var array) || array.ValueKind != JsonValueKind.Array) return list;
|
||
|
||
foreach (var item in array.EnumerateArray())
|
||
{
|
||
if (item.ValueKind != JsonValueKind.Object) continue;
|
||
|
||
list.Add(new ApiSubject(
|
||
GetInt(item, "id"),
|
||
GetString(item, "name") ?? $"#{GetInt(item, "id")}",
|
||
GetString(item, "expireAt"),
|
||
item.TryGetProperty("expired", out var expired) && expired.ValueKind == JsonValueKind.True,
|
||
GetInt(item, "role"),
|
||
GetInt(item, "memberCount"),
|
||
GetString(item, "memberName")));
|
||
}
|
||
return list;
|
||
}
|
||
|
||
private static ApiUser ReadUser(JsonElement data)
|
||
{
|
||
// 登录接口是 { token, user },/api/web/me 是直接一个 user
|
||
var userElement = data.TryGetProperty("user", out var nested) ? nested : data;
|
||
|
||
var id = userElement.TryGetProperty("id", out var idElement) && idElement.TryGetInt32(out var value) ? value : 0;
|
||
var username = GetString(userElement, "username");
|
||
var nickname = GetString(userElement, "nickname");
|
||
return new ApiUser(id, username, nickname);
|
||
}
|
||
|
||
private static string? GetString(JsonElement element, string property)
|
||
{
|
||
return element.TryGetProperty(property, out var value) && value.ValueKind == JsonValueKind.String
|
||
? value.GetString()
|
||
: null;
|
||
}
|
||
|
||
private static int GetInt(JsonElement element, string property)
|
||
{
|
||
if (!element.TryGetProperty(property, out var value)) return 0;
|
||
return value.ValueKind switch
|
||
{
|
||
JsonValueKind.Number => value.TryGetInt32(out var number) ? number : 0,
|
||
JsonValueKind.String => int.TryParse(value.GetString(), out var parsed) ? parsed : 0,
|
||
_ => 0,
|
||
};
|
||
}
|
||
|
||
private static long? GetLong(JsonElement element, string property)
|
||
{
|
||
if (!element.TryGetProperty(property, out var value)) return null;
|
||
return value.ValueKind switch
|
||
{
|
||
JsonValueKind.Number => value.TryGetInt64(out var number) ? number : null,
|
||
JsonValueKind.String => long.TryParse(value.GetString(), out var parsed) ? parsed : null,
|
||
_ => null,
|
||
};
|
||
}
|
||
|
||
private static DateTimeOffset? GetDateTime(JsonElement element, string property)
|
||
{
|
||
var text = GetString(element, property);
|
||
return !string.IsNullOrWhiteSpace(text) && DateTimeOffset.TryParse(text, out var parsed) ? parsed : null;
|
||
}
|
||
}
|