dsh-mc-server-ops 0.0.0-stage → 0.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +251 -3
- package/client.js +360 -0
- package/cordis.patch.yml +17 -0
- package/index.js +893 -0
- package/ops/adapters/index.mjs +37 -0
- package/ops/adapters/local.mjs +45 -0
- package/ops/adapters/pterodactyl.mjs +105 -0
- package/ops/command-guard.mjs +102 -0
- package/ops/mcadmin.ps1 +982 -0
- package/ops/qq-bridge.mjs +408 -0
- package/ops/rcon-probe.mjs +91 -0
- package/ops/rcon.mjs +471 -0
- package/ops/server-console.ps1 +92 -0
- package/ops/watchdog.ps1 +117 -0
- package/package.json +67 -4
package/ops/mcadmin.ps1
ADDED
|
@@ -0,0 +1,982 @@
|
|
|
1
|
+
param(
|
|
2
|
+
[Parameter(Mandatory = $true)]
|
|
3
|
+
[ValidateSet('status', 'players', 'say', 'cmd', 'start', 'stop', 'restart', 'logs', 'crashinfo', 'whoami', 'help', 'gamemode', 'bind-player', 'unbind-player', 'my-players', 'bindings', 'whitelist-sync', 'kubejs-backup', 'kubejs-reload', 'vote-start', 'vote-approve', 'vote-reject', 'vote-status', 'export-data', 'import-data', 'owner-add', 'owner-del', 'owner-list', 'watchdog')]
|
|
4
|
+
[string]$Action,
|
|
5
|
+
|
|
6
|
+
[string]$Arg = '',
|
|
7
|
+
[string]$Actor = '',
|
|
8
|
+
[Alias('Lines')]
|
|
9
|
+
[int]$TailLines = 40,
|
|
10
|
+
[string]$ServerDir = '',
|
|
11
|
+
[string]$Channel = '',
|
|
12
|
+
[switch]$Json
|
|
13
|
+
)
|
|
14
|
+
|
|
15
|
+
$ErrorActionPreference = 'Stop'
|
|
16
|
+
try { [Console]::OutputEncoding = [System.Text.Encoding]::UTF8 } catch { }
|
|
17
|
+
if ([string]::IsNullOrWhiteSpace($ServerDir)) {
|
|
18
|
+
if ($env:MC_SERVER_DIR) { $ServerDir = $env:MC_SERVER_DIR } else { $ServerDir = 'D:\server' }
|
|
19
|
+
}
|
|
20
|
+
$ServerDir = $ServerDir.TrimEnd('\', '/')
|
|
21
|
+
$OpsDir = Join-Path $ServerDir 'ops'
|
|
22
|
+
$DataDir = Join-Path $OpsDir 'data'
|
|
23
|
+
$LogDir = Join-Path $ServerDir 'logs'
|
|
24
|
+
$LogFile = Join-Path $LogDir 'latest.log'
|
|
25
|
+
$BindFile = Join-Path $DataDir 'bindings.json'
|
|
26
|
+
$VoteFile = Join-Path $DataDir 'votes.json'
|
|
27
|
+
$WhitelistFile = Join-Path $ServerDir 'whitelist.json'
|
|
28
|
+
$StateFile = Join-Path $DataDir 'state.json'
|
|
29
|
+
$OwnerFile = Join-Path $DataDir 'owners.json'
|
|
30
|
+
$ConfigFile = Join-Path $DataDir 'config.json'
|
|
31
|
+
$PidFile = Join-Path $DataDir 'server.pid'
|
|
32
|
+
$PropsFile = Join-Path $ServerDir 'server.properties'
|
|
33
|
+
$ForgeArgs = '@libraries/net/minecraftforge/forge/1.20.1-47.2.23/win_args.txt'
|
|
34
|
+
if (-not (Test-Path (Join-Path $ServerDir $ForgeArgs.TrimStart('@')))) {
|
|
35
|
+
$found = Get-ChildItem (Join-Path $ServerDir 'libraries') -Recurse -Filter 'win_args.txt' -ErrorAction SilentlyContinue | Select-Object -First 1
|
|
36
|
+
if ($found) { $ForgeArgs = '@' + $found.FullName.Substring($ServerDir.Length + 1) }
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
New-Item -ItemType Directory -Force -Path $OpsDir, $DataDir, $LogDir | Out-Null
|
|
40
|
+
|
|
41
|
+
# ---------------- 基础工具 ----------------
|
|
42
|
+
function Read-Json([string]$path, $default) {
|
|
43
|
+
if (Test-Path $path) {
|
|
44
|
+
try { return ((Get-Content $path -Raw -Encoding UTF8).TrimStart([char]0xFEFF) | ConvertFrom-Json) } catch { return $default }
|
|
45
|
+
}
|
|
46
|
+
return $default
|
|
47
|
+
}
|
|
48
|
+
function Write-Json([string]$path, $obj) {
|
|
49
|
+
$obj | ConvertTo-Json -Depth 8 | Set-Content -Path $path -Encoding UTF8
|
|
50
|
+
}
|
|
51
|
+
function Get-Prop($obj, [string]$name, $default) {
|
|
52
|
+
if ($null -eq $obj) { return $default }
|
|
53
|
+
$p = $obj.PSObject.Properties[$name]
|
|
54
|
+
if ($null -eq $p -or $null -eq $p.Value) { return $default }
|
|
55
|
+
return $p.Value
|
|
56
|
+
}
|
|
57
|
+
function Get-Owners {
|
|
58
|
+
$doc = Read-Json $OwnerFile ([pscustomobject]@{ owners = @() })
|
|
59
|
+
$list = @()
|
|
60
|
+
foreach ($x in @(Get-Prop $doc 'owners' @())) { if ($x) { $list += [string]$x } }
|
|
61
|
+
return $list
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
$config = Read-Json $ConfigFile ([pscustomobject]@{ ownerSecret = '' })
|
|
65
|
+
$secret = [string](Get-Prop $config 'ownerSecret' '')
|
|
66
|
+
|
|
67
|
+
$ownerIds = @(Get-Owners)
|
|
68
|
+
$role = 'unknown'
|
|
69
|
+
if ($Actor -and ($ownerIds -contains $Actor)) { $role = 'owner' }
|
|
70
|
+
# 本机控制台(面板/命令行)当作服主:只在 Channel 为空时生效,QQ 侧调用一律带 group/c2c
|
|
71
|
+
if ($Actor -eq 'LOCAL-CONSOLE' -and ($Channel -eq '' -or $Channel -eq 'console')) { $role = 'owner' }
|
|
72
|
+
|
|
73
|
+
function Get-Bindings {
|
|
74
|
+
$doc = Read-Json $BindFile @()
|
|
75
|
+
$list = @()
|
|
76
|
+
foreach ($x in @($doc)) {
|
|
77
|
+
if ($x -and $x.qq -and $x.name) {
|
|
78
|
+
$list += [pscustomobject]@{ qq = [string]$x.qq; name = [string]$x.name; at = [string]$x.at }
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
return $list
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
function Save-Bindings($list) {
|
|
85
|
+
$json = ConvertTo-Json -InputObject @($list) -Depth 5
|
|
86
|
+
[System.IO.File]::WriteAllText($BindFile, $json, (New-Object System.Text.UTF8Encoding($false)))
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
function Get-OfflineUuid([string]$name) {
|
|
90
|
+
$md5 = [System.Security.Cryptography.MD5]::Create()
|
|
91
|
+
$hash = $md5.ComputeHash([System.Text.Encoding]::UTF8.GetBytes("OfflinePlayer:$name"))
|
|
92
|
+
$hash[6] = ($hash[6] -band 0x0F) -bor 0x30
|
|
93
|
+
$hash[8] = ($hash[8] -band 0x3F) -bor 0x80
|
|
94
|
+
$h = ($hash | ForEach-Object { $_.ToString('x2') }) -join ''
|
|
95
|
+
return "$($h.Substring(0,8))-$($h.Substring(8,4))-$($h.Substring(12,4))-$($h.Substring(16,4))-$($h.Substring(20,12))"
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
function Read-Whitelist {
|
|
99
|
+
if (-not (Test-Path $WhitelistFile)) { return @() }
|
|
100
|
+
try {
|
|
101
|
+
$txt = (Get-Content $WhitelistFile -Raw -Encoding UTF8).TrimStart([char]0xFEFF).Trim()
|
|
102
|
+
if (-not $txt -or $txt -eq '[]') { return @() }
|
|
103
|
+
$doc = $txt | ConvertFrom-Json
|
|
104
|
+
if ($null -eq $doc) { return @() }
|
|
105
|
+
$out = @()
|
|
106
|
+
foreach ($x in @($doc)) {
|
|
107
|
+
if ($x -and $x.name -and $x.uuid) { $out += [pscustomobject]@{ uuid = [string]$x.uuid; name = [string]$x.name } }
|
|
108
|
+
}
|
|
109
|
+
return $out
|
|
110
|
+
} catch { return @() }
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
function Save-Whitelist($list) {
|
|
114
|
+
$json = ConvertTo-Json -InputObject @($list) -Depth 5
|
|
115
|
+
[System.IO.File]::WriteAllText($WhitelistFile, $json, (New-Object System.Text.UTF8Encoding($false)))
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
function Add-WhitelistName([string]$name) {
|
|
119
|
+
# 注意:不能用 RCON 的 whitelist add —— 服务端会把名字转小写再算 UUID,
|
|
120
|
+
# 和玩家实际登录时的 UUID(保留大小写)对不上,导致白名单失效。
|
|
121
|
+
# 这里自己按原始大小写写 whitelist.json,再让服务端 reload。
|
|
122
|
+
$list = @(Read-Whitelist | Where-Object { $_.name -ine $name })
|
|
123
|
+
$list += [pscustomobject]@{ uuid = (Get-OfflineUuid $name); name = $name }
|
|
124
|
+
Save-Whitelist $list
|
|
125
|
+
if (Get-ServerProcess) {
|
|
126
|
+
try { Invoke-Rcon 'whitelist reload' 5000 | Out-Null } catch { }
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
function Remove-WhitelistName([string]$name) {
|
|
131
|
+
$list = @(Read-Whitelist | Where-Object { $_.name -ine $name })
|
|
132
|
+
Save-Whitelist $list
|
|
133
|
+
if (Get-ServerProcess) {
|
|
134
|
+
try { Invoke-Rcon 'whitelist reload' 5000 | Out-Null } catch { }
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
function Enable-Whitelist {
|
|
139
|
+
if (Get-ServerProcess) {
|
|
140
|
+
try { Invoke-Rcon 'whitelist on' 5000 | Out-Null } catch { }
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
$VoteConfigFile = Join-Path $DataDir 'vote-config.json'
|
|
145
|
+
$VoteApproveNeed = 2
|
|
146
|
+
$VoteRejectNeed = 1
|
|
147
|
+
$VoteTimeoutMinutes = 15
|
|
148
|
+
$VoteVetoEnabled = $true
|
|
149
|
+
try {
|
|
150
|
+
if (Test-Path $VoteConfigFile) {
|
|
151
|
+
$vc = Get-Content $VoteConfigFile -Raw -Encoding UTF8 | ConvertFrom-Json
|
|
152
|
+
if ($vc.approveNeed) { $VoteApproveNeed = [Math]::Max(1, [int]$vc.approveNeed) }
|
|
153
|
+
if ($vc.rejectNeed) { $VoteRejectNeed = [Math]::Max(1, [int]$vc.rejectNeed) }
|
|
154
|
+
if ($vc.timeoutMinutes) { $VoteTimeoutMinutes = [Math]::Max(1, [int]$vc.timeoutMinutes) }
|
|
155
|
+
if ($null -ne $vc.vetoEnabled) { $VoteVetoEnabled = [bool]$vc.vetoEnabled }
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
catch { }
|
|
159
|
+
|
|
160
|
+
# 到点没凑够门槛的投票自动作废,避免一直挂在「待确认」里
|
|
161
|
+
function Clear-ExpiredVotes {
|
|
162
|
+
$all = @(Get-Votes)
|
|
163
|
+
if ($all.Count -eq 0) { return }
|
|
164
|
+
$changed = $false
|
|
165
|
+
foreach ($v in $all) {
|
|
166
|
+
if ($v.status -eq 'open' -and $v.expiresAt -and ((Get-Date) -gt [datetime]$v.expiresAt)) {
|
|
167
|
+
$v.status = 'expired'
|
|
168
|
+
$changed = $true
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
if ($changed) { Save-Votes $all }
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
function Get-Votes {
|
|
175
|
+
$doc = Read-Json $VoteFile @()
|
|
176
|
+
$list = @()
|
|
177
|
+
foreach ($x in @($doc)) {
|
|
178
|
+
if ($x -and $x.id) {
|
|
179
|
+
$list += [pscustomobject]@{
|
|
180
|
+
id = [string]$x.id
|
|
181
|
+
desc = [string]$x.desc
|
|
182
|
+
need = [int]$x.need
|
|
183
|
+
votes = @($x.votes)
|
|
184
|
+
rejects = @($x.rejects)
|
|
185
|
+
status = [string]$x.status
|
|
186
|
+
createdAt = [string]$x.createdAt
|
|
187
|
+
expiresAt = [string]$x.expiresAt
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
return $list
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
function Save-Votes($list) {
|
|
195
|
+
$json = ConvertTo-Json -InputObject @($list) -Depth 6
|
|
196
|
+
[System.IO.File]::WriteAllText($VoteFile, $json, (New-Object System.Text.UTF8Encoding($false)))
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
function Get-RconPassword {
|
|
200
|
+
$hit = Select-String -Path $PropsFile -Pattern '^rcon\.password=' | Select-Object -First 1
|
|
201
|
+
if (-not $hit) { return '' }
|
|
202
|
+
return ($hit.Line -replace '^rcon\.password=', '').Trim()
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
# 静态命令拦截(与 ops/command-guard.mjs 同规则):只拦“一条命令搞崩整个服”的类型。
|
|
206
|
+
# 这里不判身份——stop 这类“仅服主”的闸由 action 层的 Assert-Owner 负责,
|
|
207
|
+
# 因为 restart 走的是 doStop → RCON stop,玩家在假死时本来就有权重启。
|
|
208
|
+
function Assert-CommandSafe([string]$Command) {
|
|
209
|
+
if ([string]::IsNullOrWhiteSpace($Command)) { return }
|
|
210
|
+
$c = (($Command.Trim() -replace '^/+', '') -replace '\s+', ' ')
|
|
211
|
+
if ($c -match '^(say|tell|msg|tellraw|title|subtitle|actionbar)\b') { return }
|
|
212
|
+
if ($c -match '^kill\s+(@[aer]\b|\*)') { throw 'BLOCKED: kill @a / @e / @r 会一次清场,已拦截。' }
|
|
213
|
+
if ($c -match '^kick\s+@[ae]\b') { throw 'BLOCKED: kick @a / @e 会踢光所有人,已拦截。' }
|
|
214
|
+
if ($c -match '^whitelist\s+(off|clear)\b') { throw 'BLOCKED: 关白名单/清空白名单已拦截。' }
|
|
215
|
+
if ($c -match '^execute\b.*\brun\s+kill\s+(@[aer]\b|\*)') { throw 'BLOCKED: execute ... run kill @a 已拦截。' }
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
function Invoke-Rcon([string]$Command, [int]$TimeoutMs = 8000) {
|
|
219
|
+
Assert-CommandSafe $Command
|
|
220
|
+
$pass = Get-RconPassword
|
|
221
|
+
if (-not $pass) { throw 'rcon password missing' }
|
|
222
|
+
$tcp = New-Object System.Net.Sockets.TcpClient
|
|
223
|
+
$ar = $tcp.BeginConnect('127.0.0.1', 25575, $null, $null)
|
|
224
|
+
if (-not $ar.AsyncWaitHandle.WaitOne($TimeoutMs)) { $tcp.Close(); throw 'rcon connect timeout' }
|
|
225
|
+
$tcp.EndConnect($ar)
|
|
226
|
+
$stream = $tcp.GetStream()
|
|
227
|
+
$stream.ReadTimeout = $TimeoutMs
|
|
228
|
+
|
|
229
|
+
function Send-Packet([int]$id, [int]$type, [string]$body) {
|
|
230
|
+
$payload = [System.Text.Encoding]::UTF8.GetBytes($body)
|
|
231
|
+
$len = 4 + 4 + $payload.Length + 2
|
|
232
|
+
$buf = New-Object byte[] (4 + $len)
|
|
233
|
+
[Array]::Copy([BitConverter]::GetBytes([int]$len), 0, $buf, 0, 4)
|
|
234
|
+
[Array]::Copy([BitConverter]::GetBytes([int]$id), 0, $buf, 4, 4)
|
|
235
|
+
[Array]::Copy([BitConverter]::GetBytes([int]$type), 0, $buf, 8, 4)
|
|
236
|
+
[Array]::Copy($payload, 0, $buf, 12, $payload.Length)
|
|
237
|
+
$stream.Write($buf, 0, $buf.Length); $stream.Flush()
|
|
238
|
+
}
|
|
239
|
+
function Read-Exact([int]$n) {
|
|
240
|
+
$b = New-Object byte[] $n; $off = 0
|
|
241
|
+
while ($off -lt $n) {
|
|
242
|
+
$r = $stream.Read($b, $off, $n - $off)
|
|
243
|
+
if ($r -le 0) { throw 'rcon connection closed' }
|
|
244
|
+
$off += $r
|
|
245
|
+
}
|
|
246
|
+
return $b
|
|
247
|
+
}
|
|
248
|
+
function Read-Packet {
|
|
249
|
+
$len = [BitConverter]::ToInt32((Read-Exact 4), 0)
|
|
250
|
+
$data = Read-Exact $len
|
|
251
|
+
return [pscustomobject]@{
|
|
252
|
+
Id = [BitConverter]::ToInt32($data, 0)
|
|
253
|
+
Type = [BitConverter]::ToInt32($data, 4)
|
|
254
|
+
Body = [System.Text.Encoding]::UTF8.GetString($data, 8, $len - 10)
|
|
255
|
+
}
|
|
256
|
+
}
|
|
257
|
+
try {
|
|
258
|
+
Send-Packet 1 3 $pass
|
|
259
|
+
$auth = Read-Packet
|
|
260
|
+
if ($auth.Id -eq -1) { throw 'rcon auth failed' }
|
|
261
|
+
Send-Packet 2 2 $Command
|
|
262
|
+
$resp = Read-Packet
|
|
263
|
+
return $resp.Body.Trim()
|
|
264
|
+
}
|
|
265
|
+
finally { $tcp.Close() }
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
function Get-ServerProcess {
|
|
269
|
+
if (Test-Path $PidFile) {
|
|
270
|
+
$raw = (Get-Content $PidFile -Raw).Trim()
|
|
271
|
+
if ($raw -match '^\d+$') {
|
|
272
|
+
$p = Get-Process -Id ([int]$raw) -ErrorAction SilentlyContinue
|
|
273
|
+
if ($p -and $p.ProcessName -eq 'java') { return $p }
|
|
274
|
+
}
|
|
275
|
+
}
|
|
276
|
+
return (Get-Process -Name java -ErrorAction SilentlyContinue |
|
|
277
|
+
Where-Object { try { $_.Path -like "$ServerDir*" } catch { $false } } |
|
|
278
|
+
Select-Object -First 1)
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
function Get-LiveLogPath {
|
|
282
|
+
if (Test-Path $LogFile) {
|
|
283
|
+
try { if ((Get-Item -LiteralPath $LogFile).Length -gt 0) { return $LogFile } } catch { }
|
|
284
|
+
}
|
|
285
|
+
return (Join-Path $LogDir 'console.log')
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
function Get-ConsoleTail([int]$count = 40) {
|
|
289
|
+
$f = Get-LiveLogPath
|
|
290
|
+
if (-not (Test-Path $f)) { return '' }
|
|
291
|
+
try { $data = @(Get-Content -LiteralPath $f -Tail $count -Encoding UTF8) } catch { return '' }
|
|
292
|
+
if ($data.Count -eq 0) { return '' }
|
|
293
|
+
return ($data -join [Environment]::NewLine)
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
function Get-CleanLog([int]$count) {
|
|
297
|
+
$raw = Get-ConsoleTail ([Math]::Max($count * 3, 60))
|
|
298
|
+
$kept = @(($raw -split "`r?`n") | Where-Object { $_ -and ($_ -notmatch 'RCON (Client|Listener)') })
|
|
299
|
+
if ($kept.Count -gt $count) { $kept = @($kept | Select-Object -Last $count) }
|
|
300
|
+
return ($kept -join [Environment]::NewLine)
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
$WatchdogTask = 'CBC-Server-Watchdog'
|
|
304
|
+
|
|
305
|
+
# 有计划的看门狗任务就拉起任务,没有(别的机器上没配过)就直接起 watchdog.ps1
|
|
306
|
+
function Start-Watchdog {
|
|
307
|
+
$taskExists = $false
|
|
308
|
+
try {
|
|
309
|
+
schtasks /Query /TN $WatchdogTask *> $null
|
|
310
|
+
$taskExists = ($LASTEXITCODE -eq 0)
|
|
311
|
+
} catch { }
|
|
312
|
+
if ($taskExists) {
|
|
313
|
+
try { schtasks /Run /TN $WatchdogTask *> $null } catch { }
|
|
314
|
+
return
|
|
315
|
+
}
|
|
316
|
+
$wdScript = Join-Path $OpsDir 'watchdog.ps1'
|
|
317
|
+
if (-not (Test-Path $wdScript)) { return }
|
|
318
|
+
try {
|
|
319
|
+
Start-Process -FilePath 'powershell.exe' -ArgumentList @('-NoProfile', '-ExecutionPolicy', 'Bypass', '-WindowStyle', 'Hidden', '-File', $wdScript, '-ServerDir', $ServerDir) -WindowStyle Hidden | Out-Null
|
|
320
|
+
} catch { }
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
function Start-McServer {
|
|
324
|
+
$proc = Get-ServerProcess
|
|
325
|
+
if ($proc) { return "already running (pid $($proc.Id))" }
|
|
326
|
+
$java = Join-Path $ServerDir 'java\bin\java.exe'
|
|
327
|
+
if (-not (Test-Path $java)) { throw "java not found: $java" }
|
|
328
|
+
# 交给计划任务里的守护进程启动:父进程是任务计划服务,关闭 DSH 不会带走服务器
|
|
329
|
+
$state = Read-Json $StateFile ([pscustomobject]@{})
|
|
330
|
+
$state | Add-Member -Force -NotePropertyName desired -NotePropertyValue $true
|
|
331
|
+
Write-Json $StateFile $state
|
|
332
|
+
$wdAlive = $false
|
|
333
|
+
$wpidFile = Join-Path $DataDir 'watchdog.pid'
|
|
334
|
+
if (Test-Path $wpidFile) {
|
|
335
|
+
$wid = (Get-Content $wpidFile -Raw).Trim()
|
|
336
|
+
if ($wid -match '^\d+$' -and (Get-Process -Id ([int]$wid) -ErrorAction SilentlyContinue)) { $wdAlive = $true }
|
|
337
|
+
}
|
|
338
|
+
if (-not $wdAlive) { Start-Watchdog }
|
|
339
|
+
$deadline = (Get-Date).AddSeconds(30)
|
|
340
|
+
while ((Get-Date) -lt $deadline) {
|
|
341
|
+
Start-Sleep -Seconds 2
|
|
342
|
+
$javaProc = Get-ServerProcess
|
|
343
|
+
if ($javaProc) {
|
|
344
|
+
$javaProc.Id | Set-Content $PidFile -Encoding ASCII
|
|
345
|
+
return "已启动(pid $($javaProc.Id),前台控制台窗口已打开)"
|
|
346
|
+
}
|
|
347
|
+
}
|
|
348
|
+
return '已请求启动,守护进程正在拉起服务器(加载约 40 秒)'
|
|
349
|
+
try {
|
|
350
|
+
$wdAlive = $false
|
|
351
|
+
if (Test-Path (Join-Path $DataDir 'watchdog.pid')) {
|
|
352
|
+
$wid = (Get-Content (Join-Path $DataDir 'watchdog.pid') -Raw).Trim()
|
|
353
|
+
if ($wid -match '^\d+$' -and (Get-Process -Id ([int]$wid) -ErrorAction SilentlyContinue)) { $wdAlive = $true }
|
|
354
|
+
}
|
|
355
|
+
if (-not $wdAlive) { schtasks /Run /TN 'CBC-Server-Watchdog' 2>&1 | Out-Null }
|
|
356
|
+
} catch { }
|
|
357
|
+
$state = Read-Json $StateFile ([pscustomobject]@{})
|
|
358
|
+
$state | Add-Member -Force -NotePropertyName desired -NotePropertyValue $true
|
|
359
|
+
Write-Json $StateFile $state
|
|
360
|
+
return "started (pid $($p.Id))"
|
|
361
|
+
}
|
|
362
|
+
|
|
363
|
+
function Stop-McServer([int]$WaitSec = 45, [switch]$Force) {
|
|
364
|
+
$proc = Get-ServerProcess
|
|
365
|
+
$state = Read-Json $StateFile ([pscustomobject]@{})
|
|
366
|
+
$state | Add-Member -Force -NotePropertyName desired -NotePropertyValue $false
|
|
367
|
+
Write-Json $StateFile $state
|
|
368
|
+
if (-not $proc) { return 'not running' }
|
|
369
|
+
try { Invoke-Rcon 'stop' 2500 | Out-Null } catch { }
|
|
370
|
+
$wait = $WaitSec
|
|
371
|
+
if ($Force) { $wait = 8 }
|
|
372
|
+
$deadline = (Get-Date).AddSeconds($wait)
|
|
373
|
+
while ((Get-Date) -lt $deadline) {
|
|
374
|
+
Start-Sleep -Seconds 1
|
|
375
|
+
if (-not (Get-Process -Id $proc.Id -ErrorAction SilentlyContinue)) { return 'stopped' }
|
|
376
|
+
}
|
|
377
|
+
Stop-Process -Id $proc.Id -Force -ErrorAction SilentlyContinue
|
|
378
|
+
return 'force-killed'
|
|
379
|
+
}
|
|
380
|
+
|
|
381
|
+
function Get-StatusText {
|
|
382
|
+
$proc = Get-ServerProcess
|
|
383
|
+
$os = Get-CimInstance Win32_OperatingSystem
|
|
384
|
+
$sysTotal = [math]::Round($os.TotalVisibleMemorySize / 1024)
|
|
385
|
+
$sysFree = [math]::Round($os.FreePhysicalMemory / 1024)
|
|
386
|
+
|
|
387
|
+
$health = Get-ServerHealth
|
|
388
|
+
$healthText = '未运行'
|
|
389
|
+
if ($health.state -eq 'healthy') { $healthText = '正常' }
|
|
390
|
+
elseif ($health.state -eq 'lagging') { $healthText = '卡顿(TPS ' + $health.tps + ')' }
|
|
391
|
+
elseif ($health.state -eq 'unresponsive') { $healthText = '无响应/假死' }
|
|
392
|
+
elseif ($health.state -eq 'booting') { $healthText = '启动中' }
|
|
393
|
+
|
|
394
|
+
$running = 'no'
|
|
395
|
+
$pidText = '-'
|
|
396
|
+
$uptime = '-'
|
|
397
|
+
$cpu = '-'
|
|
398
|
+
$mem = '-'
|
|
399
|
+
$players = '-'
|
|
400
|
+
$tps = '-'
|
|
401
|
+
if ($proc) {
|
|
402
|
+
$running = 'yes'
|
|
403
|
+
$pidText = [string]$proc.Id
|
|
404
|
+
try { $uptime = ((Get-Date) - $proc.StartTime).ToString('d\.hh\:mm\:ss') } catch { }
|
|
405
|
+
try {
|
|
406
|
+
$c1 = $proc.CPU
|
|
407
|
+
Start-Sleep -Milliseconds 700
|
|
408
|
+
$proc.Refresh()
|
|
409
|
+
$c2 = $proc.CPU
|
|
410
|
+
$cpu = [string][math]::Round((($c2 - $c1) / 0.7) * 100 / [Environment]::ProcessorCount, 1) + '%'
|
|
411
|
+
} catch { }
|
|
412
|
+
$mem = [string][math]::Round($proc.WorkingSet64 / 1MB) + ' MB'
|
|
413
|
+
try {
|
|
414
|
+
$list = Invoke-Rcon 'list' 4000
|
|
415
|
+
if ($list -match 'There are (\d+) of a max of (\d+) players online:?\s*(.*)') {
|
|
416
|
+
$players = $Matches[1] + '/' + $Matches[2]
|
|
417
|
+
if ($Matches[3].Trim()) { $players = $players + ' (' + $Matches[3].Trim() + ')' }
|
|
418
|
+
}
|
|
419
|
+
} catch { }
|
|
420
|
+
$tpsProbe = Get-ServerTps
|
|
421
|
+
if ($null -ne $tpsProbe) { $tps = $tpsProbe }
|
|
422
|
+
|
|
423
|
+
}
|
|
424
|
+
|
|
425
|
+
$difficulty = '-'; $port = '35942'
|
|
426
|
+
foreach ($line in (Get-Content $PropsFile -ErrorAction SilentlyContinue)) {
|
|
427
|
+
if ($line -match '^difficulty=(.*)$') { $difficulty = $Matches[1] }
|
|
428
|
+
if ($line -match '^server-port=(\d+)$') { $port = $Matches[1] }
|
|
429
|
+
}
|
|
430
|
+
$diskFree = '-'
|
|
431
|
+
$driveLetter = (Get-Item $ServerDir).PSDrive.Name
|
|
432
|
+
$drv = Get-PSDrive $driveLetter
|
|
433
|
+
if ($drv) { $diskFree = [string][math]::Round($drv.Free / 1GB, 1) + ' GB' }
|
|
434
|
+
$worldSize = '-'
|
|
435
|
+
$worldDir = Join-Path $ServerDir 'world'
|
|
436
|
+
if (Test-Path $worldDir) {
|
|
437
|
+
$sum = (Get-ChildItem $worldDir -Recurse -File -ErrorAction SilentlyContinue | Measure-Object Length -Sum).Sum
|
|
438
|
+
if ($sum) { $worldSize = [string][math]::Round($sum / 1MB) + ' MB' }
|
|
439
|
+
}
|
|
440
|
+
$state = Read-Json $StateFile ([pscustomobject]@{})
|
|
441
|
+
$restarts = @(Get-Prop $state 'restarts' @()).Count
|
|
442
|
+
|
|
443
|
+
$text = "运行: $running 健康: $healthText pid: $pidText 在线: $players`n"
|
|
444
|
+
$text += "CPU: $cpu 内存: $mem 系统剩余: $sysFree / $sysTotal MB`n"
|
|
445
|
+
$text += "TPS: $tps 运行时长: $uptime 重启次数: $restarts`n"
|
|
446
|
+
$text += "地图: $worldSize 磁盘剩余: $diskFree`n"
|
|
447
|
+
if ($health.state -eq 'unresponsive') { $text += "`n`n[!] 服务器已假死:进程还在但没有响应(RCON 连续超时)。任何人现在都可以执行 restart 强制重启。" }
|
|
448
|
+
elseif ($health.state -eq 'lagging') { $text += "`n`n[!] 服务器严重卡顿(TPS " + $health.tps + "),接近假死;如果持续不恢复,建议 restart。" }
|
|
449
|
+
$text += "`n难度: $difficulty 端口: $port"
|
|
450
|
+
return $text
|
|
451
|
+
}
|
|
452
|
+
|
|
453
|
+
function Get-RateFile { Join-Path $DataDir 'ratelimit.json' }
|
|
454
|
+
|
|
455
|
+
function Assert-SayRate {
|
|
456
|
+
$rl = Read-Json (Get-RateFile) ([pscustomobject]@{})
|
|
457
|
+
$now = (Get-Date).ToUniversalTime()
|
|
458
|
+
$last = Get-Prop $rl 'sayAt' $null
|
|
459
|
+
if ($last) {
|
|
460
|
+
$dt = [datetime]$last
|
|
461
|
+
if (($now - $dt.ToUniversalTime()).TotalSeconds -lt 5) { throw 'RATE_LIMIT: 广播太频繁,请等 5 秒再试。' }
|
|
462
|
+
}
|
|
463
|
+
$rl | Add-Member -Force -NotePropertyName sayAt -NotePropertyValue $now.ToString('o')
|
|
464
|
+
Write-Json (Get-RateFile) $rl
|
|
465
|
+
}
|
|
466
|
+
|
|
467
|
+
function Assert-StartCooldown {
|
|
468
|
+
$rl = Read-Json (Get-RateFile) ([pscustomobject]@{})
|
|
469
|
+
$now = (Get-Date).ToUniversalTime()
|
|
470
|
+
$last = Get-Prop $rl 'startAt' $null
|
|
471
|
+
if ($last) {
|
|
472
|
+
$dt = [datetime]$last
|
|
473
|
+
if (($now - $dt.ToUniversalTime()).TotalSeconds -lt 90) { throw 'COOLDOWN: 刚发起过启动,服务器正在加载,请等大约 1 分钟再试。' }
|
|
474
|
+
}
|
|
475
|
+
$rl | Add-Member -Force -NotePropertyName startAt -NotePropertyValue $now.ToString('o')
|
|
476
|
+
Write-Json (Get-RateFile) $rl
|
|
477
|
+
}
|
|
478
|
+
|
|
479
|
+
function Get-ServerTps {
|
|
480
|
+
# 不同服务端 TPS 命令不一样:Forge/NeoForge=forge tps,Paper/Spigot= tps,Fabric(Carpet)=carpet tps,spark=spark tps
|
|
481
|
+
$probes = @(
|
|
482
|
+
@{ cmd = 'forge tps'; re = 'Mean TPS:\s*([\d.]+)' },
|
|
483
|
+
@{ cmd = 'tps'; re = 'TPS[^\d]*([\d.]+)' },
|
|
484
|
+
@{ cmd = 'spark tps'; re = 'TPS[^\d]*([\d.]+)' },
|
|
485
|
+
@{ cmd = 'carpet tps'; re = 'TPS[^\d]*([\d.]+)' }
|
|
486
|
+
)
|
|
487
|
+
foreach ($p in $probes) {
|
|
488
|
+
try {
|
|
489
|
+
$out = Invoke-Rcon $p.cmd 3000
|
|
490
|
+
if ($out -and ($out -match $p.re)) { return [double]$Matches[1] }
|
|
491
|
+
}
|
|
492
|
+
catch { }
|
|
493
|
+
}
|
|
494
|
+
return $null
|
|
495
|
+
}
|
|
496
|
+
|
|
497
|
+
function Get-ServerHealth {
|
|
498
|
+
$proc = Get-ServerProcess
|
|
499
|
+
if (-not $proc) {
|
|
500
|
+
return [pscustomobject]@{ state = 'stopped'; tps = $null; rcon = $false; pid = $null; detail = '未运行' }
|
|
501
|
+
}
|
|
502
|
+
# 以 RCON 为准:日志按天滚动(latest.log 每天 0 点重建),靠日志里的 "Done (" 判断会误报「启动中」。
|
|
503
|
+
$rconOk = $false
|
|
504
|
+
$lastErr = ''
|
|
505
|
+
for ($i = 0; $i -lt 2 -and -not $rconOk; $i++) {
|
|
506
|
+
try { Invoke-Rcon 'list' 3000 | Out-Null; $rconOk = $true }
|
|
507
|
+
catch { $lastErr = $_.Exception.Message; Start-Sleep -Milliseconds 400 }
|
|
508
|
+
}
|
|
509
|
+
if (-not $rconOk) {
|
|
510
|
+
$age = 99999
|
|
511
|
+
try { $age = ((Get-Date) - $proc.StartTime).TotalSeconds } catch { }
|
|
512
|
+
if ($age -lt 180) {
|
|
513
|
+
return [pscustomobject]@{ state = 'booting'; tps = $null; rcon = $false; pid = $proc.Id; detail = '启动中' }
|
|
514
|
+
}
|
|
515
|
+
return [pscustomobject]@{ state = 'unresponsive'; tps = $null; rcon = $false; pid = $proc.Id; detail = 'RCON 无响应,疑似假死' }
|
|
516
|
+
}
|
|
517
|
+
$tps = Get-ServerTps
|
|
518
|
+
|
|
519
|
+
if ($null -ne $tps -and $tps -lt 3) {
|
|
520
|
+
return [pscustomobject]@{ state = 'lagging'; tps = $tps; rcon = $true; pid = $proc.Id; detail = "TPS $tps,严重卡顿" }
|
|
521
|
+
}
|
|
522
|
+
return [pscustomobject]@{ state = 'healthy'; tps = $tps; rcon = $true; pid = $proc.Id; detail = '正常' }
|
|
523
|
+
}
|
|
524
|
+
|
|
525
|
+
function Get-ServerPhase {
|
|
526
|
+
return (Get-ServerHealth).state
|
|
527
|
+
}
|
|
528
|
+
|
|
529
|
+
function Assert-Owner {
|
|
530
|
+
if ($role -ne 'owner') {
|
|
531
|
+
if ([string]::IsNullOrWhiteSpace($Actor)) {
|
|
532
|
+
throw 'NO_ACTOR: 无法识别发送者身份(缺少 [昵称(ID)] 标记),已拒绝。'
|
|
533
|
+
}
|
|
534
|
+
throw 'FORBIDDEN: 该操作仅服主可用。'
|
|
535
|
+
}
|
|
536
|
+
}
|
|
537
|
+
|
|
538
|
+
# ---------------- 动作 ----------------
|
|
539
|
+
$result = ''
|
|
540
|
+
try {
|
|
541
|
+
switch ($Action) {
|
|
542
|
+
|
|
543
|
+
'status' { $result = Get-StatusText }
|
|
544
|
+
|
|
545
|
+
'players' {
|
|
546
|
+
if (-not (Get-ServerProcess)) { $result = '服务器未运行' }
|
|
547
|
+
else { $result = (Invoke-Rcon 'list') }
|
|
548
|
+
}
|
|
549
|
+
|
|
550
|
+
'say' {
|
|
551
|
+
if (-not $Arg) { throw 'USAGE: say <message>' }
|
|
552
|
+
if (-not (Get-ServerProcess)) { throw '服务器未运行' }
|
|
553
|
+
$msg = ($Arg -replace '[\r\n]+', ' ').Trim()
|
|
554
|
+
if ($msg.Length -gt 200) { $msg = $msg.Substring(0, 200) + '...' }
|
|
555
|
+
Assert-SayRate
|
|
556
|
+
Invoke-Rcon ('say ' + $msg) | Out-Null
|
|
557
|
+
$result = "已广播: $msg"
|
|
558
|
+
}
|
|
559
|
+
|
|
560
|
+
'cmd' {
|
|
561
|
+
Assert-Owner
|
|
562
|
+
if (-not $Arg) { throw 'USAGE: cmd <minecraft command>' }
|
|
563
|
+
if (-not (Get-ServerProcess)) { throw '服务器未运行' }
|
|
564
|
+
$clean = $Arg.Trim().TrimStart('/')
|
|
565
|
+
$r = Invoke-Rcon $clean
|
|
566
|
+
if (-not $r) { $r = '已执行' }
|
|
567
|
+
$result = $r
|
|
568
|
+
}
|
|
569
|
+
|
|
570
|
+
'start' {
|
|
571
|
+
$health = Get-ServerHealth
|
|
572
|
+
if ($health.state -eq 'stopped') {
|
|
573
|
+
if ([string]::IsNullOrWhiteSpace($Actor)) { throw 'NO_ACTOR: 无法识别发送者身份,已拒绝。' }
|
|
574
|
+
if ($role -ne 'owner') { Assert-StartCooldown }
|
|
575
|
+
$result = Start-McServer
|
|
576
|
+
}
|
|
577
|
+
elseif ($health.state -eq 'booting') {
|
|
578
|
+
if ($role -eq 'owner') { $result = '服务器正在启动中(约 40 秒),如需强制重启用 restart' }
|
|
579
|
+
else { throw 'DENIED: 服务器正在启动中,请等它加载完成(约 40 秒),不要重复启动。' }
|
|
580
|
+
}
|
|
581
|
+
elseif ($health.state -eq 'unresponsive') {
|
|
582
|
+
throw 'DENIED: 服务器进程还在但已无响应(假死)。请改用 restart 强制重启(任何人可用)。'
|
|
583
|
+
}
|
|
584
|
+
else {
|
|
585
|
+
if ($role -eq 'owner') { $result = '服务器在线且响应正常(' + $health.detail + '),无需启动' }
|
|
586
|
+
else { throw 'DENIED: 服务器在线且响应正常,玩家无权启动/重启。只有确认关闭或确认无响应(假死)时,才能由玩家 restart。' }
|
|
587
|
+
}
|
|
588
|
+
}
|
|
589
|
+
|
|
590
|
+
'stop' {
|
|
591
|
+
Assert-Owner
|
|
592
|
+
$result = Stop-McServer
|
|
593
|
+
}
|
|
594
|
+
|
|
595
|
+
'restart' {
|
|
596
|
+
$health = Get-ServerHealth
|
|
597
|
+
if ($health.state -eq 'stopped') {
|
|
598
|
+
if ([string]::IsNullOrWhiteSpace($Actor)) { throw 'NO_ACTOR: 无法识别发送者身份,已拒绝。' }
|
|
599
|
+
if ($role -ne 'owner') { Assert-StartCooldown }
|
|
600
|
+
$result = '服务器确认已关闭,直接启动:' + (Start-McServer)
|
|
601
|
+
}
|
|
602
|
+
elseif ($health.state -eq 'unresponsive') {
|
|
603
|
+
if ([string]::IsNullOrWhiteSpace($Actor)) { throw 'NO_ACTOR: 无法识别发送者身份,已拒绝。' }
|
|
604
|
+
$stopped = Stop-McServer -Force
|
|
605
|
+
Start-Sleep -Seconds 2
|
|
606
|
+
$result = "检测到假死($($health.detail)),已强制结束:$stopped;" + (Start-McServer)
|
|
607
|
+
}
|
|
608
|
+
else {
|
|
609
|
+
if ($role -ne 'owner') {
|
|
610
|
+
if ($health.state -eq 'booting') {
|
|
611
|
+
throw 'DENIED: 服务器正在启动中,玩家不能重启,等它加载完成(约 40 秒)。'
|
|
612
|
+
}
|
|
613
|
+
throw 'DENIED: 服务器在线且响应正常,玩家无权重启。只有确认关闭或确认无响应(假死)时才能由玩家重启;正常在线时的重启请找服主。'
|
|
614
|
+
}
|
|
615
|
+
$stopped = Stop-McServer
|
|
616
|
+
Start-Sleep -Seconds 2
|
|
617
|
+
$result = "停止: $stopped;" + (Start-McServer)
|
|
618
|
+
}
|
|
619
|
+
}
|
|
620
|
+
|
|
621
|
+
'gamemode' {
|
|
622
|
+
if (-not $Arg) { throw 'USAGE: gamemode <survival|spectator|creative|adventure> <玩家名>' }
|
|
623
|
+
if ([string]::IsNullOrWhiteSpace($Actor)) { throw 'NO_ACTOR: 无法识别发送者身份,已拒绝。' }
|
|
624
|
+
$parts = @($Arg.Trim() -split '\s+', 2)
|
|
625
|
+
if ($parts.Count -lt 2) { throw 'USAGE: gamemode <模式> <玩家名>' }
|
|
626
|
+
$mode = $parts[0].ToLower()
|
|
627
|
+
$target = $parts[1].Trim()
|
|
628
|
+
if (@('survival', 'spectator', 'creative', 'adventure') -notcontains $mode) { throw 'USAGE: 模式只能是 survival / spectator / creative / adventure' }
|
|
629
|
+
if (@('survival', 'spectator') -notcontains $mode) { Assert-Owner }
|
|
630
|
+
elseif ($role -ne 'owner') {
|
|
631
|
+
$mine = @(Get-Bindings | Where-Object { $_.qq -eq $Actor })
|
|
632
|
+
$allowed = @($mine | Where-Object { $_.name -ieq $target })
|
|
633
|
+
if ($allowed.Count -eq 0) {
|
|
634
|
+
if ($mine.Count -eq 0) { throw 'FORBIDDEN: 你还没绑定游戏名。先发「绑定游戏名 你的ID」,绑好之后只能切自己的名字。' }
|
|
635
|
+
throw ("FORBIDDEN: 只能切换自己绑定的游戏名(你绑了:" + (($mine | ForEach-Object { $_.name }) -join ', ') + ")。")
|
|
636
|
+
}
|
|
637
|
+
}
|
|
638
|
+
if (-not (Get-ServerProcess)) { throw '服务器未运行' }
|
|
639
|
+
$r = Invoke-Rcon ("gamemode " + $mode + " " + $target)
|
|
640
|
+
if (-not $r) { $r = '已执行' }
|
|
641
|
+
$result = $r
|
|
642
|
+
}
|
|
643
|
+
|
|
644
|
+
'bind-player' {
|
|
645
|
+
if ([string]::IsNullOrWhiteSpace($Actor)) { throw 'NO_ACTOR: 先在群里 @ 我一下再绑定。' }
|
|
646
|
+
if (-not $Arg) { throw 'USAGE: bind-player <游戏名>' }
|
|
647
|
+
$name = $Arg.Trim()
|
|
648
|
+
if ($name -notmatch '^[A-Za-z0-9_]{1,16}$') { throw '游戏名只能是 1-16 位字母、数字或下划线。' }
|
|
649
|
+
$all = @(Get-Bindings)
|
|
650
|
+
$mine = @($all | Where-Object { $_.qq -eq $Actor })
|
|
651
|
+
$dup = @($mine | Where-Object { $_.name -ieq $name })
|
|
652
|
+
if ($dup.Count -gt 0) { $result = "已经绑过 $name 了。" }
|
|
653
|
+
else {
|
|
654
|
+
if ($mine.Count -ge 10) { throw 'FORBIDDEN: 一个 QQ 最多绑 10 个游戏名,先解绑几个吧。' }
|
|
655
|
+
$owners = @($all | Where-Object { $_.name -ieq $name })
|
|
656
|
+
if ($owners.Count -ge 3) { throw 'FORBIDDEN: 这个游戏名已经被 3 个 QQ 绑定,不能再绑了。' }
|
|
657
|
+
$all += [pscustomobject]@{ qq = $Actor; name = $name; at = (Get-Date).ToString('o') }
|
|
658
|
+
Save-Bindings $all
|
|
659
|
+
Add-WhitelistName $name
|
|
660
|
+
Enable-Whitelist
|
|
661
|
+
$result = "绑定成功:$name(当前 $($mine.Count + 1)/10)。已经加进服务器白名单,可以进服了;切模式也只能用这个名字。"
|
|
662
|
+
}
|
|
663
|
+
}
|
|
664
|
+
|
|
665
|
+
'unbind-player' {
|
|
666
|
+
if ([string]::IsNullOrWhiteSpace($Actor)) { throw 'NO_ACTOR: 先在群里 @ 我一下。' }
|
|
667
|
+
if (-not $Arg) { throw 'USAGE: unbind-player <游戏名>' }
|
|
668
|
+
$name = $Arg.Trim()
|
|
669
|
+
$all = @(Get-Bindings)
|
|
670
|
+
$kept = @($all | Where-Object { -not ($_.qq -eq $Actor -and $_.name -ieq $name) })
|
|
671
|
+
if ($kept.Count -eq $all.Count) { $result = "没有找到这个绑定:$name" }
|
|
672
|
+
else {
|
|
673
|
+
Save-Bindings $kept
|
|
674
|
+
$still = @($kept | Where-Object { $_.name -ieq $name })
|
|
675
|
+
if ($still.Count -eq 0) { Remove-WhitelistName $name }
|
|
676
|
+
$result = "已解绑 $name。" + $(if ($still.Count -eq 0) { "已同时从服务器白名单移除。" } else { "这个游戏名还有 $($still.Count) 个 QQ 绑定着,白名单保留。" })
|
|
677
|
+
}
|
|
678
|
+
}
|
|
679
|
+
|
|
680
|
+
'my-players' {
|
|
681
|
+
if ([string]::IsNullOrWhiteSpace($Actor)) { throw 'NO_ACTOR: 先在群里 @ 我一下。' }
|
|
682
|
+
$mine = @(Get-Bindings | Where-Object { $_.qq -eq $Actor })
|
|
683
|
+
if ($mine.Count -eq 0) { $result = '你还没绑定游戏名,发「绑定游戏名 你的ID」就行。' }
|
|
684
|
+
else {
|
|
685
|
+
$online = @()
|
|
686
|
+
try {
|
|
687
|
+
$l = Invoke-Rcon 'list' 4000
|
|
688
|
+
if ($l -match 'online:?\s*(.*)$') { $online = @($Matches[1] -split ',' | ForEach-Object { $_.Trim() } | Where-Object { $_ }) }
|
|
689
|
+
} catch { }
|
|
690
|
+
$lines = @()
|
|
691
|
+
foreach ($b in $mine) {
|
|
692
|
+
$tag = if ($online -contains $b.name) { '在线' } else { '离线' }
|
|
693
|
+
$lines += " $($b.name) [$tag]"
|
|
694
|
+
}
|
|
695
|
+
$result = "你绑定的游戏名($($mine.Count)/10):`n" + ($lines -join "`n")
|
|
696
|
+
}
|
|
697
|
+
}
|
|
698
|
+
|
|
699
|
+
'bindings' {
|
|
700
|
+
Assert-Owner
|
|
701
|
+
$all = @(Get-Bindings)
|
|
702
|
+
if ($all.Count -eq 0) { $result = '还没有任何绑定。' }
|
|
703
|
+
else {
|
|
704
|
+
$result = (@($all | Group-Object qq | ForEach-Object { "$($_.Name): " + (($_.Group | ForEach-Object { $_.name }) -join ', ') })) -join "`n"
|
|
705
|
+
}
|
|
706
|
+
}
|
|
707
|
+
|
|
708
|
+
'whitelist-sync' {
|
|
709
|
+
Assert-Owner
|
|
710
|
+
$all = @(Get-Bindings)
|
|
711
|
+
$names = @($all | ForEach-Object { $_.name } | Select-Object -Unique)
|
|
712
|
+
foreach ($n in $names) { Add-WhitelistName $n }
|
|
713
|
+
Enable-Whitelist
|
|
714
|
+
if ($names.Count -eq 0) { $result = '当前没有任何绑定,白名单是空的。' }
|
|
715
|
+
else { $result = "已同步 $($names.Count) 个绑定名到白名单:" + ($names -join ', ') }
|
|
716
|
+
}
|
|
717
|
+
|
|
718
|
+
'kubejs-backup' {
|
|
719
|
+
$src = Join-Path $ServerDir 'kubejs\server_scripts'
|
|
720
|
+
if (-not (Test-Path $src)) { throw 'kubejs/server_scripts 不存在' }
|
|
721
|
+
$stamp = Get-Date -Format 'yyyyMMdd-HHmmss'
|
|
722
|
+
$dst = Join-Path $ServerDir ("kubejs\backups\server_scripts-" + $stamp)
|
|
723
|
+
New-Item -ItemType Directory -Force -Path $dst | Out-Null
|
|
724
|
+
$items = @(Get-ChildItem -LiteralPath $src -Force -ErrorAction SilentlyContinue)
|
|
725
|
+
foreach ($it in $items) { Copy-Item -LiteralPath $it.FullName -Destination $dst -Recurse -Force -ErrorAction SilentlyContinue }
|
|
726
|
+
$count = @(Get-ChildItem -LiteralPath $dst -Recurse -File -ErrorAction SilentlyContinue).Count
|
|
727
|
+
$result = "已备份 $count 个脚本文件到 $dst"
|
|
728
|
+
}
|
|
729
|
+
|
|
730
|
+
'kubejs-reload' {
|
|
731
|
+
if (-not (Get-ServerProcess)) { throw '服务器未运行' }
|
|
732
|
+
$parts = @()
|
|
733
|
+
try { $a = Invoke-Rcon 'kubejs reload server_scripts' 15000; if ($a) { $parts += $a } } catch { }
|
|
734
|
+
try { $b = Invoke-Rcon 'reload' 15000; if ($b) { $parts += $b } } catch { }
|
|
735
|
+
if ($parts.Count -eq 0) { $result = '已发送重载指令(KubeJS 不一定有回显)' }
|
|
736
|
+
else { $result = ($parts -join "`n") }
|
|
737
|
+
}
|
|
738
|
+
|
|
739
|
+
'vote-start' {
|
|
740
|
+
Clear-ExpiredVotes
|
|
741
|
+
if ([string]::IsNullOrWhiteSpace($Actor)) { throw 'NO_ACTOR: 先在群里 @ 我一下。' }
|
|
742
|
+
if (-not $Arg) { throw 'USAGE: vote-start <要做什么的一句话说明>' }
|
|
743
|
+
$all = @(Get-Votes)
|
|
744
|
+
$open = @($all | Where-Object { $_.status -eq 'open' })
|
|
745
|
+
if ($open.Count -ge 3) { throw '同时最多 3 个待确认投票,先等前面的处理完。' }
|
|
746
|
+
$id = (Get-Date -Format 'HHmmss')
|
|
747
|
+
$all += [pscustomobject]@{
|
|
748
|
+
id = $id
|
|
749
|
+
desc = $Arg.Trim()
|
|
750
|
+
need = $VoteApproveNeed
|
|
751
|
+
votes = @()
|
|
752
|
+
rejects = @()
|
|
753
|
+
status = 'open'
|
|
754
|
+
createdAt = (Get-Date).ToString('o')
|
|
755
|
+
expiresAt = (Get-Date).AddMinutes($VoteTimeoutMinutes).ToString('o')
|
|
756
|
+
}
|
|
757
|
+
Save-Votes $all
|
|
758
|
+
$result = '投票已发起,编号 ' + $id + '。需要 ' + $VoteApproveNeed + ' 位群友回复「同意 ' + $id + '」才会放行;' + $(if (-not $VoteVetoEnabled) { '当前设置关闭了一票否决,反对票只记录、不作废。' } elseif ($VoteRejectNeed -le 1) { '凑够 ' + $VoteApproveNeed + ' 票之前只要有人回复「拒绝 ' + $id + '」,这次就不授权了。' } else { '凑够 ' + $VoteApproveNeed + ' 票之前有 ' + $VoteRejectNeed + ' 人回复「拒绝 ' + $id + '」,这次就不授权了。' })
|
|
759
|
+
}
|
|
760
|
+
|
|
761
|
+
'vote-approve' {
|
|
762
|
+
Clear-ExpiredVotes
|
|
763
|
+
if ([string]::IsNullOrWhiteSpace($Actor)) { throw 'NO_ACTOR: 先在群里 @ 我一下。' }
|
|
764
|
+
if (-not $Arg) { throw 'USAGE: vote-approve <编号>' }
|
|
765
|
+
$id = $Arg.Trim()
|
|
766
|
+
$all = @(Get-Votes)
|
|
767
|
+
$vote = @($all | Where-Object { $_.id -eq $id }) | Select-Object -First 1
|
|
768
|
+
if (-not $vote) { throw "没有找到编号 $id 的投票。" }
|
|
769
|
+
if ($vote.status -eq 'rejected') { $result = "编号 $id 已经被否决了,这次不能授权,要动手得重新发起投票。" }
|
|
770
|
+
elseif ($vote.status -ne 'open') { $result = "这个投票已经结束($($vote.status))。" }
|
|
771
|
+
elseif ((Get-Date) -gt [datetime]$vote.expiresAt) {
|
|
772
|
+
$vote.status = 'expired'
|
|
773
|
+
Save-Votes $all
|
|
774
|
+
$result = '这个投票已经过期了,重新发起吧。'
|
|
775
|
+
}
|
|
776
|
+
else {
|
|
777
|
+
$voters = @($vote.votes | ForEach-Object { [string]$_.qq })
|
|
778
|
+
if ($voters -contains $Actor) { $result = "你已经投过了(当前 $($voters.Count)/$($vote.need))。" }
|
|
779
|
+
else {
|
|
780
|
+
$vote.votes = @($vote.votes) + @([pscustomobject]@{ qq = $Actor; at = (Get-Date).ToString('o') })
|
|
781
|
+
$count = @($vote.votes).Count
|
|
782
|
+
if ($count -ge $vote.need) {
|
|
783
|
+
$vote.status = 'passed'
|
|
784
|
+
$result = "投票通过($count/$($vote.need)):$($vote.desc)。已开放 10 分钟高权限窗口。"
|
|
785
|
+
}
|
|
786
|
+
else { $result = "已记录($count/$($vote.need)),还需要 $($vote.need - $count) 位群友确认。" }
|
|
787
|
+
Save-Votes $all
|
|
788
|
+
}
|
|
789
|
+
}
|
|
790
|
+
}
|
|
791
|
+
|
|
792
|
+
'vote-reject' {
|
|
793
|
+
Clear-ExpiredVotes
|
|
794
|
+
if ([string]::IsNullOrWhiteSpace($Actor)) { throw 'NO_ACTOR: 先在群里 @ 我一下。' }
|
|
795
|
+
if (-not $Arg) { throw 'USAGE: vote-reject <编号>' }
|
|
796
|
+
$id = $Arg.Trim()
|
|
797
|
+
$all = @(Get-Votes)
|
|
798
|
+
$vote = @($all | Where-Object { $_.id -eq $id }) | Select-Object -First 1
|
|
799
|
+
if (-not $vote) { throw "没有找到编号 $id 的投票。" }
|
|
800
|
+
if ($vote.status -eq 'passed') { $result = "编号 $id 已经通过并授权了,这时候再拒绝无效。" }
|
|
801
|
+
elseif ($vote.status -eq 'rejected') { $result = "编号 $id 已经否决过了,不用再点。" }
|
|
802
|
+
elseif ($vote.status -ne 'open') { $result = "这个投票已经结束($($vote.status)),拒绝无效。" }
|
|
803
|
+
elseif ((Get-Date) -gt [datetime]$vote.expiresAt) {
|
|
804
|
+
$vote.status = 'expired'
|
|
805
|
+
Save-Votes $all
|
|
806
|
+
$result = '这个投票已经过期了,不算数,重新发起吧。'
|
|
807
|
+
}
|
|
808
|
+
else {
|
|
809
|
+
$already = @($vote.rejects | ForEach-Object { [string]$_.qq })
|
|
810
|
+
if ($already -contains $Actor) {
|
|
811
|
+
$result = "你已经投过反对了(当前 $(@($vote.rejects).Count)/$VoteRejectNeed)。"
|
|
812
|
+
}
|
|
813
|
+
else {
|
|
814
|
+
$vote.rejects = @($vote.rejects) + @([pscustomobject]@{ qq = $Actor; at = (Get-Date).ToString('o') })
|
|
815
|
+
$rejectCount = @($vote.rejects).Count
|
|
816
|
+
if (-not $VoteVetoEnabled) {
|
|
817
|
+
Save-Votes $all
|
|
818
|
+
$result = "已记录反对($rejectCount 票),不过当前设置关闭了一票否决,这个投票继续有效。"
|
|
819
|
+
}
|
|
820
|
+
elseif ($rejectCount -ge $VoteRejectNeed) {
|
|
821
|
+
$vote.status = 'rejected'
|
|
822
|
+
$approved = @($vote.votes).Count
|
|
823
|
+
Save-Votes $all
|
|
824
|
+
$result = "编号 $id 已被否决:$($vote.desc)。刚才只有 $approved/$($vote.need) 票同意、$rejectCount/$VoteRejectNeed 票反对,这次不授权了,谁再点同意也不算,要动手得重新发起投票。"
|
|
825
|
+
}
|
|
826
|
+
else {
|
|
827
|
+
Save-Votes $all
|
|
828
|
+
$result = "已记录反对($rejectCount/$VoteRejectNeed),还差 $($VoteRejectNeed - $rejectCount) 票才会作废。"
|
|
829
|
+
}
|
|
830
|
+
}
|
|
831
|
+
}
|
|
832
|
+
}
|
|
833
|
+
|
|
834
|
+
'export-data' {
|
|
835
|
+
Assert-Owner
|
|
836
|
+
if (-not $Arg) { throw 'USAGE: export-data <zip 路径>' }
|
|
837
|
+
$dst = $Arg.Trim()
|
|
838
|
+
if (-not [System.IO.Path]::IsPathRooted($dst)) { $dst = Join-Path $ServerDir $dst }
|
|
839
|
+
$parent = Split-Path -Parent $dst
|
|
840
|
+
if ($parent -and -not (Test-Path $parent)) { New-Item -ItemType Directory -Force -Path $parent | Out-Null }
|
|
841
|
+
if (Test-Path $dst) { Remove-Item $dst -Force }
|
|
842
|
+
if (-not (Test-Path $DataDir)) { throw '没有可导出的数据目录。' }
|
|
843
|
+
Compress-Archive -Path (Join-Path $DataDir '*') -DestinationPath $dst -Force
|
|
844
|
+
$result = "已导出到 $dst(绑定、投票、服主名单、口令、投票门槛;不含存档和日志)"
|
|
845
|
+
}
|
|
846
|
+
|
|
847
|
+
'import-data' {
|
|
848
|
+
Assert-Owner
|
|
849
|
+
if (-not $Arg) { throw 'USAGE: import-data <zip 路径>' }
|
|
850
|
+
$src = $Arg.Trim()
|
|
851
|
+
if (-not [System.IO.Path]::IsPathRooted($src)) { $src = Join-Path $ServerDir $src }
|
|
852
|
+
if (-not (Test-Path $src)) { throw "找不到文件:$src" }
|
|
853
|
+
# 防 zip slip:条目里带 .. 或绝对路径的直接拒绝
|
|
854
|
+
try {
|
|
855
|
+
Add-Type -AssemblyName System.IO.Compression.FileSystem -ErrorAction Stop
|
|
856
|
+
$zip = [System.IO.Compression.ZipFile]::OpenRead($src)
|
|
857
|
+
$bad = @($zip.Entries | Where-Object {
|
|
858
|
+
$_.FullName -match '(^|[\\/])\.\.([\\/]|$)' -or $_.FullName.StartsWith('/') -or $_.FullName -match '^[a-zA-Z]:'
|
|
859
|
+
})
|
|
860
|
+
$zip.Dispose()
|
|
861
|
+
if ($bad.Count -gt 0) { throw '压缩包里有可疑路径(含 .. 或绝对路径),已拒绝导入。' }
|
|
862
|
+
}
|
|
863
|
+
catch {
|
|
864
|
+
if ($_.Exception.Message -like '*可疑路径*') { throw }
|
|
865
|
+
}
|
|
866
|
+
New-Item -ItemType Directory -Force -Path $DataDir | Out-Null
|
|
867
|
+
Expand-Archive -Path $src -DestinationPath $DataDir -Force
|
|
868
|
+
$result = "已从 $src 导入到 $DataDir(同名文件覆盖,其它保留)"
|
|
869
|
+
}
|
|
870
|
+
|
|
871
|
+
'vote-status' {
|
|
872
|
+
Clear-ExpiredVotes
|
|
873
|
+
$all = @(Get-Votes)
|
|
874
|
+
$open = @($all | Where-Object { $_.status -eq 'open' })
|
|
875
|
+
if ($Arg) {
|
|
876
|
+
$vote = @($all | Where-Object { $_.id -eq $Arg.Trim() }) | Select-Object -First 1
|
|
877
|
+
if (-not $vote) { $result = '没有这个投票。' }
|
|
878
|
+
else {
|
|
879
|
+
$approveCount = @($vote.votes).Count
|
|
880
|
+
$rejectCount = @($vote.rejects).Count
|
|
881
|
+
$extra = if ($rejectCount -gt 0) { ",$rejectCount 人点了拒绝" } else { '' }
|
|
882
|
+
$result = "编号 $($vote.id):$($vote.desc) —— 同意 $approveCount/$($vote.need)$extra,状态 $($vote.status)。"
|
|
883
|
+
}
|
|
884
|
+
}
|
|
885
|
+
elseif ($open.Count -eq 0) { $result = '当前没有待确认的投票。' }
|
|
886
|
+
else {
|
|
887
|
+
$result = (@($open | ForEach-Object { "编号 $($_.id):$($_.desc) —— 同意 $(@($_.votes).Count)/$($_.need),回复「同意 $($_.id)」或「拒绝 $($_.id)」表决" })) -join "`n"
|
|
888
|
+
}
|
|
889
|
+
}
|
|
890
|
+
|
|
891
|
+
'logs' {
|
|
892
|
+
if ($Arg) {
|
|
893
|
+
$raw = Get-CleanLog ([Math]::Max($TailLines * 4, 200))
|
|
894
|
+
$hits = @(($raw -split "`r?`n") | Where-Object { $_ -like "*$Arg*" })
|
|
895
|
+
if ($hits.Count -gt $TailLines) { $hits = @($hits | Select-Object -Last $TailLines) }
|
|
896
|
+
$text = $hits -join [Environment]::NewLine
|
|
897
|
+
}
|
|
898
|
+
else { $text = Get-CleanLog $TailLines }
|
|
899
|
+
if (-not $text) { $text = '(空)' }
|
|
900
|
+
$result = $text
|
|
901
|
+
}
|
|
902
|
+
|
|
903
|
+
'crashinfo' {
|
|
904
|
+
$sum = Read-Json $StateFile ([pscustomobject]@{})
|
|
905
|
+
$crash = Get-Prop $sum 'lastCrash' $null
|
|
906
|
+
if (-not $crash) { $result = '没有记录到崩溃' }
|
|
907
|
+
else {
|
|
908
|
+
$raw = [string](Get-Prop $crash 'tail' '')
|
|
909
|
+
$kept = @(($raw -split "`r?`n") | Where-Object { $_ -and ($_ -notmatch 'RCON (Client|Listener)') })
|
|
910
|
+
if ($kept.Count -gt 20) { $kept = @($kept | Select-Object -Last 20) }
|
|
911
|
+
$result = "上次异常退出: $(Get-Prop $crash 'at' '-')`n" + ($kept -join [Environment]::NewLine)
|
|
912
|
+
}
|
|
913
|
+
}
|
|
914
|
+
|
|
915
|
+
'whoami' {
|
|
916
|
+
if ($Actor) { $result = "身份: $role`nID: $Actor" }
|
|
917
|
+
else { $result = "身份: unknown`nID: (缺少 [昵称(ID)] 标记)" }
|
|
918
|
+
}
|
|
919
|
+
|
|
920
|
+
'help' {
|
|
921
|
+
$result = @'
|
|
922
|
+
可用指令:
|
|
923
|
+
状态 / 在线人数 / CPU / 内存 / TPS -> status
|
|
924
|
+
在线玩家名单 -> players
|
|
925
|
+
游戏内广播 -> say <内容>
|
|
926
|
+
查看日志 -> logs [行数]
|
|
927
|
+
崩溃原因摘要 -> crashinfo
|
|
928
|
+
启动 / 关闭 / 重启 -> start / stop / restart
|
|
929
|
+
执行后台指令(仅服主) -> cmd <命令>
|
|
930
|
+
查看自己的身份 -> whoami
|
|
931
|
+
|
|
932
|
+
权限:玩家可用 status/players/say/logs/crashinfo;服务器已宕机时任何人可 start;
|
|
933
|
+
stop/restart/cmd(含 op/ban/kick 等)仅服主可用。
|
|
934
|
+
'@
|
|
935
|
+
}
|
|
936
|
+
|
|
937
|
+
'owner-add' {
|
|
938
|
+
# 引导:一个服主都没有时,只允许从本机(非群聊/非私聊)把自己加进去,否则永远没有服主
|
|
939
|
+
if (@($ownerIds).Count -gt 0) { Assert-Owner }
|
|
940
|
+
elseif ($Channel -eq 'group' -or $Channel -eq 'c2c') {
|
|
941
|
+
throw 'FORBIDDEN: 首次绑定服主请用私聊口令,或在服务器本机执行 owner-add。'
|
|
942
|
+
}
|
|
943
|
+
if (-not $Arg) { throw 'USAGE: owner-add <id>' }
|
|
944
|
+
if ($ownerIds -notcontains $Arg) { $ownerIds = @($ownerIds) + $Arg }
|
|
945
|
+
Write-Json $OwnerFile ([pscustomobject]@{ owners = $ownerIds; boundAt = (Get-Date).ToString('o') })
|
|
946
|
+
$result = '服主列表: ' + ($ownerIds -join ', ')
|
|
947
|
+
}
|
|
948
|
+
|
|
949
|
+
'owner-del' {
|
|
950
|
+
Assert-Owner
|
|
951
|
+
if (-not $Arg) { throw 'USAGE: owner-del <id>' }
|
|
952
|
+
$ownerIds = @($ownerIds | Where-Object { $_ -ne $Arg })
|
|
953
|
+
Write-Json $OwnerFile ([pscustomobject]@{ owners = $ownerIds; boundAt = (Get-Date).ToString('o') })
|
|
954
|
+
$result = '服主列表: ' + ($ownerIds -join ', ')
|
|
955
|
+
}
|
|
956
|
+
|
|
957
|
+
'owner-list' {
|
|
958
|
+
if ($ownerIds.Count) { $result = '服主列表: ' + ($ownerIds -join ', ') }
|
|
959
|
+
else { $result = '尚未绑定服主' }
|
|
960
|
+
}
|
|
961
|
+
|
|
962
|
+
'watchdog' {
|
|
963
|
+
Assert-Owner
|
|
964
|
+
$want = ($Arg -eq 'on')
|
|
965
|
+
$state = Read-Json $StateFile ([pscustomobject]@{})
|
|
966
|
+
$state | Add-Member -Force -NotePropertyName desired -NotePropertyValue $want
|
|
967
|
+
Write-Json $StateFile $state
|
|
968
|
+
$result = "自动守护: $want"
|
|
969
|
+
}
|
|
970
|
+
|
|
971
|
+
default { throw "unknown action: $Action" }
|
|
972
|
+
}
|
|
973
|
+
}
|
|
974
|
+
catch {
|
|
975
|
+
$errMsg = $_.Exception.Message
|
|
976
|
+
if ($Json) { [pscustomobject]@{ ok = $false; result = $errMsg } | ConvertTo-Json -Depth 6 }
|
|
977
|
+
else { Write-Output $errMsg }
|
|
978
|
+
exit 1
|
|
979
|
+
}
|
|
980
|
+
|
|
981
|
+
if ($Json) { [pscustomobject]@{ ok = $true; result = $result } | ConvertTo-Json -Depth 6 }
|
|
982
|
+
else { $result }
|