-
Notifications
You must be signed in to change notification settings - Fork 5
/
anorak.py
396 lines (323 loc) · 11.8 KB
/
anorak.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
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
import os
import sys
import datetime
import ConfigParser
import lib.web as web
import lib.anidb as anidb
from optparse import OptionParser
from anorak.downloader import *
from anorak import metadata, model, process, search
urls = (
'/', 'Index',
'/anime/(\d+)', 'Anime',
'/settings', 'Settings',
'/search', 'Search',
'/add/(\d+)', 'Add',
'/remove/(\d+)', 'Remove',
'/refresh/(\d+)', 'Refresh',
'/process', 'Process',
'/shutdown', 'Shutdown'
)
searchForm = web.form.Form(
web.form.Textbox('query',
web.form.notnull,
size=15,
height="100%",
description="",
id="search"),
web.form.Button('Search',
id="search_button"),
)
def setupDatabase():
import os
if not os.path.exists('anorak.db'):
import sqlite3
conn = sqlite3.connect('anorak.db')
c = conn.cursor()
schema = open('schema.sql', 'r').read()
c.executescript(schema)
conn.commit()
c.close()
def getConfig():
try:
file = open("anorak.cfg", "r")
settings.readfp(file)
file.close()
except IOError, e:
print "Creating configuration file"
setupConfig()
def setupConfig():
# Setup the default settings and create the sections
if not settings.has_section("Anorak"):
settings.add_section("Anorak")
settings.add_section("SABnzbd")
settings.add_section("Plex")
settings.set("Anorak", "port", 26463)
settings.set("Anorak", "searchFrequency", 30)
settings.set("SABnzbd", "url", "localhost:8080")
settings.set("SABnzbd", "key", "")
settings.set("SABnzbd", "category", "")
settings.set("SABnzbd", "username", "")
settings.set("SABnzbd", "password", "")
settings.set("Plex", "url", "localhost:32400")
settings.set("Plex", "enabled", False)
file = open("anorak.cfg","w")
settings.write(file)
file.close()
# Weirdness, settings must be reloaded from file or else ConfigParser throws a hissy fit
file = open("anorak.cfg", "r")
settings.readfp(file)
file.close()
### Templates
t_globals = {
'datestr': web.datestr,
'str': str,
'len': len,
'datetime': datetime,
'searchForm': searchForm,
'createTitleListing': metadata.createTitleListing
}
#web.config.debug = False
render = web.template.render('templates', base='base', globals=t_globals)
anidb.set_client('anorakk', 1)
settings = ConfigParser.ConfigParser()
getConfig()
setupDatabase()
class Index:
def GET(self):
""" List anime """
animes = model.get_animes()
return render.index(animes)
class Anime:
def episodeForm(self,episode=None):
return web.form.Form(
web.form.Hidden('episode', value=episode),
web.form.Hidden('form', value="episode"),
#web.form.Button('Try'),
)
def editorForm(self,anime):
return web.form.Form(
web.form.Textbox('location', web.form.notnull,
size=30,
value=anime.location,
description="Location:"),
web.form.Textbox('alternativeTitle',
size=30,
value=anime.alternativeTitle,
description="Name override (for searching only):"),
web.form.Textbox('releaseGroup',
size=30,
value=anime.subber,
description="Release Group:"),
web.form.Dropdown('quality',
[('0', 'None'), ('720', '720p'), ('480', '480p'), ('1080', '1080p')],
value=str(anime.quality),
description="Force a quality. Leave 'None' if your release group doesn't have more than one quality."),
web.form.Hidden('form', value="editor"),
web.form.Button('Update'),
)
def GET(self, id):
""" List anime episodes """
anime = model.get_anime(id)
episodes = model.get_episodes(id)
editorForm = self.editorForm(anime)
return render.anime(anime, episodes, self.episodeForm, editorForm)
def POST(self, id):
i = web.input()
# assuming that the name of the hidden field is "form"
if i.form == "editor":
return self.POST_editor(id)
else:
return self.POST_snatch(id)
def POST_snatch(self, id):
anime = model.get_anime(id)
downloader = Downloader()
downloader.anime = anime
downloader.episode = web.input().episode
if (downloader.download()):
model.snatched_episode(id, web.input().episode)
return "Snatched successfully"
else:
return "Couldn't snatch episode %s" % web.input().episode
def POST_editor(self, id):
anime = model.get_anime(id)
episodes = model.get_episodes(id)
editorForm = self.editorForm(anime)
if not editorForm.validates():
return render.anime(anime,episodes,self.episodeForm,editorForm)
model.update_anime(id, web.input().alternativeTitle, web.input().releaseGroup, web.input().location, int(web.input().quality))
return render.anime(anime,episodes,self.episodeForm,editorForm)
class Add:
form = web.form.Form(
web.form.Dropdown('quality',
[(0, 'None'), (720, '720p'), (480, '480p'), (1080, '1080p')],
description="Force a quality. Leave 'None' if your release group doesn't have more than one quality."),
web.form.Textbox('subber', web.form.notnull,
size=30,
description="Enter the release group"),
web.form.Textbox('location', web.form.notnull,
size=30,
description="Enter the file path for storing episodes"),
web.form.Button('Complete Add'),
)
anime = None
def GET(self, id):
""" Show the groups doing releases (UDP only feature, we're using TCP) """
form = self.form()
anime = anidb.query(anidb.QUERY_ANIME, int(id))
return render.add(form, anime)
def POST(self, id):
form = self.form()
anime = anidb.query(anidb.QUERY_ANIME, int(id))
if not form.validates():
return render.add(form, anime)
metadata.newAnime(anime, form.d.subber, form.d.location, form.d.quality)
raise web.seeother('/anime/%s' % int(id))
class Remove:
def GET(self, id):
model.remove_anime(id)
raise web.seeother('/')
class Refresh:
def GET(self, id):
metadata.refreshForAnime(int(id))
raise web.seeother('/anime/%s' % id)
class Process:
def GET(self):
query = web.input()
try:
nzbName = query.nzbName
except:
nzbName = None
if (process.processEpisode(query.dir, nzbName)):
return "Successfully processed episode."
return "Episode failed to process."
class Search:
def GET(self):
""" Search for Anime and add it """
return render.search(None)
def POST(self):
if not searchForm.validates():
return render.search(None)
results = anidb.search(searchForm.d.query)
return render.search(results)
class Settings:
sabnzbdForm = web.form.Form(
web.form.Textbox('url', web.form.notnull,
size=30,
value=settings.get("SABnzbd", "url"),
description="SABnzbd URL:"),
web.form.Textbox('username',
size=30,
value=settings.get("SABnzbd", "username"),
description="SABnzbd Username:"),
web.form.Password('password',
size=30,
value=settings.get("SABnzbd", "password"),
description="SABnzbd Password:"),
web.form.Textbox('key', web.form.notnull,
size=30,
value=settings.get("SABnzbd", "key"),
description="SABnzbd API key:"),
web.form.Textbox('category',
size=30,
value=settings.get("SABnzbd", "category"),
description="SABnzbd Category:"),
web.form.Hidden('form', value="sabnzbd"),
web.form.Button('Update'),
)
settingsForm = web.form.Form(
web.form.Textbox('port', web.form.notnull,
size=30,
value=str(settings.get("Anorak", "port")),
description="Port Number:"),
web.form.Textbox('searchFrequency', web.form.notnull,
size=30,
value=str(settings.get("Anorak", "searchFrequency")),
description="Search Frequency:"),
web.form.Hidden('form', value="settings"),
web.form.Button('Update'),
)
plexForm = web.form.Form(
web.form.Checkbox('enabled',
checked=settings.getboolean("Plex", "enabled"),
description="Plex Enabled:"),
web.form.Textbox('url', web.form.notnull,
size=30,
value=str(settings.get("Plex", "url")),
description="Plex URL:"),
web.form.Hidden('form', value="plex"),
web.form.Button('Update'),
)
def GET(self):
return render.settings(self.settingsForm, self.sabnzbdForm, self.plexForm)
def POST(self):
i = web.input()
# determine which form to process based on the hidden value "form"
if i.form == "settings":
return self.POST_settings()
if i.form == "sabnzbd":
return self.POST_sabnzbd()
if i.form == "plex":
return self.POST_plex()
def POST_settings(self):
if not self.settingsForm.validates():
return render.settings(self.settingsForm, self.sabnzbdForm, self.plexForm)
settings.set("Anorak", "searchFrequency", self.settingsForm.d.searchFrequency)
settings.set("Anorak", "port", self.settingsForm.d.port)
file = open("anorak.cfg","w")
settings.write(file)
file.close()
return render.settings(self.settingsForm, self.sabnzbdForm, self.plexForm)
def POST_sabnzbd(self):
if not self.sabnzbdForm.validates():
return render.settings(self.settingsForm, self.sabnzbdForm, self.plexForm)
settings.set("SABnzbd", "url", self.sabnzbdForm.d.url)
settings.set("SABnzbd", "username", self.sabnzbdForm.d.username)
settings.set("SABnzbd", "password", self.sabnzbdForm.d.password)
settings.set("SABnzbd", "key", self.sabnzbdForm.d.key)
settings.set("SABnzbd", "category", self.sabnzbdForm.d.category)
file = open("anorak.cfg","w")
settings.write(file)
file.close()
return render.settings(self.settingsForm, self.sabnzbdForm, self.plexForm)
def POST_plex(self):
if not self.plexForm.validates():
return render.settings(self.settingsForm, self.sabnzbdForm, self.plexForm)
settings.set("Plex", "url", self.plexForm.d.url)
settings.set("Plex", "enabled", self.plexForm.d.enabled)
file = open("anorak.cfg","w")
settings.write(file)
file.close()
return render.settings(self.settingsForm, self.sabnzbdForm, self.plexForm)
class Shutdown(object):
def GET(self):
os._exit(0)
class NullDevice:
def write(self, s):
pass
def daemonize():
"""Become a daemon"""
if os.fork():
os._exit(0)
# decouple from parent environment
os.setsid()
os.umask(0)
sys.stdin.close()
sys.stdout = NullDevice()
sys.stderr = NullDevice()
app = web.application(urls, globals())
search = search.SearchThread()
if __name__ == '__main__':
port = settings.get("Anorak", "port")
optionParser = OptionParser()
optionParser.add_option('-d', '--daemon', action = "store_true",
dest = 'daemon', help = "Run the server as a daemon")
options, args = optionParser.parse_args()
if options.daemon:
if not sys.platform == 'win32':
daemonize()
else:
print "Daemon mode not supported under Windows, starting normally."
sys.argv[1:] = [port]
search.start()
app.run()