forked from rembo10/headphones
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwebServer.py
More file actions
436 lines (380 loc) · 17.2 KB
/
webServer.py
File metadata and controls
436 lines (380 loc) · 17.2 KB
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
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
import templates
import config
import cherrypy
import musicbrainz2.webservice as ws
import musicbrainz2.model as m
import musicbrainz2.utils as u
import os
import string
import time
import datetime
import sqlite3
import sys
import configobj
from headphones import FULL_PATH, config_file
import logger
database = os.path.join(FULL_PATH, 'headphones.db')
class Headphones:
def index(self):
page = [templates._header]
page.append(templates._logobar)
page.append(templates._nav)
#Display Database if it exists:
if os.path.exists(database):
#logger.log(u"Loading artists from the database...")
conn=sqlite3.connect(database)
c=conn.cursor()
c.execute('SELECT ArtistName, ArtistID, Status from artists order by ArtistSortName collate nocase')
results = c.fetchall()
i = 0
page.append('''<div class="table"><table border="0" cellpadding="3">
<tr>
<th align="left" width="170">Artist Name</th>
<th align="center" width="100">Status</th>
<th align="center" width="300">Upcoming Albums</th>
<th> </th>
</tr>''')
while i < len(results):
c.execute('''SELECT AlbumTitle, ReleaseDate, DateAdded, AlbumID from albums WHERE ArtistID='%s' order by ReleaseDate DESC''' % results[i][1])
latestalbum = c.fetchall()
today = datetime.date.today()
if len(latestalbum) > 0:
if latestalbum[0][1] > datetime.date.isoformat(today):
newalbumName = '<font color="#5DFC0A" size="3px"><a href="albumPage?AlbumID=%s"><i>%s</i>' % (latestalbum[0][3], latestalbum[0][0])
releaseDate = '(%s)</a></font>' % latestalbum[0][1]
else:
newalbumName = '<font color="#CFCFCF">None</font>'
releaseDate = ""
if len(latestalbum) == 0:
newalbumName = '<font color="#CFCFCF">None</font>'
releaseDate = ""
if results[i][2] == 'Paused':
newStatus = '''<font color="red"><b>%s</b></font>(<A class="external" href="resumeArtist?ArtistID=%s">resume</a>)''' % (results[i][2], results[i][1])
else:
newStatus = '''%s(<A class="external" href="pauseArtist?ArtistID=%s">pause</a>)''' % (results[i][2], results[i][1])
page.append('''<tr><td align="left" width="300"><a href="artistPage?ArtistID=%s">%s</a>
(<A class="external" href="http://musicbrainz.org/artist/%s">link</a>) [<A class="externalred" href="deleteArtist?ArtistID=%s">delete</a>]</td>
<td align="center" width="160">%s</td>
<td align="center">%s %s</td></tr>''' % (results[i][1], results[i][0], results[i][1], results[i][1], newStatus, newalbumName, releaseDate))
i = i+1
c.close()
page.append('''</table></div>''')
else:
page.append("""<div class="datanil">Add some artists to the database!</div>""")
page.append(templates._footer)
return page
index.exposed = True
def artistPage(self, ArtistID):
page = [templates._header]
page.append(templates._logobar)
page.append(templates._nav)
conn=sqlite3.connect(database)
c=conn.cursor()
c.execute('''SELECT ArtistName from artists WHERE ArtistID="%s"''' % ArtistID)
artistname = c.fetchall()
c.execute('''SELECT AlbumTitle, ReleaseDate, AlbumID, Status, ArtistName, AlbumASIN from albums WHERE ArtistID="%s" order by ReleaseDate DESC''' % ArtistID)
results = c.fetchall()
c.close()
i = 0
page.append('''<div class="table"><table border="0" cellpadding="3">
<tr><p align="center">%s <br /></p></tr>
<tr>
<th align="left" width="50"></th>
<th align="left" width="120">Album Name</th>
<th align="center" width="100">Release Date</th>
<th align="center" width="300">Status</th>
<th> </th>
</tr>''' % (artistname[0]))
while i < len(results):
if results[i][3] == 'Skipped':
newStatus = '''%s [<A class="external" href="queueAlbum?AlbumID=%s&ArtistID=%s">want</a>]''' % (results[i][3], results[i][2], ArtistID)
elif results[i][3] == 'Wanted':
newStatus = '''<b>%s</b>[<A class="external" href="unqueueAlbum?AlbumID=%s&ArtistID=%s">skip</a>]''' % (results[i][3], results[i][2], ArtistID)
elif results[i][3] == 'Downloaded':
newStatus = '''<b>%s</b>[<A class="external" href="queueAlbum?AlbumID=%s&ArtistID=%s">retry</a>]''' % (results[i][3], results[i][2], ArtistID)
elif results[i][3] == 'Snatched':
newStatus = '''<b>%s</b>[<A class="external" href="queueAlbum?AlbumID=%s&ArtistID=%s">retry</a>]''' % (results[i][3], results[i][2], ArtistID)
else:
newStatus = '%s' % (results[i][3])
page.append('''<tr><td align="left"><img src="http://ec1.images-amazon.com/images/P/%s.01.MZZZZZZZ.jpg" height="50" width="50"></td>
<td align="left" width="240"><a href="albumPage?AlbumID=%s">%s</a>
(<A class="external" href="http://musicbrainz.org/release/%s.html">link</a>)</td>
<td align="center" width="160">%s</td>
<td align="center">%s</td></tr>''' % (results[i][5], results[i][2], results[i][0], results[i][2], results[i][1], newStatus))
i = i+1
page.append('''</table></div>''')
page.append(templates._footer)
return page
artistPage.exposed = True
def albumPage(self, AlbumID):
page = [templates._header]
page.append(templates._logobar)
page.append(templates._nav)
conn=sqlite3.connect(database)
c=conn.cursor()
c.execute('''SELECT ArtistID, ArtistName, AlbumTitle, TrackTitle, TrackDuration, TrackID, AlbumASIN from tracks WHERE AlbumID="%s"''' % AlbumID)
results = c.fetchall()
if results[0][6]:
albumart = '''<br /><img src="http://ec1.images-amazon.com/images/P/%s.01.LZZZZZZZ.jpg" height="200" width="200"><br /><br />''' % results[0][6]
else:
albumart = ''
c.close()
i = 0
page.append('''<div class="table" align="center"><table border="0" cellpadding="3">
<tr><a href="artistPage?ArtistID=%s">%s</a> - %s<br />
<a href="queueAlbum?AlbumID=%s&ArtistID=%s">Download<br />%s</tr>
<br /><tr>
<th align="left" width="100">Track #</th>
<th align="left" width="100">Track Title</th>
<th align="center" width="300">Duration</th>
<th> </th>
</tr>''' % (results[0][0], results[0][1], results[0][2], AlbumID, results[0][0], albumart))
while i < len(results):
if results[i][4]:
duration = time.strftime("%M:%S", time.gmtime(int(results[i][4])/1000))
else:
duration = 'n/a'
page.append('''<tr><td align="left" width="120">%s</td>
<td align="left" width="240">%s (<A class="external" href="http://musicbrainz.org/recording/%s.html">link</a>)</td>
<td align="center">%s</td></tr>''' % (i+1, results[i][3], results[i][5], duration))
i = i+1
page.append('''</table></div>''')
page.append(templates._footer)
return page
albumPage.exposed = True
def findArtist(self, name):
page = [templates._header]
if len(name) == 0 or name == 'Add an artist':
raise cherrypy.HTTPRedirect("/")
else:
artistResults = ws.Query().getArtists(ws.ArtistFilter(string.replace(name, '&', '%38'), limit=8))
if len(artistResults) == 0:
logger.log(u"No results found for " + name)
page.append('''No results!<a class="blue" href="/">Go back</a>''')
return page
elif len(artistResults) > 1:
page.append('''Search returned multiple artists. Click the artist you want to add:<br /><br />''')
for result in artistResults:
artist = result.artist
page.append('''<a href="/addArtist?artistid=%s">%s</a> (<a class="externalred" href="/artistInfo?artistid=%s">more info</a>)<br />''' % (u.extractUuid(artist.id), artist.name, u.extractUuid(artist.id)))
return page
else:
for result in artistResults:
artist = result.artist
logger.log(u"Found one artist matching your search term: " + artist.name +" ("+ artist.id+")")
raise cherrypy.HTTPRedirect("/addArtist?artistid=%s" % u.extractUuid(artist.id))
findArtist.exposed = True
def artistInfo(self, artistid):
page = [templates._header]
inc = ws.ArtistIncludes(releases=(m.Release.TYPE_OFFICIAL, m.Release.TYPE_ALBUM), releaseGroups=True)
artist = ws.Query().getArtistById(artistid, inc)
page.append('''Artist Name: %s </br> ''' % artist.name)
page.append('''Unique ID: %s </br></br>Albums:<br />''' % u.extractUuid(artist.id))
for rg in artist.getReleaseGroups():
page.append('''%s <br />''' % rg.title)
return page
artistInfo.exposed = True
def addArtist(self, artistid):
inc = ws.ArtistIncludes(releases=(m.Release.TYPE_OFFICIAL, m.Release.TYPE_ALBUM), ratings=False, releaseGroups=False)
artist = ws.Query().getArtistById(artistid, inc)
conn=sqlite3.connect(database)
c=conn.cursor()
c.execute('CREATE TABLE IF NOT EXISTS artists (ArtistID TEXT UNIQUE, ArtistName TEXT, ArtistSortName TEXT, DateAdded TEXT, Status TEXT)')
c.execute('CREATE TABLE IF NOT EXISTS albums (ArtistID TEXT, ArtistName TEXT, AlbumTitle TEXT, AlbumASIN TEXT, ReleaseDate TEXT, DateAdded TEXT, AlbumID TEXT UNIQUE, Status TEXT)')
c.execute('CREATE TABLE IF NOT EXISTS tracks (ArtistID TEXT, ArtistName TEXT, AlbumTitle TEXT, AlbumASIN TEXT, AlbumID TEXT, TrackTitle TEXT, TrackDuration, TrackID TEXT)')
c.execute('SELECT ArtistID from artists')
artistlist = c.fetchall()
if any(artistid in x for x in artistlist):
page = [templates._header]
page.append('''%s has already been added. Go <a href="/">back</a>.''' % artist.name)
logger.log(artist.name + u" is already in the database!", logger.WARNING)
c.close()
return page
else:
logger.log(u"Adding " + artist.name + " to the database.")
c.execute('INSERT INTO artists VALUES( ?, ?, ?, CURRENT_DATE, ?)', (artistid, artist.name, artist.sortName, 'Active'))
for release in artist.getReleases():
releaseid = u.extractUuid(release.id)
inc = ws.ReleaseIncludes(artist=True, releaseEvents= True, tracks= True, releaseGroup=True)
results = ws.Query().getReleaseById(releaseid, inc)
time.sleep(0.6)
for event in results.releaseEvents:
if event.country == 'US':
logger.log(u"Now adding album: " + results.title+ " to the database")
c.execute('INSERT INTO albums VALUES( ?, ?, ?, ?, ?, CURRENT_DATE, ?, ?)', (artistid, results.artist.name, results.title, results.asin, results.getEarliestReleaseDate(), u.extractUuid(results.id), 'Skipped'))
c.execute('SELECT ReleaseDate, DateAdded from albums WHERE AlbumID="%s"' % u.extractUuid(results.id))
latestrelease = c.fetchall()
if latestrelease[0][0] > latestrelease[0][1]:
logger.log(results.title + u" is an upcoming album. Setting its status to 'Wanted'...")
c.execute('UPDATE albums SET Status = "Wanted" WHERE AlbumID="%s"' % u.extractUuid(results.id))
else:
pass
for track in results.tracks:
c.execute('INSERT INTO tracks VALUES( ?, ?, ?, ?, ?, ?, ?, ?)', (artistid, results.artist.name, results.title, results.asin, u.extractUuid(results.id), track.title, track.duration, u.extractUuid(track.id)))
else:
logger.log(results.title + " is not a US release. Skipping it for now", logger.DEBUG)
conn.commit()
c.close()
raise cherrypy.HTTPRedirect("/")
addArtist.exposed = True
#page for pausing an artist
def pauseArtist(self, ArtistID):
conn=sqlite3.connect(database)
c=conn.cursor()
logger.log(u"Pausing artist: " + ArtistID)
c.execute('UPDATE artists SET status = "Paused" WHERE ArtistId="%s"' % ArtistID)
conn.commit()
c.close()
raise cherrypy.HTTPRedirect("/")
pauseArtist.exposed = True
def resumeArtist(self, ArtistID):
conn=sqlite3.connect(database)
c=conn.cursor()
logger.log(u"Resuming artist: " + ArtistID)
c.execute('UPDATE artists SET status = "Active" WHERE ArtistId="%s"' % ArtistID)
conn.commit()
c.close()
raise cherrypy.HTTPRedirect("/")
resumeArtist.exposed = True
def deleteArtist(self, ArtistID):
conn=sqlite3.connect(database)
c=conn.cursor()
logger.log(u"Deleting all traces of artist: " + ArtistID)
c.execute('''DELETE from artists WHERE ArtistID="%s"''' % ArtistID)
c.execute('''DELETE from albums WHERE ArtistID="%s"''' % ArtistID)
c.execute('''DELETE from tracks WHERE ArtistID="%s"''' % ArtistID)
conn.commit()
c.close()
raise cherrypy.HTTPRedirect("/")
deleteArtist.exposed = True
def queueAlbum(self, AlbumID, ArtistID):
conn=sqlite3.connect(database)
c=conn.cursor()
logger.log(u"Marking album: " + AlbumID + "as wanted...")
c.execute('UPDATE albums SET status = "Wanted" WHERE AlbumID="%s"' % AlbumID)
conn.commit()
c.close()
import searcher
searcher.searchNZB(AlbumID)
raise cherrypy.HTTPRedirect("/artistPage?ArtistID=%s" % ArtistID)
queueAlbum.exposed = True
def unqueueAlbum(self, AlbumID, ArtistID):
conn=sqlite3.connect(database)
c=conn.cursor()
logger.log(u"Marking album: " + AlbumID + "as skipped...")
c.execute('UPDATE albums SET status = "Skipped" WHERE AlbumID="%s"' % AlbumID)
conn.commit()
c.close()
raise cherrypy.HTTPRedirect("/artistPage?ArtistID=%s" % ArtistID)
unqueueAlbum.exposed = True
def upcoming(self):
page = [templates._header]
page.append(templates._logobar)
page.append(templates._nav)
page.append(templates._footer)
return page
upcoming.exposed = True
def manage(self):
config = configobj.ConfigObj(config_file)
try:
path = config['General']['path_to_xml']
except:
path = 'Absolute path to iTunes XML or Top-Level Music Directory'
page = [templates._header]
page.append(templates._logobar)
page.append(templates._nav)
page.append('''<div class="table"><div class="config"><h1>Import or Sync Your iTunes Library/Music Folder</h1><br />
Enter the full path to your iTunes XML file or music folder<br /><br />
i.e. /Users/"username"/Music/iTunes/iTunes Music Library.xml<br />
<i>or</i> /Users/"username"/Music/iTunes/iTunes Media/Music <br /><br />(artists should have their own directories for folder import to work)
<br /><br />note: This process can take a LONG time!<br /><br />
Once you click "Submit" you can navigate away from this
page while the process runs.<br /><br /><br />
<form action="importItunes" method="GET" align="center">
<input type="text" value="%s" onfocus="if
(this.value==this.defaultValue) this.value='';" name="path" size="70" />
<input type="submit" /></form><br /><br /></div></div>
<div class="table"><div class="config"><h1>Force Search</h1><br />
<a href="forceSearch">Force Check for Wanted Albums</a><br /><br />
<a href="forceUpdate">Force Update Active Artists </a><br /><br /><br /></div></div>''' % path)
page.append(templates._footer)
return page
manage.exposed = True
def importItunes(self, path):
config = configobj.ConfigObj(config_file)
config['General']['path_to_xml'] = path
config.write()
import itunesimport
itunesimport.itunesImport(path)
raise cherrypy.HTTPRedirect("/")
importItunes.exposed = True
def forceUpdate(self):
import updater
updater.dbUpdate()
raise cherrypy.HTTPRedirect("/")
forceUpdate.exposed = True
def forceSearch(self):
import searcher
searcher.searchNZB()
raise cherrypy.HTTPRedirect("/")
forceSearch.exposed = True
def history(self):
page = [templates._header]
page.append(templates._logobar)
page.append(templates._nav)
page.append(templates._footer)
return page
history.exposed = True
def config(self):
page = [templates._header]
page.append(templates._logobar)
page.append(templates._nav)
page.append(config.form)
page.append(templates._footer)
return page
config.exposed = True
def configUpdate(self, http_host='127.0.0.1', http_username=None, http_port=8181, http_password=None, launch_browser=0,
sab_host=None, sab_username=None, sab_apikey=None, sab_password=None, sab_category=None, music_download_dir=None,
usenet_retention=None, nzbmatrix=0, nzbmatrix_username=None, nzbmatrix_apikey=None, newznab=0, newznab_host=None, newznab_apikey=None,
nzbsorg=0, nzbsorg_uid=None, nzbsorg_hash=None, include_lossless=0,flac_to_mp3=0, move_to_itunes=0, path_to_itunes=None, rename_mp3s=0, cleanup=0, add_album_art=0):
configs = configobj.ConfigObj(config_file)
SABnzbd = configs['SABnzbd']
General = configs['General']
NZBMatrix = configs['NZBMatrix']
Newznab = configs['Newznab']
NZBsorg = configs['NZBsorg']
General['http_host'] = http_host
General['http_port'] = http_port
General['http_username'] = http_username
General['http_password'] = http_password
General['launch_browser'] = launch_browser
SABnzbd['sab_host'] = sab_host
SABnzbd['sab_username'] = sab_username
SABnzbd['sab_password'] = sab_password
SABnzbd['sab_apikey'] = sab_apikey
SABnzbd['sab_category'] = sab_category
General['music_download_dir'] = music_download_dir
General['usenet_retention'] = usenet_retention
NZBMatrix['nzbmatrix'] = nzbmatrix
NZBMatrix['nzbmatrix_username'] = nzbmatrix_username
NZBMatrix['nzbmatrix_apikey'] = nzbmatrix_apikey
Newznab['newznab'] = newznab
Newznab['newznab_host'] = newznab_host
Newznab['newznab_apikey'] = newznab_apikey
NZBsorg['nzbsorg'] = nzbsorg
NZBsorg['nzbsorg_uid'] = nzbsorg_uid
NZBsorg['nzbsorg_hash'] = nzbsorg_hash
General['include_lossless'] = include_lossless
General['flac_to_mp3'] = flac_to_mp3
General['move_to_itunes'] = move_to_itunes
General['path_to_itunes'] = path_to_itunes
General['rename_mp3s'] = rename_mp3s
General['cleanup'] = cleanup
General['add_album_art'] = add_album_art
configs.write()
reload(config)
raise cherrypy.HTTPRedirect("/config")
configUpdate.exposed = True
def shutdown(self):
sys.exit(0)
shutdown.exposed = True