Add SCUM log sessions and trajectory projections

This commit is contained in:
npc0-hue
2026-08-27 12:34:07 +08:00
parent 0940780058
commit 316efbe780
38 changed files with 1549 additions and 84 deletions
Binary file not shown.

After

Width:  |  Height:  |  Size: 2.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 16 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 12 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.0 KiB

@@ -3,10 +3,13 @@ package companion
import (
"crypto/sha256"
"encoding/hex"
"regexp"
"strings"
"time"
)
var scumLoginLogLine = regexp.MustCompile(`^\d{4}\.\d{2}\.\d{2}-\d{2}\.\d{2}\.\d{2}: '([0-9.]+) (\d{1,50}):([^']{1,80})\(\d+\)' logged (in|out)(?: .*)?$`)
// ConsoleRecord is supplied by Run's stdout/stderr stream, not by the server
// execution log. The channel never accepts a file path or a raw log archive.
type ConsoleRecord struct {
@@ -21,6 +24,7 @@ type SemanticEvent struct {
Sequence uint64
Type string
PlayerID string
DisplayName string
OccurredAt time.Time
NetworkCorrelation string
}
@@ -62,6 +66,9 @@ func ParseConsoleRecords(serverID string, records []ConsoleRecord, correlationSe
return batch
}
func parseConsoleRecord(record ConsoleRecord, secret string) (SemanticEvent, bool) {
if event, ok := parseLoginLogRecord(record, secret); ok {
return event, true
}
fields := strings.Fields(record.Text)
if len(fields) < 3 || fields[0] != "SCUM" || (fields[1] != "LOGIN" && fields[1] != "LOGOUT") || !steamID64(fields[2]) {
return SemanticEvent{}, false
@@ -76,9 +83,26 @@ func parseConsoleRecord(record ConsoleRecord, secret string) (SemanticEvent, boo
}
return event, true
}
func parseLoginLogRecord(record ConsoleRecord, secret string) (SemanticEvent, bool) {
match := scumLoginLogLine.FindStringSubmatch(record.Text)
if match == nil || !steamID64(match[2]) {
return SemanticEvent{}, false
}
eventType := "scum.login"
if match[4] == "out" {
eventType = "scum.logout"
}
event := SemanticEvent{ServerID: record.ServerID, Sequence: record.Sequence, Type: eventType, PlayerID: match[2], DisplayName: match[3], OccurredAt: record.OccurredAt}
if secret != "" {
event.NetworkCorrelation = networkCorrelation(record.ServerID, match[1], secret)
}
return event, true
}
func networkCorrelation(serverID, value, secret string) string {
digest := sha256.Sum256([]byte(serverID + "\x00" + secret + "\x00" + value))
return hex.EncodeToString(digest[:16])
return hex.EncodeToString(digest[:])
}
func appendDiagnostic(existing []EventDiagnostic, diagnostic EventDiagnostic) []EventDiagnostic {
if len(existing) >= 32 {
@@ -17,4 +17,24 @@ func TestConsoleSemanticEventProducerParsesOnlyBoundedKnownOutput(t *testing.T)
if batch.Events[0].NetworkCorrelation == "10.0.0.1" {
t.Fatal("raw network value leaked")
}
if len(batch.Events[0].NetworkCorrelation) != 64 {
t.Fatalf("network correlation must be full sha256 hex, got %q", batch.Events[0].NetworkCorrelation)
}
}
func TestConsoleSemanticEventProducerParsesScumLoginLog(t *testing.T) {
observedAt := time.Date(2026, 8, 27, 12, 0, 0, 0, time.UTC)
batch := ParseConsoleRecords("server-1", []ConsoleRecord{
{ServerID: "server-1", Stream: "stdout", Sequence: 1, OccurredAt: observedAt, Text: "2026.08.27-12.00.00: '10.0.0.2 76561198000000002:Ada(42)' logged in at: X=1 Y=2 Z=3"},
{ServerID: "server-1", Stream: "stdout", Sequence: 2, OccurredAt: observedAt.Add(time.Second), Text: "2026.08.27-12.00.01: '10.0.0.2 76561198000000002:Ada(42)' logged out"},
}, "fixture-secret")
if len(batch.Events) != 2 || batch.Events[0].Type != "scum.login" || batch.Events[1].Type != "scum.logout" {
t.Fatalf("login log events not parsed: %+v", batch)
}
if batch.Events[0].PlayerID != "76561198000000002" || batch.Events[0].DisplayName != "Ada" || len(batch.Events[0].NetworkCorrelation) != 64 {
t.Fatalf("login event fields are incomplete: %+v", batch.Events[0])
}
if batch.Events[0].NetworkCorrelation == "10.0.0.2" {
t.Fatal("raw login log IP leaked")
}
}
@@ -111,11 +111,12 @@ export type SCUMSurfaceData = {
mapSettings: RecordMap[];
vehicles: RecordMap[];
flags: RecordMap[];
trajectories: RecordMap[];
};
export const emptySCUMSurfaceData: SCUMSurfaceData = {
players: [], squads: [], members: [], events: [], eventProduces: [], eventRuns: [], nativeEventRounds: [], tasks: [], activityEvents: [],
gifts: [], giftClaims: [], pendingGifts: [], giftDeliveries: [], timedGiftEvents: [], mapPoints: [], mapRegions: [], mapSettings: [], vehicles: [], flags: []
gifts: [], giftClaims: [], pendingGifts: [], giftDeliveries: [], timedGiftEvents: [], mapPoints: [], mapRegions: [], mapSettings: [], vehicles: [], flags: [], trajectories: []
};
export const scumCollections = {
@@ -137,16 +138,17 @@ export const scumCollections = {
mapRegions: "scum_map_regions",
mapSettings: "scum_map_settings",
vehicles: "scum_vehicles",
flags: "scum_flags"
flags: "scum_flags",
trajectories: "scum_trajectories"
} as const;
type SurfaceKey = keyof SCUMSurfaceData;
type PageKey = "players" | "squads" | "live-map" | "gifts" | "workflows";
const pageCollections: Record<PageKey, SurfaceKey[]> = {
players: ["players", "members", "activityEvents", "giftClaims", "pendingGifts", "giftDeliveries"],
players: ["players", "members", "activityEvents", "giftClaims", "pendingGifts", "giftDeliveries", "trajectories", "vehicles"],
squads: ["squads", "members", "flags"],
"live-map": ["mapPoints", "mapRegions", "mapSettings", "players", "vehicles", "flags"],
"live-map": ["mapPoints", "mapRegions", "mapSettings", "players", "vehicles", "flags", "trajectories"],
gifts: ["gifts", "giftClaims", "pendingGifts", "giftDeliveries", "timedGiftEvents", "players"],
workflows: ["events", "eventProduces", "eventRuns", "nativeEventRounds", "tasks", "activityEvents"]
};
@@ -161,6 +163,10 @@ export async function loadSCUMSurface(actions: SCUMWorkspaceActions, pageKey: st
const playersSnapshot = await actions.gameClient.snapshots({ profileKey: "scum-client-manager", type: "players", streamKey: "current", limit: 1 }).catch(() => undefined);
data.players = mergePlayerSnapshots(data.players, playersSnapshot);
}
if (keys.includes("vehicles") && actions.gameClient) {
const vehiclesSnapshot = await actions.gameClient.snapshots({ profileKey: "scum-client-manager", type: "vehicles", streamKey: "current", limit: 1 }).catch(() => undefined);
data.vehicles = mergeVehicleSnapshots(data.vehicles, vehiclesSnapshot);
}
return data;
}
@@ -184,6 +190,25 @@ export function mergePlayerSnapshots(players: RecordMap[], playersResponse: unkn
return merged;
}
export function mergeVehicleSnapshots(vehicles: RecordMap[], vehiclesResponse: unknown): RecordMap[] {
const vehicleSnapshot = latestSnapshotPayload(vehiclesResponse);
const merged = vehicles.map((vehicle) => ({ ...vehicle }));
const snapshotVehicles = Array.isArray(vehicleSnapshot?.vehicles) ? vehicleSnapshot.vehicles.filter(isRecord) : [];
if (!snapshotVehicles.length) return merged;
const byIdentity = vehicleIndex(merged);
for (const snapshotVehicle of snapshotVehicles) {
const match = findVehicle(byIdentity, snapshotVehicle);
const value = { ...(match ? merged[match.index] : {}), ...snapshotVehicle, vehicleObservedAt: textValue(vehicleSnapshot?.observedAt) };
if (match) merged[match.index] = value;
else {
const created = { ...value, vehicleId: firstText(snapshotVehicle, "vehicleId", "entityId", "id") };
merged.push(created);
addVehicleToIndex(byIdentity, created, merged.length - 1);
}
}
return merged;
}
export async function saveGiftDefinition(actions: SCUMWorkspaceActions, gift: RecordMap): Promise<unknown> {
const key = requiredKey(gift, "code", "礼包编号");
return requirePluginData(actions).transact(scumCollections.gifts, [{ operation: "put", key, value: gift }]);
@@ -342,6 +367,10 @@ function snapshotOrder(snapshot: RecordMap): number { const observed = Date.pars
function playerIndex(players: RecordMap[]): Map<string, number> { const result = new Map<string, number>(); players.forEach((player, index) => addPlayerToIndex(result, player, index)); return result; }
function addPlayerToIndex(index: Map<string, number>, player: RecordMap, playerIndex: number): void { playerIdentities(player).forEach((identity) => index.set(identity, playerIndex)); }
function findPlayer(index: Map<string, number>, player: RecordMap): { index: number } | undefined { for (const identity of playerIdentities(player)) { const found = index.get(identity); if (found !== undefined) return { index: found }; } return undefined; }
function vehicleIndex(vehicles: RecordMap[]): Map<string, number> { const result = new Map<string, number>(); vehicles.forEach((vehicle, index) => addVehicleToIndex(result, vehicle, index)); return result; }
function addVehicleToIndex(index: Map<string, number>, vehicle: RecordMap, vehicleIndex: number): void { vehicleIdentities(vehicle).forEach((identity) => index.set(identity, vehicleIndex)); }
function findVehicle(index: Map<string, number>, vehicle: RecordMap): { index: number } | undefined { for (const identity of vehicleIdentities(vehicle)) { const found = index.get(identity); if (found !== undefined) return { index: found }; } return undefined; }
function vehicleIdentities(vehicle: RecordMap): string[] { return ["vehicleId", "entityId", "id"].map((key) => textValue(vehicle[key])).filter(Boolean).map((value) => `vehicle:${value}`); }
function playerIdentities(player: RecordMap): string[] {
const identities = new Set<string>();
for (const key of ["gamePlayerId", "playerId", "steamId", "id"]) { const value = textValue(player[key]); if (value) identities.add(`player:${value}`); }
@@ -31,6 +31,24 @@ type PlayerPanelKind = "closed" | "attributes" | "gifts" | "items" | "history" |
type PlayerPanelState = { kind: PlayerPanelKind; playerId: string };
type AttributeDraft = { fieldKey: string; label: string; before: string; after: string };
const scumMapBackground = new URL("../assets/map/scum-map-overview.jpg", import.meta.url).href;
const scumMapSize = 256;
const rideDistanceThreshold = 50000;
const vehicleIconByClass: Record<string, string> = {
BPC_Barba: new URL("../assets/vehicles/vehicle-BPC_Barba.webp", import.meta.url).href,
BPC_CityBike: new URL("../assets/vehicles/vehicle-BPC_CityBike.webp", import.meta.url).href,
BPC_Cruiser: new URL("../assets/vehicles/vehicle-BPC_Cruiser.webp", import.meta.url).href,
BPC_Dirtbike: new URL("../assets/vehicles/vehicle-BPC_Dirtbike.webp", import.meta.url).href,
BPC_Kinglet_Duster: new URL("../assets/vehicles/vehicle-BPC_Kinglet_Duster.webp", import.meta.url).href,
BPC_Kinglet_Mariner: new URL("../assets/vehicles/vehicle-BPC_Kinglet_Mariner.webp", import.meta.url).href,
BPC_Laika: new URL("../assets/vehicles/vehicle-BPC_Laika.webp", import.meta.url).href,
BPC_MountainBike: new URL("../assets/vehicles/vehicle-BPC_MountainBike.webp", import.meta.url).href,
BPC_Rager: new URL("../assets/vehicles/vehicle-BPC_Rager.webp", import.meta.url).href,
BPC_RIS: new URL("../assets/vehicles/vehicle-BPC_RIS.webp", import.meta.url).href,
BPC_Tractor: new URL("../assets/vehicles/vehicle-BPC_Tractor.webp", import.meta.url).href,
BPC_WolfsWagen: new URL("../assets/vehicles/vehicle-BPC_WolfsWagen.webp", import.meta.url).href,
BP_WheelBarrow_Improvised: new URL("../assets/vehicles/vehicle-BP_WheelBarrow_Improvised.webp", import.meta.url).href,
BP_WheelBarrow_Metal: new URL("../assets/vehicles/vehicle-BP_WheelBarrow_Metal.webp", import.meta.url).href
};
export type ReactLike = {
createElement: (...args: any[]) => any;
@@ -122,7 +140,7 @@ export function renderSCUMFeaturePage(react: ReactLike, input: SCUMPageContext)
if (react.useEffect) react.useEffect(() => {
if (playerPanel.kind === "closed") refresh();
if (playerPanel.kind !== "closed") return;
const interval = setInterval(refresh, 10000);
const interval = setInterval(refresh, 3000);
return () => clearInterval(interval);
}, [input.serverInstanceId, pageKey, input.workspaceActions, playerPanel.kind]);
@@ -236,7 +254,7 @@ function playerDrawer(e: ReactLike["createElement"], player: RecordMap, data: SC
e("div", { className: "panel-header" }, e("div", null, e("h2", null, title), e("span", { className: "provider-id" }, `${name} · Steam ${textField(player, "steamId", "providerId") || "未同步"}`)), e("button", { type: "button", className: "drawer-close", onClick: close }, "关闭")),
e("div", { className: "console-record-meta scum-player-overview" },
e("span", null, `Profile ${textField(player, "userProfileId", "profileId") || "未同步"}`),
e("span", null, `登录 IP ${textField(player, "lastLoginIp", "loginIp", "ipAddress", "lastIp") || "未同步"}`),
e("span", null, `网络相关 ${shortHash(textField(player, "networkCorrelation")) || "未同步"}`),
e("span", null, `Fame ${numField(player, "famePoints")}`),
e("span", null, `Cash ${numField(player, "normalBalance", "moneyBalance")} · Gold ${numField(player, "goldBalance")}`),
e("span", null, `上次登录 ${userDateField(player, "lastLoginTime", "lastLoginAt", "lastLoginObservedAt")}`)),
@@ -286,12 +304,12 @@ function playerItemsPanel(e: ReactLike["createElement"], player: RecordMap) {
function playerHistoryPanel(e: ReactLike["createElement"], player: RecordMap, data: SCUMSurfaceData) {
const rows = playerRecords(data.activityEvents, player).filter((row) => ["login", "logout", "scum.login", "scum.logout"].includes(textField(row, "eventType", "type").toLowerCase()));
return e("div", { className: "console-record-list" }, e("p", { className: "dialog-description" }, "登录历史来自插件日志同步事件;网络信息按插件声明字段展示。"), e("div", { className: "console-row-list" }, rows.length ? rows.map((row, index) => e("div", { key: idOf(row, `history-${index}`), className: "console-row" }, e("span", null, textField(row, "eventType", "type") || "登录事件"), e("strong", null, dateField(row, "occurredAt", "observedAt", "createdAt")), e("strong", null, textField(row, "loginIp", "ipAddress", "lastIp") || "IP 未同步"))) : e("p", { className: "page-status" }, "没有该用户的真实登录历史。")));
return e("div", { className: "console-record-list" }, e("p", { className: "dialog-description" }, "登录历史来自插件声明的 SCUM 登录日志投影;网络字段只显示不可逆相关性哈希。"), e("div", { className: "console-row-list" }, rows.length ? rows.map((row, index) => e("div", { key: idOf(row, `history-${index}`), className: "console-row" }, e("span", null, textField(row, "eventType", "type") || "登录事件"), e("strong", null, dateField(row, "occurredAt", "observedAt", "createdAt")), e("strong", null, shortHash(textField(row, "networkCorrelation")) || textField(row, "reason") || "无网络字段"))) : e("p", { className: "page-status" }, "没有该用户的真实登录历史。")));
}
function playerTrajectoryPanel(e: ReactLike["createElement"], player: RecordMap, data: SCUMSurfaceData) {
const rows = playerRecords(data.activityEvents, player).filter((row) => hasCoordinates(positionOf(row)));
return e("div", { className: "console-record-list" }, e("p", { className: "dialog-description" }, "用户轨迹只展示插件声明并已同步的位置事件,不从机器文件或 SCUM.db 外部猜测。"), e("div", { className: "console-row-list" }, rows.length ? rows.map((row, index) => e("div", { key: idOf(row, `trajectory-${index}`), className: "console-row" }, e("span", null, dateField(row, "occurredAt", "observedAt", "createdAt")), e("strong", null, coords(positionOf(row))), e("strong", null, textField(row, "source") || "plugin log"))) : e("p", { className: "page-status" }, "没有该用户的真实轨迹记录。")));
const rows = playerRecords(data.trajectories, player).filter((row) => layerOf(row) === "players" && hasCoordinates(positionOf(row))).sort((left, right) => trajectoryOrder(right) - trajectoryOrder(left)).slice(0, 120);
return e("div", { className: "console-record-list" }, e("p", { className: "dialog-description" }, "用户轨迹来自 Run 每 3 秒查询 SCUM.db 的采样投影;乘车状态按同一时刻附近载具保守标识。"), e("div", { className: "console-row-list" }, rows.length ? rows.map((row, index) => { const ride = nearbyVehicle(row, data.vehicles); return e("div", { key: idOf(row, `trajectory-${index}`), className: "console-row" }, e("span", null, dateField(row, "sampledAt", "observedAt", "createdAt")), e("strong", null, coords(positionOf(row))), e("strong", null, ride ? `疑似乘坐 ${pointTitle(ride)}` : textField(row, "source") || "run.sqlite")); }) : e("p", { className: "page-status" }, "没有该用户的真实轨迹记录。")));
}
function playerRecords(rows: RecordMap[], player: RecordMap): RecordMap[] { const identities = playerIdentities(player); return rows.filter((row) => identities.includes(textField(row, "steamId", "playerId", "gamePlayerId", "userProfileId", "profileId"))); }
@@ -513,8 +531,10 @@ function mapSurface(e: ReactLike["createElement"], data: SCUMSurfaceData, input:
const search = view.mapSearch.trim().toLowerCase();
const visible = points.filter((point) => view.mapLayers[layerOf(point)] && matchesText(point, search, "name", "label", "subjectId", "subjectType", "layer"));
const selected = visible.find((point, index) => idOf(point, `point-${index}`) === view.selectedMapPoint) ?? visible[0];
const trails = visibleTrajectoryPoints(data.trajectories, view.mapLayers, search).sort((left, right) => trajectoryOrder(right) - trajectoryOrder(left)).slice(0, 180).reverse();
const selectedTrails = selected ? trajectoryRecordsForPoint(data.trajectories, selected).sort((left, right) => trajectoryOrder(right) - trajectoryOrder(left)).slice(0, 8) : [];
return e("div", { className: "console-record-list" },
statsStrip(e, [["地图点", points.length], ["用户", data.players.length], ["载具", data.vehicles.length], ["旗帜/区域", data.flags.length + data.mapRegions.length]]),
statsStrip(e, [["地图点", points.length], ["用户", data.players.length], ["载具", data.vehicles.length], ["轨迹采样", data.trajectories.length]]),
e("div", { className: "resource-filter-bar scum-filter-bar" },
labeledField(e, "筛选地图点", e("input", { value: view.mapSearch, "aria-label": "筛选地图点", placeholder: "名称 / 类型 / ID", onChange: (event: InputEvent) => view.setMapSearch(inputValue(event)) })),
(["players", "vehicles", "flags", "regions", "other"] as MapLayer[]).map((layer) => e("label", { key: layer, className: "scum-layer-toggle" }, e("input", { type: "checkbox", checked: view.mapLayers[layer], onChange: (event: InputEvent) => view.setMapLayers((previous) => ({ ...previous, [layer]: Boolean(event.target?.checked) })) }), layerLabel(layer)))
@@ -529,8 +549,8 @@ function mapSurface(e: ReactLike["createElement"], data: SCUMSurfaceData, input:
e("button", { type: "button", className: "primary-command", disabled: !actions?.pluginData, onClick: () => runAction(view.setAction, "正在保存地图范围…", async () => { await saveMapSettings(actions ?? {}, { customMapEnabled: customEnabled, centerX: numberInput(centerX, 0), centerY: numberInput(centerY, 0), widthKm: numberInput(widthKm, 15.24), heightKm: numberInput(heightKm, 15.24) }); view.refresh(); return "地图范围已保存。"; }) }, "保存地图范围"))
),
e("div", { className: "overview-two-col" },
e("div", { className: "map-projection-board", "aria-label": "SCUM 地图图层", style: { backgroundImage: `url(${scumMapBackground})` } }, visible.map((point, index) => e("button", { key: idOf(point, `point-${index}`), type: "button", className: "map-projection-dot", title: `${pointTitle(point)} ${coords(point)}`, "aria-label": pointTitle(point), style: mapPointStyle(point, bounds), onClick: () => view.setSelectedMapPoint(idOf(point, `point-${index}`)) }, ""))),
e("article", { className: "console-module" }, e("div", { className: "panel-header" }, e("h2", null, "地图点详情"), e("span", { className: "page-status" }, `${visible.length} 个可见点`)), selected ? e("div", { className: "console-record" }, e("strong", null, pointTitle(selected)), e("span", { className: "status-pill status-active" }, layerLabel(layerOf(selected))), e("span", { className: "provider-id" }, coords(selected)), e("div", { className: "console-record-meta" }, e("span", null, `ID ${textField(selected, "subjectId", "id", "_recordKey") || "unknown"}`), e("span", null, `来源 ${textField(selected, "source") || "plugin collection"}`), e("span", null, freshness(selected)))) : e("p", { className: "page-status" }, "当前图层和筛选条件下没有真实地图点。"))
e("div", { className: "map-projection-board", "aria-label": "SCUM 地图图层", style: { backgroundImage: `url(${scumMapBackground})` } }, mapGridOverlay(e), trails.map((point, index) => e("span", { key: `trail-${index}-${idOf(point, "sample")}`, className: `map-trajectory-dot map-layer-${layerOf(point)}`, title: `${pointTitle(point)} ${dateField(point, "sampledAt", "observedAt")}`, style: mapPointStyle(point, bounds) })), visible.map((point, index) => { const ride = layerOf(point) === "players" ? nearbyVehicle(point, data.vehicles) : undefined; return e("button", { key: idOf(point, `point-${index}`), type: "button", className: `map-projection-dot map-layer-${layerOf(point)}${ride ? " map-projection-dot-riding" : ""}`, title: `${pointTitle(point)} ${coords(point)}${ride ? ` · 疑似乘坐 ${pointTitle(ride)}` : ""}`, "aria-label": pointTitle(point), style: mapPointStyle(point, bounds), onClick: () => view.setSelectedMapPoint(idOf(point, `point-${index}`)) }, vehicleIconFor(point) ? e("img", { src: vehicleIconFor(point), alt: "" }) : ""); })),
e("article", { className: "console-module" }, e("div", { className: "panel-header" }, e("h2", null, "地图点详情"), e("span", { className: "page-status" }, `${visible.length} 个可见点`)), selected ? e("div", { className: "console-record" }, e("strong", null, pointTitle(selected)), e("span", { className: "status-pill status-active" }, layerLabel(layerOf(selected))), e("span", { className: "provider-id" }, coords(selected)), e("div", { className: "console-record-meta" }, e("span", null, `ID ${textField(selected, "subjectId", "id", "_recordKey") || "unknown"}`), e("span", null, `来源 ${textField(selected, "source") || "plugin collection"}`), e("span", null, freshness(selected))), selectedTrails.length ? e("div", { className: "console-row-list" }, selectedTrails.map((row, index) => e("div", { key: `selected-trail-${index}`, className: "console-row" }, e("span", null, dateField(row, "sampledAt", "observedAt")), e("strong", null, coords(row)), e("strong", null, textField(row, "source") || "run.sqlite")))) : null) : e("p", { className: "page-status" }, "当前图层和筛选条件下没有真实地图点。"))
)
);
}
@@ -557,7 +577,7 @@ export function collectMapPoints(data: SCUMSurfaceData): RecordMap[] {
return [...uniquePoints.values()];
}
function withPosition(row: RecordMap, layer: MapLayer, name: string, subjectId: string): RecordMap[] { const position = positionOf(row); return hasCoordinates(position) ? [{ ...position, layer, name, subjectId, _recordKey: `${layer}:${subjectId}`, source: textField(row, "source") }] : []; }
function withPosition(row: RecordMap, layer: MapLayer, name: string, subjectId: string): RecordMap[] { const position = positionOf(row); return hasCoordinates(position) ? [{ ...row, ...position, layer, name, subjectId, _recordKey: `${layer}:${subjectId}`, source: textField(row, "source") }] : []; }
function positionOf(row: RecordMap | undefined): RecordMap | undefined { const nested = field(row, "position", "location"); return isRecord(nested) ? nested : row; }
function hasCoordinates(row: RecordMap | undefined): row is RecordMap { return Boolean(row) && Number.isFinite(Number(field(row, "x", "locationX"))) && Number.isFinite(Number(field(row, "y", "locationY"))); }
function layerOf(point: RecordMap): MapLayer { const value = textField(point, "layer", "subjectType", "type").toLowerCase(); if (value.includes("player") || value.includes("user")) return "players"; if (value.includes("vehicle")) return "vehicles"; if (value.includes("flag")) return "flags"; if (value.includes("region") || value.includes("zone") || value === "base") return "regions"; return "other"; }
@@ -567,11 +587,28 @@ function mapPointIdentity(point: RecordMap): string { const subject = textField(
export function mapPointStyle(point: RecordMap, bounds: RecordMap): Record<string, string> {
const x = Number(field(point, "x", "locationX") ?? 0); const y = Number(field(point, "y", "locationY") ?? 0);
const minX = Number(field(bounds, "worldMinX")); const minY = Number(field(bounds, "worldMinY")); const maxX = Number(field(bounds, "worldMaxX")); const maxY = Number(field(bounds, "worldMaxY"));
const left = Number.isFinite(minX) && Number.isFinite(maxX) && maxX > minX ? 100 - (x - minX) / (maxX - minX) * 100 : 50;
const top = Number.isFinite(minY) && Number.isFinite(maxY) && maxY > minY ? 100 - (y - minY) / (maxY - minY) * 100 : 50;
const mapX = Number.isFinite(minX) && Number.isFinite(maxX) && maxX > minX ? scumMapSize - (x - minX) * scumMapSize / (maxX - minX) : scumMapSize / 2;
const mapY = Number.isFinite(minY) && Number.isFinite(maxY) && maxY > minY ? scumMapSize - (y - minY) * scumMapSize / (maxY - minY) : scumMapSize / 2;
const left = mapX / scumMapSize * 100;
const top = mapY / scumMapSize * 100;
return { left: `${Math.max(1, Math.min(99, left))}%`, top: `${Math.max(1, Math.min(99, top))}%` };
}
function mapGridOverlay(e: ReactLike["createElement"]) {
const rows = ["D", "C", "B", "A", "Z"]; const cols = ["4", "3", "2", "1", "0"]; const breaks = [20, 40, 60, 80];
return e("div", { className: "map-grid-overlay", "aria-hidden": "true" }, breaks.map((value) => e("span", { key: `v-${value}`, className: "map-grid-line map-grid-line-v", style: { left: `${value}%` } })), breaks.map((value) => e("span", { key: `h-${value}`, className: "map-grid-line map-grid-line-h", style: { top: `${value}%` } })), cols.map((label, index) => e("span", { key: `c-${label}`, className: "map-grid-label map-grid-col-label", style: { left: `${(index + 0.5) * 20}%` } }, label)), rows.map((label, index) => e("span", { key: `r-${label}`, className: "map-grid-label map-grid-row-label", style: { top: `${(index + 0.5) * 20}%` } }, label)));
}
function visibleTrajectoryPoints(rows: RecordMap[], layers: Record<MapLayer, boolean>, search: string): RecordMap[] { return rows.filter((row) => (layerOf(row) === "players" || layerOf(row) === "vehicles") && layers[layerOf(row)] && hasCoordinates(positionOf(row)) && matchesText(row, search, "displayName", "label", "subjectId", "steamId", "vehicleId", "subjectType")); }
function trajectoryRecordsForPoint(rows: RecordMap[], point: RecordMap): RecordMap[] { const ids = new Set([textField(point, "subjectId"), textField(point, "steamId"), textField(point, "gamePlayerId"), textField(point, "vehicleId"), textField(point, "id")].filter(Boolean)); const layer = layerOf(point); return rows.filter((row) => layerOf(row) === layer && trajectoryIdentity(row).some((identity) => ids.has(identity))); }
function trajectoryIdentity(row: RecordMap): string[] { return [textField(row, "subjectId"), textField(row, "steamId"), textField(row, "gamePlayerId"), textField(row, "vehicleId"), textField(row, "id")].filter(Boolean); }
function trajectoryOrder(row: RecordMap): number { const stamp = Date.parse(textField(row, "sampledAt", "observedAt", "createdAt")); return Number.isNaN(stamp) ? 0 : stamp; }
function nearbyVehicle(point: RecordMap, vehicles: RecordMap[]): RecordMap | undefined { if (!hasCoordinates(positionOf(point))) return undefined; let best: { vehicle: RecordMap; distance: number } | undefined; for (const vehicle of vehicles) { if (!hasCoordinates(positionOf(vehicle))) continue; const distance = distance2D(positionOf(point)!, positionOf(vehicle)!); if (distance <= rideDistanceThreshold && (!best || distance < best.distance)) best = { vehicle, distance }; } return best?.vehicle; }
function distance2D(left: RecordMap, right: RecordMap): number { const dx = Number(field(left, "x", "locationX")) - Number(field(right, "x", "locationX")); const dy = Number(field(left, "y", "locationY")) - Number(field(right, "y", "locationY")); return Math.sqrt(dx * dx + dy * dy); }
function vehicleIconFor(point: RecordMap): string { return vehicleIconByClass[normalizedVehicleClass(textField(point, "className", "vehicleClass", "entityClass"))] ?? ""; }
function normalizedVehicleClass(value: string): string { return value.replace(/_C$/i, "").split(".").pop()?.trim() ?? value.trim(); }
function shortHash(value: string): string { return value ? `${value.slice(0, 10)}${value.slice(-6)}` : ""; }
function runAction(setAction: StateSetter<ActionState>, pending: string, task: () => Promise<string>) { setAction({ status: "pending", message: pending }); void task().then((message) => setAction({ status: "ok", message })).catch((error) => setAction({ status: "error", message: errorMessage(error, "操作失败。") })); }
function usePluginState<T>(react: ReactLike, initial: T): [T, StateSetter<T>] { return react.useState ? react.useState<T>(initial) : [initial, () => undefined]; }
function inputValue(event: InputEvent): string { return event.target?.value ?? ""; }
@@ -310,7 +310,45 @@
"sqlRef": "sql/scum-db-v57/vehicles.sql",
"pollIntervalSeconds": 3,
"maxRows": 500,
"timeoutSeconds": 15
"timeoutSeconds": 15,
"projections": [
{
"collection": "scum_vehicles",
"rowPath": "rows",
"upsertKeys": [
"vehicleId"
],
"fixedValues": {
"source": "run.sqlite.scum.vehicles"
},
"observedAtField": "sampledAt"
},
{
"collection": "scum_trajectories",
"rowPath": "rows",
"upsertKeys": [
"subjectType",
"subjectId",
"sampledAt"
],
"fieldMappings": {
"subjectId": "vehicleId",
"vehicleId": "vehicleId",
"entityId": "entityId",
"className": "className",
"label": "label",
"x": "x",
"y": "y",
"z": "z",
"lastAccessTime": "lastAccessTime"
},
"fixedValues": {
"subjectType": "vehicle",
"source": "run.sqlite.scum.vehicles"
},
"observedAtField": "sampledAt"
}
]
},
{
"key": "scum.flags",
@@ -338,7 +376,69 @@
"sqlRef": "sql/scum-db-v57/map-points.sql",
"pollIntervalSeconds": 3,
"maxRows": 500,
"timeoutSeconds": 15
"timeoutSeconds": 15,
"projections": [
{
"collection": "scum_users",
"rowPath": "rows",
"matchField": "subjectType",
"matchValue": "player",
"upsertKeys": [
"steamId"
],
"fieldMappings": {
"steamId": "subjectId",
"userProfileId": "userProfileId",
"gamePlayerId": "gamePlayerId",
"x": "x",
"y": "y",
"z": "z",
"lastPositionObservedAt": "observedAt"
},
"fixedValues": {
"source": "run.sqlite.scum.positions"
},
"observedAtField": "positionSampledAt"
},
{
"collection": "scum_map_points",
"rowPath": "rows",
"upsertKeys": [
"subjectType",
"subjectId"
],
"fixedValues": {
"source": "run.sqlite.scum.positions"
},
"observedAtField": "sampledAt"
},
{
"collection": "scum_trajectories",
"rowPath": "rows",
"matchField": "subjectType",
"matchValue": "player",
"upsertKeys": [
"subjectType",
"subjectId",
"sampledAt"
],
"fieldMappings": {
"subjectType": "subjectType",
"subjectId": "subjectId",
"steamId": "subjectId",
"userProfileId": "userProfileId",
"gamePlayerId": "gamePlayerId",
"x": "x",
"y": "y",
"z": "z",
"observedAt": "observedAt"
},
"fixedValues": {
"source": "run.sqlite.scum.positions"
},
"observedAtField": "sampledAt"
}
]
},
{
"key": "scum.tasks",
@@ -437,6 +537,237 @@
"observedAtField": "observedAt"
}
}
},
{
"key": "scum.login-log.login",
"streamKeys": [
"scum.login"
],
"steps": [
{
"pattern": "^\\d{4}\\.\\d{2}\\.\\d{2}-\\d{2}\\.\\d{2}\\.\\d{2}: '(?P<ip>[0-9.]+) (?P<steamId>\\d{1,50}):(?P<displayName>[^']{1,80})\\(\\d+\\)' logged in(?: at: X=.*)?$"
}
],
"correlationFields": [
"steamId"
],
"maxInterveningLines": 0,
"target": {
"collection": "scum_users",
"upsertKeys": [
"steamId"
],
"captureMappings": {
"steamId": "steamId",
"displayName": "displayName"
},
"hashMappings": {
"networkCorrelation": "ip"
},
"fixedValues": {
"online": "true",
"status": "online",
"source": "scum.login"
},
"observedAtField": "lastLoginObservedAt"
},
"presence": {
"timestampField": "lastLoginObservedAt",
"activeWindowSeconds": 1,
"activityTarget": {
"collection": "scum_activity_events",
"upsertKeys": [
"steamId",
"observedAt"
],
"captureMappings": {
"steamId": "steamId",
"displayName": "displayName"
},
"hashMappings": {
"networkCorrelation": "ip"
},
"fixedValues": {
"eventType": "login",
"source": "scum.login"
},
"observedAtField": "observedAt"
}
}
},
{
"key": "scum.login-log.logout",
"streamKeys": [
"scum.login"
],
"steps": [
{
"pattern": "^\\d{4}\\.\\d{2}\\.\\d{2}-\\d{2}\\.\\d{2}\\.\\d{2}: '(?P<ip>[0-9.]+) (?P<steamId>\\d{1,50}):(?P<displayName>[^']{1,80})\\(\\d+\\)' logged out.*$"
}
],
"correlationFields": [
"steamId"
],
"maxInterveningLines": 0,
"target": {
"collection": "scum_users",
"upsertKeys": [
"steamId"
],
"captureMappings": {
"steamId": "steamId",
"displayName": "displayName"
},
"hashMappings": {
"networkCorrelation": "ip"
},
"fixedValues": {
"online": "false",
"status": "offline",
"logoutReason": "disconnect",
"source": "scum.login"
},
"observedAtField": "lastLogoutObservedAt"
},
"presence": {
"timestampField": "lastLogoutObservedAt",
"activeWindowSeconds": 1,
"activityTarget": {
"collection": "scum_activity_events",
"upsertKeys": [
"steamId",
"observedAt"
],
"captureMappings": {
"steamId": "steamId",
"displayName": "displayName"
},
"hashMappings": {
"networkCorrelation": "ip"
},
"fixedValues": {
"eventType": "logout",
"reason": "disconnect",
"source": "scum.login"
},
"observedAtField": "observedAt"
}
}
}
],
"lifecycleProjections": [
{
"key": "scum.lifecycle.stop-logout",
"capabilities": [
"process.stop"
],
"target": {
"collection": "scum_users",
"matchField": "online",
"matchValue": "true",
"fixedValues": {
"online": "false",
"status": "offline",
"logoutReason": "server-stop",
"source": "run.lifecycle"
},
"observedAtField": "lastLogoutObservedAt",
"activityTarget": {
"collection": "scum_activity_events",
"upsertKeys": [
"steamId",
"observedAt",
"eventType"
],
"rowMappings": {
"steamId": "steamId",
"displayName": "displayName"
},
"fixedValues": {
"eventType": "logout",
"reason": "server-stop",
"source": "run.lifecycle"
},
"observedAtField": "observedAt"
}
}
},
{
"key": "scum.lifecycle.restart-logout",
"capabilities": [
"process.restart"
],
"target": {
"collection": "scum_users",
"matchField": "online",
"matchValue": "true",
"fixedValues": {
"online": "false",
"status": "offline",
"logoutReason": "server-stop",
"source": "run.lifecycle"
},
"observedAtField": "lastLogoutObservedAt",
"activityTarget": {
"collection": "scum_activity_events",
"upsertKeys": [
"steamId",
"observedAt",
"eventType"
],
"rowMappings": {
"steamId": "steamId",
"displayName": "displayName"
},
"fixedValues": {
"eventType": "logout",
"reason": "server-stop",
"source": "run.lifecycle"
},
"observedAtField": "observedAt"
}
}
},
{
"key": "scum.lifecycle.status-logout",
"capabilities": [
"process.status"
],
"processStates": [
"stopped",
"not-started",
"exited"
],
"target": {
"collection": "scum_users",
"matchField": "online",
"matchValue": "true",
"fixedValues": {
"online": "false",
"status": "offline",
"logoutReason": "server-stop",
"source": "run.lifecycle"
},
"observedAtField": "lastLogoutObservedAt",
"activityTarget": {
"collection": "scum_activity_events",
"upsertKeys": [
"steamId",
"observedAt",
"eventType"
],
"rowMappings": {
"steamId": "steamId",
"displayName": "displayName"
},
"fixedValues": {
"eventType": "logout",
"reason": "server-stop",
"source": "run.lifecycle"
},
"observedAtField": "observedAt"
}
}
}
],
"dataPacks": [
@@ -797,6 +1128,62 @@
"path": "assets/map/scum-map-overview.jpg",
"mode": 384
},
{
"path": "assets/vehicles/vehicle-BPC_Barba.webp",
"mode": 384
},
{
"path": "assets/vehicles/vehicle-BPC_CityBike.webp",
"mode": 384
},
{
"path": "assets/vehicles/vehicle-BPC_Cruiser.webp",
"mode": 384
},
{
"path": "assets/vehicles/vehicle-BPC_Dirtbike.webp",
"mode": 384
},
{
"path": "assets/vehicles/vehicle-BPC_Kinglet_Duster.webp",
"mode": 384
},
{
"path": "assets/vehicles/vehicle-BPC_Kinglet_Mariner.webp",
"mode": 384
},
{
"path": "assets/vehicles/vehicle-BPC_Laika.webp",
"mode": 384
},
{
"path": "assets/vehicles/vehicle-BPC_MountainBike.webp",
"mode": 384
},
{
"path": "assets/vehicles/vehicle-BPC_RIS.webp",
"mode": 384
},
{
"path": "assets/vehicles/vehicle-BPC_Rager.webp",
"mode": 384
},
{
"path": "assets/vehicles/vehicle-BPC_Tractor.webp",
"mode": 384
},
{
"path": "assets/vehicles/vehicle-BPC_WolfsWagen.webp",
"mode": 384
},
{
"path": "assets/vehicles/vehicle-BP_WheelBarrow_Improvised.webp",
"mode": 384
},
{
"path": "assets/vehicles/vehicle-BP_WheelBarrow_Metal.webp",
"mode": 384
},
{
"path": "sql/scum-db-v57/users.sql",
"mode": 384