Repository navigation
Expand file tree
/
Copy pathPlexMatchGUI.ps1
More file actions
967 lines (909 loc) · 41.5 KB
/
Copy pathPlexMatchGUI.ps1
File metadata and controls
967 lines (909 loc) · 41.5 KB
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
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
#Requires -Version 5.1
<#
PlexMatchGUI.ps1 - v1.2.2
Gleicht eine Plex-Filmbibliothek gegen eine Liste (MDBList / IMDb-CSV / Freitext) ab
und markiert vorhanden / fehlt / unsicher sowie "nur in Plex".
Native WPF-Oberflaeche, keine externen Module, reines ASCII.
Author: ezek1el3000
Lizenz: MIT
Repo: https://github.com/ezek1el/plexmatch
#>
[CmdletBinding()]
param(
[string]$SettingsPath = (Join-Path $env:APPDATA 'PlexMatch\settings.json')
)
Add-Type -AssemblyName PresentationFramework, PresentationCore, WindowsBase, System.Xaml
# ==========================================================================
# XAML
# ==========================================================================
$Xaml = @'
<Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="plexmatch - Bibliothek gegen Liste abgleichen"
Height="800" Width="1200" MinHeight="620" MinWidth="960"
WindowStartupLocation="CenterScreen" Background="#FF1C1D21"
FontFamily="Consolas" FontSize="12">
<Window.Resources>
<SolidColorBrush x:Key="Ink" Color="#FFD6D8DD"/>
<SolidColorBrush x:Key="Dim" Color="#FF83878F"/>
<SolidColorBrush x:Key="Panel" Color="#FF212226"/>
<SolidColorBrush x:Key="Line" Color="#FF3A3D45"/>
<SolidColorBrush x:Key="Field" Color="#FF191A1E"/>
<SolidColorBrush x:Key="Accent" Color="#FF1D9AC7"/>
<Style TargetType="TextBlock">
<Setter Property="Foreground" Value="{StaticResource Ink}"/>
<Setter Property="VerticalAlignment" Value="Center"/>
</Style>
<Style x:Key="Lbl" TargetType="TextBlock">
<Setter Property="Foreground" Value="{StaticResource Dim}"/>
<Setter Property="FontSize" Value="10"/>
<Setter Property="Margin" Value="0,0,0,3"/>
</Style>
<Style TargetType="TextBox">
<Setter Property="Background" Value="{StaticResource Field}"/>
<Setter Property="Foreground" Value="{StaticResource Ink}"/>
<Setter Property="BorderBrush" Value="{StaticResource Line}"/>
<Setter Property="CaretBrush" Value="{StaticResource Accent}"/>
<Setter Property="Padding" Value="4,3"/>
</Style>
<Style TargetType="PasswordBox">
<Setter Property="Background" Value="{StaticResource Field}"/>
<Setter Property="Foreground" Value="{StaticResource Ink}"/>
<Setter Property="BorderBrush" Value="{StaticResource Line}"/>
<Setter Property="Padding" Value="4,3"/>
</Style>
<Style TargetType="ComboBox">
<Setter Property="Background" Value="{StaticResource Field}"/>
<Setter Property="Foreground" Value="#FF101114"/>
<Setter Property="BorderBrush" Value="{StaticResource Line}"/>
<Setter Property="Padding" Value="4,3"/>
</Style>
<Style TargetType="CheckBox">
<Setter Property="Foreground" Value="{StaticResource Dim}"/>
<Setter Property="VerticalAlignment" Value="Center"/>
</Style>
<Style TargetType="Button">
<Setter Property="Background" Value="#FF26282D"/>
<Setter Property="Foreground" Value="{StaticResource Ink}"/>
<Setter Property="BorderBrush" Value="{StaticResource Line}"/>
<Setter Property="Padding" Value="10,5"/>
<Setter Property="Margin" Value="0,0,6,0"/>
<Setter Property="MinWidth" Value="90"/>
</Style>
<Style x:Key="Primary" TargetType="Button" BasedOn="{StaticResource {x:Type Button}}">
<Setter Property="Background" Value="{StaticResource Accent}"/>
<Setter Property="Foreground" Value="#FF08191F"/>
<Setter Property="FontWeight" Value="Bold"/>
</Style>
<Style TargetType="GroupBox">
<Setter Property="Foreground" Value="{StaticResource Dim}"/>
<Setter Property="BorderBrush" Value="{StaticResource Line}"/>
<Setter Property="Background" Value="{StaticResource Panel}"/>
<Setter Property="Padding" Value="8"/>
<Setter Property="Margin" Value="0,0,0,8"/>
</Style>
<Style TargetType="DataGrid">
<Setter Property="Background" Value="{StaticResource Panel}"/>
<Setter Property="Foreground" Value="{StaticResource Ink}"/>
<Setter Property="BorderBrush" Value="{StaticResource Line}"/>
<Setter Property="RowBackground" Value="#FF212226"/>
<Setter Property="AlternatingRowBackground" Value="#FF25262B"/>
<Setter Property="GridLinesVisibility" Value="Horizontal"/>
<Setter Property="HorizontalGridLinesBrush" Value="#FF2E3036"/>
<Setter Property="HeadersVisibility" Value="Column"/>
</Style>
<Style TargetType="DataGridColumnHeader">
<Setter Property="Background" Value="#FF1C1D21"/>
<Setter Property="Foreground" Value="{StaticResource Dim}"/>
<Setter Property="BorderBrush" Value="{StaticResource Line}"/>
<Setter Property="BorderThickness" Value="0,0,0,1"/>
<Setter Property="Padding" Value="6,4"/>
<Setter Property="HorizontalContentAlignment" Value="Left"/>
</Style>
</Window.Resources>
<Grid Margin="12">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<!-- Plex -->
<GroupBox Grid.Row="0" Header="PLEX">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="2*"/>
<ColumnDefinition Width="2*"/>
<ColumnDefinition Width="1.6*"/>
<ColumnDefinition Width="Auto"/>
</Grid.ColumnDefinitions>
<StackPanel Grid.Column="0" Margin="0,0,8,0">
<TextBlock Style="{StaticResource Lbl}" Text="SERVER-URL"/>
<TextBox x:Name="txtUrl" Text="http://127.0.0.1:32400"/>
</StackPanel>
<StackPanel Grid.Column="1" Margin="0,0,8,0">
<TextBlock Style="{StaticResource Lbl}" Text="X-PLEX-TOKEN"/>
<PasswordBox x:Name="pwToken"/>
</StackPanel>
<StackPanel Grid.Column="2" Margin="0,0,8,0">
<TextBlock Style="{StaticResource Lbl}" Text="BIBLIOTHEK"/>
<ComboBox x:Name="cboSection" DisplayMemberPath="Label"/>
</StackPanel>
<StackPanel Grid.Column="3" VerticalAlignment="Bottom">
<Button x:Name="btnSections" Content="Bibliotheken laden" MinWidth="150"/>
</StackPanel>
</Grid>
</GroupBox>
<!-- Liste -->
<GroupBox Grid.Row="1" Header="LISTE">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<Grid Grid.Row="0" Margin="0,0,0,6">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="Auto"/>
</Grid.ColumnDefinitions>
<StackPanel Grid.Column="0" Margin="0,0,8,0">
<TextBlock Style="{StaticResource Lbl}"
Text="LISTEN-URL (MDBLIST, TRAKT-JSON, ROHE TEXTDATEI)"/>
<TextBox x:Name="txtListUrl"/>
</StackPanel>
<StackPanel Grid.Column="1" VerticalAlignment="Bottom">
<Button x:Name="btnFetch" Content="URL laden" MinWidth="110"/>
</StackPanel>
<StackPanel Grid.Column="2" VerticalAlignment="Bottom">
<Button x:Name="btnFile" Content="Datei oeffnen" MinWidth="120"/>
</StackPanel>
</Grid>
<StackPanel Grid.Row="1">
<TextBlock Style="{StaticResource Lbl}"
Text="INHALT - JSON, CSV ODER EINE ZEILE PRO FILM (tt0111161 | Der Pate (1972) | Dune;2021)"/>
<TextBox x:Name="txtList" Height="130" AcceptsReturn="True" TextWrapping="NoWrap"
VerticalScrollBarVisibility="Auto" HorizontalScrollBarVisibility="Auto"
FontSize="11"/>
</StackPanel>
</Grid>
</GroupBox>
<!-- Aktionen -->
<StackPanel Grid.Row="2" Orientation="Horizontal" Margin="0,0,0,8">
<Button x:Name="btnRun" Content="Abgleich starten" Style="{StaticResource Primary}" MinWidth="150"/>
<Button x:Name="btnSave" Content="Einstellungen speichern" MinWidth="170"/>
<CheckBox x:Name="chkToken" Content="Token speichern (DPAPI)" Margin="10,0,14,0"/>
<CheckBox x:Name="chkYear" Content="Jahr +/-1 tolerieren"/>
</StackPanel>
<!-- Statistik -->
<Border Grid.Row="3" Background="#FF212226" BorderBrush="#FF3A3D45" BorderThickness="1"
Padding="10,6" Margin="0,0,0,8">
<StackPanel Orientation="Horizontal">
<TextBlock x:Name="stList" Margin="0,0,22,0" Text="Liste: -"/>
<TextBlock x:Name="stOk" Margin="0,0,22,0" Text="Vorhanden: -" Foreground="#FF4CAF6D"/>
<TextBlock x:Name="stMiss" Margin="0,0,22,0" Text="Fehlt: -" Foreground="#FFE0554B"/>
<TextBlock x:Name="stMaybe" Margin="0,0,22,0" Text="Unsicher: -" Foreground="#FFD9A441"/>
<TextBlock x:Name="stOnly" Margin="0,0,22,0" Text="Nur in Plex: -" Foreground="#FF1D9AC7"/>
<TextBlock x:Name="stPlex" Text="Plex gesamt: -" Foreground="#FF83878F"/>
</StackPanel>
</Border>
<!-- Filter -->
<StackPanel Grid.Row="4" Orientation="Horizontal" Margin="0,0,0,6">
<TextBlock Text="Ansicht" Foreground="#FF83878F" Margin="0,0,6,0"/>
<ComboBox x:Name="cboView" Width="150" Margin="0,0,12,0"/>
<TextBlock Text="Filter" Foreground="#FF83878F" Margin="0,0,6,0"/>
<TextBox x:Name="txtFilter" Width="220" Margin="0,0,12,0"/>
<Button x:Name="btnCsv" Content="CSV exportieren" MinWidth="130"/>
<Button x:Name="btnIds" Content="IMDb-IDs exportieren" MinWidth="160"/>
<Button x:Name="btnTitles" Content="Titel exportieren" MinWidth="140"/>
</StackPanel>
<!-- Tabelle -->
<DataGrid Grid.Row="5" x:Name="grid" AutoGenerateColumns="False" IsReadOnly="True"
CanUserAddRows="False" SelectionMode="Extended" EnableRowVirtualization="True">
<DataGrid.RowStyle>
<Style TargetType="DataGridRow">
<Setter Property="Foreground" Value="#FFD6D8DD"/>
<Style.Triggers>
<DataTrigger Binding="{Binding Status}" Value="fehlt">
<Setter Property="Foreground" Value="#FFE0554B"/>
</DataTrigger>
<DataTrigger Binding="{Binding Status}" Value="vorhanden">
<Setter Property="Foreground" Value="#FF4CAF6D"/>
</DataTrigger>
<DataTrigger Binding="{Binding Status}" Value="unsicher">
<Setter Property="Foreground" Value="#FFD9A441"/>
</DataTrigger>
<DataTrigger Binding="{Binding Status}" Value="nur Plex">
<Setter Property="Foreground" Value="#FF1D9AC7"/>
</DataTrigger>
</Style.Triggers>
</Style>
</DataGrid.RowStyle>
<DataGrid.Columns>
<DataGridTextColumn Header="Status" Binding="{Binding Status}" Width="95"/>
<DataGridTextColumn Header="Titel" Binding="{Binding Titel}" Width="2*"/>
<DataGridTextColumn Header="Jahr" Binding="{Binding Jahr}" Width="55"/>
<DataGridTextColumn Header="IMDb" Binding="{Binding IMDb}" Width="100"/>
<DataGridTextColumn Header="Treffer in Plex" Binding="{Binding PlexTitel}" Width="2*"/>
<DataGridTextColumn Header="Jahr" Binding="{Binding PlexJahr}" Width="55"/>
<DataGridTextColumn Header="Match" Binding="{Binding Match}" Width="100"/>
</DataGrid.Columns>
</DataGrid>
<!-- Statuszeile -->
<Border Grid.Row="6" Background="#FF212226" BorderBrush="#FF3A3D45" BorderThickness="1"
Padding="8,5" Margin="0,8,0,0">
<TextBlock x:Name="lblStatus" Text="Bereit." Foreground="#FF83878F" TextTrimming="CharacterEllipsis"/>
</Border>
</Grid>
</Window>
'@
# ==========================================================================
# Kernlogik (wird auch im Hintergrund-Runspace verwendet)
# ==========================================================================
$Core = {
function Set-TlsDefaults {
# Systemvorgabe beibehalten und TLS 1.2/1.3 ergaenzen. Ein hartes
# Erzwingen von Tls12 laesst Hosts scheitern, die TLS 1.3 verlangen.
param([switch]$LegacyOnly)
if ($LegacyOnly) {
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
return
}
$names = [Enum]::GetNames([Net.SecurityProtocolType])
$sp = [Net.ServicePointManager]::SecurityProtocol
foreach ($n in 'Tls12', 'Tls13') {
if ($names -contains $n) { $sp = $sp -bor [Net.SecurityProtocolType]::$n }
}
[Net.ServicePointManager]::SecurityProtocol = $sp
}
function Set-CertBypass {
# Nur fuer den eigenen Plex-Server, nicht fuer fremde Hosts.
param([bool]$On)
if ($On) { [Net.ServicePointManager]::ServerCertificateValidationCallback = { $true } }
else { [Net.ServicePointManager]::ServerCertificateValidationCallback = $null }
}
function Get-NormTitle {
param([string]$Text)
if ([string]::IsNullOrWhiteSpace($Text)) { return '' }
$d = $Text.Normalize([Text.NormalizationForm]::FormD)
$sb = New-Object Text.StringBuilder
foreach ($c in $d.ToCharArray()) {
if ([Globalization.CharUnicodeInfo]::GetUnicodeCategory($c) -ne 'NonSpacingMark') {
[void]$sb.Append($c)
}
}
$s = $sb.ToString().ToLowerInvariant().Replace('&', ' and ').Replace('+', ' and ')
$s = [regex]::Replace($s, '\b(part|teil)\b', ' ')
$s = [regex]::Replace($s, '[^a-z0-9]+', ' ').Trim()
foreach ($a in @('the ', 'a ', 'an ', 'der ', 'die ', 'das ', 'le ', 'la ', 'les ', 'el ', 'il ')) {
if ($s.StartsWith($a)) { $s = $s.Substring($a.Length); break }
}
return [regex]::Replace($s, '\s+', ' ').Trim()
}
function Get-Year {
param($Value)
if ($null -eq $Value) { return $null }
$t = ([string]$Value).Trim()
if ($t.Length -ge 4 -and $t.Substring(0, 4) -match '^\d{4}$') { return [int]$t.Substring(0, 4) }
return $null
}
function Invoke-PlexXml {
param([string]$BaseUrl, [string]$Token, [string]$Path, [hashtable]$Query)
if ([string]::IsNullOrWhiteSpace($BaseUrl)) { throw 'Keine Server-URL angegeben.' }
if ([string]::IsNullOrWhiteSpace($Token)) { throw 'Kein Plex-Token angegeben.' }
$parts = @("X-Plex-Token=$([uri]::EscapeDataString($Token))")
if ($Query) {
foreach ($k in $Query.Keys) {
$parts += ('{0}={1}' -f $k, [uri]::EscapeDataString([string]$Query[$k]))
}
}
$url = $BaseUrl.TrimEnd('/') + $Path + '?' + ($parts -join '&')
Set-CertBypass ($url -like 'https://*')
$resp = Invoke-WebRequest -Uri $url -UseBasicParsing -TimeoutSec 60 `
-Headers @{ 'X-Plex-Product' = 'PlexMatchGUI' }
return [xml]$resp.Content
}
function Get-PlexSections {
param([string]$BaseUrl, [string]$Token)
$xml = Invoke-PlexXml -BaseUrl $BaseUrl -Token $Token -Path '/library/sections'
$out = @()
foreach ($d in $xml.SelectNodes('/MediaContainer/Directory')) {
$out += [pscustomobject]@{
Key = $d.GetAttribute('key')
Title = $d.GetAttribute('title')
Type = $d.GetAttribute('type')
Agent = $d.GetAttribute('agent')
}
}
return $out
}
function Get-PlexItems {
param([string]$BaseUrl, [string]$Token, [string]$SectionKey,
[string]$SectionType = 'movie', [int]$PageSize = 400, $Sync)
$plexType = 1
$nodeName = 'Video'
if ($SectionType -eq 'show') { $plexType = 2; $nodeName = 'Directory' }
$items = New-Object Collections.Generic.List[object]
$start = 0
while ($true) {
$xml = Invoke-PlexXml -BaseUrl $BaseUrl -Token $Token `
-Path ('/library/sections/{0}/all' -f $SectionKey) `
-Query @{ 'type' = $plexType; 'includeGuids' = 1;
'X-Plex-Container-Start' = $start; 'X-Plex-Container-Size' = $PageSize }
$mc = $xml.SelectSingleNode('/MediaContainer')
if ($null -eq $mc) { throw 'Unerwartete Antwort vom Plex-Server.' }
$nodes = $mc.SelectNodes($nodeName)
foreach ($v in $nodes) {
$ids = New-Object Collections.Generic.List[string]
foreach ($m in [regex]::Matches($v.GetAttribute('guid'), 'tt\d{6,10}')) { $ids.Add($m.Value) }
foreach ($g in $v.SelectNodes('Guid')) {
foreach ($m in [regex]::Matches($g.GetAttribute('id'), 'tt\d{6,10}')) { $ids.Add($m.Value) }
}
$imdb = $null
if ($ids.Count -gt 0) { $imdb = @($ids | Sort-Object -Unique)[0] }
$items.Add([pscustomobject]@{
Title = $v.GetAttribute('title')
Year = Get-Year $v.GetAttribute('year')
Imdb = $imdb
RatingKey = $v.GetAttribute('ratingKey')
})
}
$total = $items.Count
$t = $mc.GetAttribute('totalSize')
if ($t -match '^\d+$') { $total = [int]$t }
else {
$t = $mc.GetAttribute('size')
if ($t -match '^\d+$' -and [int]$t -eq $PageSize) { $total = $items.Count + 1 }
}
if ($Sync) { $Sync.Status = ('Lese Plex-Bibliothek: {0} / {1} Eintraege ...' -f $items.Count, $total) }
$start += $PageSize
if ($nodes.Count -eq 0 -or $items.Count -ge $total) { break }
}
return $items
}
function ConvertTo-ListEntries {
param([string]$Text)
$Text = $Text.TrimStart([char]0xFEFF).Trim()
if (-not $Text) { return @() }
$out = New-Object Collections.Generic.List[object]
# --- HTML (z.B. MDBList-Seite statt JSON): nur IMDb-IDs herausziehen ---
$head = $Text.Substring(0, [Math]::Min(400, $Text.Length)).ToLowerInvariant()
if ($head.StartsWith('<!doctype') -or $head.StartsWith('<html') -or $head.Contains('<head')) {
$seen = @{}
$ms = [regex]::Matches($Text, 'imdb\.com/title/(tt\d{6,10})')
if ($ms.Count -eq 0) { $ms = [regex]::Matches($Text, '(tt\d{6,10})') }
foreach ($m in $ms) {
$id = $m.Groups[1].Value
if (-not $seen.ContainsKey($id)) {
$seen[$id] = $true
$out.Add([pscustomobject]@{ Imdb = $id; Title = ''; Year = $null })
}
}
return $out
}
# --- JSON ---
if ($Text[0] -eq '[' -or $Text[0] -eq '{') {
try {
$data = $Text | ConvertFrom-Json
if ($data -isnot [Array]) {
foreach ($k in 'items', 'movies', 'results', 'data', 'entries') {
if ($data.PSObject.Properties.Name -contains $k -and $data.$k -is [Array]) {
$data = $data.$k; break
}
}
}
foreach ($row in @($data)) {
if ($row -is [string]) { continue }
$imdb = $null
foreach ($k in 'imdb_id', 'imdbid', 'imdb', 'id', 'const') {
if ($row.PSObject.Properties.Name -contains $k) {
$m = [regex]::Match([string]$row.$k, '^tt\d{6,10}$')
if ($m.Success) { $imdb = $m.Value; break }
}
}
$title = $null
foreach ($k in 'title', 'name', 'originalTitle') {
if ($row.PSObject.Properties.Name -contains $k -and $row.$k) { $title = [string]$row.$k; break }
}
$year = $null
foreach ($k in 'release_year', 'year', 'releaseYear', 'released') {
if ($row.PSObject.Properties.Name -contains $k) { $year = Get-Year $row.$k }
if ($year) { break }
}
$mt = $null
foreach ($k in 'mediatype', 'media_type', 'type') {
if ($row.PSObject.Properties.Name -contains $k -and $row.$k) {
$mt = ([string]$row.$k).Trim().ToLowerInvariant(); break
}
}
if (@('tv', 'series', 'tvshow') -contains $mt) { $mt = 'show' }
elseif (@('movie', 'show') -notcontains $mt) { $mt = $null }
if ($imdb -or $title) {
$out.Add([pscustomobject]@{ Imdb = $imdb; Title = $title; Year = $year; MediaType = $mt })
}
}
if ($out.Count) { return $out }
} catch { }
}
$lines = $Text -split "`r?`n"
$first = $lines[0].ToLowerInvariant()
# --- CSV ---
$delim = $null
foreach ($d in ',', ';', "`t") { if ($first.Contains($d)) { $delim = $d; break } }
if ($delim -and ($first -match 'title|const|imdb|year|name')) {
try {
$rows = $Text | ConvertFrom-Csv -Delimiter $delim
$cols = @($rows[0].PSObject.Properties.Name)
function Find-Col { param($Cands)
foreach ($c in $Cands) {
$hit = @($cols | Where-Object { $_.Trim().ToLowerInvariant() -eq $c })
if ($hit.Count -gt 0) { return $hit[0] }
}
return $null
}
$cI = Find-Col @('const', 'imdb_id', 'imdbid', 'imdb', 'tconst', 'id')
$cT = Find-Col @('title', 'name', 'primarytitle', 'original title', 'originaltitle')
$cY = Find-Col @('year', 'release_year', 'startyear', 'released', 'release date')
if ($cI -or $cT) {
foreach ($r in $rows) {
$imdb = $null
if ($cI) { $m = [regex]::Match([string]$r.$cI, 'tt\d{6,10}'); if ($m.Success) { $imdb = $m.Value } }
$title = ''
if ($cT) { $title = [string]$r.$cT }
$year = $null
if ($cY) { $year = Get-Year $r.$cY }
if ($imdb -or $title) {
$out.Add([pscustomobject]@{ Imdb = $imdb; Title = $title.Trim(); Year = $year })
}
}
if ($out.Count) { return $out }
}
} catch { }
}
# --- Freitext ---
foreach ($line in $lines) {
$l = $line.Trim()
if (-not $l -or $l.StartsWith('#')) { continue }
$imdb = $null
$m = [regex]::Match($l, 'tt\d{6,10}')
$rest = $l
if ($m.Success) {
$imdb = $m.Value
$rest = ($l.Substring(0, $m.Index) + ' ' + $l.Substring($m.Index + $m.Length))
}
$rest = $rest.Trim(" `t-|,;:".ToCharArray())
$year = $null
$ym = [regex]::Match($rest, '[\(\[](\d{4})[\)\]]\s*$')
if ($ym.Success) {
$year = [int]$ym.Groups[1].Value
$rest = $rest.Substring(0, $ym.Index).Trim()
} else {
$parts = $rest -split '[;\t|]'
if ($parts.Count -ge 2 -and $parts[-1].Trim() -match '^\d{4}$') {
$year = [int]$parts[-1].Trim()
$rest = ($parts[0..($parts.Count - 2)] -join ';').Trim()
}
}
if ($rest -match '^https?://\S*imdb\S*$') { $rest = '' }
if ($imdb -or $rest) {
$out.Add([pscustomobject]@{ Imdb = $imdb; Title = $rest; Year = $year })
}
}
return $out
}
function Compare-PlexList {
param($Movies, $Entries, [int]$YearTolerance = 0, [string]$SectionType = 'movie')
$byImdb = @{}; $byKey = @{}; $byTitle = @{}
foreach ($it in $Movies) {
if ($it.Imdb -and -not $byImdb.ContainsKey($it.Imdb)) { $byImdb[$it.Imdb] = $it }
$nt = Get-NormTitle $it.Title
if ($nt) {
if (-not $byTitle.ContainsKey($nt)) { $byTitle[$nt] = New-Object Collections.Generic.List[object] }
$byTitle[$nt].Add($it)
if ($it.Year) {
$k = "$nt|$($it.Year)"
if (-not $byKey.ContainsKey($k)) { $byKey[$k] = $it }
}
}
}
$matched = @{}
$results = New-Object Collections.Generic.List[object]
foreach ($e in $Entries) {
$hit = $null; $how = $null
if ($e.Imdb -and $byImdb.ContainsKey($e.Imdb)) { $hit = $byImdb[$e.Imdb]; $how = 'imdb' }
if (-not $hit) {
$nt = Get-NormTitle $e.Title
if ($nt) {
if ($e.Year) {
for ($d = 0; $d -le $YearTolerance -and -not $hit; $d++) {
foreach ($y in @(($e.Year - $d), ($e.Year + $d) | Sort-Object -Unique)) {
$k = "$nt|$y"
if ($byKey.ContainsKey($k)) {
$hit = $byKey[$k]
$how = if ($d -eq 0) { 'titel+jahr' } else { 'titel+jahr~' }
break
}
}
}
}
if (-not $hit -and $byTitle.ContainsKey($nt)) {
$cand = $byTitle[$nt]
if ($cand.Count -eq 1 -and -not $e.Year) { $hit = $cand[0]; $how = 'titel' }
elseif ($cand.Count) { $hit = $cand[0]; $how = 'titel?' }
}
}
}
if ($hit) { $matched[$hit.RatingKey] = $true }
$status = 'fehlt'
if (@('imdb', 'titel+jahr', 'titel+jahr~', 'titel') -contains $how) { $status = 'vorhanden' }
elseif ($how) { $status = 'unsicher' }
$t = $e.Title
if (-not $t) { $t = $e.Imdb }
$pT = ''; $pJ = $null; $pM = ''
if ($hit) { $pT = $hit.Title; $pJ = $hit.Year }
if ($how) { $pM = $how }
$results.Add([pscustomobject]@{
Status = $status
Titel = $t
Jahr = $e.Year
IMDb = $e.Imdb
PlexTitel = $pT
PlexJahr = $pJ
Match = $pM
})
}
$plexOnly = New-Object Collections.Generic.List[object]
foreach ($it in $Movies) {
if (-not $matched.ContainsKey($it.RatingKey)) {
$plexOnly.Add([pscustomobject]@{
Status = 'nur Plex'; Titel = $it.Title; Jahr = $it.Year; IMDb = $it.Imdb
PlexTitel = $it.Title; PlexJahr = $it.Year; Match = ''
})
}
}
return [pscustomobject]@{
Results = $results
PlexOnly = ($plexOnly | Sort-Object Titel)
Stats = [pscustomobject]@{
List = @($Entries).Count
Plex = @($Movies).Count
Present = @($results | Where-Object { $_.Status -eq 'vorhanden' }).Count
Unsure = @($results | Where-Object { $_.Status -eq 'unsicher' }).Count
Missing = @($results | Where-Object { $_.Status -eq 'fehlt' }).Count
PlexOnly = $plexOnly.Count
NoGuid = @($Movies | Where-Object { -not $_.Imdb }).Count
Mismatch = @($Entries | Where-Object { $_.MediaType -and $_.MediaType -ne $SectionType }).Count
SecType = $SectionType
}
}
}
}
. $Core
Set-TlsDefaults
# ==========================================================================
# Fenster aufbauen
# ==========================================================================
$reader = New-Object Xml.XmlNodeReader ([xml]$Xaml)
$win = [Windows.Markup.XamlReader]::Load($reader)
$script:AppVersion = '1.2.2'
$win.Title = "plexmatch $script:AppVersion - Bibliothek gegen Liste abgleichen"
$ui = @{}
foreach ($n in 'txtUrl', 'pwToken', 'cboSection', 'btnSections', 'txtListUrl', 'btnFetch',
'btnFile', 'txtList', 'btnRun', 'btnSave', 'chkToken', 'chkYear',
'stList', 'stOk', 'stMiss', 'stMaybe', 'stOnly', 'stPlex',
'cboView', 'txtFilter', 'btnCsv', 'btnIds', 'btnTitles', 'grid', 'lblStatus') {
$ui[$n] = $win.FindName($n)
}
$script:Data = $null
$script:Job = $null
$script:Sync = [hashtable]::Synchronized(@{ Status = ''; Done = $false; Error = $null; Result = $null })
foreach ($v in 'Fehlt', 'Vorhanden', 'Unsicher', 'Alle', 'Nur in Plex') { [void]$ui.cboView.Items.Add($v) }
$ui.cboView.SelectedIndex = 0
function Set-Status { param([string]$Text) $ui.lblStatus.Text = $Text }
function Set-Busy {
param([bool]$On)
foreach ($b in 'btnSections', 'btnFetch', 'btnFile', 'btnRun', 'btnSave', 'btnCsv', 'btnIds', 'btnTitles') {
$ui[$b].IsEnabled = -not $On
}
if ($On) { $win.Cursor = [Windows.Input.Cursors]::Wait } else { $win.Cursor = $null }
}
# ---------------- Einstellungen ----------------
function Import-Settings {
if (-not (Test-Path $SettingsPath)) { return }
try {
$s = Get-Content -LiteralPath $SettingsPath -Raw -Encoding UTF8 | ConvertFrom-Json
if ($s.PlexUrl) { $ui.txtUrl.Text = $s.PlexUrl }
if ($s.ListUrl) { $ui.txtListUrl.Text = $s.ListUrl }
$ui.chkYear.IsChecked = [bool]$s.YearTolerance
$ui.chkToken.IsChecked = [bool]$s.SaveToken
if ($s.SaveToken -and $s.Token) {
$sec = ConvertTo-SecureString $s.Token
$bstr = [Runtime.InteropServices.Marshal]::SecureStringToBSTR($sec)
$ui.pwToken.Password = [Runtime.InteropServices.Marshal]::PtrToStringAuto($bstr)
[Runtime.InteropServices.Marshal]::ZeroFreeBSTR($bstr)
}
if ($s.SectionKey) {
$secType = 'movie'
if ($s.SectionType) { $secType = [string]$s.SectionType }
$ui.cboSection.Items.Add([pscustomobject]@{
Label = "gespeichert (key $($s.SectionKey))"; Key = [string]$s.SectionKey
Type = $secType }) | Out-Null
$ui.cboSection.SelectedIndex = 0
}
} catch { Set-Status "Einstellungen nicht lesbar: $($_.Exception.Message)" }
}
function Export-Settings {
$dir = Split-Path -Parent $SettingsPath
if (-not (Test-Path $dir)) { New-Item -ItemType Directory -Path $dir -Force | Out-Null }
$secKey = ''
$secType = 'movie'
if ($ui.cboSection.SelectedItem) {
$secKey = [string]$ui.cboSection.SelectedItem.Key
if ($ui.cboSection.SelectedItem.Type) { $secType = [string]$ui.cboSection.SelectedItem.Type }
}
$obj = [ordered]@{
PlexUrl = $ui.txtUrl.Text.Trim()
ListUrl = $ui.txtListUrl.Text.Trim()
SectionKey = $secKey
SectionType = $secType
YearTolerance = [bool]$ui.chkYear.IsChecked
SaveToken = [bool]$ui.chkToken.IsChecked
}
if ($ui.chkToken.IsChecked -and $ui.pwToken.Password) {
$obj.Token = ConvertTo-SecureString $ui.pwToken.Password -AsPlainText -Force | ConvertFrom-SecureString
}
$obj | ConvertTo-Json | Set-Content -LiteralPath $SettingsPath -Encoding UTF8
Set-Status "Gespeichert: $SettingsPath"
}
# ---------------- Anzeige ----------------
function Get-VisibleRows {
if (-not $script:Data) { return @() }
$view = [string]$ui.cboView.SelectedItem
$rows = switch ($view) {
'Alle' { $script:Data.Results }
'Nur in Plex' { $script:Data.PlexOnly }
default { $script:Data.Results | Where-Object { $_.Status -eq $view.ToLowerInvariant() } }
}
$f = $ui.txtFilter.Text.Trim()
if ($f) {
$rows = $rows | Where-Object {
("$($_.Titel) $($_.IMDb) $($_.PlexTitel)") -like "*$f*"
}
}
return @($rows)
}
function Update-Grid {
$rows = Get-VisibleRows
$ui.grid.ItemsSource = $rows
if ($script:Data) {
$s = $script:Data.Stats
$txt = '{0} Eintraege in dieser Ansicht. {1} Plex-Eintraege ohne IMDb-ID (dort greift nur Titel+Jahr).' -f
$rows.Count, $s.NoGuid
if ($s.Mismatch -gt 0) {
$listKind = 'Filme'
$libKind = 'Serien'
if ($s.SecType -eq 'movie') { $listKind = 'Serien'; $libKind = 'Filme' }
$txt = "ACHTUNG: $($s.Mismatch) Listeneintraege sind $listKind, die gewaehlte Bibliothek enthaelt $libKind. " + $txt
}
Set-Status $txt
}
}
function Update-Stats {
$s = $script:Data.Stats
$ui.stList.Text = "Liste: $($s.List)"
$ui.stOk.Text = "Vorhanden: $($s.Present)"
$ui.stMiss.Text = "Fehlt: $($s.Missing)"
$ui.stMaybe.Text = "Unsicher: $($s.Unsure)"
$ui.stOnly.Text = "Nur in Plex: $($s.PlexOnly)"
$ui.stPlex.Text = "Plex gesamt: $($s.Plex)"
}
# ---------------- Events ----------------
$ui.btnSections.Add_Click({
Set-Busy $true; Set-Status 'Lade Bibliotheken ...'
try {
$secs = Get-PlexSections -BaseUrl $ui.txtUrl.Text.Trim() -Token $ui.pwToken.Password
$usable = @($secs | Where-Object { $_.Type -eq 'movie' -or $_.Type -eq 'show' })
$ui.cboSection.Items.Clear()
foreach ($s in $usable) {
$kind = 'Filme'
if ($s.Type -eq 'show') { $kind = 'Serien' }
[void]$ui.cboSection.Items.Add([pscustomobject]@{
Label = "$($s.Title) [$kind, key $($s.Key)]"; Key = $s.Key; Type = $s.Type })
}
$skipped = @($secs | Where-Object { $_.Type -ne 'movie' -and $_.Type -ne 'show' })
$note = ''
if ($skipped.Count) {
$names = ($skipped | ForEach-Object { "$($_.Title) [$($_.Type)]" }) -join ', '
$note = " Nicht unterstuetzt (kein IMDb-Abgleich moeglich): $names."
}
if ($usable.Count) {
$ui.cboSection.SelectedIndex = 0
Set-Status "$($usable.Count) von $($secs.Count) Bibliotheken nutzbar.$note"
} else {
Set-Status "Keine Film- oder Serien-Bibliothek gefunden.$note"
}
} catch {
Set-Status "Fehler: $($_.Exception.Message)"
} finally { Set-Busy $false }
})
function Get-NormalizedListUrl {
param([string]$Url)
$u = $Url.Trim()
if ($u -match 'mdblist\.com/lists/') {
$base = ($u -split '\?')[0].TrimEnd('/')
if ($base -match '/json$') { return $base + '/' }
elseif ($base -match '/items$') { return $base }
else { return $base + '/json/' }
}
return $u
}
function Import-ListFromUrl {
# Laedt die Listen-URL in das Inhaltsfeld. Gibt die Anzahl erkannter Filme zurueck.
$url = Get-NormalizedListUrl $ui.txtListUrl.Text
if (-not $url) { throw 'Keine Listen-URL angegeben.' }
$ui.txtListUrl.Text = $url
Set-Status "Lade $url ..."
$ua = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0 Safari/537.36'
$hdr = @{ 'User-Agent' = $ua; 'Accept' = 'application/json, text/html, text/plain, */*' }
Set-CertBypass $false
Set-TlsDefaults
try {
$r = Invoke-WebRequest -Uri $url -UseBasicParsing -TimeoutSec 60 -Headers $hdr
} catch {
# Zweiter Versuch mit reinem TLS 1.2, falls der Host das braucht.
Set-TlsDefaults -LegacyOnly
$r = Invoke-WebRequest -Uri $url -UseBasicParsing -TimeoutSec 60 -Headers $hdr
Set-TlsDefaults
}
$ui.txtList.Text = $r.Content
return @(ConvertTo-ListEntries -Text $r.Content).Count
}
$ui.btnFetch.Add_Click({
if (-not $ui.txtListUrl.Text.Trim()) { Set-Status 'Keine Listen-URL angegeben.'; return }
Set-Busy $true
try {
$n = Import-ListFromUrl
if ($n -eq 0) {
Set-Status 'Geladen, aber 0 Filme erkannt. Ist die Liste oeffentlich? Sonst JSON/CSV manuell einfuegen.'
} else {
Set-Status "$n Filme erkannt aus $($ui.txtListUrl.Text)."
}
} catch { Set-Status "Fehler beim Laden: $($_.Exception.Message)" } finally { Set-Busy $false }
})
$ui.btnFile.Add_Click({
$dlg = New-Object Microsoft.Win32.OpenFileDialog
$dlg.Filter = 'Listen (*.csv;*.json;*.txt;*.tsv)|*.csv;*.json;*.txt;*.tsv|Alle Dateien (*.*)|*.*'
if ($dlg.ShowDialog()) {
$ui.txtList.Text = Get-Content -LiteralPath $dlg.FileName -Raw -Encoding UTF8
Set-Status "Datei geladen: $($dlg.FileName)"
}
})
$ui.btnSave.Add_Click({ try { Export-Settings } catch { Set-Status "Fehler: $($_.Exception.Message)" } })
$ui.cboView.Add_SelectionChanged({ Update-Grid })
$ui.txtFilter.Add_TextChanged({ Update-Grid })
$ui.btnRun.Add_Click({
if (-not $ui.cboSection.SelectedItem) { Set-Status 'Erst eine Bibliothek laden und auswaehlen.'; return }
if (-not $ui.txtList.Text.Trim()) {
if (-not $ui.txtListUrl.Text.Trim()) {
Set-Status 'Keine Liste: entweder URL laden, Datei oeffnen oder Inhalt einfuegen.'
return
}
Set-Busy $true
try {
$n = Import-ListFromUrl
if ($n -eq 0) {
Set-Status 'Von der URL geladen, aber 0 Filme erkannt. Inhalt pruefen.'
Set-Busy $false
return
}
} catch {
Set-Status "Fehler beim Laden der Listen-URL: $($_.Exception.Message)"
Set-Busy $false
return
}
Set-Busy $false
}
Set-Busy $true
$script:Sync.Status = 'Starte ...'
$script:Sync.Done = $false
$script:Sync.Error = $null
$script:Sync.Result = $null
$secType = 'movie'
if ($ui.cboSection.SelectedItem.Type) { $secType = [string]$ui.cboSection.SelectedItem.Type }
$jobArgs = @{
BaseUrl = $ui.txtUrl.Text.Trim()
Token = $ui.pwToken.Password
Section = [string]$ui.cboSection.SelectedItem.Key
SecType = $secType
ListText = $ui.txtList.Text
Tolerance = [int][bool]$ui.chkYear.IsChecked
}
$worker = {
param($Core, $A, $Sync)
try {
. ([scriptblock]::Create($Core))
Set-TlsDefaults
$Sync.Status = 'Lese Plex-Bibliothek ...'
$movies = Get-PlexItems -BaseUrl $A.BaseUrl -Token $A.Token -SectionKey $A.Section `
-SectionType $A.SecType -Sync $Sync
$Sync.Status = 'Lese Liste ...'
$entries = ConvertTo-ListEntries -Text $A.ListText
if (@($entries).Count -eq 0) { throw 'Liste konnte nicht gelesen werden (0 Eintraege erkannt).' }
$Sync.Status = 'Gleiche ab ...'
$Sync.Result = Compare-PlexList -Movies $movies -Entries $entries `
-YearTolerance $A.Tolerance -SectionType $A.SecType
} catch {
$Sync.Error = $_.Exception.Message
} finally {
$Sync.Done = $true
}
}
$rs = [runspacefactory]::CreateRunspace()
$rs.ApartmentState = 'STA'
$rs.ThreadOptions = 'ReuseThread'
$rs.Open()
$ps = [powershell]::Create()
$ps.Runspace = $rs
[void]$ps.AddScript($worker).AddArgument($Core.ToString()).AddArgument($jobArgs).AddArgument($script:Sync)
$script:Job = @{ PS = $ps; Handle = $ps.BeginInvoke(); RS = $rs }
$script:Timer.Start()
})
$script:Timer = New-Object Windows.Threading.DispatcherTimer
$script:Timer.Interval = [TimeSpan]::FromMilliseconds(250)
$script:Timer.Add_Tick({
if ($script:Sync.Status) { Set-Status $script:Sync.Status }
if (-not $script:Sync.Done) { return }
$script:Timer.Stop()
try { $script:Job.PS.EndInvoke($script:Job.Handle) | Out-Null } catch { }
$script:Job.PS.Dispose(); $script:Job.RS.Close(); $script:Job.RS.Dispose()
$script:Job = $null
Set-Busy $false
if ($script:Sync.Error) { Set-Status "Fehler: $($script:Sync.Error)"; return }
$script:Data = $script:Sync.Result
Update-Stats
Update-Grid
})
# ---------------- Export ----------------
function Save-Rows {
param([string]$Suffix, [string]$Extension, [scriptblock]$Builder)
$rows = Get-VisibleRows
if (-not $rows.Count) { Set-Status 'Nichts in dieser Ansicht zu exportieren.'; return }
$dlg = New-Object Microsoft.Win32.SaveFileDialog
$dlg.FileName = 'plexmatch-{0}-{1}.{2}' -f $Suffix, (Get-Date -Format 'yyyy-MM-dd'), $Extension
$dlg.Filter = "$Extension|*.$Extension|Alle Dateien (*.*)|*.*"
if (-not $dlg.ShowDialog()) { return }
& $Builder $rows $dlg.FileName
Set-Status "Exportiert: $($dlg.FileName)"
}
$ui.btnCsv.Add_Click({
Save-Rows 'export' 'csv' {
param($Rows, $Path)
$Rows | Select-Object Status, Titel, Jahr, IMDb, PlexTitel, PlexJahr, Match |
Export-Csv -LiteralPath $Path -NoTypeInformation -Encoding UTF8 -Delimiter ';'
}
})
$ui.btnIds.Add_Click({
Save-Rows 'imdb' 'txt' {
param($Rows, $Path)
($Rows | Where-Object { $_.IMDb } | ForEach-Object { $_.IMDb }) |
Set-Content -LiteralPath $Path -Encoding ASCII
}
})
$ui.btnTitles.Add_Click({
Save-Rows 'titel' 'txt' {
param($Rows, $Path)
($Rows | ForEach-Object { if ($_.Jahr) { "$($_.Titel) ($($_.Jahr))" } else { $_.Titel } }) |
Set-Content -LiteralPath $Path -Encoding UTF8
}
})
$win.Add_Closed({
if ($script:Job) {
try { $script:Job.PS.Stop(); $script:Job.PS.Dispose(); $script:Job.RS.Dispose() } catch { }
}
})
Import-Settings
Set-Status "Bereit (v$script:AppVersion). Server-URL und Token eintragen, dann Bibliotheken laden."
[void]$win.ShowDialog()