# LaDolce Print Agent # Runs on the office PC (as a scheduled task, at startup, as SYSTEM). # Long-polls https://print.ladolcecorp.com/agent/ for queued jobs, prints each # PDF to the local printer with SumatraPDF, then reports the result. # Only outbound HTTPS is used — no ports are opened on the office network. $ErrorActionPreference = 'Stop' $Home_ = 'C:\ProgramData\LaDolcePrint' $Config = Get-Content (Join-Path $Home_ 'config.json') -Raw | ConvertFrom-Json $LogFile = Join-Path $Home_ 'agent.log' $Sumatra = Join-Path $Home_ 'SumatraPDF.exe' $Headers = @{ Authorization = "Bearer $($Config.token)" } $Server = $Config.server.TrimEnd('/') [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 function Write-Log([string]$Message) { if ((Test-Path $LogFile) -and (Get-Item $LogFile).Length -gt 1MB) { Move-Item $LogFile "$LogFile.1" -Force } "$(Get-Date -Format 'yyyy-MM-dd HH:mm:ss') $Message" | Add-Content $LogFile } function Send-Result([string]$Id, [bool]$Ok, [string]$Message) { $body = @{ id = $Id; status = $(if ($Ok) { 'ok' } else { 'error' }); message = $Message } Invoke-RestMethod "$Server/agent/done.php" -Method Post -Headers $Headers -Body $body -TimeoutSec 30 | Out-Null } function Print-Job($Job) { $pdf = Join-Path $env:TEMP "ladolce-$($Job.id).pdf" try { Invoke-WebRequest "$Server/agent/file.php?id=$($Job.id)" -Headers $Headers ` -OutFile $pdf -UseBasicParsing -TimeoutSec 120 $copies = [Math]::Max(1, [int]$Job.copies) # Start-Process (PS 5.1) joins arguments without quoting, so quote them here $args_ = "-print-to `"$($Config.printer)`" -print-settings `"${copies}x,fit`" -silent -exit-when-done `"$pdf`"" $proc = Start-Process $Sumatra -ArgumentList $args_ -PassThru -Wait -WindowStyle Hidden if ($proc.ExitCode -eq 0) { Write-Log "printed $($Job.id) user=$($Job.user) copies=$copies title=$($Job.title)" Send-Result $Job.id $true '' } else { Write-Log "FAILED $($Job.id): SumatraPDF exit code $($proc.ExitCode)" Send-Result $Job.id $false "SumatraPDF exit code $($proc.ExitCode)" } } finally { Remove-Item $pdf -Force -ErrorAction SilentlyContinue } } Write-Log "agent started (printer: $($Config.printer))" while ($true) { try { $r = Invoke-RestMethod "$Server/agent/next.php" -Headers $Headers -TimeoutSec 45 if ($r.job) { Print-Job $r.job } } catch { Write-Log "error: $($_.Exception.Message)" Start-Sleep -Seconds 15 } }