-
Notifications
You must be signed in to change notification settings - Fork 201
/
uTorrentPostProcess.py
executable file
·246 lines (216 loc) · 10.3 KB
/
uTorrentPostProcess.py
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
import os
import re
import sys
import shutil
from autoprocess import autoProcessTV, autoProcessTVSR, sonarr, radarr
from resources.log import getLogger
from resources.readsettings import ReadSettings
from resources.mediaprocessor import MediaProcessor
log = getLogger("uTorrentPostProcess")
log.info("uTorrent post processing started.")
# Args: %L %T %D %K %F %I Label, Tracker, Directory, single|multi, NameofFile(if single), InfoHash
def getHost(host='localhost', port=8080, ssl=False):
protocol = "https://" if ssl else "http://"
return protocol + host + ":" + str(port) + "/"
def _authToken(session=None, host=None, username=None, password=None):
auth = None
if not session:
session = requests.Session()
response = session.get(host + "gui/token.html", auth=(username, password), verify=False, timeout=30)
if response.status_code == 200:
auth = re.search("<div.*?>(\S+)<\/div>", response.text).group(1)
else:
log.error("Authentication Failed - Status Code " + response.status_code + ".")
return auth, session
def _sendRequest(session, host='http://localhost:8080/', username=None, password=None, params=None, files=None, fnct=None):
try:
response = session.post(host + "gui/", auth=(username, password), params=params, files=files, timeout=30)
except (requests.exceptions.ConnectionError, requests.exceptions.HTTPError):
log.exception("Problem sending command")
return False
if response.status_code == 200:
log.debug("Request sent successfully - %s." % fnct)
return True
log.error("Problem sending command " + fnct + ", return code = " + str(response.status_code) + ".")
return False
if len(sys.argv) < 6:
log.error("Not enough command line parameters present, are you launching this from uTorrent?")
log.error("#Args: %L %T %D %K %F %I %N Label, Tracker, Directory, single|multi, NameofFile(if single), InfoHash, Name")
log.error("Length was %s" % str(len(sys.argv)))
log.error(str(sys.argv[1:]))
sys.exit(1)
try:
settings = ReadSettings()
path = str(sys.argv[3])
label = sys.argv[1].lower().strip()
kind = sys.argv[4].lower().strip()
filename = sys.argv[5].strip()
categories = [settings.uTorrent['sb'], settings.uTorrent['sonarr'], settings.uTorrent['radarr'], settings.uTorrent['sr'], settings.uTorrent['bypass']]
torrent_hash = sys.argv[6]
try:
name = sys.argv[7]
except:
name = sys.argv[6]
path_mapping = settings.uTorrent['path-mapping']
log.debug("Path: %s." % path)
log.debug("Label: %s." % label)
log.debug("Categories: %s." % categories)
log.debug("Torrent hash: %s." % torrent_hash)
log.debug("Torrent name: %s." % name)
log.debug("Kind: %s." % kind)
log.debug("Filename: %s." % filename)
if not label or len([x for x in categories if x.startswith(label)]) < 1:
log.error("No valid label detected.")
sys.exit(1)
if len(categories) != len(set(categories)):
log.error("Duplicate category detected. Category names must be unique.")
sys.exit(1)
# Import requests
try:
import requests
except ImportError:
log.exception("Python module REQUESTS is required. Install with 'pip install requests' then try again.")
sys.exit(1)
try:
web_ui = settings.uTorrent['webui']
log.debug("WebUI is true.")
except:
log.debug("WebUI is false.")
web_ui = False
delete_dir = False
host = getHost(settings.uTorrent['host'], settings.uTorrent['port'], settings.uTorrent['ssl'])
# Run a uTorrent action before conversion.
session = None
auth = None
if web_ui:
session = requests.Session()
if session:
auth, session = _authToken(session, host, settings.uTorrent['username'], settings.uTorrent['password'])
if auth and settings.uTorrent['actionbefore']:
params = {'token': auth, 'action': settings.uTorrent['actionbefore'], 'hash': torrent_hash}
_sendRequest(session, host, settings.uTorrent['username'], settings.uTorrent['password'], params, None, "Before Function")
log.debug("Sending action %s to uTorrent" % settings.uTorrent['actionbefore'])
if settings.uTorrent['convert']:
# Check for custom uTorrent output directory
if settings.uTorrent['output-dir']:
settings.output_dir = settings.uTorrent['output-dir']
log.debug("Overriding output_dir to %s." % settings.uTorrent['output-dir'])
# Perform conversion.
log.info("Performing conversion")
settings.delete = False
if not settings.output_dir:
suffix = "convert"
if kind == 'single':
log.info("Single File Torrent")
settings.output_dir = os.path.join(path, ("%s-%s" % (re.sub(settings.regex, '_', name), suffix)))
else:
log.info("Multi File Torrent")
settings.output_dir = os.path.abspath(os.path.join(path, '..', ("%s-%s" % (re.sub(settings.regex, '_', name), suffix))))
if not os.path.exists(settings.output_dir):
try:
os.makedirs(settings.output_dir)
except:
log.exception("Error creating output directory.")
else:
settings.output_dir = re.sub(settings.regex, '_', os.path.abspath(os.path.join(settings.output_dir, re.sub(settings.regex, '_', name))))
if not os.path.exists(settings.output_dir):
try:
os.makedirs(settings.output_dir)
except:
log.exception("Error creating output sub directory.")
mp = MediaProcessor(settings)
if kind == 'single':
inputfile = os.path.join(path, filename)
info = mp.isValidSource(inputfile)
if info:
log.info("Processing file %s." % inputfile)
try:
output = mp.process(inputfile, info=info)
if not output:
log.error("No output file generated for single torrent download.")
sys.exit(1)
except:
log.exception("Error converting file %s." % inputfile)
else:
log.debug("Ignoring file %s." % inputfile)
else:
log.debug("Processing multiple files.")
ignore = []
for r, d, f in os.walk(path):
for files in f:
inputfile = os.path.join(r, files)
info = mp.isValidSource(inputfile)
if info and inputfile not in ignore:
log.info("Processing file %s." % inputfile)
try:
output = mp.process(inputfile, info=info)
if output and output.get('output'):
ignore.append(output.get('output'))
else:
log.error("Converting file failed %s." % inputfile)
except:
log.exception("Error converting file %s." % inputfile)
else:
log.debug("Ignoring file %s." % inputfile)
if len(ignore) < 1:
log.error("No output files generated for the entirety of this mutli file torrent, aborting.")
sys.exit(1)
path = settings.output_dir
delete_dir = settings.output_dir
else:
suffix = "copy"
# name = name[:260-len(suffix)]
if kind == 'single':
log.info("Single File Torrent")
newpath = os.path.join(path, ("%s-%s" % (re.sub(settings.regex, '_', name), suffix)))
else:
log.info("Multi File Torrent")
newpath = os.path.abspath(os.path.join(path, '..', ("%s-%s" % (re.sub(settings.regex, '_', name), suffix))))
if not os.path.exists(newpath):
try:
os.makedirs(newpath)
log.debug("Creating temporary directory %s" % newpath)
except:
log.exception("Error creating temporary directory.")
if kind == 'single':
inputfile = os.path.join(path, filename)
shutil.copy(inputfile, newpath)
log.debug("Copying %s to %s" % (inputfile, newpath))
else:
for r, d, f in os.walk(path):
for files in f:
inputfile = os.path.join(r, files)
shutil.copy(inputfile, newpath)
log.debug("Copying %s to %s" % (inputfile, newpath))
path = newpath
delete_dir = newpath
if settings.uTorrent['sb'].startswith(label):
log.info("Passing %s directory to Sickbeard." % path)
autoProcessTV.processEpisode(path, settings, pathMapping=path_mapping)
elif settings.uTorrent['sonarr'].startswith(label):
log.info("Passing %s directory to Sonarr." % path)
sonarr.processEpisode(path, settings, pathMapping=path_mapping)
elif settings.uTorrent['radarr'].startswith(label):
log.info("Passing %s directory to Radarr." % path)
radarr.processMovie(path, settings, pathMapping=path_mapping)
elif settings.uTorrent['sr'].startswith(label):
log.info("Passing %s directory to Sickrage." % path)
autoProcessTVSR.processEpisode(path, settings, pathMapping=path_mapping)
elif settings.uTorrent['bypass'].startswith(label):
log.info("Bypassing any further processing as per category.")
# Run a uTorrent action after conversion.
if web_ui:
if session and auth and settings.uTorrent['actionafter']:
params = {'token': auth, 'action': settings.uTorrent['actionafter'], 'hash': torrent_hash}
_sendRequest(session, host, settings.uTorrent['username'], settings.uTorrent['password'], params, None, "After Function")
log.debug("Sending action %s to uTorrent" % settings.uTorrent['actionafter'])
if delete_dir:
if os.path.exists(delete_dir):
try:
os.rmdir(delete_dir)
log.debug("Successfully removed tempoary directory %s." % delete_dir)
except:
log.exception("Unable to delete temporary directory")
except:
log.exception("Unexpected exception.")
sys.exit(1)