forked from mdhiggins/sickbeard_mp4_automator
-
Notifications
You must be signed in to change notification settings - Fork 0
/
uTorrentPostProcess.py
executable file
·233 lines (205 loc) · 8.76 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
import os
import re
import sys
import shutil
from log import getLogger
from autoprocess import autoProcessTV, autoProcessMovie, autoProcessTVSR, sonarr, radarr
from readSettings import ReadSettings
from mkvtomp4 import MkvtoMp4
import logging
from logging.config import fileConfig
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 _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), e:
log.exception("Problem sending command " + fnct + " - " + str(e) + ".")
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()
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['cp'], 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]
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 label not in categories:
log.error("No valid label detected.")
sys.exit()
if len(categories) != len(set(categories)):
log.error("Duplicate category detected. Category names must be unique.")
sys.exit()
# Import requests
try:
import requests
except ImportError:
log.exception("Python module REQUESTS is required. Install with 'pip install requests' then try again.")
sys.exit()
try:
web_ui = settings.uTorrentWebUI
log.debug("WebUI is true.")
except:
log.debug("WebUI is false.")
web_ui = False
delete_dir = False
# Run a uTorrent action before conversion.
if web_ui:
session = requests.Session()
if session:
auth, session = _authToken(session, settings.uTorrentHost, settings.uTorrentUsername, settings.uTorrentPassword)
if auth and settings.uTorrentActionBefore:
params = {'token': auth, 'action': settings.uTorrentActionBefore, 'hash': torrent_hash}
_sendRequest(session, settings.uTorrentHost, settings.uTorrentUsername, settings.uTorrentPassword, params, None, "Before Function")
log.debug("Sending action %s to uTorrent" % settings.uTorrentActionBefore)
if settings.uTorrent['convert']:
# Check for custom uTorrent output_dir
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" % (name, suffix)))
else:
log.info("Multi File Torrent")
settings.output_dir = os.path.abspath(os.path.join(path, '..', ("%s-%s" % (name, suffix))))
if not os.path.exists(settings.output_dir):
try:
os.mkdir(settings.output_dir)
except:
log.exception("Error creating output directory.")
else:
settings.output_dir = os.path.abspath(os.path.join(settings.output_dir, name))
if not os.path.exists(settings.output_dir):
try:
os.makedirs(settings.output_dir)
except:
log.exception("Error creating output sub directory.")
converter = MkvtoMp4(settings)
if kind == 'single':
inputfile = os.path.join(path, filename)
info = converter.isValidSource(inputfile)
if info:
log.info("Processing file %s." % inputfile)
try:
output = converter.process(inputfile, reportProgress=True, info=info)
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 = converter.isValidSource(inputfile)
if info and inputfile not in ignore:
log.info("Processing file %s." % inputfile)
try:
output = converter.process(inputfile, info=info)
if output is not False:
ignore.append(output['output'])
else:
log.error("Converting file failed %s." % inputfile)
except:
log.exception("Error converting file %s." % inputfile)
else:
log.debug("Ignoring file %s." % inputfile)
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" % (name, suffix)))
else:
log.info("Multi File Torrent")
newpath = os.path.abspath(os.path.join(path, '..', ("%s-%s" % (name, suffix))))
if not os.path.exists(newpath):
try:
os.mkdir(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 label == categories[0]:
log.info("Passing %s directory to Couch Potato." % path)
autoProcessMovie.process(path, settings)
elif label == categories[1]:
log.info("Passing %s directory to Sickbeard." % path)
autoProcessTV.processEpisode(path, settings)
elif label == categories[2]:
log.info("Passing %s directory to Sonarr." % path)
sonarr.processEpisode(path, settings)
elif label == categories[3]:
log.info("Passing %s directory to Radarr." % path)
radarr.processMovie(path, settings)
elif label == categories[4]:
log.info("Passing %s directory to Sickrage." % path)
autoProcessTVSR.processEpisode(path, settings)
elif label == categories[5]:
log.info("Bypassing any further processing as per category.")
# Run a uTorrent action after conversion.
if web_ui:
if session and auth and settings.uTorrentActionAfter:
params = {'token': auth, 'action': settings.uTorrentActionAfter, 'hash': torrent_hash}
_sendRequest(session, settings.uTorrentHost, settings.uTorrentUsername, settings.uTorrentPassword, params, None, "After Function")
log.debug("Sending action %s to uTorrent" % settings.uTorrentActionAfter)
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")
sys.exit()