-
Notifications
You must be signed in to change notification settings - Fork 1
/
Helpers.ps1
202 lines (161 loc) · 6.47 KB
/
Helpers.ps1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
param(
[Parameter(Position = 0, Mandatory = $true)]
[Alias("n")]
[string]$scriptName,
[Alias("t")]
[Parameter(Position = 1, Mandatory = $false)]
[int]$terminate
)
$path = (Split-Path $MyInvocation.MyCommand.Path -Parent)
Set-Location $path
$script:attempt = 0
function OnStreamEndAsJob() {
return Start-Job -Name "$scriptName-OnStreamEnd" -ScriptBlock {
param($path, $scriptName, $arguments)
Write-Debug "Setting location to $path"
Set-Location $path
Write-Debug "Loading Helpers.ps1 with script name $scriptName"
. .\Helpers.ps1 -n $scriptName
Write-Debug "Loading Events.ps1 with script name $scriptName"
. .\Events.ps1 -n $scriptName
Write-Host "Stream has ended, now invoking code"
Write-Debug "Creating pipe with name $scriptName-OnStreamEnd"
$job = Create-Pipe -pipeName "$scriptName-OnStreamEnd"
while ($true) {
$maxTries = 25
$tries = 0
Write-Debug "Checking job state: $($job.State)"
if ($job.State -eq "Completed") {
Write-Host "Another instance of $scriptName has been started again. This current session is now redundant and will terminate without further action."
Write-Debug "Job state is 'Completed'. Exiting loop."
break;
}
Write-Debug "Invoking OnStreamEnd with arguments: $arguments"
if ((OnStreamEnd $arguments)) {
Write-Debug "OnStreamEnd returned true. Exiting loop."
break;
}
while (($tries -lt $maxTries) -and ($job.State -ne "Completed")) {
Start-Sleep -Milliseconds 200
$tries++
}
}
Write-Debug "Sending 'Terminate' message to pipe $scriptName-OnStreamEnd"
Send-PipeMessage "$scriptName-OnStreamEnd" Terminate
} -ArgumentList $path, $scriptName, $script:arguments
}
function IsCurrentlyStreaming() {
$sunshineProcess = Get-Process sunshine -ErrorAction SilentlyContinue
if($null -eq $sunshineProcess) {
return $false
}
return $null -ne (Get-NetUDPEndpoint -OwningProcess $sunshineProcess.Id -ErrorAction Ignore)
}
function Stop-Script() {
Send-PipeMessage -pipeName $scriptName Terminate
}
function Send-PipeMessage($pipeName, $message) {
Write-Debug "Attempting to send message to pipe: $pipeName"
$pipeExists = Get-ChildItem -Path "\\.\pipe\" | Where-Object { $_.Name -eq $pipeName }
Write-Debug "Pipe exists check: $($pipeExists.Length -gt 0)"
if ($pipeExists.Length -gt 0) {
$pipe = New-Object System.IO.Pipes.NamedPipeClientStream(".", $pipeName, [System.IO.Pipes.PipeDirection]::Out)
Write-Debug "Connecting to pipe: $pipeName"
$pipe.Connect(3000)
$streamWriter = New-Object System.IO.StreamWriter($pipe)
Write-Debug "Sending message: $message"
$streamWriter.WriteLine($message)
try {
$streamWriter.Flush()
$streamWriter.Dispose()
$pipe.Dispose()
Write-Debug "Message sent and resources disposed successfully."
}
catch {
Write-Debug "Error during disposal: $_"
# We don't care if the disposal fails, this is common with async pipes.
# Also, this powershell script will terminate anyway.
}
} else {
Write-Debug "Pipe not found: $pipeName"
}
}
function Create-Pipe($pipeName) {
return Start-Job -Name "$pipeName-PipeJob" -ScriptBlock {
param($pipeName, $scriptName)
Register-EngineEvent -SourceIdentifier $scriptName -Forward
$pipe = New-Object System.IO.Pipes.NamedPipeServerStream($pipeName, [System.IO.Pipes.PipeDirection]::In, 10, [System.IO.Pipes.PipeTransmissionMode]::Byte, [System.IO.Pipes.PipeOptions]::Asynchronous)
$streamReader = New-Object System.IO.StreamReader($pipe)
Write-Output "Waiting for named pipe to recieve kill command"
$pipe.WaitForConnection()
$message = $streamReader.ReadLine()
if ($message) {
Write-Output "Terminating pipe..."
$pipe.Dispose()
$streamReader.Dispose()
New-Event -SourceIdentifier $scriptName -MessageData $message
}
} -ArgumentList $pipeName, $scriptName
}
function Remove-OldLogs {
# Get all log files in the directory
$logFiles = Get-ChildItem -Path './logs' -Filter "log_*.txt" -ErrorAction SilentlyContinue
# Sort the files by creation time, oldest first
$sortedFiles = $logFiles | Sort-Object -Property CreationTime -ErrorAction SilentlyContinue
if ($sortedFiles) {
# Calculate how many files to delete
$filesToDelete = $sortedFiles.Count - 10
# Check if there are more than 10 files
if ($filesToDelete -gt 0) {
# Delete the oldest files, keeping the latest 10
$sortedFiles[0..($filesToDelete - 1)] | Remove-Item -Force
}
}
}
function Start-Logging {
# Get the current timestamp
$timeStamp = [int][double]::Parse((Get-Date -UFormat "%s"))
$logDirectory = "./logs"
# Define the path and filename for the log file
$logFileName = "log_$timeStamp.txt"
$logFilePath = Join-Path $logDirectory $logFileName
# Check if the log directory exists, and create it if it does not
if (-not (Test-Path $logDirectory)) {
New-Item -Path $logDirectory -ItemType Directory
}
# Start logging to the log file
Start-Transcript -Path $logFilePath
}
function Stop-Logging {
Stop-Transcript
}
function Get-Settings {
# Read the file content
$jsonContent = Get-Content -Path ".\settings.json" -Raw
# Remove single line comments
$jsonContent = $jsonContent -replace '//.*', ''
# Remove multi-line comments
$jsonContent = $jsonContent -replace '/\*[\s\S]*?\*/', ''
# Remove trailing commas from arrays and objects
$jsonContent = $jsonContent -replace ',\s*([\]}])', '$1'
try {
# Convert JSON content to PowerShell object
$jsonObject = $jsonContent | ConvertFrom-Json
return $jsonObject
}
catch {
Write-Error "Failed to parse JSON: $_"
}
}
function Wait-ForStreamEndJobToComplete() {
$job = OnStreamEndAsJob
while ($job.State -ne "Completed") {
$job | Receive-Job
Start-Sleep -Seconds 1
}
$job | Wait-Job | Receive-Job
}
if ($terminate -eq 1) {
Write-Host "Stopping Script"
Stop-Script | Out-Null
}