forked from mdhiggins/sickbeard_mp4_automator
-
Notifications
You must be signed in to change notification settings - Fork 0
/
uTorrentPostProcess.py
executable file
·222 lines (194 loc) · 8.51 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
import os
import re
import sys
import shutil
from autoprocess import autoProcessTV, autoProcessMovie, autoProcessTVSR, sonarr, radarr
from readSettings import ReadSettings
from mkvtomp4 import MkvtoMp4
import logging
from logging.config import fileConfig
logpath = '/var/log/sickbeard_mp4_automator'
if os.name == 'nt':
logpath = os.path.dirname(sys.argv[0])
elif not os.path.isdir(logpath):
try:
os.mkdir(logpath)
except:
logpath = os.path.dirname(sys.argv[0])
fileConfig(os.path.join(os.path.dirname(sys.argv[0]), 'logging.ini'), defaults={'logfilename': os.path.join(logpath, 'index.log')})
log = logging.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(os.path.dirname(sys.argv[0]), "autoProcess.ini")
path = str(sys.argv[3])
label = sys.argv[1].lower()
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)
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 str(sys.argv[4]) == '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):
os.mkdir(settings.output_dir)
delete_dir = settings.output_dir
converter = MkvtoMp4(settings)
if str(sys.argv[4]) == 'single':
inputfile = os.path.join(path, str(sys.argv[5]))
if MkvtoMp4(settings).validSource(inputfile):
log.info("Processing file %s." % inputfile)
try:
output = converter.process(inputfile, reportProgress=True)
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)
if MkvtoMp4(settings).validSource(inputfile) and inputfile not in ignore:
log.info("Processing file %s." % inputfile)
try:
output = converter.process(inputfile)
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 = converter.output_dir
else:
suffix = "copy"
# name = name[:260-len(suffix)]
if str(sys.argv[4]) == '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):
os.mkdir(newpath)
log.debug("Creating temporary directory %s" % newpath)
if str(sys.argv[4]) == 'single':
inputfile = os.path.join(path, str(sys.argv[5]))
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()