# ClassNotifyAgent.ps1 - Windows Classroom Background Agent # Responsible for: WebSocket communication, Heartbeat, Watchdog over ClassNotify.exe, Remote commands [CmdletBinding()] param() $ScriptDir = Split-Path -Parent $MyInvocation.MyCommand.Path $ConfigFile = Join-Path $ScriptDir "config.json" $LogDir = Join-Path $ScriptDir "logs" $LogFile = Join-Path $LogDir "agent.log" $ExePath = Join-Path $ScriptDir "ClassNotify.exe" # Ensure log directory exists if (-not (Test-Path $LogDir)) { New-Item -ItemType Directory -Force -Path $LogDir | Out-Null } function Write-Log { param([string]$Message, [string]$Level = "INFO") $timestamp = (Get-Date).ToString("yyyy-MM-dd HH:mm:ss") $line = "[$timestamp] [$Level] $Message" try { Add-Content -Path $LogFile -Value $line -Encoding UTF8 } catch {} } Write-Log "========== ClassNotify Agent Starting ==========" # Load Configuration function Get-Config { if (-not (Test-Path $ConfigFile)) { Write-Log "Config file not found at $ConfigFile" "ERROR" return $null } try { $content = Get-Content -Path $ConfigFile -Raw -Encoding UTF8 return ($content | ConvertFrom-Json) } catch { Write-Log "Failed to parse config.json: $_" "ERROR" return $null } } $config = Get-Config if ($null -eq $config) { Write-Log "Agent cannot start without valid config. Exiting." "FATAL" exit 1 } Write-Log "Loaded config for Class: $($config.class_name) ($($config.class_id)), Server: $($config.server_url)" # Self Check Function function Run-SelfCheck { param($config) $result = @{ timestamp = (Get-Date).ToString("o") class_id = $config.class_id config_valid = ($null -ne $config) exe_exists = (Test-Path $ExePath) tts_available = $false network_available = $false dns_ok = $false server_reachable = $false } # Check TTS try { Add-Type -AssemblyName System.Speech -ErrorAction Stop $synth = New-Object System.Speech.Synthesis.SpeechSynthesizer if ($synth.GetInstalledVoices().Count -gt 0) { $result.tts_available = $true } $synth.Dispose() } catch { $result.tts_available = $false } # Check Network & Server try { $uri = [System.Uri]$config.server_url $dnsTest = [System.Net.Dns]::GetHostAddresses($uri.DnsSafeHost) if ($dnsTest.Length -gt 0) { $result.dns_ok = $true $result.network_available = $true } } catch { $result.dns_ok = $false } return $result } # Main WebSocket Loop function Start-AgentLoop { while ($true) { $config = Get-Config if ($null -eq $config) { Start-Sleep -Seconds 10 continue } Write-Log "Connecting to WebSocket server: $($config.server_url)..." $ws = New-Object System.Net.WebSockets.ClientWebSocket $cts = New-Object System.Threading.CancellationTokenSource try { $serverUri = New-Object System.Uri($config.server_url) $connectTask = $ws.ConnectAsync($serverUri, $cts.Token) $connectTask.Wait(8000) # 8 seconds timeout if ($ws.State -ne [System.Net.WebSockets.WebSocketState]::Open) { Write-Log "Failed to connect to server (State: $($ws.State)). Retrying in $($config.reconnect_interval_sec)s..." "WARN" Start-Sleep -Seconds $config.reconnect_interval_sec continue } Write-Log "WebSocket connected successfully!" # 1. Send Registration $regMsg = @{ type = "register" class_id = $config.class_id class_name = $config.class_name device_token = $config.device_token version = "1.0.0" hostname = $env:COMPUTERNAME } | ConvertTo-Json -Compress $regBytes = [System.Text.Encoding]::UTF8.GetBytes($regMsg) $regSeg = New-Object System.ArraySegment[byte] -ArgumentList @($regBytes, 0, $regBytes.Length) $ws.SendAsync($regSeg, [System.Net.WebSockets.WebSocketMessageType]::Text, $true, [System.Threading.CancellationToken]::None).Wait() Write-Log "Sent registration for $($config.class_name)" $lastHeartbeat = [DateTime]::MinValue $buffer = New-Object byte[] 8192 $segment = New-Object System.ArraySegment[byte] -ArgumentList @($buffer, 0, $buffer.Length) while ($ws.State -eq [System.Net.WebSockets.WebSocketState]::Open) { # Check Heartbeat $now = Get-Date if (($now - $lastHeartbeat).TotalSeconds -ge $config.heartbeat_interval_sec) { $hb = @{ type = "heartbeat" class_id = $config.class_id device_token = $config.device_token timestamp = $now.ToString("o") } | ConvertTo-Json -Compress $hbBytes = [System.Text.Encoding]::UTF8.GetBytes($hb) $hbSeg = New-Object System.ArraySegment[byte] -ArgumentList @($hbBytes, 0, $hbBytes.Length) $ws.SendAsync($hbSeg, [System.Net.WebSockets.WebSocketMessageType]::Text, $true, [System.Threading.CancellationToken]::None).Wait() $lastHeartbeat = $now } # Receive messages asynchronously with small timeout to allow heartbeat loop $receiveTask = $ws.ReceiveAsync($segment, $cts.Token) if ($receiveTask.Wait(500)) { $result = $receiveTask.Result if ($result.MessageType -eq [System.Net.WebSockets.WebSocketMessageType]::Close) { Write-Log "Server closed WebSocket connection." "WARN" break } $receivedJson = [System.Text.Encoding]::UTF8.GetString($buffer, 0, $result.Count) Write-Log "Received message: $receivedJson" try { $msg = $receivedJson | ConvertFrom-Json Handle-ServerMessage -ws $ws -msg $msg -config $config } catch { Write-Log "Failed to parse message: $_" "ERROR" } } } } catch { Write-Log "WebSocket error: $_" "ERROR" } finally { if ($null -ne $ws) { try { $ws.Dispose() } catch {} } if ($null -ne $cts) { try { $cts.Dispose() } catch {} } } Write-Log "Disconnected from server. Reconnecting in $($config.reconnect_interval_sec)s..." "WARN" Start-Sleep -Seconds $config.reconnect_interval_sec } } # Message Handler function Handle-ServerMessage { param($ws, $msg, $config) switch ($msg.type) { { $_ -in @("notify", "call") } { Write-Log "Handling notification: $($msg.text)" # Send immediate delivery receipt if ($msg.msg_id) { $ack = @{ type = "status" msg_id = $msg.msg_id class_id = $config.class_id status = "delivered" timestamp = (Get-Date).ToString("o") } | ConvertTo-Json -Compress $ackBytes = [System.Text.Encoding]::UTF8.GetBytes($ack) $ackSeg = New-Object System.ArraySegment[byte] -ArgumentList @($ackBytes, 0, $ackBytes.Length) $ws.SendAsync($ackSeg, [System.Net.WebSockets.WebSocketMessageType]::Text, $true, [System.Threading.CancellationToken]::None).Wait() } # Prepare parameters for ClassNotify.exe $title = if ($msg.title) { $msg.title } else { "πŸ”” θ€εΈˆε‘Όε«" } $text = if ($msg.text) { $msg.text } else { "请注意" } $mType = if ($msg.msg_type) { $msg.msg_type } else { "call" } $voice = if ($null -ne $msg.voice) { $msg.voice.ToString().ToLower() } else { "true" } $shake = if ($null -ne $msg.shake) { $msg.shake.ToString().ToLower() } else { "true" } $duration = if ($msg.duration) { [int]$msg.duration } else { 15 } $argList = "--title `"$title`" --msg `"$text`" --type `"$mType`" --voice $voice --shake $shake --duration $duration" Write-Log "Spawning: $ExePath $argList" # Execute EXE in thread/background so we can wait for exit code and send final receipt [System.Threading.ThreadPool]::QueueUserWorkItem({ param($state) $pInfo = $state try { $proc = Start-Process -FilePath $pInfo.ExePath -ArgumentList $pInfo.ArgList -Wait -PassThru -NoNewWindow $exitCode = $proc.ExitCode $status = switch ($exitCode) { 0 { "acknowledged" } # Student clicked "ζˆ‘ηŸ₯道了" 1 { "timeout" } # Auto closed after countdown default { "closed" } } Write-Log "ClassNotify.exe exited with code $exitCode ($status)" # Send final ack if ($pInfo.MsgId -and $pInfo.Ws.State -eq [System.Net.WebSockets.WebSocketState]::Open) { $finalAck = @{ type = "status" msg_id = $pInfo.MsgId class_id = $pInfo.ClassId status = $status timestamp = (Get-Date).ToString("o") } | ConvertTo-Json -Compress $fBytes = [System.Text.Encoding]::UTF8.GetBytes($finalAck) $fSeg = New-Object System.ArraySegment[byte] -ArgumentList @($fBytes, 0, $fBytes.Length) $pInfo.Ws.SendAsync($fSeg, [System.Net.WebSockets.WebSocketMessageType]::Text, $true, [System.Threading.CancellationToken]::None).Wait() } } catch { Write-Log "Failed to execute ClassNotify.exe: $_" "ERROR" } }, @{ ExePath = $ExePath ArgList = $argList MsgId = $msg.msg_id ClassId = $config.class_id Ws = $ws }) | Out-Null } "command" { Write-Log "Received remote command: $($msg.command)" switch ($msg.command) { "self_check" { $checkResult = Run-SelfCheck -config $config $resp = @{ type = "self_check_result" class_id = $config.class_id result = $checkResult } | ConvertTo-Json -Compress $respBytes = [System.Text.Encoding]::UTF8.GetBytes($resp) $respSeg = New-Object System.ArraySegment[byte] -ArgumentList @($respBytes, 0, $respBytes.Length) $ws.SendAsync($respSeg, [System.Net.WebSockets.WebSocketMessageType]::Text, $true, [System.Threading.CancellationToken]::None).Wait() Write-Log "Self-check completed and sent to server." } "restart_client" { Get-Process -Name "ClassNotify" -ErrorAction SilentlyContinue | Stop-Process -Force Write-Log "ClassNotify.exe process terminated by remote command." } "get_logs" { $recentLogs = @() if (Test-Path $LogFile) { $recentLogs = Get-Content -Path $LogFile -Tail 30 } $resp = @{ type = "logs_result" class_id = $config.class_id logs = $recentLogs } | ConvertTo-Json -Compress $respBytes = [System.Text.Encoding]::UTF8.GetBytes($resp) $respSeg = New-Object System.ArraySegment[byte] -ArgumentList @($respBytes, 0, $respBytes.Length) $ws.SendAsync($respSeg, [System.Net.WebSockets.WebSocketMessageType]::Text, $true, [System.Threading.CancellationToken]::None).Wait() } } } } } # Start the agent Start-AgentLoop