From fb8216be90fd5ccb3d8b97fc97b3e97af64d31fe Mon Sep 17 00:00:00 2001 From: Rouzax Date: Thu, 25 May 2023 14:38:12 +0200 Subject: [PATCH] Change code Layout --- TorrentScript.ps1 | 134 +++++++++---------------- functions/CleanProcessPath.ps1 | 35 +++---- functions/Format-Size.ps1 | 26 ++--- functions/Get-Input.ps1 | 16 ++- functions/Import-Medusa.ps1 | 61 +++++------ functions/Import-Radarr.ps1 | 56 ++++------- functions/New-Mutex.ps1 | 20 ++-- functions/Remove-Mutex.ps1 | 11 +- functions/Send-Mail.ps1 | 22 ++-- functions/Start-MKV-Subtitle-Strip.ps1 | 102 +++++++------------ functions/Start-RoboCopy.ps1 | 75 +++++--------- functions/Start-SubEdit.ps1 | 26 ++--- functions/Start-Subliminal.ps1 | 45 +++------ functions/Start-UnRar.ps1 | 26 ++--- functions/Stop-Script.ps1 | 19 ++-- functions/Test-Variable-Path.ps1 | 11 +- functions/Write-HTMLLog.ps1 | 48 ++++----- 17 files changed, 271 insertions(+), 462 deletions(-) diff --git a/TorrentScript.ps1 b/TorrentScript.ps1 index 100365f..d86889d 100644 --- a/TorrentScript.ps1 +++ b/TorrentScript.ps1 @@ -1,33 +1,32 @@ +[CmdletBinding()] param( [Parameter( mandatory = $false )] - [string] $DownloadPath, + [string]$DownloadPath, [Parameter( mandatory = $false )] - [string] $DownloadLabel, + [string]$DownloadLabel, [Parameter( mandatory = $false )] - [string] $TorrentHash, + [string]$TorrentHash, [Parameter( Mandatory = $false )] - [switch] $NoCleanUp + [switch]$NoCleanUp ) # User Variables -try -{ +try { $configPath = Join-Path $PSScriptRoot 'config.json' $Config = Get-Content $configPath -ErrorAction Stop | ConvertFrom-Json -ErrorAction Stop } -catch -{ +catch { Write-Host 'Exception:' $_.Exception.Message -ForegroundColor Red Write-Host 'Invalid config.json file' -ForegroundColor Red exit 1 @@ -91,15 +90,12 @@ $SubtitleNamesToRemove = $Config.SubtitleNamesToRemove # Get function definition files. $Functions = @( Get-ChildItem -Path $PSScriptRoot\functions\*.ps1 -ErrorAction SilentlyContinue ) # Dot source the files -ForEach ($import in @($Functions)) -{ - Try - { +ForEach ($import in @($Functions)) { + Try { # Lightweight alternative to dotsourcing a function script . ([ScriptBlock]::Create([System.Io.File]::ReadAllText($import))) } - Catch - { + Catch { Write-Error -Message "Failed to import function $($import.fullname): $_" } } @@ -115,8 +111,7 @@ Test-Variable-Path -Path $MailSendPath -Name 'MailSendPath' # Get input if no parameters defined # Build the download Location, this is the Download Root Path added with the Download name -if ( ($Null -eq $DownloadPath) -or ($DownloadPath -eq '') ) -{ +if ( ($Null -eq $DownloadPath) -or ($DownloadPath -eq '') ) { $DownloadPath = Get-Input -Message 'Download Name' -Required $DownloadPath = Join-Path -Path $DownloadRootPath -ChildPath $DownloadPath } @@ -125,13 +120,11 @@ if ( ($Null -eq $DownloadPath) -or ($DownloadPath -eq '') ) $DownloadName = Split-Path -Path $DownloadPath -Leaf # Download Label -if ( ($Null -eq $DownloadLabel) -or ($DownloadLabel -eq '') ) -{ +if ( ($Null -eq $DownloadLabel) -or ($DownloadLabel -eq '') ) { $DownloadLabel = Get-Input -Message 'Download Label' } # Torrent Hash (only needed for Radarr) -if ( ($Null -eq $TorrentHash) -or ($TorrentHash -eq '') ) -{ +if ( ($Null -eq $TorrentHash) -or ($TorrentHash -eq '') ) { $TorrentHash = Get-Input -Message 'Torrent Hash' } @@ -139,15 +132,13 @@ if ( ($Null -eq $TorrentHash) -or ($TorrentHash -eq '') ) $TorrentHash = $TorrentHash.ToUpper() # Handle NoProcess Torrent Label -if ($DownloadLabel -eq 'NoProcess') -{ +if ($DownloadLabel -eq 'NoProcess') { Write-Host 'Do nothing' Exit } # Handle empty Torrent Label -if ($DownloadLabel -eq '') -{ +if ($DownloadLabel -eq '') { $DownloadLabel = 'NoLabel' } @@ -164,12 +155,10 @@ Write-HTMLLog -Column1 'Name:' -Column2 $DownloadName Write-HTMLLog -Column1 'Hash:' -Column2 $TorrentHash # Test File Paths -If (!(Test-Path -LiteralPath $ProcessPath)) -{ +If (!(Test-Path -LiteralPath $ProcessPath)) { New-Item -ItemType Directory -Force -Path $ProcessPath | Out-Null } -If (!(Test-Path -LiteralPath $LogArchivePath)) -{ +If (!(Test-Path -LiteralPath $LogArchivePath)) { New-Item -ItemType Directory -Force -Path $LogArchivePath | Out-Null } @@ -180,8 +169,7 @@ $ScriptMutex = New-Mutex -MutexName 'DownloadScript' $StopWatch = [system.diagnostics.stopwatch]::startNew() # Check paths from Parameters -If (!(Test-Path -LiteralPath $DownloadPath)) -{ +If (!(Test-Path -LiteralPath $DownloadPath)) { Write-Host "$DownloadPath - Not valid location" Write-HTMLLog -Column1 'Path:' -Column2 "$DownloadPath - Not valid location" -ColorBg 'Error' Write-HTMLLog -Column1 'Result:' -Column2 'Failed' -ColorBg 'Error' @@ -193,46 +181,38 @@ $SingleFile = (Get-Item -LiteralPath $DownloadPath) -is [System.IO.FileInfo] $Folder = (Get-Item -LiteralPath $DownloadPath) -is [System.IO.DirectoryInfo] # Set Source and Destination paths and get Rar paths -if ($Folder) -{ +if ($Folder) { $ProcessPathFull = Join-Path -Path $ProcessPath -ChildPath $DownloadLabel | Join-Path -ChildPath $DownloadName $RarFilePaths = (Get-ChildItem -LiteralPath $DownloadPath -Recurse -Filter '*.rar').FullName } -elseif ($SingleFile) -{ +elseif ($SingleFile) { $ProcessPathFull = Join-Path -Path $ProcessPath -ChildPath $DownloadLabel | Join-Path -ChildPath $DownloadName.Substring(0, $DownloadName.LastIndexOf('.')) $DownloadRootPath = Split-Path -Path $DownloadPath - if ([IO.Path]::GetExtension($DownloadPath) -eq '.rar') - { + if ([IO.Path]::GetExtension($DownloadPath) -eq '.rar') { $RarFilePaths = (Get-Item -LiteralPath $DownloadPath).FullName } } # Find rar files $RarCount = $RarFilePaths.Count -if ($RarCount -gt 0) -{ +if ($RarCount -gt 0) { $RarFile = $true } -else -{ +else { $RarFile = $false } # Check is destination folder exists otherwise create it -If (!(Test-Path -LiteralPath $ProcessPathFull)) -{ +If (!(Test-Path -LiteralPath $ProcessPathFull)) { New-Item -ItemType Directory -Force -Path $ProcessPathFull | Out-Null } -if ($RarFile) -{ +if ($RarFile) { Write-HTMLLog -Column1 '*** Unrar Download ***' -Header Write-HTMLLog -Column1 'Starting:' -Column2 'Unpacking files' - $TotalSize = (Get-ChildItem -LiteralPath $DownloadPath -Recurse | Measure-Object -Property Length -sum).Sum + $TotalSize = (Get-ChildItem -LiteralPath $DownloadPath -Recurse | Measure-Object -Property Length -Sum).Sum $UnRarStopWatch = [system.diagnostics.stopwatch]::startNew() - foreach ($Rar in $RarFilePaths) - { + foreach ($Rar in $RarFilePaths) { Start-UnRar -UnRarSourcePath $Rar -UnRarTargetPath $ProcessPathFull } # Stop the Stopwatch @@ -240,33 +220,27 @@ if ($RarFile) Write-HTMLLog -Column1 'Size:' -Column2 (Format-Size -SizeInBytes $TotalSize) Write-HTMLLog -Column1 'Throughput:' -Column2 "$(Format-Size -SizeInBytes ($TotalSize/$UnRarStopWatch.Elapsed.TotalSeconds))/s" } -elseif (-not $RarFile -and $SingleFile) -{ +elseif (-not $RarFile -and $SingleFile) { Write-HTMLLog -Column1 '*** Single File ***' -Header Start-RoboCopy -Source $DownloadRootPath -Destination $ProcessPathFull -File $DownloadName } -elseif (-not $RarFile -and $Folder) -{ +elseif (-not $RarFile -and $Folder) { Write-HTMLLog -Column1 '*** Folder ***' -Header Start-RoboCopy -Source $DownloadPath -Destination $ProcessPathFull -File '*.*' } # Starting Post Processing for Movies and TV Shows -if ($DownloadLabel -eq $TVLabel) -{ +if ($DownloadLabel -eq $TVLabel) { $MKVFiles = Get-ChildItem -LiteralPath $ProcessPathFull -Recurse -Filter '*.mkv' $MKVCount = $MKVFiles.Count - if ($MKVCount -gt 0) - { + if ($MKVCount -gt 0) { $MKVFile = $true } - else - { + else { $MKVFile = $false } - if ($MKVFile) - { + if ($MKVFile) { # Download any missing subs Start-Subliminal -Source $ProcessPathFull @@ -277,26 +251,21 @@ if ($DownloadLabel -eq $TVLabel) Start-SubEdit -File '*.srt' -Source $ProcessPathFull Write-HTMLLog -Column1 '*** MKV Files ***' -Header - foreach ($Mkv in $MKVFiles) - { + foreach ($Mkv in $MKVFiles) { Write-HTMLLog -Column1 ' ' -Column2 $Mkv.name } $SrtFiles = Get-ChildItem -LiteralPath $ProcessPathFull -Recurse -Filter '*.srt' - if ($SrtFiles.Count -gt 0) - { + if ($SrtFiles.Count -gt 0) { Write-HTMLLog -Column1 '*** Subtitle Files ***' -Header - foreach ($Srt in $SrtFiles) - { + foreach ($Srt in $SrtFiles) { Write-HTMLLog -Column1 ' ' -Column2 $srt.name } } } - else - { + else { Write-HTMLLog -Column1 '*** Files ***' -Header $Files = Get-ChildItem -LiteralPath $ProcessPathFull -Recurse -Filter '*.*' - foreach ($File in $Files) - { + foreach ($File in $Files) { Write-HTMLLog -Column1 'File:' -Column2 $File.name } } @@ -306,20 +275,16 @@ if ($DownloadLabel -eq $TVLabel) CleanProcessPath -Path $ProcessPathFull -NoCleanUp $NoCleanUp Stop-Script -ExitReason "$DownloadLabel - $DownloadName" } -elseif ($DownloadLabel -eq $MovieLabel) -{ +elseif ($DownloadLabel -eq $MovieLabel) { $MKVFiles = Get-ChildItem -LiteralPath $ProcessPathFull -Recurse -Filter '*.mkv' $MKVCount = $MKVFiles.Count - if ($MKVCount -gt 0) - { + if ($MKVCount -gt 0) { $MKVFile = $true } - else - { + else { $MKVFile = $false } - if ($MKVFile) - { + if ($MKVFile) { # Download any missing subs Start-Subliminal -Source $ProcessPathFull @@ -330,23 +295,19 @@ elseif ($DownloadLabel -eq $MovieLabel) Start-SubEdit -File '*.srt' -Source $ProcessPathFull Write-HTMLLog -Column1 '*** MKV Files ***' -Header - foreach ($Mkv in $MKVFiles) - { + foreach ($Mkv in $MKVFiles) { Write-HTMLLog -Column1 ' ' -Column2 $Mkv.name } Write-HTMLLog -Column1 '*** Subtitle Files ***' -Header $SrtFiles = Get-ChildItem -LiteralPath $ProcessPathFull -Recurse -Filter '*.srt' - foreach ($Srt in $SrtFiles) - { + foreach ($Srt in $SrtFiles) { Write-HTMLLog -Column1 ' ' -Column2 $srt.name } } - else - { + else { Write-HTMLLog -Column1 '*** Files ***' -Header $Files = Get-ChildItem -LiteralPath $ProcessPathFull -Recurse -Filter '*.*' - foreach ($File in $Files) - { + foreach ($File in $Files) { Write-HTMLLog -Column1 'File:' -Column2 $File.name } } @@ -360,8 +321,7 @@ elseif ($DownloadLabel -eq $MovieLabel) # Reached the end of script Write-HTMLLog -Column1 '*** Post Process General Download ***' -Header $Files = Get-ChildItem -LiteralPath $ProcessPathFull -Recurse -Filter '*.*' -foreach ($File in $Files) -{ +foreach ($File in $Files) { Write-HTMLLog -Column1 'File:' -Column2 $File.name } Stop-Script -ExitReason "$DownloadLabel - $DownloadName" \ No newline at end of file diff --git a/functions/CleanProcessPath.ps1 b/functions/CleanProcessPath.ps1 index dff4c6d..ea38673 100644 --- a/functions/CleanProcessPath.ps1 +++ b/functions/CleanProcessPath.ps1 @@ -1,30 +1,26 @@ -function CleanProcessPath -{ +function CleanProcessPath { + [CmdletBinding()] param ( [Parameter( Mandatory = $true )] - [string] $Path, + [string]$Path, [Parameter( Mandatory = $false )] - [bool] $NoCleanUp + [bool]$NoCleanUp ) # Make sure needed functions are available otherwise try to load them. $commands = 'Write-HTMLLog' - foreach ($commandName in $commands) - { - if (!($command = Get-Command $commandName -ErrorAction SilentlyContinue)) - { - Try - { + foreach ($commandName in $commands) { + if (!($command = Get-Command $commandName -ErrorAction SilentlyContinue)) { + Try { . $PSScriptRoot\$commandName.ps1 Write-Host "$commandName Function loaded." -ForegroundColor Green } - Catch - { + Catch { Write-Error -Message "Failed to import $commandName function: $_" exit 1 } @@ -32,21 +28,16 @@ function CleanProcessPath } # Start - if ($NoCleanUp) - { + if ($NoCleanUp) { Write-HTMLLog -Column1 'Cleanup' -Column2 'NoCleanUp switch was given at command line, leaving files' } - else - { - try - { - If (Test-Path -LiteralPath $ProcessPathFull) - { + else { + try { + If (Test-Path -LiteralPath $ProcessPathFull) { Remove-Item -Force -Recurse -LiteralPath $ProcessPathFull } } - catch - { + catch { Write-HTMLLog -Column1 'Exception:' -Column2 $_.Exception.Message -ColorBg 'Error' Write-HTMLLog -Column1 'Result:' -Column2 'Failed' -ColorBg 'Error' } diff --git a/functions/Format-Size.ps1 b/functions/Format-Size.ps1 index d07eb29..bcae90e 100644 --- a/functions/Format-Size.ps1 +++ b/functions/Format-Size.ps1 @@ -1,5 +1,4 @@ -function Format-Size() -{ +function Format-Size() { <# .SYNOPSIS Takes bytes and converts it to KB.MB,GB,TB,PB @@ -26,32 +25,25 @@ function Format-Size() Mandatory = $true, ValueFromPipeline = $true )] - [double] $SizeInBytes + [double]$SizeInBytes ) - switch ([math]::Max($SizeInBytes, 0)) - { - { $_ -ge 1PB } - { + switch ([math]::Max($SizeInBytes, 0)) { + { $_ -ge 1PB } { '{0:N2} PB' -f ($SizeInBytes / 1PB); break } - { $_ -ge 1TB } - { + { $_ -ge 1TB } { '{0:N2} TB' -f ($SizeInBytes / 1TB); break } - { $_ -ge 1GB } - { + { $_ -ge 1GB } { '{0:N2} GB' -f ($SizeInBytes / 1GB); break } - { $_ -ge 1MB } - { + { $_ -ge 1MB } { '{0:N2} MB' -f ($SizeInBytes / 1MB); break } - { $_ -ge 1KB } - { + { $_ -ge 1KB } { '{0:N2} KB' -f ($SizeInBytes / 1KB); break } - default - { + default { "$SizeInBytes Bytes" } } diff --git a/functions/Get-Input.ps1 b/functions/Get-Input.ps1 index 663f4dd..4feefa0 100644 --- a/functions/Get-Input.ps1 +++ b/functions/Get-Input.ps1 @@ -1,5 +1,4 @@ -Function Get-Input -{ +Function Get-Input { <# .SYNOPSIS Get input from user @@ -25,24 +24,21 @@ Function Get-Input [Parameter( Mandatory = $true )] - [string] $Message, + [string]$Message, [Parameter( Mandatory = $false )] - [switch] $Required + [switch]$Required ) - if ($Required) - { - While ( ($Null -eq $Variable) -or ($Variable -eq '') ) - { + if ($Required) { + While ( ($Null -eq $Variable) -or ($Variable -eq '') ) { $Variable = Read-Host -Prompt "$Message" $Variable = $Variable.Trim() } } - else - { + else { $Variable = Read-Host -Prompt "$Message" $Variable = $Variable.Trim() } diff --git a/functions/Import-Medusa.ps1 b/functions/Import-Medusa.ps1 index da4a93b..a5a3f43 100644 --- a/functions/Import-Medusa.ps1 +++ b/functions/Import-Medusa.ps1 @@ -1,6 +1,5 @@ -function Import-Medusa -{ +function Import-Medusa { <# .SYNOPSIS Start import in Medusa @@ -17,24 +16,23 @@ function Import-Medusa .NOTES General notes #> + [CmdletBinding()] param ( - [Parameter(Mandatory = $true)] - $Source + [Parameter( + Mandatory = $true + )] + [string]$Source ) # Make sure needed functions are available otherwise try to load them. $commands = 'Write-HTMLLog', 'Stop-Script' - foreach ($commandName in $commands) - { - if (!($command = Get-Command $commandName -ErrorAction SilentlyContinue)) - { - Try - { + foreach ($commandName in $commands) { + if (!($command = Get-Command $commandName -ErrorAction SilentlyContinue)) { + Try { . $PSScriptRoot\$commandName.ps1 Write-Host "$commandName Function loaded." -ForegroundColor Green } - Catch - { + Catch { Write-Error -Message "Failed to import $commandName function: $_" exit 1 } @@ -58,28 +56,22 @@ function Import-Medusa 'X-Api-Key' = $MedusaApiKey } Write-HTMLLog -Column1 '*** Medusa Import ***' -Header - try - { + try { $response = Invoke-RestMethod -Uri "http://$MedusaHost`:$MedusaPort/api/v2/postprocess" -Method Post -Body $Body -Headers $headers } - catch - { + catch { Write-HTMLLog -Column1 'Exception:' -Column2 $_.Exception.Message -ColorBg 'Error' Write-HTMLLog -Column1 'Result:' -Column2 'Failed' -ColorBg 'Error' Stop-Script -ExitReason "Medusa Error: $DownloadLabel - $DownloadName" } - if ($response.status -eq 'success') - { + if ($response.status -eq 'success') { $timeout = New-TimeSpan -Minutes $MedusaTimeOutMinutes $endTime = (Get-Date).Add($timeout) - do - { - try - { + do { + try { $status = Invoke-RestMethod -Uri "http://$MedusaHost`:$MedusaPort/api/v2/postprocess/$($response.queueItem.identifier)" -Method Get -Headers $headers } - catch - { + catch { Write-HTMLLog -Column1 'Exception:' -Column2 $_.Exception.Message -ColorBg 'Error' Write-HTMLLog -Column1 'Result:' -Column2 'Failed' -ColorBg 'Error' Stop-Script -ExitReason "Medusa Error: $DownloadLabel - $DownloadName" @@ -87,39 +79,32 @@ function Import-Medusa Start-Sleep 1 } until ($status.success -or ((Get-Date) -gt $endTime)) - if ($status.success) - { + if ($status.success) { $ValuesToFind = 'Processing failed', 'aborting post-processing', 'Unable to figure out what folder to process' $MatchPattern = ($ValuesToFind | ForEach-Object { [regex]::Escape($_) }) -join '|' - if ($status.output -match $MatchPattern) - { + if ($status.output -match $MatchPattern) { $ValuesToFind = 'Retrieving episode object for', 'Current quality', 'New quality', 'Old size', 'New size', 'Processing failed', 'aborting post-processing', 'Unable to figure out what folder to process' $MatchPattern = ($ValuesToFind | ForEach-Object { [regex]::Escape($_) }) -join '|' - foreach ($line in $status.output ) - { - if ($line -match $MatchPattern) - { + foreach ($line in $status.output ) { + if ($line -match $MatchPattern) { Write-HTMLLog -Column1 'Medusa:' -Column2 $line -ColorBg 'Error' } } Write-HTMLLog -Column1 'Result:' -Column2 'Failed' -ColorBg 'Error' Stop-Script -ExitReason "Medusa Error: $DownloadLabel - $DownloadName" } - else - { + else { Write-HTMLLog -Column1 'Result:' -Column2 'Successful' -ColorBg 'Success' } } - else - { + else { Write-HTMLLog -Column1 'Medusa:' -Column2 $status.success -ColorBg 'Error' Write-HTMLLog -Column1 'Medusa:' -Column2 "Import Timeout: ($MedusaTimeOutMinutes) minutes" -ColorBg 'Error' Write-HTMLLog -Column1 'Result:' -Column2 'Failed' -ColorBg 'Error' Stop-Script -ExitReason "Medusa Error: $DownloadLabel - $DownloadName" } } - else - { + else { Write-HTMLLog -Column1 'Medusa:' -Column2 $response.status -ColorBg 'Error' Write-HTMLLog -Column1 'Result:' -Column2 'Failed' -ColorBg 'Error' Stop-Script -ExitReason "Medusa Error: $DownloadLabel - $DownloadName" diff --git a/functions/Import-Radarr.ps1 b/functions/Import-Radarr.ps1 index abf9adc..7f36f1a 100644 --- a/functions/Import-Radarr.ps1 +++ b/functions/Import-Radarr.ps1 @@ -1,5 +1,4 @@ -function Import-Radarr -{ +function Import-Radarr { <# .SYNOPSIS Start Radarr movie import @@ -16,26 +15,23 @@ function Import-Radarr .NOTES General notes #> + [CmdletBinding()] param ( [Parameter( Mandatory = $true )] - [string] $Source + [string]$Source ) # Make sure needed functions are available otherwise try to load them. $commands = 'Write-HTMLLog', 'Stop-Script' - foreach ($commandName in $commands) - { - if (!($command = Get-Command $commandName -ErrorAction SilentlyContinue)) - { - Try - { + foreach ($commandName in $commands) { + if (!($command = Get-Command $commandName -ErrorAction SilentlyContinue)) { + Try { . $PSScriptRoot\$commandName.ps1 Write-Host "$commandName Function loaded." -ForegroundColor Green } - Catch - { + Catch { Write-Error -Message "Failed to import $commandName function: $_" exit 1 } @@ -51,32 +47,26 @@ function Import-Radarr } | ConvertTo-Json $headers = @{ - 'X-Api-Key' = $RadarrApiKey + 'X-Api-Key' = $RadarrApiKey 'Content-Type' = 'application/json' } Write-HTMLLog -Column1 '*** Radarr Import ***' -Header - try - { + try { $response = Invoke-RestMethod -Uri "http://$RadarrHost`:$RadarrPort/api/v3/command" -Method Post -Body $Body -Headers $headers } - catch - { + catch { Write-HTMLLog -Column1 'Exception:' -Column2 $_.Exception.Message -ColorBg 'Error' Write-HTMLLog -Column1 'Result:' -Column2 'Failed' -ColorBg 'Error' Stop-Script -ExitReason "Radarr Error: $DownloadLabel - $DownloadName" } - if ($response.status -eq 'queued' -or $response.status -eq 'started' -or $response.status -eq 'completed') - { + if ($response.status -eq 'queued' -or $response.status -eq 'started' -or $response.status -eq 'completed') { $timeout = New-TimeSpan -Minutes $RadarrTimeOutMinutes $endTime = (Get-Date).Add($timeout) - do - { - try - { + do { + try { $status = Invoke-RestMethod -Uri "http://$RadarrHost`:$RadarrPort/api/v3/command/$($response.id)" -Method Get -Headers $headers } - catch - { + catch { Write-HTMLLog -Column1 'Exception:' -Column2 $_.Exception.Message -ColorBg 'Error' Write-HTMLLog -Column1 'Result:' -Column2 'Failed' -ColorBg 'Error' Stop-Script -ExitReason "Radarr Error: $DownloadLabel - $DownloadName" @@ -84,37 +74,31 @@ function Import-Radarr Start-Sleep 1 } until ($status.status -ne 'started' -or ((Get-Date) -gt $endTime) ) - if ($status.status -eq 'completed') - { - if ($status.duration -gt '00:00:05.0000000') - { + if ($status.status -eq 'completed') { + if ($status.duration -gt '00:00:05.0000000') { Write-HTMLLog -Column1 'Result:' -Column2 'Successful' -ColorBg 'Success' } - else - { + else { Write-HTMLLog -Column1 'Radarr:' -Column2 'API command completed but likely failed import' -ColorBg 'Error' Write-HTMLLog -Column1 'Radarr:' -Column2 'Radarr has no failed handling in API see: https://github.com/Radarr/Radarr/issues/5539' -ColorBg 'Error' Write-HTMLLog -Column1 'Result:' -Column2 'Failed' -ColorBg 'Error' Stop-Script -ExitReason "Radarr Error: $DownloadLabel - $DownloadName" } } - if ($status.status -eq 'failed') - { + if ($status.status -eq 'failed') { Write-HTMLLog -Column1 'Radarr:' -Column2 $status.status -ColorBg 'Error' Write-HTMLLog -Column1 'Radarr:' -Column2 $status.exception -ColorBg 'Error' Write-HTMLLog -Column1 'Result:' -Column2 'Failed' -ColorBg 'Error' Stop-Script -ExitReason "Radarr Error: $DownloadLabel - $DownloadName" } - if ((Get-Date) -gt $endTime) - { + if ((Get-Date) -gt $endTime) { Write-HTMLLog -Column1 'Radarr:' -Column2 $status.status -ColorBg 'Error' Write-HTMLLog -Column1 'Radarr:' -Column2 "Import Timeout: ($RadarrTimeOutMinutes) minutes" -ColorBg 'Error' Write-HTMLLog -Column1 'Result:' -Column2 'Failed' -ColorBg 'Error' Stop-Script -ExitReason "Radarr Error: $DownloadLabel - $DownloadName" } } - else - { + else { Write-HTMLLog -Column1 'Radarr:' -Column2 $response.status -ColorBg 'Error' Write-HTMLLog -Column1 'Result:' -Column2 'Failed' -ColorBg 'Error' Stop-Script -ExitReason "Radarr Error: $DownloadLabel - $DownloadName" diff --git a/functions/New-Mutex.ps1 b/functions/New-Mutex.ps1 index 1a67920..8f94862 100644 --- a/functions/New-Mutex.ps1 +++ b/functions/New-Mutex.ps1 @@ -1,5 +1,4 @@ -function New-Mutex -{ +function New-Mutex { <# .SYNOPSIS Create a Mutex @@ -36,30 +35,25 @@ function New-Mutex Mandatory = $true )] [ValidateNotNullOrEmpty()] - [string] $MutexName + [string]$MutexName ) $MutexWasCreated = $false $Mutex = $Null Write-Host "Waiting to acquire lock [$MutexName]..." -ForegroundColor DarkGray [void][System.Reflection.Assembly]::LoadWithPartialName('System.Threading') - try - { + try { $Mutex = [System.Threading.Mutex]::OpenExisting($MutexName) } - catch - { + catch { $Mutex = New-Object System.Threading.Mutex($true, $MutexName, [ref]$MutexWasCreated) } - try - { - if (!$MutexWasCreated) - { + try { + if (!$MutexWasCreated) { $Mutex.WaitOne() | Out-Null } } - catch - { + catch { } Write-Host "Lock [$MutexName] acquired. Executing..." -ForegroundColor DarkGray Write-Output ([PSCustomObject]@{ Name = $MutexName; Mutex = $Mutex }) diff --git a/functions/Remove-Mutex.ps1 b/functions/Remove-Mutex.ps1 index bfc6ce9..91dd60a 100644 --- a/functions/Remove-Mutex.ps1 +++ b/functions/Remove-Mutex.ps1 @@ -1,5 +1,4 @@ -function Remove-Mutex -{ +function Remove-Mutex { <# .SYNOPSIS Removes a previously created Mutex @@ -20,16 +19,14 @@ function Remove-Mutex Mandatory = $true )] [ValidateNotNull()] - [PSObject] $MutexObject + [PSObject]$MutexObject ) # $MutexObject | fl * | Out-String | Write-Host Write-Host "Releasing lock [$($MutexObject.Name)]..." -ForegroundColor DarkGray - try - { + try { [void]$MutexObject.Mutex.ReleaseMutex() } - catch - { + catch { } } # Remove-Mutex \ No newline at end of file diff --git a/functions/Send-Mail.ps1 b/functions/Send-Mail.ps1 index 8bb7cd8..4f369de 100644 --- a/functions/Send-Mail.ps1 +++ b/functions/Send-Mail.ps1 @@ -1,5 +1,4 @@ -function Send-Mail -{ +function Send-Mail { <# .SYNOPSIS Send mail @@ -40,51 +39,52 @@ function Send-Mail .NOTES General notes #> + [CmdletBinding()] param ( [Parameter( Mandatory = $true )] - [string] $SMTPserver, + [string]$SMTPserver, [Parameter( Mandatory = $true )] - [string] $SMTPport, + [string]$SMTPport, [Parameter( Mandatory = $true )] - [string] $MailTo, + [string]$MailTo, [Parameter( Mandatory = $true )] - [string] $MailFrom, + [string]$MailFrom, [Parameter( Mandatory = $true )] - [string] $MailFromName, + [string]$MailFromName, [Parameter( Mandatory = $true )] - [string] $MailSubject, + [string]$MailSubject, [Parameter( Mandatory = $true )] - [string] $MailBody, + [string]$MailBody, [Parameter( Mandatory = $true )] - [string] $SMTPuser, + [string]$SMTPuser, [Parameter( Mandatory = $true )] - [string] $SMTPpass + [string]$SMTPpass ) $StartInfo = New-Object System.Diagnostics.ProcessStartInfo diff --git a/functions/Start-MKV-Subtitle-Strip.ps1 b/functions/Start-MKV-Subtitle-Strip.ps1 index 9e7fa5a..3029818 100644 --- a/functions/Start-MKV-Subtitle-Strip.ps1 +++ b/functions/Start-MKV-Subtitle-Strip.ps1 @@ -1,5 +1,4 @@ -function Start-MKV-Subtitle-Strip -{ +function Start-MKV-Subtitle-Strip { <# .SYNOPSIS Extract wanted SRT subtitles from MKVs in root folder and remux MKVs to strip out unwanted subtitle languages @@ -20,26 +19,23 @@ function Start-MKV-Subtitle-Strip MKV files without the unwanted subtitles file.mkv #> + [CmdletBinding()] param( [Parameter( Mandatory = $true )] - [string] $Source + [string]$Source ) # Make sure needed functions are available otherwise try to load them. $commands = 'Write-HTMLLog' - foreach ($commandName in $commands) - { - if (!($command = Get-Command $commandName -ErrorAction SilentlyContinue)) - { - Try - { + foreach ($commandName in $commands) { + if (!($command = Get-Command $commandName -ErrorAction SilentlyContinue)) { + Try { . $PSScriptRoot\$commandName.ps1 Write-Host "$commandName Function loaded." -ForegroundColor Green } - Catch - { + Catch { Write-Error -Message "Failed to import $commandName function: $_" exit 1 } @@ -74,24 +70,20 @@ function Start-MKV-Subtitle-Strip # Write-Host "stdout: $stdout" # Write-Host "stderr: $stderr" $Process.WaitForExit() - if ($Process.ExitCode -eq 2) - { + if ($Process.ExitCode -eq 2) { Write-HTMLLog -Column1 'Exit Code:' -Column2 $($Process.ExitCode) -ColorBg 'Error' Write-HTMLLog -Column1 'mkvmerge:' -Column2 $stdout -ColorBg 'Error' Write-HTMLLog -Column1 'Result:' -Column2 'Failed' -ColorBg 'Error' } - elseif ($Process.ExitCode -eq 1) - { + elseif ($Process.ExitCode -eq 1) { Write-HTMLLog -Column1 'Exit Code:' -Column2 $($Process.ExitCode) -ColorBg 'Error' Write-HTMLLog -Column1 'mkvmerge:' -Column2 $stdout -ColorBg 'Error' Write-HTMLLog -Column1 'Result:' -Column2 'Warning' -ColorBg 'Error' } - elseif ($Process.ExitCode -eq 0) - { + elseif ($Process.ExitCode -eq 0) { $fileMetadata = $stdout | ConvertFrom-Json } - else - { + else { Write-HTMLLog -Column1 'Exit Code:' -Column2 $($Process.ExitCode) -ColorBg 'Error' Write-HTMLLog -Column1 'mkvmerge:' -Column2 $stdout -ColorBg 'Error' Write-HTMLLog -Column1 'Result:' -Column2 'Warning' -ColorBg 'Error' @@ -119,28 +111,22 @@ function Start-MKV-Subtitle-Strip $episode.FileTracks | ForEach-Object { $FileTrack = $_ - if ($FileTrack.id) - { + if ($FileTrack.id) { # Check if subtitle is srt - if ($FileTrack.type -eq 'subtitles' -and $FileTrack.codec -eq 'SubRip/SRT') - { + if ($FileTrack.type -eq 'subtitles' -and $FileTrack.codec -eq 'SubRip/SRT') { # Check to see if track_name is part of $SubtitleNamesToRemove list - if ($null -ne ($SubtitleNamesToRemove | Where-Object { $FileTrack.properties.track_name -match $_ })) - { + if ($null -ne ($SubtitleNamesToRemove | Where-Object { $FileTrack.properties.track_name -match $_ })) { $SubIDsToRemove += $FileTrack.id } # Check is subtitle is in $WantedLanguages list - elseif ($FileTrack.properties.language -in $WantedLanguages) - { + elseif ($FileTrack.properties.language -in $WantedLanguages) { # Handle multiple subtitles of same language, if exist append ID to file - if ("$($episode.FileName).$($FileTrack.properties.language).srt" -in $SubNamesToKeep) - { + if ("$($episode.FileName).$($FileTrack.properties.language).srt" -in $SubNamesToKeep) { $prefix = "$($FileTrack.id).$($FileTrack.properties.language)" } - else - { + else { $prefix = "$($FileTrack.properties.language)" } @@ -153,8 +139,7 @@ function Start-MKV-Subtitle-Strip # Add subtitle ID to for MKV remux $SubIDsToExtract += $FileTrack.id } - else - { + else { $SubIDsToRemove += $FileTrack.id } } @@ -166,8 +151,7 @@ function Start-MKV-Subtitle-Strip $TotalSubsToRemove = $TotalSubsToRemove + $SubIDsToRemove.count # Extract the wanted subtitle languages - if ($SubIDsToExtract.count -gt 0) - { + if ($SubIDsToExtract.count -gt 0) { $StartInfo = New-Object System.Diagnostics.ProcessStartInfo $StartInfo.FileName = $MKVExtractPath $StartInfo.RedirectStandardError = $true @@ -182,25 +166,21 @@ function Start-MKV-Subtitle-Strip # Write-Host "stdout: $stdout" # Write-Host "stderr: $stderr" $Process.WaitForExit() - if ($Process.ExitCode -eq 2) - { + if ($Process.ExitCode -eq 2) { Write-HTMLLog -Column1 'Exit Code:' -Column2 $($Process.ExitCode) -ColorBg 'Error' Write-HTMLLog -Column1 'mkvextract:' -Column2 $stdout -ColorBg 'Error' Write-HTMLLog -Column1 'Result:' -Column2 'Failed' -ColorBg 'Error' } - elseif ($Process.ExitCode -eq 1) - { + elseif ($Process.ExitCode -eq 1) { Write-HTMLLog -Column1 'Exit Code:' -Column2 $($Process.ExitCode) -ColorBg 'Error' Write-HTMLLog -Column1 'mkvextract:' -Column2 $stdout -ColorBg 'Error' Write-HTMLLog -Column1 'Result:' -Column2 'Warning' -ColorBg 'Error' } - elseif ($Process.ExitCode -eq 0) - { + elseif ($Process.ExitCode -eq 0) { $SubsExtracted = $true # Write-HTMLLog -Column1 "Extracted:" -Column2 "$($SubsToExtract.count) Subtitles" } - else - { + else { Write-HTMLLog -Column1 'Exit Code:' -Column2 $($Process.ExitCode) -ColorBg 'Error' Write-HTMLLog -Column1 'mkvextract:' -Column2 $stdout -ColorBg 'Error' Write-HTMLLog -Column1 'Result:' -Column2 'Unknown' -ColorBg 'Error' @@ -208,8 +188,7 @@ function Start-MKV-Subtitle-Strip } # Remux and strip out all unwanted subtitle languages - if ($SubIDsToRemove.Count -gt 0) - { + if ($SubIDsToRemove.Count -gt 0) { $TmpFileName = $Episode.FileName + '.tmp' $TmpMkvPath = Join-Path $episode.FileRoot $TmpFileName $StartInfo = New-Object System.Diagnostics.ProcessStartInfo @@ -226,26 +205,22 @@ function Start-MKV-Subtitle-Strip # Write-Host "stdout: $stdout" # Write-Host "stderr: $stderr" $Process.WaitForExit() - if ($Process.ExitCode -eq 2) - { + if ($Process.ExitCode -eq 2) { Write-HTMLLog -Column1 'Exit Code:' -Column2 $($Process.ExitCode) -ColorBg 'Error' Write-HTMLLog -Column1 'mkvmerge:' -Column2 $stdout -ColorBg 'Error' Write-HTMLLog -Column1 'Result:' -Column2 'Failed' -ColorBg 'Error' } - elseif ($Process.ExitCode -eq 1) - { + elseif ($Process.ExitCode -eq 1) { Write-HTMLLog -Column1 'Exit Code:' -Column2 $($Process.ExitCode) -ColorBg 'Error' Write-HTMLLog -Column1 'mkvmerge:' -Column2 $stdout -ColorBg 'Error' Write-HTMLLog -Column1 'Result:' -Column2 'Warning' -ColorBg 'Error' } - elseif ($Process.ExitCode -eq 0) - { + elseif ($Process.ExitCode -eq 0) { # Overwrite original mkv after successful remux Move-Item -Path $TmpMkvPath -Destination $($episode.FilePath) -Force # Write-HTMLLog -Column1 "Removed:" -Column2 "$($SubIDsToRemove.Count) unwanted subtitle languages" } - else - { + else { Write-HTMLLog -Column1 'Exit Code:' -Column2 $($Process.ExitCode) -ColorBg 'Error' Write-HTMLLog -Column1 'mkvmerge:' -Column2 $stdout -ColorBg 'Error' Write-HTMLLog -Column1 'Result:' -Column2 'Warning' -ColorBg 'Error' @@ -254,38 +229,31 @@ function Start-MKV-Subtitle-Strip } # Rename extracted subs to correct 2 county code based on $LanguageCodes - if ($SubsExtracted) - { + if ($SubsExtracted) { $SrtFiles = Get-ChildItem -LiteralPath $Source -Recurse -Filter '*.srt' - foreach ($srt in $SrtFiles) - { + foreach ($srt in $SrtFiles) { $FileDirectory = $srt.Directory $FilePath = $srt.FullName $FileName = $srt.Name - foreach ($LanguageCode in $Config.LanguageCodes) - { + foreach ($LanguageCode in $Config.LanguageCodes) { $FileNameNew = $FileName.Replace(".$($LanguageCode.alpha3).", ".$($LanguageCode.alpha2).") $ReplacementWasMade = $FileName -cne $FileNameNew - if ($ReplacementWasMade) - { + if ($ReplacementWasMade) { $Destination = Join-Path -Path $FileDirectory -ChildPath $FileNameNew Move-Item -Path $FilePath -Destination $Destination -Force break } } } - if ($TotalSubsToExtract -gt 0) - { + if ($TotalSubsToExtract -gt 0) { Write-HTMLLog -Column1 'Subtitles:' -Column2 "$TotalSubsToExtract Extracted" } - if ($TotalSubsToRemove -gt 0) - { + if ($TotalSubsToRemove -gt 0) { Write-HTMLLog -Column1 'Subtitles:' -Column2 "$TotalSubsToRemove Removed" } Write-HTMLLog -Column1 'Result:' -Column2 'Successful' -ColorBg 'Success' } - else - { + else { Write-HTMLLog -Column1 'Result:' -Column2 'No SRT subs found in MKV' } } \ No newline at end of file diff --git a/functions/Start-RoboCopy.ps1 b/functions/Start-RoboCopy.ps1 index 522ef9a..9217c96 100644 --- a/functions/Start-RoboCopy.ps1 +++ b/functions/Start-RoboCopy.ps1 @@ -1,5 +1,4 @@ -function Start-RoboCopy -{ +function Start-RoboCopy { <# .SYNOPSIS RoboCopy wrapper @@ -17,36 +16,33 @@ function Start-RoboCopy Start-RoboCopy -Source 'C:\Temp\Source' -Destination 'C:\Temp\Destination' -File '*.*' Start-RoboCopy -Source 'C:\Temp\Source' -Destination 'C:\Temp\Destination' -File 'file.ext' #> + [CmdletBinding()] param( [Parameter( Mandatory = $true )] - [string] $Source, + [string]$Source, [Parameter( Mandatory = $true )] - [string] $Destination, + [string]$Destination, [Parameter( Mandatory = $true )] - [string] $File + [string]$File ) # Make sure needed functions are available otherwise try to load them. $commands = 'Write-HTMLLog', 'Stop-Script', 'Format-Size' - foreach ($commandName in $commands) - { - if (!($command = Get-Command $commandName -ErrorAction SilentlyContinue)) - { - Try - { + foreach ($commandName in $commands) { + if (!($command = Get-Command $commandName -ErrorAction SilentlyContinue)) { + Try { . $PSScriptRoot\$commandName.ps1 Write-Host "$commandName Function loaded." -ForegroundColor Green } - Catch - { + Catch { Write-Error -Message "Failed to import $commandName function: $_" exit 1 } @@ -54,12 +50,10 @@ function Start-RoboCopy } # Start - if ($File -ne '*.*') - { + if ($File -ne '*.*') { $options = @('/R:1', '/W:1', '/J', '/NP', '/NP', '/NJH', '/NFL', '/NDL', '/MT8') } - elseif ($File -eq '*.*') - { + elseif ($File -eq '*.*') { $options = @('/R:1', '/W:1', '/E', '/J', '/NP', '/NJH', '/NFL', '/NDL', '/MT8') } @@ -67,26 +61,21 @@ function Start-RoboCopy # executing unrar command Write-HTMLLog -Column1 'Starting:' -Column2 'Copy files' - try - { + try { # executing Robocopy command $Output = robocopy @cmdArgs } - catch - { + catch { Write-Host 'Exception:' $_.Exception.Message -ForegroundColor Red Write-Host 'RoboCopy not found' -ForegroundColor Red exit 1 } - foreach ($line in $Output) - { - switch -Regex ($line) - { + foreach ($line in $Output) { + switch -Regex ($line) { # Dir metrics - '^\s+Dirs\s:\s*' - { + '^\s+Dirs\s:\s*' { # Example: Dirs : 35 0 0 0 0 0 $dirs = $_.Replace('Dirs :', '').Trim() # Now remove the white space between the values.' @@ -98,8 +87,7 @@ function Start-RoboCopy $FailedDirs = $dirs[4] } # File metrics - '^\s+Files\s:\s[^*]' - { + '^\s+Files\s:\s[^*]' { # Example: Files : 8318 0 8318 0 0 0 $files = $_.Replace('Files :', '').Trim() # Now remove the white space between the values.' @@ -111,8 +99,7 @@ function Start-RoboCopy $FailedFiles = $files[4] } # Byte metrics - '^\s+Bytes\s:\s*' - { + '^\s+Bytes\s:\s*' { # Example: Bytes : 1.607 g 0 1.607 g 0 0 0 $bytes = $_.Replace('Bytes :', '').Trim() # Now remove the white space between the values.' @@ -123,25 +110,20 @@ function Start-RoboCopy $counter = 0 $tempByteArray = 0, 0, 0, 0, 0, 0 $tempByteArrayCounter = 0 - foreach ($column in $bytes) - { - if ($column -eq 'k') - { - $tempByteArray[$tempByteArrayCounter - 1] = '{0:N2}' -f ([single]($bytes[$counter - 1])* 1024) + foreach ($column in $bytes) { + if ($column -eq 'k') { + $tempByteArray[$tempByteArrayCounter - 1] = '{0:N2}' -f ([single]($bytes[$counter - 1]) * 1024) $counter += 1 } - elseif ($column -eq 'm') - { + elseif ($column -eq 'm') { $tempByteArray[$tempByteArrayCounter - 1] = '{0:N2}' -f ([single]($bytes[$counter - 1]) * 1048576) $counter += 1 } - elseif ($column -eq 'g') - { + elseif ($column -eq 'g') { $tempByteArray[$tempByteArrayCounter - 1] = '{0:N2}' -f ([single]($bytes[$counter - 1]) * 1073741824) $counter += 1 } - else - { + else { $tempByteArray[$tempByteArrayCounter] = $column $counter += 1 $tempByteArrayCounter += 1 @@ -154,8 +136,7 @@ function Start-RoboCopy # array columns 2,3, and 5 are available, but not being used currently. } # Speed metrics - '^\s+Speed\s:.*sec.$' - { + '^\s+Speed\s:.*sec.$' { # Example: Speed : 120.816 Bytes/min. $speed = $_.Replace('Speed :', '').Trim() $speed = $speed.Replace('Bytes/sec.', '').Trim() @@ -166,8 +147,7 @@ function Start-RoboCopy } - if ($FailedDirs -gt 0 -or $FailedFiles -gt 0) - { + if ($FailedDirs -gt 0 -or $FailedFiles -gt 0) { Write-HTMLLog -Column1 'Dirs' -Column2 "$TotalDirs Total" -ColorBg 'Error' Write-HTMLLog -Column1 'Dirs' -Column2 "$FailedDirs Failed" -ColorBg 'Error' Write-HTMLLog -Column1 'Files:' -Column2 "$TotalFiles Total" -ColorBg 'Error' @@ -177,8 +157,7 @@ function Start-RoboCopy Write-HTMLLog -Column1 'Result:' -Column2 'Failed' -ColorBg 'Error' Stop-Script -ExitReason "Copy Error: $DownloadLabel - $DownloadName" } - else - { + else { Write-HTMLLog -Column1 'Dirs:' -Column2 "$CopiedDirs Copied" Write-HTMLLog -Column1 'Files:' -Column2 "$CopiedFiles Copied" Write-HTMLLog -Column1 'Size:' -Column2 "$CopiedSize" diff --git a/functions/Start-SubEdit.ps1 b/functions/Start-SubEdit.ps1 index 5a6de09..137341a 100644 --- a/functions/Start-SubEdit.ps1 +++ b/functions/Start-SubEdit.ps1 @@ -1,5 +1,4 @@ -function Start-SubEdit -{ +function Start-SubEdit { <# .SYNOPSIS Start Subtitle Edit @@ -19,31 +18,28 @@ function Start-SubEdit .NOTES General notes #> + [CmdletBinding()] param ( [Parameter( Mandatory = $true )] - [string] $Source, + [string]$Source, [Parameter( Mandatory = $true )] - [string] $Files + [string]$Files ) # Make sure needed functions are available otherwise try to load them. $commands = 'Write-HTMLLog' - foreach ($commandName in $commands) - { - if (!($command = Get-Command $commandName -ErrorAction SilentlyContinue)) - { - Try - { + foreach ($commandName in $commands) { + if (!($command = Get-Command $commandName -ErrorAction SilentlyContinue)) { + Try { . $PSScriptRoot\$commandName.ps1 Write-Host "$commandName Function loaded." -ForegroundColor Green } - Catch - { + Catch { Write-Error -Message "Failed to import $commandName function: $_" exit 1 } @@ -64,15 +60,13 @@ function Start-SubEdit $stdout = $Process.StandardOutput.ReadToEnd() $stderr = $Process.StandardError.ReadToEnd() $Process.WaitForExit() - if ($Process.ExitCode -gt 1) - { + if ($Process.ExitCode -gt 1) { Write-HTMLLog -Column1 'Exit Code:' -Column2 $($Process.ExitCode) -ColorBg 'Error' Write-HTMLLog -Column1 'Error:' -Column2 $stderr -ColorBg 'Error' Write-HTMLLog -Column1 'Result:' -Column2 'Failed' -ColorBg 'Error' Stop-Script -ExitReason "SubEdit Error: $DownloadLabel - $DownloadName" } - else - { + else { Write-HTMLLog -Column1 'Result:' -Column2 'Successful' -ColorBg 'Success' } } \ No newline at end of file diff --git a/functions/Start-Subliminal.ps1 b/functions/Start-Subliminal.ps1 index 69edf07..26aa8a6 100644 --- a/functions/Start-Subliminal.ps1 +++ b/functions/Start-Subliminal.ps1 @@ -1,5 +1,4 @@ -function Start-Subliminal -{ +function Start-Subliminal { <# .SYNOPSIS Start Subliminal to download subs @@ -16,26 +15,23 @@ function Start-Subliminal .NOTES General notes #> + [CmdletBinding()] param ( [Parameter( Mandatory = $true )] - [string] $Source + [string]$Source ) # Make sure needed functions are available otherwise try to load them. $commands = 'Write-HTMLLog' - foreach ($commandName in $commands) - { - if (!($command = Get-Command $commandName -ErrorAction SilentlyContinue)) - { - Try - { + foreach ($commandName in $commands) { + if (!($command = Get-Command $commandName -ErrorAction SilentlyContinue)) { + Try { . $PSScriptRoot\$commandName.ps1 Write-Host "$commandName Function loaded." -ForegroundColor Green } - Catch - { + Catch { Write-Error -Message "Failed to import $commandName function: $_" exit 1 } @@ -58,36 +54,28 @@ function Start-Subliminal $Process.WaitForExit() # Write-Host $stdout # Write-Host $stderr - if ($stdout -match '(\d+)(?=\s*video collected)') - { + if ($stdout -match '(\d+)(?=\s*video collected)') { $VideoCollected = $Matches.0 } - if ($stdout -match '(\d+)(?=\s*video ignored)') - { + if ($stdout -match '(\d+)(?=\s*video ignored)') { $VideoIgnored = $Matches.0 } - if ($stdout -match '(\d+)(?=\s*error)') - { + if ($stdout -match '(\d+)(?=\s*error)') { $VideoError = $Matches.0 } - if ($stdout -match '(\d+)(?=\s*subtitle)') - { + if ($stdout -match '(\d+)(?=\s*subtitle)') { $SubsDownloaded = $Matches.0 } - if ($stdout -match 'Some providers have been discarded due to unexpected errors') - { + if ($stdout -match 'Some providers have been discarded due to unexpected errors') { $SubliminalExitCode = 1 } - if ($SubliminalExitCode -gt 0) - { + if ($SubliminalExitCode -gt 0) { Write-HTMLLog -Column1 'Exit Code:' -Column2 $($Process.ExitCode) -ColorBg 'Error' Write-HTMLLog -Column1 'Error:' -Column2 $stderr -ColorBg 'Error' Write-HTMLLog -Column1 'Result:' -Column2 'Failed' -ColorBg 'Error' } - else - { - if ($SubsDownloaded -gt 0) - { + else { + if ($SubsDownloaded -gt 0) { # Write-HTMLLog -Column1 "Downloaded:" -Column2 "$SubsDownloaded Subtitles" Write-HTMLLog -Column1 'Collected:' -Column2 "$VideoCollected Videos" Write-HTMLLog -Column1 'Ignored:' -Column2 "$VideoIgnored Videos" @@ -95,8 +83,7 @@ function Start-Subliminal Write-HTMLLog -Column1 'Downloaded:' -Column2 "$SubsDownloaded Subtitles" Write-HTMLLog -Column1 'Result:' -Column2 'Successful' -ColorBg 'Success' } - else - { + else { Write-HTMLLog -Column1 'Result:' -Column2 'No subs downloaded with Subliminal' } } diff --git a/functions/Start-UnRar.ps1 b/functions/Start-UnRar.ps1 index abf39b7..2956f76 100644 --- a/functions/Start-UnRar.ps1 +++ b/functions/Start-UnRar.ps1 @@ -1,5 +1,4 @@ -function Start-UnRar -{ +function Start-UnRar { <# .SYNOPSIS Unrar file @@ -12,31 +11,28 @@ function Start-UnRar .EXAMPLE Start-UnRar -UnRarSourcePath 'C:\Temp\Source\file.rar' -UnRarTargetPath 'C:\Temp\Destination' #> + [CmdletBinding()] Param( [Parameter( Mandatory = $true )] - [string] $UnRarSourcePath, + [string]$UnRarSourcePath, [Parameter( Mandatory = $true )] - [string] $UnRarTargetPath + [string]$UnRarTargetPath ) # Make sure needed functions are available otherwise try to load them. $commands = 'Write-HTMLLog', 'Stop-Script' - foreach ($commandName in $commands) - { - if (!($command = Get-Command $commandName -ErrorAction SilentlyContinue)) - { - Try - { + foreach ($commandName in $commands) { + if (!($command = Get-Command $commandName -ErrorAction SilentlyContinue)) { + Try { . $PSScriptRoot\$commandName.ps1 Write-Host "$commandName Function loaded." -ForegroundColor Green } - Catch - { + Catch { Write-Error -Message "Failed to import $commandName function: $_" exit 1 } @@ -61,15 +57,13 @@ function Start-UnRar # Write-Host "stdout: $stdout" # Write-Host "stderr: $stderr" $Process.WaitForExit() - if ($Process.ExitCode -gt 0) - { + if ($Process.ExitCode -gt 0) { Write-HTMLLog -Column1 'Exit Code:' -Column2 $($Process.ExitCode) -ColorBg 'Error' Write-HTMLLog -Column1 'Error:' -Column2 $stderr -ColorBg 'Error' Write-HTMLLog -Column1 'Result:' -Column2 'Failed' -ColorBg 'Error' Stop-Script -ExitReason "Unrar Error: $DownloadLabel - $DownloadName" } - else - { + else { Write-HTMLLog -Column1 'Result:' -Column2 'Successful' -ColorBg 'Success' } } \ No newline at end of file diff --git a/functions/Stop-Script.ps1 b/functions/Stop-Script.ps1 index 0824376..f1afbc0 100644 --- a/functions/Stop-Script.ps1 +++ b/functions/Stop-Script.ps1 @@ -1,5 +1,4 @@ -function Stop-Script -{ +function Stop-Script { <# .SYNOPSIS Stops the script and removes Mutex @@ -16,27 +15,23 @@ function Stop-Script .NOTES General notes #> - + [CmdletBinding()] Param( [Parameter( Mandatory = $true )] - [string] $ExitReason + [string]$ExitReason ) # Make sure needed functions are available otherwise try to load them. $commands = 'Write-HTMLLog', 'Send-Mail', 'Remove-Mutex' - foreach ($commandName in $commands) - { - if (!($command = Get-Command $commandName -ErrorAction SilentlyContinue)) - { - Try - { + foreach ($commandName in $commands) { + if (!($command = Get-Command $commandName -ErrorAction SilentlyContinue)) { + Try { . $PSScriptRoot\$commandName.ps1 Write-Host "$commandName Function loaded." -ForegroundColor Green } - Catch - { + Catch { Write-Error -Message "Failed to import $commandName function: $_" exit 1 } diff --git a/functions/Test-Variable-Path.ps1 b/functions/Test-Variable-Path.ps1 index 354fe2a..f4bb4d6 100644 --- a/functions/Test-Variable-Path.ps1 +++ b/functions/Test-Variable-Path.ps1 @@ -1,5 +1,4 @@ -function Test-Variable-Path -{ +function Test-Variable-Path { <# .SYNOPSIS Test path to variables @@ -19,19 +18,19 @@ function Test-Variable-Path .NOTES General notes #> + [CmdletBinding()] param ( [Parameter( Mandatory = $true )] - [string] $Path, + [string]$Path, [Parameter( Mandatory = $true )] - [string] $Name + [string]$Name ) - if (!(Test-Path -LiteralPath $Path)) - { + if (!(Test-Path -LiteralPath $Path)) { Write-Host "Cannot find: $Path" -ForegroundColor Red Write-Host "As defined in variable: $Name" -ForegroundColor Red Write-Host 'Will now exit!' -ForegroundColor Red diff --git a/functions/Write-HTMLLog.ps1 b/functions/Write-HTMLLog.ps1 index 0136624..298e603 100644 --- a/functions/Write-HTMLLog.ps1 +++ b/functions/Write-HTMLLog.ps1 @@ -1,5 +1,4 @@ -function Format-Table -{ +function Format-Table { <# .SYNOPSIS Starts and stops Log file @@ -17,15 +16,15 @@ function Format-Table .NOTES General notes #> + [CmdletBinding()] param ( [Parameter( Mandatory = $false )] - [switch] $Start + [switch]$Start ) - if ($Start) - { + if ($Start) { $global:Log = @() $global:Log += "" $global:Log += '' } - else - { + else { $global:Log += '' $global:Log += '
' } } -Function Write-HTMLLog -{ +Function Write-HTMLLog { <# .SYNOPSIS Add line to in memory log @@ -75,52 +72,49 @@ Function Write-HTMLLog .NOTES General notes #> + [CmdletBinding()] Param( [Parameter( Mandatory = $true )] - [string] $Column1, + [string]$Column1, [Parameter( Mandatory = $false )] - [string] $Column2, + [string]$Column2, [Parameter( Mandatory = $false )] - [switch] $Header, + [switch]$Header, [Parameter( Mandatory = $false )] [ValidateSet( - 'Success', 'Error' + 'Success', + 'Error' )] - [string] $ColorBg + [string]$ColorBg ) $global:Log += '' - if ($Header) - { + if ($Header) { $global:Log += "$Column1" } - else - { - if ($ColorBg -eq '') - { + else { + if ($ColorBg -eq '') { $global:Log += "$Column1" $global:Log += "$Column2" $global:Log += '' } - elseif ($ColorBg -eq 'Success') - { + elseif ($ColorBg -eq 'Success') { $global:Log += "$Column1" $global:Log += "$Column2" $global:Log += '' } - elseif ($ColorBg -eq 'Error') - { + elseif ($ColorBg -eq 'Error') { $global:Log += "$Column1" $global:Log += "$Column2" $global:Log += '' @@ -130,8 +124,7 @@ Function Write-HTMLLog } -function Write-Log -{ +function Write-Log { <# .SYNOPSIS Write log to disk @@ -148,11 +141,12 @@ function Write-Log .NOTES General notes #> + [CmdletBinding()] param ( [Parameter( Mandatory = $true )] - [string] $LogFile + [string]$LogFile ) Set-Content -LiteralPath $LogFile -Value $global:Log } \ No newline at end of file