mirror of
https://github.com/soarqin/DSP_Mods.git
synced 2026-11-19 17:05:20 +08:00
feat(livestreamassist): add a simple example
This commit is contained in:
1 parent
e95c832e03
commit
92e6511d91
3 files changed
+163
-24
No files matched your search
@@ -26,5 +26,7 @@ Port = 18080
|
|||||||
|
|
||||||
Then connect to `ws://<host>:18080/api/v1`. There is no authentication. Use a LAN bind address or `0.0.0.0` only on trusted networks. Configuration changes require a game restart.
|
Then connect to `ws://<host>:18080/api/v1`. There is no authentication. Use a LAN bind address or `0.0.0.0` only on trusted networks. Configuration changes require a game restart.
|
||||||
|
|
||||||
|
Open [examples/research-overlay.html](https://github.com/soarqin/DSP_Mods/blob/master/LiveStreamAssist/examples/research-overlay.html) in a browser or OBS Browser Source to show the current research ID, level, and hash progress. Default URL is `ws://127.0.0.1:18080/api/v1`; override with `?ws=`.
|
||||||
|
|
||||||
- [WebSocket API reference](https://github.com/soarqin/DSP_Mods/blob/master/LiveStreamAssist/docs/WebSocketApi.md)
|
- [WebSocket API reference](https://github.com/soarqin/DSP_Mods/blob/master/LiveStreamAssist/docs/WebSocketApi.md)
|
||||||
- [WebSocket design and transport migration plan](https://github.com/soarqin/DSP_Mods/blob/master/LiveStreamAssist/docs/WebSocketDesign.md)
|
- [WebSocket design and transport migration plan](https://github.com/soarqin/DSP_Mods/blob/master/LiveStreamAssist/docs/WebSocketDesign.md)
|
||||||
@@ -0,0 +1,121 @@
|
|||||||
|
<!DOCTYPE html>
|
||||||
|
<html lang="en">
|
||||||
|
<head>
|
||||||
|
<meta charset="utf-8">
|
||||||
|
<title>LiveStreamAssist research</title>
|
||||||
|
<style>
|
||||||
|
:root { color-scheme: dark; }
|
||||||
|
html, body { margin: 0; background: transparent; font: 18px/1.4 system-ui, sans-serif; color: #f2f5f8; }
|
||||||
|
.card {
|
||||||
|
min-width: 320px; max-width: 420px; padding: 16px 18px;
|
||||||
|
background: rgba(12, 18, 28, 0.72); border-radius: 10px;
|
||||||
|
}
|
||||||
|
.label { opacity: 0.65; font-size: 12px; letter-spacing: 0.08em; text-transform: uppercase; }
|
||||||
|
.title { margin: 4px 0 10px; font-size: 22px; font-weight: 650; }
|
||||||
|
.bar { height: 10px; background: #1d2a3c; border-radius: 999px; overflow: hidden; }
|
||||||
|
.fill { height: 100%; width: 0; background: #3d9cff; }
|
||||||
|
.meta { margin-top: 8px; font-variant-numeric: tabular-nums; font-size: 14px; opacity: 0.9; }
|
||||||
|
.status { margin-top: 8px; font-size: 13px; opacity: 0.7; }
|
||||||
|
input {
|
||||||
|
width: 100%; margin: 0 0 12px; box-sizing: border-box; padding: 6px 8px;
|
||||||
|
border: 0; border-radius: 6px; background: #1d2a3c; color: inherit;
|
||||||
|
}
|
||||||
|
</style>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<div class="card">
|
||||||
|
<input id="url" value="ws://127.0.0.1:18080/api/v1">
|
||||||
|
<div class="label">Current research</div>
|
||||||
|
<div class="title" id="title">Connecting…</div>
|
||||||
|
<div class="bar"><div class="fill" id="fill"></div></div>
|
||||||
|
<div class="meta" id="meta"></div>
|
||||||
|
<div class="status" id="status"></div>
|
||||||
|
</div>
|
||||||
|
<script>
|
||||||
|
const qs = new URLSearchParams(location.search);
|
||||||
|
const urlInput = document.getElementById("url");
|
||||||
|
const titleEl = document.getElementById("title");
|
||||||
|
const fillEl = document.getElementById("fill");
|
||||||
|
const metaEl = document.getElementById("meta");
|
||||||
|
const statusEl = document.getElementById("status");
|
||||||
|
urlInput.value = qs.get("ws") || urlInput.value;
|
||||||
|
|
||||||
|
let ws, seq = 0, pending = new Map(), pollTimer, backoff = 500;
|
||||||
|
|
||||||
|
function rpc(method, params) {
|
||||||
|
const id = "r-" + (++seq);
|
||||||
|
return new Promise((resolve, reject) => {
|
||||||
|
pending.set(id, { resolve, reject });
|
||||||
|
ws.send(JSON.stringify({ jsonrpc: "2.0", id, method, params: params || {} }));
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function fmt(n) {
|
||||||
|
try { return BigInt(n).toString(); } catch { return String(n ?? ""); }
|
||||||
|
}
|
||||||
|
|
||||||
|
function pct(up, need) {
|
||||||
|
try {
|
||||||
|
const n = BigInt(need || "0");
|
||||||
|
if (n === 0n) return 0;
|
||||||
|
return Number(BigInt(up || "0") * 10000n / n) / 100;
|
||||||
|
} catch { return 0; }
|
||||||
|
}
|
||||||
|
|
||||||
|
async function tick() {
|
||||||
|
const tech = await rpc("data.read", { root: "history", path: ["currentTech"] });
|
||||||
|
if (tech.error) throw new Error(tech.error.data && tech.error.data.kind || tech.error.message);
|
||||||
|
const id = tech.result.value;
|
||||||
|
if (!id) {
|
||||||
|
titleEl.textContent = "No active research";
|
||||||
|
fillEl.style.width = "0%";
|
||||||
|
metaEl.textContent = "";
|
||||||
|
statusEl.textContent = "session " + (tech.result.sessionId || "");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const state = await rpc("data.read", {
|
||||||
|
root: "history",
|
||||||
|
path: ["techStates", { key: id }],
|
||||||
|
select: ["curLevel", "hashUploaded", "hashNeeded"]
|
||||||
|
});
|
||||||
|
if (state.error) throw new Error(state.error.data && state.error.data.kind || state.error.message);
|
||||||
|
const v = state.result.value;
|
||||||
|
const p = pct(v.hashUploaded, v.hashNeeded);
|
||||||
|
titleEl.textContent = "Tech " + id + " Lv " + v.curLevel;
|
||||||
|
fillEl.style.width = p.toFixed(2) + "%";
|
||||||
|
metaEl.textContent = fmt(v.hashUploaded) + " / " + fmt(v.hashNeeded) + " (" + p.toFixed(1) + "%)";
|
||||||
|
statusEl.textContent = "session " + (state.result.sessionId || "");
|
||||||
|
}
|
||||||
|
|
||||||
|
function connect() {
|
||||||
|
statusEl.textContent = "Connecting";
|
||||||
|
ws = new WebSocket(urlInput.value);
|
||||||
|
ws.onopen = () => {
|
||||||
|
backoff = 500;
|
||||||
|
statusEl.textContent = "Connected";
|
||||||
|
pollTimer = setInterval(() => { tick().catch(err => { statusEl.textContent = err.message; }); }, 1000);
|
||||||
|
tick().catch(err => { statusEl.textContent = err.message; });
|
||||||
|
};
|
||||||
|
ws.onmessage = ev => {
|
||||||
|
const msg = JSON.parse(ev.data);
|
||||||
|
const wait = pending.get(msg.id);
|
||||||
|
if (!wait) return;
|
||||||
|
pending.delete(msg.id);
|
||||||
|
wait.resolve(msg);
|
||||||
|
};
|
||||||
|
ws.onclose = () => {
|
||||||
|
clearInterval(pollTimer);
|
||||||
|
pending.forEach(p => p.reject(new Error("disconnected")));
|
||||||
|
pending.clear();
|
||||||
|
titleEl.textContent = "Disconnected";
|
||||||
|
statusEl.textContent = "Retrying";
|
||||||
|
setTimeout(connect, backoff);
|
||||||
|
backoff = Math.min(backoff * 2, 8000);
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
urlInput.onchange = () => { if (ws) ws.close(); };
|
||||||
|
connect();
|
||||||
|
</script>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
@@ -21,66 +21,82 @@ function New-OpCts {
|
|||||||
[Threading.CancellationTokenSource]::new([TimeSpan]::FromSeconds($TimeoutSec))
|
[Threading.CancellationTokenSource]::new([TimeSpan]::FromSeconds($TimeoutSec))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function Get-ConnSocket {
|
||||||
|
param($Conn)
|
||||||
|
if ($null -eq $Conn) { return $null }
|
||||||
|
if ($Conn -is [hashtable]) {
|
||||||
|
if ($Conn.ContainsKey('Ws')) { return $Conn['Ws'] }
|
||||||
|
return $null
|
||||||
|
}
|
||||||
|
if ($Conn.PSObject.Properties.Name -contains 'Ws') { return $Conn.Ws }
|
||||||
|
return $null
|
||||||
|
}
|
||||||
|
|
||||||
function Connect-Api {
|
function Connect-Api {
|
||||||
param([string] $Uri)
|
param([string] $Uri)
|
||||||
$ws = [Net.WebSockets.ClientWebSocket]::new()
|
$ws = [Net.WebSockets.ClientWebSocket]::new()
|
||||||
$cts = New-OpCts
|
$cts = New-OpCts
|
||||||
try {
|
try {
|
||||||
$ws.ConnectAsync([Uri]$Uri, $cts.Token).GetAwaiter().GetResult()
|
$null = $ws.ConnectAsync([Uri]$Uri, $cts.Token).GetAwaiter().GetResult()
|
||||||
} catch {
|
} catch {
|
||||||
$ws.Dispose()
|
$null = $ws.Dispose()
|
||||||
throw
|
throw
|
||||||
} finally {
|
} finally {
|
||||||
$cts.Dispose()
|
$null = $cts.Dispose()
|
||||||
}
|
}
|
||||||
return @{ Ws = $ws }
|
[pscustomobject]@{ Ws = $ws }
|
||||||
}
|
}
|
||||||
|
|
||||||
function Close-Api {
|
function Close-Api {
|
||||||
param($Conn)
|
param($Conn)
|
||||||
if (-not $Conn) { return }
|
$ws = Get-ConnSocket $Conn
|
||||||
|
if ($null -eq $ws) { return }
|
||||||
$cts = New-OpCts
|
$cts = New-OpCts
|
||||||
try {
|
try {
|
||||||
if ($Conn.Ws.State -eq [Net.WebSockets.WebSocketState]::Open -or
|
if ($ws.State -eq [Net.WebSockets.WebSocketState]::Open -or
|
||||||
$Conn.Ws.State -eq [Net.WebSockets.WebSocketState]::CloseReceived) {
|
$ws.State -eq [Net.WebSockets.WebSocketState]::CloseReceived) {
|
||||||
$Conn.Ws.CloseAsync([Net.WebSockets.WebSocketCloseStatus]::NormalClosure, '', $cts.Token).GetAwaiter().GetResult()
|
$null = $ws.CloseAsync([Net.WebSockets.WebSocketCloseStatus]::NormalClosure, '', $cts.Token).GetAwaiter().GetResult()
|
||||||
}
|
}
|
||||||
} catch { }
|
} catch { }
|
||||||
finally { $cts.Dispose() }
|
finally { $null = $cts.Dispose() }
|
||||||
try { $Conn.Ws.Dispose() } catch { }
|
try { $null = $ws.Dispose() } catch { }
|
||||||
}
|
}
|
||||||
|
|
||||||
function Send-Text {
|
function Send-Text {
|
||||||
param($Conn, [string] $Text, [bool] $End = $true)
|
param($Conn, [string] $Text, [bool] $End = $true)
|
||||||
|
$ws = Get-ConnSocket $Conn
|
||||||
$bytes = $utf8.GetBytes($Text)
|
$bytes = $utf8.GetBytes($Text)
|
||||||
$seg = [ArraySegment[byte]]::new($bytes)
|
$seg = [ArraySegment[byte]]::new($bytes)
|
||||||
$cts = New-OpCts
|
$cts = New-OpCts
|
||||||
try {
|
try {
|
||||||
$Conn.Ws.SendAsync($seg, [Net.WebSockets.WebSocketMessageType]::Text, $End, $cts.Token).GetAwaiter().GetResult()
|
$null = $ws.SendAsync($seg, [Net.WebSockets.WebSocketMessageType]::Text, $End, $cts.Token).GetAwaiter().GetResult()
|
||||||
} finally { $cts.Dispose() }
|
} finally { $null = $cts.Dispose() }
|
||||||
}
|
}
|
||||||
|
|
||||||
function Receive-Message {
|
function Receive-Message {
|
||||||
param($Conn)
|
param($Conn)
|
||||||
|
$ws = Get-ConnSocket $Conn
|
||||||
$buffer = [byte[]]::new(65536)
|
$buffer = [byte[]]::new(65536)
|
||||||
$ms = [IO.MemoryStream]::new()
|
$ms = [IO.MemoryStream]::new()
|
||||||
$cts = New-OpCts
|
$cts = New-OpCts
|
||||||
try {
|
try {
|
||||||
do {
|
do {
|
||||||
$seg = [ArraySegment[byte]]::new($buffer)
|
$seg = [ArraySegment[byte]]::new($buffer)
|
||||||
$result = $Conn.Ws.ReceiveAsync($seg, $cts.Token).GetAwaiter().GetResult()
|
$result = $ws.ReceiveAsync($seg, $cts.Token).GetAwaiter().GetResult()
|
||||||
if ($result.MessageType -eq [Net.WebSockets.WebSocketMessageType]::Close) {
|
if ($result.MessageType -eq [Net.WebSockets.WebSocketMessageType]::Close) {
|
||||||
return @{ Closed = $true; CloseStatus = [int]$Conn.Ws.CloseStatus; Text = $null }
|
$code = 0
|
||||||
|
if ($null -ne $ws.CloseStatus) { $code = [int]$ws.CloseStatus }
|
||||||
|
return [pscustomobject]@{ Closed = $true; CloseStatus = $code; Text = $null }
|
||||||
}
|
}
|
||||||
if ($result.MessageType -ne [Net.WebSockets.WebSocketMessageType]::Text -or $ms.Length + $result.Count -gt 262144) {
|
if ($result.MessageType -ne [Net.WebSockets.WebSocketMessageType]::Text -or $ms.Length + $result.Count -gt 262144) {
|
||||||
throw 'Expected a text response within maxResponseBytes'
|
throw 'Expected a text response within maxResponseBytes'
|
||||||
}
|
}
|
||||||
$ms.Write($buffer, 0, $result.Count)
|
$null = $ms.Write($buffer, 0, $result.Count)
|
||||||
} while (-not $result.EndOfMessage)
|
} while (-not $result.EndOfMessage)
|
||||||
return @{ Closed = $false; Text = $utf8.GetString($ms.ToArray()) }
|
return [pscustomobject]@{ Closed = $false; CloseStatus = 0; Text = $utf8.GetString($ms.ToArray()) }
|
||||||
} finally {
|
} finally {
|
||||||
$ms.Dispose()
|
$null = $ms.Dispose()
|
||||||
$cts.Dispose()
|
$null = $cts.Dispose()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -167,12 +183,12 @@ try {
|
|||||||
|
|
||||||
$cts = New-OpCts
|
$cts = New-OpCts
|
||||||
try {
|
try {
|
||||||
$conn.Ws.SendAsync(
|
$null = (Get-ConnSocket $conn).SendAsync(
|
||||||
[ArraySegment[byte]]::new([byte[]](1, 2, 3)),
|
[ArraySegment[byte]]::new([byte[]](1, 2, 3)),
|
||||||
[Net.WebSockets.WebSocketMessageType]::Binary,
|
[Net.WebSockets.WebSocketMessageType]::Binary,
|
||||||
$true,
|
$true,
|
||||||
$cts.Token).GetAwaiter().GetResult()
|
$cts.Token).GetAwaiter().GetResult()
|
||||||
} finally { $cts.Dispose() }
|
} finally { $null = $cts.Dispose() }
|
||||||
$bin = Receive-Message $conn
|
$bin = Receive-Message $conn
|
||||||
Assert-True ($bin.Closed -and $bin.CloseStatus -eq 1003) "binary rejected $($bin.CloseStatus)"
|
Assert-True ($bin.Closed -and $bin.CloseStatus -eq 1003) "binary rejected $($bin.CloseStatus)"
|
||||||
|
|
||||||
@@ -200,10 +216,10 @@ try {
|
|||||||
$response = $http.SendAsync($request, [Net.Http.HttpCompletionOption]::ResponseHeadersRead, $cts.Token).GetAwaiter().GetResult()
|
$response = $http.SendAsync($request, [Net.Http.HttpCompletionOption]::ResponseHeadersRead, $cts.Token).GetAwaiter().GetResult()
|
||||||
Assert-True ([int]$response.StatusCode -eq 404) 'wrong path HTTP rejection'
|
Assert-True ([int]$response.StatusCode -eq 404) 'wrong path HTTP rejection'
|
||||||
} finally {
|
} finally {
|
||||||
if ($null -ne $response) { $response.Dispose() }
|
if ($null -ne $response) { $null = $response.Dispose() }
|
||||||
$request.Dispose()
|
$null = $request.Dispose()
|
||||||
$http.Dispose()
|
$null = $http.Dispose()
|
||||||
$cts.Dispose()
|
$null = $cts.Dispose()
|
||||||
}
|
}
|
||||||
|
|
||||||
$conn = Connect-Api $ServerUri
|
$conn = Connect-Api $ServerUri
|
||||||
|
|||||||
Reference in new issue
Block a user