643 lines
29 KiB
C#
643 lines
29 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) : base(message)
|
||
{
|
||
StatusCode = statusCode;
|
||
}
|
||
|
||
/// <summary>HTTP 状态码(网络层失败为 0)</summary>
|
||
public int StatusCode { get; }
|
||
}
|
||
|
||
/// <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>激活设备服务的结果</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>
|
||
/// 后端接口客户端(登录 / 主体 / 设备服务 / 上报)
|
||
///
|
||
/// 契约见 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) };
|
||
|
||
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 new ApiException(message, (int)response.StatusCode);
|
||
|
||
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 new ApiException(message, (int)response.StatusCode);
|
||
|
||
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 new ApiException(message, (int)response.StatusCode);
|
||
|
||
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 new ApiException(message, (int)response.StatusCode);
|
||
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 new ApiException(message, (int)response.StatusCode);
|
||
|
||
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 new ApiException(message, (int)response.StatusCode);
|
||
|
||
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 new ApiException(message, (int)response.StatusCode);
|
||
|
||
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 new ApiException(message, (int)response.StatusCode);
|
||
}
|
||
|
||
/// <summary>设备心跳(`POST /api/scanner/heartbeat`):刷新服务端 `last_seen_at`</summary>
|
||
public async Task 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 new ApiException(message, (int)response.StatusCode);
|
||
}
|
||
|
||
/// <summary>上报通道(设备令牌;`POST /api/scan/channels`)</summary>
|
||
public async Task ReportChannelsAsync(string deviceToken, IEnumerable<(string ChannelId, string ChannelName)> channels,
|
||
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 }, 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 new ApiException(message, (int)response.StatusCode);
|
||
}
|
||
|
||
/// <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 new ApiException(message, (int)response.StatusCode);
|
||
}
|
||
|
||
/// <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 new ApiException(message, (int)response.StatusCode);
|
||
return data.Value;
|
||
}
|
||
|
||
/// <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 new ApiException(message, (int)response.StatusCode);
|
||
|
||
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 new ApiException(message, (int)response.StatusCode);
|
||
|
||
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/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 new ApiException(message, (int)response.StatusCode);
|
||
|
||
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>解析 `{ 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,
|
||
};
|
||
}
|
||
}
|