-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdlp-script.ps1
2390 lines (2371 loc) · 116 KB
/
dlp-script.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
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
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<#
.Synopsis
Script to run yt-dlp, mkvmerge, subtitle edit, and filebot for downloading and processing videos
.EXAMPLE
Runs the script using the mySiteHere as a manual run with the defined config using login, cookies, archive file, mkvmerge, and sends out a discord message
D:\_DL\dlp-script.ps1 -sn mySiteHere -l -c -mk -a -sd
.EXAMPLE
Runs the script using the mySiteHere as a daily run with the defined config using login, cookies, no archive file, and filebot/plex
D:\_DL\dlp-script.ps1 -sn mySiteHere -d -l -c -f
.NOTES
See https://github.com/wamasi/dlp-filehandler for more details
Script was designed to be ran via powershell by being called through console on a cronjob or task scheduler. copying and pasting into powershell console will not work.
#>
[CmdletBinding()]
param(
[Parameter(ParameterSetName = 'Help', Mandatory = $True)]
[Alias('H')]
[switch]$help,
[Parameter(ParameterSetName = 'NewConfig', Mandatory = $True)]
[Alias('NC')]
[switch]$newConfig,
[Alias('SU')]
[Parameter(ParameterSetName = 'SupportFiles', Mandatory = $True)]
[switch]$supportFiles,
[Alias('SN')]
[ValidateScript({ if (Test-Path -Path "$PSScriptRoot\config.xml") {
if (([xml](Get-Content -Path "$PSScriptRoot\config.xml")).getElementsByTagName('site').siteName -contains $_ ) {
$true
}
else {
$validSites = (([xml](Get-Content -Path "$PSScriptRoot\config.xml")).getElementsByTagName('site').siteName) -join "`r`n"
throw "The following Sites are valid:`r`n$validSites"
}
}
else {
throw "No valid config.xml found in $PSScriptRoot. Run ($PSScriptRoot\dlp-script.ps1 -nc) for a new config file."
}
})]
[Parameter(ParameterSetName = 'Site', Mandatory = $True)]
[Parameter(ParameterSetName = 'Test', Mandatory = $True)]
[string]$site,
[Alias('OD')]
[Parameter(ParameterSetName = 'Site', Mandatory = $false)]
[Parameter(ParameterSetName = 'Test', Mandatory = $false)]
[string]$overrideBatch,
[Alias('D')]
[Parameter(ParameterSetName = 'Site', Mandatory = $false)]
[Parameter(ParameterSetName = 'Test', Mandatory = $false)]
[switch]$daily,
[Alias('L')]
[Parameter(ParameterSetName = 'Site', Mandatory = $false)]
[Parameter(ParameterSetName = 'Test', Mandatory = $false)]
[switch]$login,
[Alias('C')]
[Parameter(ParameterSetName = 'Site', Mandatory = $false)]
[Parameter(ParameterSetName = 'Test', Mandatory = $false)]
[switch]$cookies,
[Alias('A')]
[Parameter(ParameterSetName = 'Site', Mandatory = $false)]
[Parameter(ParameterSetName = 'Test', Mandatory = $false)]
[switch]$archive,
[Alias('AT')]
[Parameter(ParameterSetName = 'Site', Mandatory = $false)]
[Parameter(ParameterSetName = 'Test', Mandatory = $false)]
[switch]$archiveTemp,
[Alias('SE')]
[Parameter(ParameterSetName = 'Site', Mandatory = $false)]
[Parameter(ParameterSetName = 'Test', Mandatory = $false)]
[switch]$subtitleEdit,
[Alias('MK')]
[Parameter(ParameterSetName = 'Site', Mandatory = $false)]
[Parameter(ParameterSetName = 'Test', Mandatory = $false)]
[switch]$mkvMerge,
[Alias('F')]
[Parameter(ParameterSetName = 'Site', Mandatory = $false)]
[Parameter(ParameterSetName = 'Test', Mandatory = $false)]
[switch]$filebot,
[Alias('SD')]
[Parameter(ParameterSetName = 'Site', Mandatory = $false)]
[Parameter(ParameterSetName = 'Test', Mandatory = $false)]
[switch]$sendDiscord,
[Alias('AL')]
[ValidateScript({
$langValues = 'ar', 'de', 'en', 'es', 'es-la', 'fr', 'it', 'ja', 'pt-br', 'pt-pt', 'ru', 'und'
if ($_ -in $langValues) {
$true
}
else {
throw "Value '{0}' is invalid. The following languages are valid:`r`n{1}" -f $_, $($langValues -join "`r`n")
}
})]
[Parameter(ParameterSetName = 'Site', Mandatory = $false)]
[Parameter(ParameterSetName = 'Test', Mandatory = $false)]
[string]$audioLang,
[Alias('SL')]
[ValidateScript({
$langValues = 'ar', 'de', 'en', 'es', 'es-la', 'fr', 'it', 'ja', 'pt-br', 'pt-pt', 'ru', 'und'
if ($_ -in $langValues ) {
$true
}
else {
throw "Value '{0}' is invalid. The following languages are valid:`r`n{1}" -f $_, $($langValues -join "`r`n")
}
})]
[Parameter(ParameterSetName = 'Site', Mandatory = $false)]
[Parameter(ParameterSetName = 'Test', Mandatory = $false)]
[string]$subtitleLang,
[Alias('T')]
[Parameter(ParameterSetName = 'Test', Mandatory = $true)]
[switch]$testScript,
[Alias('DS')]
[Parameter(ParameterSetName = 'Site', Mandatory = $false)]
[switch]$debugScript
)
# Timer for script
$scriptStopWatch = [System.Diagnostics.Stopwatch]::StartNew()
# Setting styling to remove error characters and width
$psStyle.OutputRendering = 'Host'
$width = $host.UI.RawUI.MaxPhysicalWindowSize.Width
$host.UI.RawUI.BufferSize = New-Object System.Management.Automation.Host.size($width, 9999)
mode con cols=9999
# Output current time in different formats
function Get-DateTime {
param (
[int]$dateType
)
switch ($dateType) {
1 { $datetime = Get-Date -Format 'yy-MM-dd' }
2 { $datetime = Get-Date -Format 'MMddHHmmssfff' }
3 { $datetime = ($(Get-Date).ToUniversalTime()).ToString('yyyy-MM-ddTHH:mm:ss.fffZ') }
Default { $datetime = Get-Date -Format 'yy-MM-dd HH-mm-ss' }
}
return $datetime
}
# Pass through expressions to format them from logging
function Invoke-ExpressionConsole {
param (
[Parameter(Mandatory = $true)]
[Alias('SCMFN')]
[string]$scmFunctionName,
[Parameter(Mandatory = $true)]
[Alias('SCMFP')]
[string]$scmFunctionParams
)
$iecArguement = "$scmFunctionParams *>&1"
$iecObject = Invoke-Expression $iecArguement
$iecObject -split "`n" | Where-Object { -not [string]::IsNullOrWhiteSpace($_) } | ForEach-Object {
# Write output then logic to grab filebot output for variables
Write-Output "[$scmFunctionName] $(Get-DateTime) - $_"
if ($scmFunctionName -eq 'Filebot') {
# Use Select-String with regex to match from, to, and title strings
$fromPattern = '\[MOVE\] from\s\[(.*?)\]\sto'
$toPattern = '\[MOVE\].*?to \[(.*?)\]$'
$titlePattern = "--set title=(.*?)' executed"
if ($_ -match $fromPattern) {
$fromVideoVar = ($_ | Select-String -Pattern $fromPattern | ForEach-Object { $_.Matches.Groups[1].Value }).Trim()
Write-Output "[$scmFunctionName] $(Get-DateTime) - From: $fromVideoVar."
}
if ($_ -match $toPattern) {
$toVideoVar = ($_ | Select-String -Pattern $toPattern | ForEach-Object { $_.Matches.Groups[1].Value }).Trim()
Write-Output "[$scmFunctionName] $(Get-DateTime) - To: $toVideoVar."
}
if ($_ -match $titlePattern) {
$titleVideoVar = ($_ | Select-String -Pattern $titlePattern | ForEach-Object { $_.Matches.Groups[1].Value }).Trim()
Write-Output "[$scmFunctionName] $(Get-DateTime) - Title: $titleVideoVar."
}
# Once all 3 are matched update associated record and clear the variables for the next video(s)
if ($fromVideoVar -and $toVideoVar -and $titleVideoVar) {
Set-VideoStatus -searchKey '_vsDestPathVideo' -searchValue $fromVideoVar -nodeKey '_vsFinalPathVideo' -nodeValue $toVideoVar
Set-VideoStatus -searchKey '_vsDestPathVideo' -searchValue $fromVideoVar -nodeKey '_vsFilebotTitle' -nodeValue $titleVideoVar
Remove-Variable -Name fromVideoVar, toVideoVar, titleVideoVar
}
}
}
}
# Get diskspace for a give filepath or Drive
function Get-DiskSpace {
param (
$drive
)
$r = ((Get-PSDrive -PSProvider 'FileSystem' | Where-Object { $_.Root -eq ([System.IO.Path]::GetPathRoot($drive)) }) | Select-Object Name, Root, Free, Used)
$rootName = $r.Name
$free = $r.Free
$used = $r.Used
$total = (Get-Volume -Partition (Get-Partition -DriveLetter $rootName)).Size
$freeO = $free
$usedO = $used
$totalO = $total
$units = @('B', 'KB', 'MB', 'GB', 'TB')
$freeIndex = 0
$usedIndex = 0
$totalIndex = 0
while ($free -ge 1KB -and $freeIndex -lt $units.Count - 1) {
$free /= 1KB
$freeIndex++
}
while ($used -ge 1KB -and $usedIndex -lt $units.Count - 1) {
$used /= 1KB
$usedIndex++
}
while ($total -ge 1KB -and $totalIndex -lt $units.Count - 1) {
$total /= 1KB
$totalIndex++
}
$freeSpace = '{0:N2}' -f $free
$usedSpace = '{0:N2}' -f $used
$totalSpace = '{0:N2}' -f $total
$FreeUnit = $units[$freeIndex]
$usedUnit = $units[$usedIndex]
$totalUnit = $units[$totalIndex]
$freeSpaceFormatted = "$($freeSpace)$($FreeUnit)"
$usedSpaceFormatted = "$($usedSpace)$($usedUnit)"
$totalSpaceFormatted = "$($totalSpace)$($totalUnit)"
$percentageFree = [math]::Round((($freeO / $totalO) * 100), 2).ToString('F2')
$percentageUsed = [math]::Round((($usedO / $totalO) * 100), 2).ToString('F2')
$diskSpacePSObj = [PSCustomObject]@{
rootName = $rootName
rootDrive = $r.Root
freeSpace = $freeSpace
usedSpace = $usedSpace
totalSpace = $totalSpace
freeSpaceFormatted = $freeSpaceFormatted
usedSpaceFormatted = $usedSpaceFormatted
totalSpaceFormatted = $totalSpaceFormatted
percentageFree = $percentageFree
percentageUsed = $percentageUsed
freeUnit = $FreeUnit
usedUnit = $usedUnit
totalUnit = $totalUnit
}
return $diskSpacePSObj
}
# Get filesize formatted
function Get-Filesize {
param (
$filePath
)
$Size = (Get-Item -Path $filePath).Length
$units = @('B', 'KB', 'MB', 'GB', 'TB')
$index = 0
while ($Size -ge 1KB -and $index -lt $units.Count - 1) {
$Size /= 1KB
$index++
}
$filesize = [math]::Round($Size, 2).ToString('F2')
$unit = $units[$index]
$filesizeFormatted = "$($filesize)$($unit)"
return $filesize, $filesizeFormatted, $unit, $Size
}
# Test if file is available to interact with
function Test-Lock {
Param(
[parameter(Mandatory = $true)]
$testLockFilename,
[switch]$literal
)
if ($literal) {
$testLockInitial = Resolve-Path -LiteralPath $testLockFilename
}
else {
$testLockInitial = Resolve-Path $testLockFilename
}
$testLockFile = Get-Item -Path ($testLockInitial) -Force
if ($testLockFile -is [IO.FileInfo]) {
trap {
Write-Output "[FileLockCheck] $(Get-DateTime) - $testLockFile File locked. Waiting."
return $true
continue
}
$testLockStream = New-Object system.IO.StreamReader $testLockFile
if ($testLockStream) { $testLockStream.Close() }
}
Write-Output "[FileLockCheck] $(Get-DateTime) - $testLockFile File unlocked. Continuing."
return $false
}
function New-Folder {
param (
[Parameter(Mandatory = $true)]
[string] $newFolderFullPath
)
if (!(Test-Path -Path $newFolderFullPath)) {
New-Item -Path $newFolderFullPath -ItemType Directory -Force -Verbose
Write-Output "$newFolderFullPath missing. Creating."
}
else {
Write-Output "$newFolderFullPath already exists."
}
}
function New-SuppFile {
param (
[Parameter(Mandatory = $true)]
[string] $newSupportFiles
)
if (!(Test-Path -Path $newSupportFiles -PathType Leaf)) {
New-Item -Path $newSupportFiles -ItemType File | Out-Null
Write-Output "$newSupportFiles file missing. Creating."
}
else {
Write-Output "$newSupportFiles file already exists."
}
}
function New-Config {
param (
[Parameter(Mandatory = $true)]
[string] $newConfigs
)
Write-Output "Creating $newConfigs"
New-Item -Path $newConfigs -ItemType File -Force
if ($newConfigs -match 'vrv') {
$vrvConfig | Set-Content -Path $newConfigs
Write-Output "$newConfigs created with VRV values."
}
elseif ($newConfigs -match 'crunchyroll') {
$crunchyrollConfig | Set-Content -Path $newConfigs
Write-Output "$newConfigs created with Crunchyroll values."
}
elseif ($newConfigs -match 'funimation') {
$funimationConfig | Set-Content -Path $newConfigs
Write-Output "$newConfigs created with Funimation values."
}
elseif ($newConfigs -match 'hidive') {
$hidiveConfig | Set-Content -Path $newConfigs
Write-Output "$newConfigs created with Hidive values."
}
elseif ($newConfigs -match 'paramountplus') {
$paramountPlusConfig | Set-Content -Path $newConfigs
Write-Output "$newConfigs created with ParamountPlus values."
}
else {
$defaultConfig | Set-Content -Path $newConfigs
Write-Output "$newConfigs created with default values."
}
}
# Delete Tmp/Src/Home folder logic
function Remove-Folders {
param (
[parameter(Mandatory = $true)]
[string]$removeFolder,
[parameter(Mandatory = $false)]
[string]$removeFolderMatch,
[parameter(Mandatory = $true)]
[string]$removeFolderBaseMatch
)
if ($removeFolder -eq $siteTemp) {
if (($removeFolder -match $removeFolderBaseMatch) -and (Test-Path -Path $removeFolder)) {
Write-Output "Force deleting $removeFolder folders/files."
Remove-Item -Path $removeFolder -Recurse -Force -Verbose
}
else {
Write-Output "SiteTemp($removeFolder) already deleted."
}
}
else {
if (!(Test-Path -Path $removeFolder)) {
Write-Output "Folder($removeFolder) already deleted."
}
elseif ((Test-Path -Path $removeFolder) -and (Get-ChildItem -Path $removeFolder -Recurse -File | Measure-Object).Count -eq 0) {
Write-Output "Folder($removeFolder) is empty. Deleting folder."
& $DeleteRecursion -deleteRecursionPath $removeFolder
}
else {
Write-Output "Folder($removeFolder) contains files. Manual attention needed."
}
}
}
# Removing Site log files
function Remove-Logfiles {
# Log cleanup
$filledLogsLimit = (Get-Date).AddDays(-$filledLogs)
$emptyLogsLimit = (Get-Date).AddDays(-$emptyLogs)
if (!(Test-Path -Path $logFolderBase)) {
Write-Output "$logFolderBase is missing. Skipping log cleanup."
}
else {
Write-Output "$logFolderBase found. Starting Filledlog($filledLogs days) cleanup."
$filledLogFiles = Get-ChildItem -Path $logFolderBase -Recurse -Force | Where-Object { !$_.PSIsContainer -and $_.FullName -match '.*-T.*' -and $_.FullName -ne $logFile -and $_.CreationTime -lt $filledLogsLimit }
if ($filledLogFiles -and ($filledLogFiles | Measure-Object).Count -gt 0) {
foreach ($f in $filledLogFiles ) {
$removeLog = $f.FullName
$removeLog | Remove-Item -Recurse -Force -Verbose
}
}
else {
Write-Output "No filled logs to remove in $logFolderBase"
}
Write-Output "$logFolderBase found. Starting emptylog($emptyLogs days) cleanup."
$emptyLogFiles = Get-ChildItem -Path $logFolderBase -Recurse -Force | Where-Object { !$_.PSIsContainer -and $_.FullName -notmatch '.*-T.*' -and $_.FullName -ne $logFile -and $_.CreationTime -lt $emptyLogsLimit }
if ($emptyLogFiles -and ($emptyLogFiles | Measure-Object).Count -gt 0) {
foreach ($e in $emptyLogFiles ) {
$removeLog = $e.FullName
$removeLog | Remove-Item -Recurse -Force -Verbose
}
}
else {
Write-Output "No empty logs to remove in $logFolderBase"
}
& $DeleteRecursion -deleteRecursionPath $logFolderBase
}
}
# Recursively deletes folders
$DeleteRecursion = {
param(
$deleteRecursionPath
)
foreach ($DeleteRecursionDirectory in Get-ChildItem -LiteralPath $deleteRecursionPath -Directory -Force) {
& $DeleteRecursion -deleteRecursionPath $DeleteRecursionDirectory.FullName
}
$drCurrentChildren = Get-ChildItem -LiteralPath $deleteRecursionPath -Force
$deleteRecursionEmpty = $drCurrentChildren -eq $null
if ($deleteRecursionEmpty) {
Write-Output "Force deleting '${deleteRecursionPath}' folders/files if empty."
Remove-Item -LiteralPath $deleteRecursionPath -Force -Verbose
}
}
# format folder/filename to get a clean name to use in filebot
function Format-Filename {
param(
[Parameter(Mandatory = $true)]
[string]$InputStr
)
# Part 1: Replace underscores with spaces
# Replace a single underscore between letters with a space
# Replace a single letter surrounded by underscores with a space
# Remove the space before a single letter not followed by another letter and not 'i' or 'I'
# Replace one or more consecutive underscores with a single space
$InputStr = $InputStr -replace '(?<=\p{L})_(?=\p{L})', ' ' -replace '(?<=_)\b\p{L}\b(?=_)', ' ' -replace '(?<!_) (?!(?i:i))\b(?!\p{L})', ' ' -replace '_+', ' '
$InputStr = $InputStr -replace '(?<=\p{L})-(?=\p{L})', ' ' -replace '(?<=-)\b\p{L}\b(?=-)', ' ' -replace '(?<!-) (?!(?i:i))\b(?!\p{L})', ' '
#$subpattern = '(?<=\.)[^.]+(?=\.)'
# $subtitleMatch = [regex]::Match($InputStr, $subpattern)
# $subtitleString = ($subtitleMatch.Value).ToLower() -replace ' ', '-'
# $InputStr = $InputStr -replace $subpattern, $subtitleString
# Part 2: Remove leading space from single character not 'i' or 'I'
# Replace ' space + single character (not 'i' or 'I' and not '-') + space ' with ' character + space '
$OutputStr = ($InputStr -replace '\s(?<=[\s])([^\diIaAoO\-\s]) ', '$1 ').Trim()
return $OutputStr
}
# sanitizng string from non-english characters with '?'
function Format-CleanString {
param (
[Parameter(Mandatory = $true, ValueFromPipeline = $true)]
[string]$InputString
)
$pattern = '[^\u0000-\u007F]'
$sanitizedString = $InputString -replace $pattern, '?'
return $sanitizedString
}
function Remove-Spaces {
param (
[Parameter(Mandatory = $true)]
[string] $removeSpacesFile
)
(Get-Content $removeSpacesFile) | Where-Object { -not [String]::IsNullOrWhiteSpace($_) } | Set-Content -Path $removeSpacesFile
$removeSpacesContent = [System.IO.File]::ReadAllText($removeSpacesFile)
$removeSpacesContent = $removeSpacesContent.Trim()
[System.IO.File]::WriteAllText($removeSpacesFile, $removeSpacesContent)
}
function Remove-ArchiveLine {
param (
$siteN,
$arc,
$eURL
)
$siteN = $siteN.ToLower()
switch ($siteN) {
'crunchyroll' { $updateA = $eURL -replace 'https://www.crunchyroll.com/watch/', "$($siteN)beta "; Write-Output "[UpdatingUrl] $(Get-DateTime) - Site Found: $updateA" }
'hidive' { $updateA = $eURL -replace 'https://www.hidive.com/stream/', "$($siteN) "; Write-Output "[UpdatingUrl] $(Get-DateTime) - Site Found: $updateA" }
Default { Write-Output "[UpdatingUrl] $(Get-DateTime) - No Site Found: $eURL" }
}
if ($updateA) {
$l = Get-Content $arc
$f = $l | Where-Object { $_ -ne $updateA }
$f | Set-Content -Path $arc
$c = (Get-Content $arc | Where-Object { $_ -eq $updateA } | Measure-Object -Line)
if ($c -eq 0) {
Write-Output "[UpdatingUrl] $(Get-DateTime) - OK - Not Found in $($arc): $updateA"
}
else {
Write-Output "[UpdatingUrl] $(Get-DateTime) - ERROR - Found in $($arc): $updateA"
}
}
}
# Setup exting script
function Exit-Script {
$scriptStopWatch.Stop()
# Cleanup folders
Invoke-ExpressionConsole -SCMFN 'Cleanup' -SCMFP "Remove-Folders -removeFolder `"$($siteTemp)`" -removeFolderBaseMatch `"$($siteTempBaseMatch)`""
Invoke-ExpressionConsole -SCMFN 'Cleanup' -SCMFP "Remove-Folders -removeFolder `"$($siteSrc)`" -removeFolderBaseMatch `"$($siteSrcBaseMatch)`""
Invoke-ExpressionConsole -SCMFN 'Cleanup' -SCMFP "Remove-Folders -removeFolder `"$($siteHome)`" -removeFolderBaseMatch `"$($siteHomeBaseMatch)`""
if ($overrideDriveList.count -gt 0) {
foreach ($orDriveList in $overrideDriveList) {
$orDriveListBaseMatch = ($orDriveList._vsDestPathBase).Replace('\', '\\')
Invoke-ExpressionConsole -SCMFN 'Cleanup' -SCMFP "Remove-Folders -removeFolder `"$($orDriveList._vsDestPath)`" -removeFolderBaseMatch `"$($orDriveListBaseMatch)`""
}
}
# Cleanup Log Files
Invoke-ExpressionConsole -SCMFN 'Cleanup' -SCMFP 'Remove-Logfiles'
$totalRuntime = $($scriptStopWatch.Elapsed.ToString('dd\:hh\:mm\:ss'))
Write-Output "[END] $(Get-DateTime) - Script completed. Total Elapsed Time: $totalRuntime"
Stop-Transcript
((Get-Content -Path $logFile | Select-Object -Skip 5) | Select-Object -SkipLast 4) | Set-Content -Path $logFile
Remove-Spaces -removeSpacesFile $logFile
$logTemp = Join-Path -Path $logFolderBaseDate -ChildPath "$dateTime-Temp.log"
New-Item -Path $logTemp -ItemType File | Out-Null
$asciiLogo | Out-File -FilePath $logTemp -Width 9999
if ($vsvTotCount -gt 0) {
$vsCompletedFilesTable | Out-File -FilePath $logTemp -Width 9999 -Append
}
if ($debugScript) {
Get-Content $logFile -ReadCount 5000 | ForEach-Object {
$_ | Add-Content -Path $logTemp
}
}
else {
Get-Content $logFile -ReadCount 5000 | ForEach-Object {
$_ | Select-String -Pattern '^\[.*\].*has already been recorded in the archive|^\[.*\].*skipping.*' -NotMatch | `
Select-String -Pattern '^\[download\]\s+(\d+\.\d+)?%.*' -NotMatch | `
Select-String -Pattern '^\[.*\].*Downloading.*\(.*\).*' -NotMatch | `
Select-String -Pattern '^\[debug\].*Loaded.*' -NotMatch | `
Select-String -Pattern '^\[debug\].*Skipping writing playlist thumbnail.*' -NotMatch | `
Select-String -Pattern '^\[download\].*Finished downloading playlist:.*' -NotMatch | `
Select-String -Pattern '^\[download\].*Downloading playlist.*' -NotMatch | `
Select-String -Pattern '^\[generic\].*Downloading webpage.*' -NotMatch | `
Select-String -Pattern '^\[generic\].*Extracting URL.*' -NotMatch | `
Select-String -Pattern '^\[redirect\].*redirect to.*' -NotMatch | `
Select-String -Pattern '^\[DL\:.*\].*' -NotMatch | `
Select-String -Pattern '^\[.*\] Sleeping.*seconds.*' -NotMatch | `
Select-String -Pattern '^\[.*\].*Retrieving signed policy.*' -NotMatch | `
Select-String -Pattern '^WARNING\: The download speed shown is only of one thread. This is a known issue.*' -NotMatch | `
Add-Content -Path $logTemp
}
$modifiedLines = @()
$lines = Get-Content $logTemp
for ($i = 0; $i -lt $lines.Length; $i++) {
if ($lines[$i] -match '^ERROR\: \[.*\].*FutureContent') {
$modifiedLines += $lines[$i] -replace '^Error\: '
$i += 2
}
else {
$modifiedLines += $lines[$i]
}
}
$modifiedLines | Out-File $logTemp -Force
}
Remove-Item -Path $logFile
if ($vsvTotCount -gt 0) {
$newLogFile = "$dateTime-T$vsvTotCount-E$vsvErrorCount.log"
Rename-Item -Path $logTemp -NewName $newLogFile
}
elseif ($testScript) {
$newLogFile = "$dateTime-DEBUG.log"
Rename-Item -Path $logTemp -NewName $newLogFile
}
else {
Rename-Item -Path $logTemp -NewName $logFile
}
exit
}
# Function to make API requests to Sonarr
function Invoke-SonarrApi {
param (
$url
)
$method = 'GET'
$headers = @{ 'X-Api-Key' = $sonarrToken }
$fullUrl = "$($sonarrHost)/api/v3/$($url)"
if ($body) {
$headers['Content-Type'] = 'application/json'
Invoke-RestMethod -Uri $fullUrl -Method $method -Headers $headers -Body $body
}
else {
Invoke-RestMethod -Uri $fullUrl -Method $method -Headers $headers
}
}
# Update $vsCompletedFilesList values with write out for logs
function Set-VideoStatus {
param (
[parameter(Mandatory = $true)]
[string]$searchKey,
[parameter(Mandatory = $true)]
[string]$searchValue,
[parameter(Mandatory = $true)]
[string]$nodeKey,
[parameter(Mandatory = $true)]
$nodeValue
)
$vsCompletedFilesList | Where-Object { $_.$SearchKey -eq $SearchValue } | ForEach-Object {
$_.$nodeKey = $nodeValue
Write-Output "[UpdateVSList] - $(Get-DateTime) - '$nodeKey' - $nodeValue for $searchValue"
}
}
# Looks at language code in filename to match a pair of vars
function Get-SubtitleLanguage {
param ($subFiles)
switch -Regex ($subFiles) {
'\.ar.*\.' { $stLang = 'ar'; $stTrackName = 'Arabic Sub'; $stLangFull = 'Arabic' }
'\.de.*\.' { $stLang = 'de'; $stTrackName = 'Deutsch Sub'; $stLangFull = 'Deutsch' }
'\.en.*\.|\.en-US\.' { $stLang = 'en'; $stTrackName = 'English Sub'; $stLangFull = 'English' }
'\.es-la\.' { $stLang = 'es'; $stTrackName = 'Spanish(Latin America) Sub'; $stLangFull = 'Spanish(Latin America)' }
'\.es-es\.|\.es.' { $stLang = 'es-es'; $stTrackName = 'Spanish(Spain) Sub'; $stLangFull = 'Spanish(Spain)' }
'\.fr.*\.' { $stLang = 'fr'; $stTrackName = 'French Sub'; $stLangFull = 'French' }
'\.it.*\.' { $stLang = 'it'; $stTrackName = 'Italian Sub'; $stLangFull = 'Italian' }
'\.ja.*\.' { $stLang = 'ja'; $stTrackName = 'Japanese Sub'; $stLangFull = 'Japanese' }
'\.pt-br\.' { $stLang = 'pt-br'; $stTrackName = 'Português(Brasil) Sub'; $stLangFull = 'Português(Brasil)' }
'\.pt-pt\.|\.pt\.' { $stLang = 'pt-pt'; $stTrackName = 'Português(Portugal) Sub'; $stLangFull = 'Português(Portugal)' }
'\.ru.*\.' { $stLang = 'ru'; $stTrackName = 'Russian Video'; $stLangFull = 'Russian' }
default { $stLang = 'und'; $stTrackName = 'und sub'; $stLangFull = 'Unknown' }
}
$return = @($stLang, $stTrackName, $stLangFull)
return $return
}
# Sending To Discord for new file notifications
function Invoke-Discord {
param (
$site,
$series,
$episode,
$siteIcon,
$color,
$subtitle,
$episodeSize,
$quality,
$videoCodec,
$audioCodec,
$duration,
$release,
$episodeURL,
$episodeDate,
$siteFooterIcon,
$siteFooterText,
$DiscordSiteUrl
)
$embedDebug = @()
$fieldObjects = @()
# Start of discord Message
$site = $(Format-CleanString -InputString $site)
$series = $(Format-CleanString -InputString $series)
$episode = $(Format-CleanString -InputString $episode)
$title = "**$site**"
$description = "**$series**`n> $episode"
$color = $color
$timestamp = Get-DateTime 3
$thumbnailObject = [PSCustomObject]@{
url = $siteIcon
}
# outputting empty footer for consistant message width
$footerObject = [PSCustomObject]@{
icon_url = $siteFooterIcon
text = "$siteFooterText"
}
# Field Objects
# Release Field
$fieldTitleRelease = 'Release'
$fieldValueRelease = "> $(Format-CleanString -InputString $release)"
$fieldInlineRelease = 'false'
$fObjRelease = [PSCustomObject]@{
name = $fieldTitleRelease
value = $fieldValueRelease
inline = $fieldInlineRelease
}
$fieldObjects += $fObjRelease
# Episode URL Field
$fieldTitleEpisodeURL = 'Episode URL'
$fieldValueEpisodeURL = "> $(Format-CleanString -InputString $episodeURL)"
$fieldInlineEpisodeURL = 'false'
$fObjEpisodeURL = [PSCustomObject]@{
name = $fieldTitleEpisodeURL
value = $fieldValueEpisodeURL
inline = $fieldInlineEpisodeURL
}
$fieldObjects += $fObjEpisodeURL
# Episode Release Field
$fieldTitleepisodeDate = 'Release Date'
$fieldValueepisodeDate = "> $(Format-CleanString -InputString $episodeDate)"
$fieldInlineepisodeDate = 'false'
$fObjepisodeDate = [PSCustomObject]@{
name = $fieldTitleepisodeDate
value = $fieldValueepisodeDate
inline = $fieldInlineepisodeDate
}
$fieldObjects += $fObjepisodeDate
# Duration Field
$fieldTitleDuration = 'Duration'
$fieldValueDuration = $duration
$fieldInlineDuration = 'true'
$fObjDuration = [PSCustomObject]@{
name = $fieldTitleDuration
value = $fieldValueDuration
inline = $fieldInlineDuration
}
$fieldObjects += $fObjDuration
# Quality Field
$fieldTitleQuality = 'Quality'
$fieldValueQuality = $quality
$fieldInlineQuality = 'true'
$fObjQuality = [PSCustomObject]@{
name = $fieldTitleQuality
value = $fieldValueQuality
inline = $fieldInlineQuality
}
$fieldObjects += $fObjQuality
# Size Field
$fieldTitleSize = 'Size'
$fieldValueSize = $episodeSize
$fieldInlineSize = 'true'
$fObjSize = [PSCustomObject]@{
name = $fieldTitleSize
value = $fieldValueSize
inline = $fieldInlineSize
}
$fieldObjects += $fObjSize
# Video Field
$fieldTitleVideoCodec = 'Video Codecs'
$fieldValueVideoCodec = "$videoCodec"
$fieldInlineVideoCodec = 'true'
$fObjVideoCodec = [PSCustomObject]@{
name = $fieldTitleVideoCodec
value = $fieldValueVideoCodec
inline = $fieldInlineVideoCodec
}
$fieldObjects += $fObjVideoCodec
# Audio Field
$fieldTitleAudioCodec = 'Audio Codecs'
$fieldValueAudioCodec = $audioCodec
$fieldInlineAudioCodec = 'true'
$fObjAudioCodec = [PSCustomObject]@{
name = $fieldTitleAudioCodec
value = $fieldValueAudioCodec
inline = $fieldInlineAudioCodec
}
$fieldObjects += $fObjAudioCodec
# Subtitle Field
$fieldValueSub = @()
$fieldTitleSub = 'Subtitle Language'
foreach ($sub in $subtitle) {
$sLang = Get-SubtitleLanguage $sub
$subResult = $($sLang[2])
$fieldValueSub += $subResult
}
$fieldValueSub = (($fieldValueSub -join ', ') -split ', ' | Select-Object -Unique | Sort-Object) -join ', '
$fieldInlineSub = 'true'
$fObjSub = [PSCustomObject]@{
name = $fieldTitleSub
value = $fieldValueSub
inline = $fieldInlineSub
}
$fieldObjects += $fObjSub
$embedDebug += "Color = $color", "Title = $site", "Series = $($series)", "Episode = $episode", "Thumbnail = $siteIcon", "Duration = $duration", "Qaulity = $quality", "Size = $fieldValueSize", `
"Video Codecs = $videoCodec", "Audio Codecs = $audioCodec", "Subtitles = $fieldValueSub", "Release = $($release)", "Timestamp = $($timestamp)"
# Embed object
[System.Collections.ArrayList]$embedArray = @()
$embedObject = [PSCustomObject]@{
color = $color
title = $title
description = $description
thumbnail = $thumbnailObject
fields = $fieldObjects
footer = $footerObject
timestamp = $timestamp
}
$payload = [PSCustomObject]@{
embeds = $embedArray
}
$embedArray.Add($embedObject) | Out-Null
$payloadJson = $payload | ConvertTo-Json -Depth 4
Invoke-ExpressionConsole -scmFunctionName 'Discord' -scmFunctionParams "write-output `"$($embedDebug -join "`n")`""
$p = Invoke-WebRequest -Uri $DiscordSiteUrl -Body $payloadJson -Method Post -ContentType 'application/json' | Select-Object -ExpandProperty Headers
$discordLimit = $p.'x-ratelimit-limit'
$discordRemainingLimit = $p.'x-ratelimit-remaining'
$discordResetAfter = [float]::Parse($p.'x-rateLimit-reset-after')
$discordResetMilliseconds = [int]($discordResetAfter * 1000)
Write-Output "[Discord] $(Get-DateTime) - Rate limit: $discordRemainingLimit/$discordLimit remaining. Resetting after $discordResetAfter seconds"
if ($discordRemainingLimit -le 2) {
Write-Output "[Discord] $(Get-DateTime) - Sleeping for $discordResetMilliseconds"
Start-Sleep -Milliseconds $discordResetMilliseconds
}
}
# Run MKVMerge process
function Invoke-MKVMerge {
param (
[parameter(Mandatory = $true)]
[string]$mkvVidInput,
[parameter(Mandatory = $true)]
[string]$mkvVidBaseName,
[parameter(Mandatory = $true)]
[array]$mkvVidSubtitle,
[parameter(Mandatory = $true)]
[string]$mkvVidTempOutput
)
Write-Output "[MKVMerge] $(Get-DateTime) - Starting MKVMerge with:"
Write-Output "[MKVMerge] $(Get-DateTime) - $mkvVidInput"
Write-Output "[MKVMerge] $(Get-DateTime) - $mkvVidSubtitle"
Write-Output "[MKVMerge] $(Get-DateTime) - Default Video = $videoLang/$videoTrackName - Default Audio Language = $audioLang/$audioTrackName - Default Subtitle = $subtitleLang/$subtitleTrackName."
While ($True) {
if ((Test-Lock $mkvVidInput) -eq $True) {
continue
}
else {
$sblist = ''
$mkvCMD = ''
$mkvVidSubtitle | ForEach-Object {
$sp = $_ | Where-Object { $_.key -eq 'origSubPath' } | Select-Object -ExpandProperty value
$StLang = Get-SubtitleLanguage -subFiles $sp
# foreach sub/sublang add to mkv command to run in mkvmerge
# if sublang defined then that will set track to default.
if ($stLang[0] -match $subtitleLang) {
$subLangCode = $stLang[0]
$subTrackName = $stLang[1]
$mkvCMD += "--language 0:`"$subLangCode`" --track-name 0:`"$subTrackName`" ( `"$sp`" ) "
}
else {
$subLangCode = $stLang[0]
$subTrackName = $stLang[1]
$mkvCMD += "--language 0:`"$subLangCode`" --track-name 0:`"$subTrackName`" --default-track-flag 0:no ( `"$sp`" ) "
}
}
$mkvCMD = $mkvCMD.TrimEnd()
if ($subFontDir -ne 'None') {
Write-Output "[MKVMerge] $(Get-DateTime) - MKV subtitle params: `"$mkvCMD`""
Write-Output "[MKVMerge] $(Get-DateTime) - Combining $sblist and $mkvVidInput files with $subFontDir."
Invoke-ExpressionConsole -SCMFN 'MKVMerge' -SCMFP "mkvmerge.exe -o `"$mkvVidTempOutput`" --language 0:`"$videoLang`" --track-name 0:`"$videoTrackName`" --language 1:`"$audioLang`" --track-name 1:`"$audioTrackName`" ( `"$mkvVidInput`" ) $mkvCMD --attach-file `"$subFontDir`" --attachment-mime-type application/x-truetype-font"
break
}
else {
Write-Output "[MKVMerge] $(Get-DateTime) - Merging as-is. No Font specified for $sblist and $mkvVidInput files with $subFontDir."
Invoke-ExpressionConsole -SCMFN 'MKVMerge' -SCMFP "mkvmerge.exe -o `"$mkvVidTempOutput`" --language 0:`"$videoLang`" --track-name 0:`"$videoTrackName`" --language 1:`"$audioLang`" --track-name 1:`"$audioTrackName`" ( `"$mkvVidInput`" ) $mkvCMD"
}
}
Start-Sleep -Seconds 1
}
While (!(Test-Path -Path $mkvVidTempOutput -ErrorAction SilentlyContinue)) {
Start-Sleep 1.5
}
While ($True) {
if (((Test-Lock $mkvVidInput) -eq $True) -and ((Test-Lock $mkvVidTempOutput) -eq $True)) {
continue
}
else {
Write-Output "[MKVMerge] $(Get-DateTime) - Removing $mkvVidInput file."
Invoke-ExpressionConsole -SCMFN 'MKVMerge' -SCMFP "Remove-Item -Path `"$mkvVidInput`" -Verbose"
$mkvVidSubtitle | ForEach-Object {
$sp = $_ | Where-Object { $_.key -eq 'origSubPath' } | Select-Object -ExpandProperty value
While ($True) {
if ((Test-Lock $sp) -eq $True) {
continue
}
else {
Write-Output "[MKVMerge] $(Get-DateTime) - Removing $sp file."
Invoke-ExpressionConsole -SCMFN 'MKVMerge' -SCMFP "Remove-Item -Path `"$sp`" -Verbose"
break
}
Start-Sleep -Seconds 1
}
}
break
}
Start-Sleep -Seconds 1
}
While ($True) {
if ((Test-Lock $mkvVidTempOutput) -eq $True) {
continue
}
else {
Write-Output "[MKVMerge] $(Get-DateTime) - Renaming $mkvVidTempOutput to $mkvVidInput."
Invoke-ExpressionConsole -SCMFN 'MKVMerge' -SCMFP "Rename-Item -Path `"$mkvVidTempOutput`" -NewName `"$mkvVidInput`" -Verbose"
break
}
Start-Sleep -Seconds 1
}
While ($True) {
if ((Test-Lock $mkvVidInput) -eq $True) {
continue
}
else {
Invoke-ExpressionConsole -SCMFN 'MKVMerge' -SCMFP "mkvpropedit `"$mkvVidInput`" --edit track:s1 --set flag-default=1"
break
}
Start-Sleep -Seconds 1
}
Set-VideoStatus -searchKey '_vsEpisodeRaw' -searchValue $mkvVidBaseName -nodeKey '_vsMKVCompleted' -nodeValue $($true)
$videoOverrideDriveList = $vsCompletedFilesList | Where-Object { $_._vsEpisodePath -eq $mkvVidInput } | Select-Object _vsEpisodePath, _vsDestPathDirectory -Unique
Write-Output "[FileMoving] $(Get-DateTime) - Moving $($videoOverrideDriveList._vsEpisodePath) to $($videoOverrideDriveList._vsDestPathDirectory)."
if (!(Test-Path -Path $videoOverrideDriveList._vsDestPathDirectory)) {
Invoke-ExpressionConsole -SCMFN 'FileMoving' -SCMFP "New-Folder -newFolderFullPath `"$($videoOverrideDriveList._vsDestPathDirectory)`" -Verbose"
}
Write-Output "[FileMoving] $(Get-DateTime) - Moving $($videoOverrideDriveList._vsEpisodePath) to $($videoOverrideDriveList._vsDestPathDirectory)."
Invoke-ExpressionConsole -SCMFN 'FileMoving' -SCMFP "Move-Item -Path `"$($videoOverrideDriveList._vsEpisodePath)`" -Destination `"$($videoOverrideDriveList._vsDestPathDirectory)`" -Force -Verbose"
if (!(Test-Path -Path $videoOverrideDriveList._vsEpisodePath)) {
Write-Output "[FileMoving] $(Get-DateTime) - Move completed for $($videoOverrideDriveList._vsEpisodePath)."
Set-VideoStatus -searchKey '_vsEpisodePath' -searchValue $videoOverrideDriveList._vsEpisodePath -nodeKey '_vsMoveCompleted' -nodeValue $($true)
}
}
# Function to process video files through FileBot
function Invoke-Filebot {
param (
[parameter(Mandatory = $true)]
[string]$filebotPath,
[string]$filebotContentType
)
Write-Output "[Filebot] $(Get-DateTime) - Looking for files to rename and move to final folder."
$filebotVideoList = $vsCompletedFilesList | Where-Object { $_._vsDestPath -eq $filebotPath } | Select-Object _vsDestPath, _vsDestPathVideo, _vsEpisodeRaw, _vsEpisodeSubtitle, _vsOverridePath
$filebotEndParams = '--conflict skip -non-strict --apply date tags clean --log info'
if ($daily) {
$filebotEndParams = '--filter "age < 5" ' + $filebotEndParams
}
foreach ($filebotFiles in $filebotVideoList) {
$filebotVidInput = $filebotFiles._vsDestPathVideo
$filebotSubInput = $filebotFiles._vsEpisodeSubtitle
$filebotVidBaseName = $filebotFiles._vsEpisodeRaw
$filebotOverrideDrive = $filebotFiles._vsOverridePath
if ($siteParentFolder.trim() -ne '' -or $siteSubFolder.trim() -ne '') {
$FilebotRootFolder = $filebotOverrideDrive + $siteParentFolder
$filebotBaseFolder = Join-Path -Path $FilebotRootFolder -ChildPath $siteSubFolder
$filebotParams = Join-Path -Path $filebotBaseFolder -ChildPath $filebotStructure
$filebotSubParams = $filebotParams + "{'.'+lang.ISO2}"
Write-Output "[Filebot] $(Get-DateTime) - Files found($filebotVidInput). Renaming video and moving files to final folder. Using path($filebotStructure)."
Invoke-ExpressionConsole -SCMFN 'Filebot' -SCMFP "filebot -rename -r `"$filebotVidInput`" --db `"$filebotDB`" --format `"$filebotParams`" $filebotEndParams"
if (!($mkvMerge)) {
$filebotSubInput | ForEach-Object {
$filebotSubParams = $filebotStructure
$osp = $_ | Where-Object { $_.key -eq 'overrideSubPath' } | Select-Object -ExpandProperty value
$StLang = Get-SubtitleLanguage -subFiles $osp
$filebotSubParams = $filebotSubParams + "{'.$($StLang[0])'}"
Write-Output "[Filebot] $(Get-DateTime) - Files found($osp). Renaming subtitle and moving files to final folder. Using path($filebotSubParams)."
Invoke-ExpressionConsole -SCMFN 'Filebot' -SCMFP "filebot -rename -r `"$osp`" --db `"$filebotDB`" --format `"$filebotSubParams`" $filebotEndParams"
}
}
}
else {
Write-Output "[Filebot] $(Get-DateTime) - Files found($filebotVidInput). ParentFolder or Subfolder path not specified. Renaming files in place using path($filebotStructure)."
$filebotSubInput | ForEach-Object {
Write-Output "[Filebot] $(Get-DateTime) - Files found($filebotVidInput). ParentFolder or Subfolder path not specified. Renaming files in place."
Invoke-ExpressionConsole -SCMFN 'Filebot' -SCMFP "filebot -rename -r `"$filebotVidInput`" --db `"$filebotDB`" --format `"$filebotParams`" $filebotEndParams"
}
if (!($mkvMerge)) {
$filebotSubInput | ForEach-Object {
$filebotSubParams = $filebotStructure
$osp = $_ | Where-Object { $_.key -eq 'overrideSubPath' } | Select-Object -ExpandProperty value
$StLang = Get-SubtitleLanguage -subFiles $osp
$filebotSubParams = $filebotSubParams + "{'.$($StLang[0])'}"
$filebotSubParams
Write-Output "[Filebot] $(Get-DateTime) - Files found($osp). Renaming subtitle($($StLang[0])) and renaming files in place using path($filebotSubParams)."
Invoke-ExpressionConsole -SCMFN 'Filebot' -SCMFP "filebot -rename -r `"$osp`" --db `"$filebotDB`" --format `"$filebotSubParams`" $filebotEndParams"
}
}
}
if (!(Test-Path -Path $filebotVidInput)) {
Write-Output "[Filebot] $(Get-DateTime) - Setting file($filebotVidInput) as completed."
Set-VideoStatus -searchKey '_vsEpisodeRaw' -searchValue $filebotVidBaseName -nodeKey '_vsFBCompleted' -nodeValue $($true)
}
else {
Write-Output "[Filebot] $(Get-DateTime) - Failed to match. Setting file($filebotVidInput) as errored."
Set-VideoStatus -searchKey '_vsEpisodeRaw' -searchValue $filebotVidBaseName -nodeKey '_vsErrored' -nodeValue $($true)
}
}
$vsvFBCount = ($vsCompletedFilesList | Where-Object { $_._vsFBCompleted -eq $true } | Measure-Object).Count
if ($vsvFBCount -eq $vsvTotCount ) {
Write-Output "[Filebot]$(Get-DateTime) - Filebot($vsvFBCount) = ($vsvTotCount)Total Videos. No other files need to be processed. Attempting Filebot cleanup."
Invoke-ExpressionConsole -SCMFN 'Filebot' -SCMFP "filebot -script fn:cleaner `"$siteHome`" --log info"
}
else {
Write-Output "[Filebot] $(Get-DateTime) - Filebot($vsvFBCount) and Total Video($vsvTotCount) count mismatch. Manual check required."
}
if ($vsvFBCount -ne $vsvTotCount) {
Write-Output "[Filebot] $(Get-DateTime) - [Cleanup] - File needs processing."
}
}
# Update Subtitle files with font name
function Update-SubtitleStyle {
param (
$SubtitleFilePath,
$subFontName
)
# Top
$subtitleContentTags = Get-Content -Path $SubtitleFilePath -Raw
$substring = $subtitleContentTags.Substring(0, $subtitleContentTags.IndexOf('[V4+ Styles]'))
$result = @()
$string = $substring -split "`r`n"
$stl = Get-SubtitleLanguage $SubtitleFilePath
foreach ($i in $string) {
switch -Regex ( $i) {
'(?<=^Title:).*' { $i = "Title: $($stl[2])" ; $result += $i }
'(?<=^Original Translation:).*' { $i = 'Original Translation:' ; $result += $i }
'(?<=^Original Editing:).*' { $i = 'Original Editing:' ; $result += $i }
'(?<=^Original Timing:).*' { $i = 'Original Timing:' ; $result += $i }
'(?<=^Script Updated By:).*' { $i = 'Script Updated By:' ; $result += $i }
'(?<=^Update Details:).*' { $i = 'Update Details:' ; $result += $i }
'(?<=^Original Script:).*' { $i = 'Original Script:'; $result += $i }
'(?<=^ScaledBorderAndShadow:).*' { $i = 'ScaledBorderAndShadow: yes' ; $result += $i }
'(?<=^WrapStyle:).*' { $i = 'WrapStyle: 0'; $result += $i }