-
Notifications
You must be signed in to change notification settings - Fork 0
/
FilebotRunner.ps1
269 lines (220 loc) · 10.3 KB
/
FilebotRunner.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
###################################
# UTORRENT CONFIGURATION
# powershell "C:/Scripts/FilebotRunner.ps1 \"%L\" \"%S\" \"%N\" \"%K\" \"%F\" \"%D\""
# Arguments
#param([string]$ut_label, [string]$ut_state, [string]$ut_title, [string]$ut_kind, [string]$ut_file, [string]$ut_dir)
###################################
# DELUGUE CONFIGURATION
## Deluge cannot pass arguments in the execute function, so a little CMD script is needed to kick off this script
# > powershell -File C:\Scripts\FilebotRunner_Deluge.ps1 %*
## Then give the path to the cmd script to Deluge
# > C:\Scripts\filebot_runner.cmd
# Arguments
## FileBot is designed for uTorrent, so the arguments from Deluge need to be mapped to the uTorrent standard
param([string]$deluge_torrent_id, [string]$torrent_title, [string]$torrent_path)
$ut_dir = [IO.Path]::Combine($torrent_path, $torrent_title)
$ut_label = [IO.Path]::GetFileName($torrent_path)
$ut_title = $torrent_title
$ut_kind = "multi"
###################################
#### EXAMPLE FILEBOT ARG STRING GENERATED BY THIS SCRIPT
#### '%' variables are replaced by uTorrent
<# filebot -script fn:amc
--output "Y:"
--log-file "C:\Logs\FileBot\amc\amc_01122017.log"
--action copy
--conflict skip
-non-strict
--def
music=y
subtitles=en
extras=y
pushbullet=pushbullet_api_key
clean=y
"extractFolder=C:/filebottmp"
"ut_label=$ut_label"
"ut_state=$ut_state"
"ut_title=$ut_title"
"ut_kind=$_ut_kind"
"ut_file=$ut_file"
"ut_dir=$ut_dir"
plex=plex.server.address:plex_token
"seriesFormat=Y:/TV Shows/{n}/Season {s}/{n} - {s00e00} - {t} - {vf} {ac}-{af}"
"movieFormat=Y:/Movies/{n} ({y}) {vf}/{n} ({y}) {vf} {ac}-{af}"
"musicFormat=X:/MusicTorrents/{String samplingRate = audio.SamplingRate[0].replace('0', '').replace('441', '44.1').replace('882', '88.2');String qualityStr = (audio.BitDepth[0] + '-' + samplingRate).replace(' -', '');String yearStr = y ? y + ' - ' : '';String discNumber = file.dir.name.toLowerCase().matches(/(cd|disc)+\ *\d+/) ? file.dir.name.match(/\d+/) : '';String trackNumber = fn.match(/\d+/);return String.format('%s/%s%s %s/%s%s. %s', artist, yearStr, album, qualityStr, discNumber, trackNumber, t);}
#>
<#
The musicFormat is constructed using a bit of a hack on filebot's format interpreter. The interpreter,
whether intentionally or by accident, happens to be able to interpret straight Java, so
I've written an easy-to-maintain block of code that makes a nicely formatted title.
The unminified and annotated code is as follows:
{
// Make a pretty sampling rate string
String samplingRate = audio.SamplingRate[0].replace('0', '').replace('441', '44.1').replace('882', '88.2');
// Make a nicely-formatted audio quality string
String qualityStr = (audio.BitDepth[0] + '-' + samplingRate).replace(' -', '');
// Make a year string that doesn't look bad when year is 'null'
String yearStr = y ? y + ' - ' : '';
// If the incoming file is in a subdirectory of a multi-disc structure, append the disk number to the track name
String discNumber = file.dir.name.toLowerCase().matches(/(cd|disc)+\ *\d+/) ? file.dir.name.match(/\d+/) : '';
// Get the track number
String trackNumber = fn.match(/\d+/);
// Organize all of the incoming data into an attractive and informational file name
return String.format('%s/%s%s %s/%s%s. %s', artist, yearStr, album, qualityStr, discNumber, trackNumber, t);
}
#>
# Output paths
$outputRoot = "Y:"
$output = $outputRoot
$tvRootPath = "$outputRoot/TV Shows"
$movieRootPath = "$outputRoot/Movies"
$musicRootPath = "X:/MusicTorrents"
$extractFolderPath = "C:/filebottmp"
$logsRootPath = "C:\Logs\FileBot"
## SCRIPT SETTINGS
$ignoreLabel = "FilebotIgnore"
$errorLogName = "error.log"
$handledLogFileName = "processed.log"
$ignoreLogFileName = "ignored.log"
$runLogsSubDir = "FilebotRunner"
$runLogTimestamp = [DateTime]::Now.ToString("MMddyyyy.HHmm.ss.fff")
$runLogRandom = (New-Object Random $([Guid]::NewGuid().GetHashCode())).Next(1000, 9999)
$timestampFormat = "MM/dd/yyyy hh:mm:ss tt"
#$pushbulletApiKey = "<pushbullet_api_key_goes_here>"
#$plexServerName = "<plex_server_dns_or_ip_goes_here>"
#$plexToken = "<plex_auth_token_goes_here>"
# FileBot naming formats (Groovy scripts)
$seriesFormat = "$tvRootPath/{n}/Season {s}/{n} - {s00e00} - {t} - {vf} {ac}-{af}"
$movieFormat = "$movieRootPath/{n} ({y}) {vf}/{n} ({y}) {vf} {ac}-{af}"
$musicFormat = "$musicRootPath/{String samplingRate = audio.SamplingRate[0].replace('0', '').replace('441', '44.1').replace('882', '88.2');String qualityStr = (audio.BitDepth[0] + '-' + samplingRate).replace(' -', '');String yearStr = y ? y + ' - ' : '';String discNumber = file.dir.name.toLowerCase().matches(/(cd|disc)+\ *\d+/) ? file.dir.name.match(/\d+/) : '';String trackNumber = fn.match(/\d+/);return String.format('%s/%s%s %s/%s%s. %s', artist, yearStr, album, qualityStr, discNumber, trackNumber, t);}"
# FileBot settings
$logFile = "C:\Logs\FileBot\amc\amc_$([DateTime]::Now.ToString("MMddyyyy")).log"
$action = "copy"
$conflict = "auto" # This is the default, but might be overridden below
# FileBot 'Def' stuff
$music = "y"
$subtitles = "en"
$extras = "y"
$clean = "y"
function Get-TimeStamp{
param([string]$timeFormat = $timestampFormat)
return "[" + [DateTime]::Now.ToString($timeFormat) + "]"
}
function Create-Regex{
param([string]$regex, [bool]$ignoreCase = $true)
if ($ignoreCase){
return New-Object Text.RegularExpressions.Regex $regex,([Text.RegularExpressions.RegexOptions]::IgnoreCase)
}
else{
return New-Object Text.RegularExpressions.Regex $regex
}
}
function Log-IgnoredTorrent{
$ignoreLogPath = [IO.Path]::Combine($logsRootPath, $ignoreLogFileName)
# If file doesn't exist, create it
if (![IO.File]::Exists($ignoreLogPath)){
$noop = New-Item -ItemType File -Path $logsRootPath -Name $ignoreLogFileName
}
# Get timestamp
$timestamp = Get-TimeStamp
# Add the content
$noop = Add-Content ($ignoreLogPath) "$timestamp IGNORED: '$ut_title'"
}
function Log-HandledTorrent{
$handledLogPath = [IO.Path]::Combine($logsRootPath, $handledLogFileName)
# If file doesn't exist, create it
if (![IO.File]::Exists($handledLogPath)){
$noop = New-Item -ItemType File -Path $logsRootPath -Name $handledLogFileName
}
# Get timestamp
$timestamp = Get-TimeStamp
# Add the content
$noop = Add-Content ($handledLogPath) "$timestamp HANDLED: '$ut_title'"
}
function Write-Log {
param([string]$message)
$fName = "filebotrunner_$runLogTimestamp-$runLogRandom.log"
$runLogFilePath = [IO.Path]::Combine($logsRootPath, $runLogsSubDir, $fName)
if (![IO.File]::Exists($runLogFilePath)){
[void][IO.Directory]::CreateDirectory([IO.Path]::GetDirectoryName($runLogFilePath))
echo $null >> $runLogFilePath
}
$message = $message.Replace("`n", [Environment]::NewLine)
tee -FilePath $runLogFilePath -InputObject $message -Append -ErrorAction SilentlyContinue
}
try{
# Make sure the important args aren't empty
if (![string]::IsNullOrWhiteSpace($ut_title) -and ![string]::IsNullOrWhiteSpace($ut_kind) -and (![string]::IsNullOrWhiteSpace($ut_file) -or ![string]::IsNullOrWhiteSpace($ut_dir)))
{
Write-Log "`nARGUMENTS`nut_label = $ut_label`nut_title = $ut_title`nut_kind = $ut_kind`nut_dir = $ut_dir`n"
}
else{
Write-Log "INVALID ARGUMENTS!"
throw New-Object Exception "Invalid arguments"
}
# Check if torrent was labled with value of '$ignoreLabel' and if so, exit
if ($ut_label.ToLower().Contains($ignoreLabel.ToLower())){
Write-Log "`nTorrent was labled with 'FilebotIgnore' tag. Skipping..."
Log-IgnoredTorrent
exit
}
# Decide if file is 'PROPER' or 'REPACK' and set filebot conflict mode to 'override'
$propRegex = Create-Regex "(proper)+"
$repRegex = Create-Regex "(repack)+"
if ($propRegex.IsMatch($ut_title) -or $repRegex.IsMatch($ut_title)){
$conflict = "override"
}
else{
$conflict = "skip"
}
Write-log "Conflict resolution mode set to '$conflict'`n"
## Filebot execution
# Argument string builder
$argString = New-Object Text.StringBuilder
# Load up general stuff
$argString.Append("-script fn:amc --output `"$output`" --log-file `"$logFile`" --action $action --conflict $conflict -non-strict ")
# Set general 'Def' stuff
$argString.Append("--def music=$music subtitles=$subtitles extras=$extras clean=$clean ")
# Set PushBullet info if specified
if ([string]::IsNullOrWhiteSpace($pushbulletApiKey)){
$argString.Append("pushbullet=$pushbulletApiKey ")
}
# Set extract folder if specified
if (![string]::IsNullOrWhiteSpace($extractFolderPath)){
$argString.Append("`"extractFolder=$extractFolderPath`" ")
}
# Set uT stuff
$argString.Append("`"ut_label=$ut_label`" `"ut_state=$ut_state`" `"ut_title=$ut_title`" `"ut_kind=$ut_kind`" `"ut_file=$ut_file`" `"ut_dir=$ut_dir`" ")
# Set Plex server info if specified
if (![string]::IsNullOrWhiteSpace($plexServerName) -and ![string]::IsNullOrWhiteSpace($plexToken)){
$argString.Append("plex=$($plexServerName):$plexToken ")
}
# Set naming formats
$argString.Append("`"seriesFormat=$seriesFormat`" ")
$argString.Append("`"movieFormat=$movieFormat`" ")
$argString.Append("`"musicFormat=$musicFormat`" ")
# Build filebot argument string
$args = $argString.ToString()
# Initialize filebot process
$startInfo = New-Object Diagnostics.ProcessStartInfo
$startInfo.FileName = "filebot"
$startInfo.Arguments = $args
$startInfo.Verb = "runas"
# Execute filebot process
Write-log "STARTING FILEBOT`nARGUMENTS: $args`n"
$filebotProcess = [Diagnostics.Process]::Start($startInfo)
# Log the processed torrent
Log-HandledTorrent
# Exit from powershell process after spawning filebot process
Write-log "Done ヽ(^Д^)ノ"
exit
}
catch {
$ts = Get-TimeStamp
Write-log "ERROR IN SCRIPT!"
Write-Log $_.Exception.Message
Write-Log $_.Exception.StackTrace
Tee-Object -FilePath ([IO.Path]::Combine($logsRootPath, $errorLogName)) -InputObject ("$ts ERROR: $($_.Exception.Message)") -Append
Write-Log "Failed (ノ﹏ヽ)"
exit 1
}