-
Notifications
You must be signed in to change notification settings - Fork 2
/
WatcherUI.ps1
332 lines (256 loc) · 13.8 KB
/
WatcherUI.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
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
$isAdmin = [bool]([System.Security.Principal.WindowsIdentity]::GetCurrent().groups -match 'S-1-5-32-544')
Add-Type -AssemblyName PresentationFramework
Add-Type -AssemblyName System.Windows.Forms
$OutputEncoding = [Console]::OutputEncoding = New-Object System.Text.Utf8Encoding
[Console]::InputEncoding = New-Object System.Text.Utf8Encoding
$flagFilePath = "$env:APPDATA\PlayniteWatcher\PlayniteWatcherAdminFlag"
class ApplicationInfo {
[string]$applicationName
[string]$uniqueId
[string]$cmd
[string]$detached
[string]$imagePath
[string]$waitAll
[string]$autoDetach
[string]$exitTimeout
}
# To minimize prompts, we will only warn the user once about admin rights.
if (-not $isAdmin) {
if (-not (Test-Path $flagFilePath)) {
$result = [System.Windows.Forms.MessageBox]::Show("You will be prompted for administrator rights, as Sunshine requires admin in order to modify the apps.json file.", "Administrator Required", [System.Windows.Forms.MessageBoxButtons]::OKCancel, [System.Windows.Forms.MessageBoxIcon]::Information)
New-Item -ItemType File -Path $flagFilePath -Force
if ($result -eq [System.Windows.Forms.DialogResult]::Cancel) {
exit
}
}
else {
Start-Process powershell.exe -Verb RunAs -ArgumentList "-ExecutionPolicy Bypass -File `"$($MyInvocation.MyCommand.Path)`"" -WindowStyle Hidden
exit
}
}
$scriptPath = Split-Path $MyInvocation.MyCommand.Path -Parent
Set-Location $scriptPath
Add-Type -AssemblyName PresentationFramework
Add-Type -AssemblyName System.Windows.Forms
function LoadConfigFilePath() {
# Retrieve the path utilizing regex from the primary script.
$scriptContents = Get-Content "./PlayniteWatcher.ps1"
$ma = $scriptContents | select-string '(\$sunshineConfigPath)\s=\s"(.*)"'
$foundPath = $ma.Matches.Groups[2].Value
$configPathTextBox.Text = $foundPath.Replace('\\', '\')
}
function LoadPlayniteExecutablePath() {
# Retrieve the path utilizing regex from the primary script.
$scriptContents = Get-Content "./PlayniteWatcher.ps1"
$ma = $scriptContents | select-string '(\$playnitepath)\s=\s"(.*)"'
$foundPath = $ma.Matches.Groups[2].Value
$playNitePathTextBox.Text = $foundPath.Replace('\\', '\')
return $foundPath.Replace("\\", "\")
}
function SaveChanges($configPath, $updatedApps) {
$appConfiguration = Get-Content -Encoding utf8 -Path $configPath -Raw | ConvertFrom-Json
[object[]]$filteredApps = FilterPlayniteApps -configPath $configPath
foreach ($app in $updatedApps) {
if ($app.uniqueId -eq "") {
continue;
}
$jsonApp = [PSCustomObject]@{
'image-path' = $app.imagePath
name = $app.applicationName
'wait-all' = $app.waitAll
'exit-timeout' = $app.exitTimeout
'auto-detach' = $app.autoDetach
}
if ($app.cmd -ne "") {
$jsonApp | Add-Member -MemberType NoteProperty -Name "cmd" -Value $app.cmd -Force
}
if ($app.detached -ne "") {
$jsonApp | Add-Member -MemberType NoteProperty -Name "detached" -Value $app.detached -Force
}
$filteredApps += $jsonApp
}
$appConfiguration.apps = $filteredApps
$appConfiguration | ConvertTo-Json -Depth 100 | Set-Content -Path $configPath -Encoding utf8
}
function ParseGames($configPath) {
$apps = @()
$JsonContent = Get-Content -Encoding utf8 -Path $configPath -Raw | ConvertFrom-Json
$JsonContent.apps | ForEach-Object {
$app = [ApplicationInfo]::new()
$_.'image-path' -match 'Apps\\(.*)\\' | Out-Null
if ($Matches) {
$id = $Matches[1]
$app.applicationName = $_.name
$app.uniqueId = $id
$app.imagePath = $_.'image-path'
$app.cmd = $_.cmd
$app.detached = $_.detached
$app.exitTimeout = if ($_. 'exit-timeout') { $_.'exit-timeout' } else { "5" }
$app.waitAll = if ($_. 'wait-all') { $_.'wait-all' } else { "false" }
$app.autoDetach = if ($_. 'auto-detach') { $_.'auto-detach' } else { "false" }
$apps += $app
}
}
return $apps
}
function FilterPlayniteApps($configPath) {
$JsonContent = Get-Content -Encoding utf8 -Path $configPath -Raw | ConvertFrom-Json
return $JsonContent.apps | Where-Object { $_.cmd -notlike '*playnite*' -and $_.detached -notlike '*playnite*' }
}
function RemoveDuplicates($apps) {
$dict = [System.Collections.Generic.Dictionary[string, ApplicationInfo]]::new()
foreach ($app in $apps) {
if ($dict.ContainsKey($app.uniqueId)) {
continue
}
else {
$dict.Add($app.uniqueId, $app);
}
}
return $dict.Values
}
function SaveSettings() {
## Replace the $playNitePath with the users selection
$playnitePath = $playNitePathTextBox.Text
$filePath = ".\PlayniteWatcher.ps1"
$content = Get-Content -Encoding utf8 -Path $filePath
$playNitePattern = '(\$playNitePath\s*=\s*")[^"]*(")'
$configPattern = '(\$sunshineConfigPath\s*=\s*")[^"]*(")'
$updatedContent = $content -replace $playNitePattern, "`$1$($playnitePath.Replace('\', '\\'))`$2"
$updatedContent = $updatedContent -replace $configPattern, "`$1$($configPathTextBox.Text.Replace('\', '\\'))`$2"
Set-Content -Path $filePath -Value $updatedContent
######
}
# OpenFileDialog Function
function ShowOpenFileDialog($filter, $initialDirectory, $textBox) {
$openFileDialog = New-Object System.Windows.Forms.OpenFileDialog
$openFileDialog.Filter = $filter
$openFileDialog.InitialDirectory = $initialDirectory
if ($openFileDialog.ShowDialog() -eq "OK") {
$textBox.Text = $openFileDialog.FileName
}
}
[xml]$xaml = @"
<Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Playnite Watcher Installer" Height="230" Width="720">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<DockPanel Grid.Row="0" Margin="10">
<Label Content="Sunshine Apps.json Path:" VerticalAlignment="Center" Width="165"/>
<TextBox Name="ConfigPath" Text="C:\Program Files\Sunshine\config\apps.json" Margin="5,0,5,0" Width="325" Height="25" IsReadOnly="true"/>
<Button Name="BrowseButton" Content="Browse" Width="75" HorizontalAlignment="Left" Margin="5,0,5,0" Height="25"/>
</DockPanel>
<DockPanel Grid.Row="1" Margin="10">
<Label Content="Playnite Executable Path:" VerticalAlignment="Center" Width="165"/>
<TextBox Name="PlaynitePath" Text="C:\Program Files\Playnite\Playnite.DesktopApp.exe" Margin="5,0,5,0" Width="325" Height="25" IsReadOnly="true"/>
<Button Name="PlayniteBrowseButton" Content="Browse" Width="75" HorizontalAlignment="Left" Margin="5,0,5,0" Height="25"/>
</DockPanel>
<DockPanel Grid.Row="2" Margin="10" VerticalAlignment="Top">
<Button Name="InstallButton" Content="Install" Width="75" Height="25" Margin="2,0,2,0"/>
<Button Name="UninstallButton" Content="Uninstall" Width="75" Height="25" Margin="2,0,2,0"/>
</DockPanel>
<TextBlock Grid.Row="3" Margin="0" TextWrapping="Wrap" HorizontalAlignment="Center" FontWeight="Bold">
NOTICE: Clicking install or uninstall will terminate existing Moonlight sessions and restart Playnite to finish the installation.
</TextBlock>
</Grid>
</Window>
"@
$reader = (New-Object System.Xml.XmlNodeReader $xaml)
$window = [Windows.Markup.XamlReader]::Load($reader)
$configPathTextBox = $window.FindName("ConfigPath")
$playNitePathTextBox = $window.FindName("PlaynitePath")
# Browse button click event handler
$window.FindName("BrowseButton").Add_Click({
ShowOpenFileDialog -filter "JSON files (*.json)|*.json|All files (*.*)|*.*" -initialDirectory ([System.IO.Path]::GetDirectoryName($configPathTextBox.Text)) -textBox $configPathTextBox
LoadGames -configPath $configPathTextBox.Text
SaveSettings
})
$window.FindName("PlayniteBrowseButton").Add_Click({
ShowOpenFileDialog -filter "Playnite Executable|Playnite.DesktopApp.exe" -initialDirectory ([System.IO.Path]::GetDirectoryName($playNitePathTextBox.Text)) -textBox $playNitePathTextBox
SaveSettings
})
$window.FindName("InstallButton").Add_Click({
$installCount = 0
$playniteRoot = Split-Path $playNitePathTextBox.Text -Parent
$updatedApps = ParseGames -configPath $configPathTextBox.Text
$updatedApps = RemoveDuplicates -apps $updatedApps
foreach ($playniteApp in $updatedApps) {
$installCount += 1
$playniteApp.detached = ""
$playniteApp.cmd = "powershell.exe -executionpolicy bypass -windowstyle hidden -file `"$scriptPath\PlayniteWatcher.ps1`" $($playniteApp.uniqueId)"
}
## add FullScreen applet
if ($null -eq ($updatedApps | Where-Object { $_.name -eq "PlayNite FullScreen App" })) {
$updatedApps = , [PSCustomObject]@{
applicationName = "PlayNite FullScreen App"
imagePath = "$scriptPath\playnite-boxart.png"
cmd = "powershell.exe -executionpolicy bypass -windowstyle hidden -file `"$scriptPath\PlayniteWatcher.ps1`" FullScreen"
detached = ""
waitAll = "false"
autoDetach = "false"
exitTimeout = "5"
} + $updatedApps
}
Remove-Item -Path "$playniteRoot\Extensions\PlayniteWatcherExt" -Recurse -Force -ErrorAction SilentlyContinue
Copy-Item -Path "./PlayNiteWatcherExt" -Destination "$playniteRoot\Extensions\PlayNiteWatcherExt" -Force -Recurse
SaveChanges -configPath $configPathTextBox.Text -updatedApps $updatedApps
$scopedInstall = {
. $scriptPath\PrepCommandInstaller.ps1 $true
}
& $scopedInstall
## Open it in a background thread, that way if user disconnected from a moonlight session it will still restart playnite.
Start-Job -ArgumentList $playNitePathTextBox.Text {
param($path)
Start-Sleep -Seconds 5
Get-Process Playnite.DesktopApp -ErrorAction SilentlyContinue | Stop-Process -ErrorAction SilentlyContinue
Start-Process -FilePath explorer.exe -ArgumentList $path
}
[System.Windows.Forms.MessageBox]::Show("The script has been successfully installed to $installCount application(s)!", "Installation Complete!", [System.Windows.Forms.MessageBoxButtons]::OK, [System.Windows.Forms.MessageBoxIcon]::Information)
})
$window.FindName("UninstallButton").Add_Click({
$msgBoxTitle = "Uninstall script"
$msgBoxText = "Are you sure you want to remove this script? This will remove all exported games from Playnite"
$msgBoxButtons = [System.Windows.Forms.MessageBoxButtons]::YesNo
$msgBoxIcon = [System.Windows.Forms.MessageBoxIcon]::Warning
$msgBoxResult = [System.Windows.Forms.MessageBox]::Show($msgBoxText, $msgBoxTitle, $msgBoxButtons, $msgBoxIcon)
if ($msgBoxResult -eq [System.Windows.Forms.DialogResult]::Yes) {
$playnitePath = $playNitePathTextBox.Text
$playniteRoot = Split-Path $playnitePath -Parent
$parsedApps = ParseGames -configPath $configPathTextBox.Text | ForEach-Object { $_.uniqueId = "" | Out-Null; $_ }
SaveChanges -configPath $configPathTextBox.Text -updatedApps $parsedApps
$scopedInstall = {
. $scriptPath\PrepCommandInstaller.ps1 $false
}
Remove-Item "$playniteRoot\Extensions\PlayNiteWatcherExt" -Force -Recurse
& $scopedInstall
[System.Windows.Forms.MessageBox]::Show("You can now close this application, the script has been successfully uninstalled", "Uninstall Complete!", [System.Windows.Forms.MessageBoxButtons]::OK, [System.Windows.Forms.MessageBoxIcon]::Information)
}
})
$window.Add_Loaded({
try {
LoadConfigFilePath
}
catch {
[System.Windows.Forms.MessageBox]::Show("An issue was encountered while attempting to retrieve your Sunshine application list. Once you dismiss this message, a window will open, prompting you to locate the Sunshine config folder. Please ensure that navigate to your Sunshine config folder and select the `"apps.json`" file within it.", "Error: Could not find apps.json file", [System.Windows.Forms.MessageBoxButtons]::OK, [System.Windows.Forms.MessageBoxIcon]::Error)
ShowOpenFileDialog -filter "JSON files (*.json)|*.json|All files (*.*)|*.*" -initialDirectory $env:ProgramFiles -textBox $configPathTextBox
}
try {
$path = LoadPlayniteExecutablePath
if (-not (Test-Path $path)) {
throw "Could not locate PlayNite"
}
}
catch {
[System.Windows.Forms.MessageBox]::Show("An issue was encountered while attempting to retrieve the PlayNite executable path. Once you dismiss this message, a window will open, prompting you to locate the PlayNite folder. Please ensure that you choose the PlayNite folder and select the `"PlayNiteDesktop.exe`" file within it.", "Error: Could not find PlayNite Executable", [System.Windows.Forms.MessageBoxButtons]::OK, [System.Windows.Forms.MessageBoxIcon]::Error)
ShowOpenFileDialog -filter "Playnite Exe|Playnite.DesktopApp.exe|All files (*.*)|*.*" -textBox $playNitePathTextBox
}
SaveSettings
})
# Show WPF window
$window.ShowDialog() | Out-Null